f-string 相关问题


如何查找给定的键是否存在于 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; } } 这是一项有用的技术。


java中的Boolean.valueOf(String)和BooleanUtils.toBoolean(String)?

我有一个 Boolean.valueOf(String) 和 BooleanUtils.toBoolean(String) 之间不同的问题 。 我使用我的应用程序就像代码 BooleanUtils.toBoolean(defaultInfoRow.getFolderType()) 一样


在 iPhone Maps.app 上获取“当前位置”

我正在使用此代码从我的应用程序运行maps.app。 NSString* urlStr = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", s_lat, s_long, d_lat, d_lo...


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

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


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

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


如何以模板文字类型返回?

我使用这样的模板文字类型: 输入 HelloSomething = `你好 ${string}` 常量字符串='世界' 函数 sayHello(string: string): HelloSomething { 返回“你好”+字符串 } (游乐场...


对成对中不同类型的元素应用同态

简而言之,我希望在 Haskell 中进行以下类型检查: 两者 f (x, y) = (f x, f y) foo :: ([Int], [Char]) foo = ([1], "a") 栏 :: ([Int], [Char]) bar = 两者(连接。复制 3...


F#租车商业模式

我是F#新手,所以请怜悯。尝试使用 F# 为汽车租赁业务建模。我的类型是: 顾客 司机 车 车辆类型 租赁协议尚未实施 我的具体问题是...


包级功能

以下输出“2”。这是为什么?它不应该递归并打印“210”吗? 包主 var f = func(x int) {} 函数酒吧(){ f := func(x int) { ...


Alamo Fire 和 Swift 无法将类型“[String : String]”的值转换为预期参数类型“HTTPHeaders?”

func requestWithRetries(tag:String, url:String, maxRetry:Int = 3,expectJSONArray:Bool,completion:@escaping jsonCompletion) { var headers = [String:String]() 让 params = [String:AnyObjec...


F#:静态let和静态成员

我是 F# 新手,目前正在阅读 F# 3.0 专家。 这是我学习的第一种编译语言(我只知道用 R 编程) 第 6 章第 117 页,我们的介绍没有太多仪式 圣...


将函数地址存储到全局变量中

考虑以下代码: 无效 f() {}; 无效* v = f; 整数 i = f; int main() { } 为什么将函数地址存储到 int 变量中会给我一个错误: 错误:初始化元素不是编译时


print/repr 中显示的十六进制整数代表什么?

在如下所示的交互式会话中: >>> f=open('test.txt','w') >>> f 0x6e610 代表什么以及我能做什么


另一个模型中的模型列表仅保存列表中所有项目中最后添加的项目

对于 (int x=0; x for (int x=0; x<listaEquipes.length; x++) { await _loadEquipe(listaEquipes[x].id.toString()); TabelaListaEquipes _reg = TabelaListaEquipes(); _reg.equipeId = listaEquipes[x].id.toString(); _reg.equipe = listaAtletaEquipe; //print (_reg.equipe![0].nome.toString()); listaEquipesGeral.add(_reg); } 此型号: class TabelaListaEquipes { String? equipeId; List<TabelaInscricoes>? equipe; TabelaListaEquipes( { this.equipeId, this.equipe}); } 现在我看到最后一个reg保存在列表的所有iten中,为什么? 这就对了: listaEquipesGeral[0].equipe == listEquipesGeral[1].equipe ...仍然添加了最后一项。为什么?? _loadEquipe 函数,它也有效,我已经测试过了, List<TabelaInscricoes> listaAtletaEquipe = []; Future<void> _loadEquipe(equipId) async { setState(() { listaAtletaEquipe.clear(); carregandoEquipe = true; }); TabelaInscricoes _result = TabelaInscricoes(); CollectionReference _dbCollection = FirebaseFirestore.instance.collection('campeonatos').doc(resultSelect.campId).collection('divisoes').doc(resultSelect.divId).collection('equipes').doc(equipId).collection('atletas'); await _dbCollection.orderBy('pos2', descending: false).get().then((QuerySnapshot querySnapshot) async { if (querySnapshot.docs.isNotEmpty) { querySnapshot.docs.forEach((element) async { _result = TabelaInscricoes.fromJson(element.data()! as Map<String, dynamic>); if (_result.campId == resultSelect.campId && _result.divId == resultSelect.divId) { _result.id = element.id; _result.filePath = ""; setState(() { listaAtletaEquipe.add(_result); }); } }); for (int x = 0; x<listaAtletaEquipe.length; x++) { for (int y = 0; y<listaAtletas.length; y++) { if (listaAtletaEquipe[x].atletaId.toString() == listaAtletas[y].id.toString()) { setState(() { listaAtletaEquipe[x].nome = listaAtletas[y].nome; listaAtletaEquipe[x].fotoNome = listaAtletas[y].fotoNome; listaAtletaEquipe[x].filePath = listaAtletas[y].filePath; listaAtletaEquipe[x].dataN = listaAtletas[y].dataN; listaAtletaEquipe[x].fone1 = listaAtletas[y].fone1; listaAtletaEquipe[x].fone2 = listaAtletas[y].fone2; listaAtletaEquipe[x].nTitulo = listaAtletas[y].nTitulo; listaAtletaEquipe[x].info = listaAtletas[y].info; listaAtletaEquipe[x].email = listaAtletas[y].email; }); } } } for (int x=0; x<listaAtletaEquipe.length; x++) { if (listaAtletaEquipe[x].fotoNome.toString().isNotEmpty) { await MyStorage.getUrl(context, "atletas/${listaAtletaEquipe[x].fotoNome.toString()}").then((value) { setState(() { listaAtletaEquipe[x].filePath = value; }); }); } } setState(() { carregandoEquipe = false; }); }else { setState(() { carregandoEquipe = false; }); } }); } AtletaEquipes 型号操作系统列表: class TabelaInscricoes{ bool? carregando = true; String? id; String? campId; String? divId; String? atletaId; String? nome_responsavel; String ?posicao; String? filePath; Uint8List? imageFile; String? usuario; String? nInscricao; String? nome; String? dataN; String? nTitulo; String? fone1; String? fone2; String? info; String? email; String? fotoNome; String? pos2; String? selected; TabelaInscricoes({ this.carregando, this.nome, this.dataN, this.nTitulo, this.fone1, this.fone2, this.info, this.email, this.id, this.campId, this.divId, this.posicao, this.nome_responsavel, this.nInscricao, this.atletaId, this.selected, this.pos2, this.fotoNome, this.filePath, this.imageFile, this.usuario}); Map<String, dynamic> toJson() => { 'campId': campId, 'divId': divId, 'atletaId': atletaId, 'nome_responsavel': nome_responsavel, 'posicao': posicao, 'usuario': usuario, 'nInscricao': nInscricao, 'pos2': pos2, 'selected': selected }; TabelaInscricoes.fromJson(Map<String, dynamic> json) : campId = json['campId'], divId = json['divId'], atletaId = json['atletaId'], nome_responsavel = json['nome_responsavel'], posicao = json['posicao'], nInscricao = json['nInscricao'], pos2 = json['pos2'], selected = json['selected'], usuario = json['usuario']; } 这里发生了什么,listaEquipesGeral 总是保存最后添加的所有项目。 我明白了,解决方案是在模型内的列表中逐项添加: for (int x=0; x<listaEquipes.length; x++) { await _loadEquipe(listaEquipes[x].id.toString()); TabelaListaEquipes _reg = TabelaListaEquipes(); _reg.equipeId = listaEquipes[x].id.toString(); _reg.equipe = []; //here above the solution, include for to put item by item, and it works for (int y = 0; y<listaAtletaEquipe.length; y++) { _reg.equipe!.add(listaAtletaEquipe[y]); } //print (_reg.equipe![0].nome.toString()); listaEquipesGeral.add(_reg); }


尝试避免 pytest 测试中的代码重复

我有这样的结构: @pytest.fixture(范围='会话') def load_config() -> 字典: 打开(r“test_plan_1.yaml”)作为f: 数据 = yaml.safe_load(f) 返回数据 课堂测试...


Kotlin - 主要和次要构造函数

class SmartDevice(val 名称: String, val 类别: String) { var deviceStatus = "在线" 构造函数(名称:字符串,类别:字符串,状态代码:Int):this(名称,类别){ ...


在使用 TypeScript 进行 React 时,输入字段在“值”处给出错误

从“react”导入{SetStateAction,useState} const 登录表单 =() =>{ const [名称,setName] = useState(); const [全名,setFullname] = useState import { SetStateAction, useState } from "react" const Loginform =() =>{ const [name, setName] = useState<String | null>(); const [fullname, setFullname] = useState<String | null>(); const inputEvent =(event: { target: { value: SetStateAction< String |null | undefined >; }; })=>{ setName(event.target.value) } const Submit = ()=>{ setFullname(name) } return <> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> <button onClick={Submit}>Submit</button> <h1>Hi {fullname==null? "Guest" :fullname}</h1> </> } export default Loginform <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> 上一行中的“value”属性显示错误 这是错误详细信息: (property) React.InputHTMLAttributes<HTMLInputElement>.value?: string | number | readonly string[] | undefined Type 'String | null | undefined' is not assignable to type 'string | number | readonly string[] | undefined'. Type 'null' is not assignable to type 'string | number | readonly string[] | undefined'.ts(2322) index.d.ts(2398, 9): The expected type comes from property 'value' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>' 也尝试写 return as any。或者尝试添加 string[],但出现错误。 进行以下调整: 将 String 替换为 string,因为原始 Typescript 类型是小写的 (number, string, boolean, etc) TypeScript 报告此错误,因为属性值不接受 null 作为值,而是接受 undefined。将代码更新为: const [name, setName] = useState<string>() 这会使用 string 作为默认类型来初始化状态。 初始状态隐式地被视为 undefined,因为如果未显式提供,TypeScript 会将类型的默认值设置为 undefined。 为了简单起见,您不需要解构事件。使用内联函数,如下例所示: <input type="text" placeholder="Enter your name" onChange={(e) => setName(e.target.value)} value={name}/> 我使用你的代码创建了一个 CodeSanbox,它似乎只需要很少的修改就可以正常工作。 您可以在这里找到沙盒 这是我想出的代码 import { SetStateAction, useState } from "react"; const Loginform = () => { const [name, setName] = useState<string | null>(); const [fullname, setFullname] = useState<string | null>(); const inputEvent = (event: { target: { value: SetStateAction<string | null | undefined> }; }) => { setName(event.target.value); }; const Submit = () => { setFullname(name); }; return ( <div> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name} /> <button onClick={Submit}>Submit</button> <h1>Hi {fullname == null ? "Guest" : fullname}</h1> </div> ); }; export default Loginform;


Julia 语法错误@kwdef,默认值为字符串

此代码会产生语法错误。我无法在 @kwdef 结构中使用默认值? @kwdef 结构 MyStruct indir::String = "./", outdir::String = "./结果", 阈值...


如何生成带有货币符号(例如 $)而不是货币代码(USD、EUR)的价格字符串?

这是我当前的代码: fun getMonthlyPriceString(yearlyPriceMicros: Long,currencyCode: String): String { val 格式:NumberFormat = NumberFormat.getCurrencyInstance() 格式。


F# 中的 IEnumerator 是否可以“yield return null”?

例如在 C# 中: 公共 IEnumerator MyFunc() { 产量返回空 } 这是我在 F# 中尝试过的: 序列{ 产生空值 } :?> IEnumerator 编译完之后用ILSpy看一下w...


在 Lisp 中删除列表中的双元素

我必须从 lisp 列表中删除所有双精度元素..这是一个示例: (A B C D E A A B F G A) => (A B C D E F G) 我该怎么做?


如何返回内在的字符串操作类型?

要返回模板文字类型,需要返回一个模板文字: 输入 HelloSomething = `你好 ${string}` const str = '世界' 函数 sayHello(str: string): HelloSomething { 返回`...


System.CommandLine F# 友好吗?

对于 F# 应用程序,我传统上使用不同的功能友好的命令行解析器,例如 Argu 和 CommandLineParser。 现在微软已经推出了 System.CommandLine(具有潜在的优势......


Python 中的 AWS Lambda 函数,生成字符串流

所以我想利用这个.net代码,我在卡盘中接收响应并单独处理每个块 公共异步任务 InvokeLambdaFunctionAsync(string functionName, string pay...


在F#的计算表达式中定义新的关键字

F# 3.0 beta 包含一个带有大量新关键字的查询 {} 计算表达式。 如何在计算生成器中定义自己的关键字?


无法将 Generic<string> 转换为 Generic<TArg>,即使我在检查 Generic<string> 是否可分配给 Generic<TArg>

和标题差不多。我有这个代码: if (typeof(Option).IsAssignableTo(typeof(Option))) { 返回新结果(无(),(选项)结果.GetErr(...


在 Android Studio 中找不到错误符号

String sAux=getResources().getString(R.string.ShareText); sAux+=” ”; sAux+="https://play.google.com/store/apps/details?id="; sAux+=getPackageName(); sAux+=” ”; ...


如何让用户在 SwiftUI 文本字段中仅使用数字输入货币,同时保留 $ 和 .?

现在,我有以下内容: 私有变量currencyFormatter:NumberFormatter = { 让 f = NumberFormatter() // 不允许出现货币符号、额外数字等 f.isLenient = true f.


为什么 sonarqube 存在安全问题?

我有以下方法: 公共列表 getZipFileList(String fullPath) 抛出 IOException { logger.debug("====> ZipService: getZipFileList <====");


如何让编译器区分 f(double...) 和 f(int, double...)

我正在编写一个用于处理多项式的小型库。 主类称为poly,它包含4个重载构造函数。 Poly 类的对象是一个多项式的表示。 满


汽车租赁商业模式

我是F#新手,所以请怜悯。尝试使用 F# 为汽车租赁业务建模。我的类型是: 顾客 司机 车 车辆类型 租赁协议尚未实施 我的具体问题是可以...


是否可以从zoned_time获取time_point?

我尝试在 std::string 中有选择地获取当地时间/UTC。 我尝试过的: (1) 获取 UTC 的 std::string 使用 std::format 可以正常工作: 自动 utc = std::chrono::system_clock::now(); std::字符串...


F# 中编写函数时堆栈溢出

基本上,我的问题是我正在尝试组合大量函数,因此我正在创建一个深层次的组合函数链。这是我的代码: let rec fn (f : (状态 -> 状态选项)...


使用 Json.NET 将 F# 判别联合序列化为字符串

我正在尝试在序列化时进行从 F# 的可辨别联合到字符串的单向转换,而不是默认的“Case”:[value]”。能够再次反序列化该值不是问题......


多重定义和静态关键字

2.o 中的函数 f 具有全局作用域,而 1.c 如果他愿意,他可以使用它。 但在 1.o 中 f 有唯一的定义。 链接器同意接受它 这里怎么没有冲突呢


Java 中多维数组的维数顺序

当我在Java中定义一个4d数组时,例如 var f = new float[1000][3][250][250];它只占用堆内存 797 MB,但是当我像 var f = new float[1000][250][250][3]; 那样定义它时;它占据了22...



MS Office 脚本中的数组转换

嗨我需要转换这个: // 转换 [[1],[2],[3],[4],["a","b","c"],["d","e","f"]] 对此: [1,2,3,4,"a","b","...


如何在 Groovy 中声明字符串数组?

如何在 Groovy 中声明字符串数组?我正在尝试如下但它抛出一个错误 def String[] osList = new String[] 行中没有数组构造函数调用的表达式: 我在做什么...


通过更少的 Java API 调用来映射 Google 云端硬盘内容的有效方法

大家好,我有一个代码,用于列出共享驱动器中存在的文件(以便稍后下载并创建相同的文件夹路径) 目前我做这样的事情: 哈希映射 大家好,我有一个代码,用于列出共享驱动器中存在的文件(以便稍后下载并创建相同的文件夹路径) 目前我正在做这样的事情: HashMap<String, Strin> foldersPathToID = new HashMap<>(); //searching all folders first saving their IDs searchAllFoldersRecursive(folderName.trim(), driveId, foldersPathToID); //then listing files in all folders HashMap<String, List<File>> pathFile = new HashMap<>(); for (Entry<String, String> pathFolder : foldersPathToID.entrySet()) { List<File> result = search(Type.FILE, pathFolder.getValue()); if (result.size() > 0) { String targetPathFolder = pathFolder.getKey().trim(); pathFile.putIfAbsent(targetPathFolder, new ArrayList<>()); for (File file : result) { pathFile.get(targetPathFolder).add(file); } } } 递归方法在哪里: private static void searchAllFoldersRecursive(String nameFold, String id, HashMap<String, String> map) throws IOException, RefreshTokenException { map.putIfAbsent(nameFold, id); List<File> result; result = search(Type.FOLDER, id); // dig deeper if (result.size() > 0) { for (File folder : result) { searchAllFoldersRecursive(nameFold + java.io.File.separator + normalizeName(folder.getName()), folder.getId(), map); } } } 搜索功能是: private static List<com.google.api.services.drive.model.File> search(Type type, String folderId) throws IOException, RefreshTokenException { String nextPageToken = "go"; List<File> driveFolders = new ArrayList<>(); com.google.api.services.drive.Drive.Files.List request = service.files() .list() .setQ("'" + folderId + "' in parents and mimeType" + (type == Type.FOLDER ? "=" : "!=") + "'application/vnd.google-apps.folder' and trashed = false") .setPageSize(100).setFields("nextPageToken, files(id, name)"); while (nextPageToken != null && nextPageToken.length() > 0) { try { FileList result = request.execute(); driveFolders.addAll(result.getFiles()); nextPageToken = result.getNextPageToken(); request.setPageToken(nextPageToken); return driveFolders; } catch (TokenResponseException tokenError) { if (tokenError.getDetails().getError().equalsIgnoreCase("invalid_grant")) { log.err("Token no more valid removing it Please retry"); java.io.File cred = new java.io.File("./tokens/StoredCredential"); if (cred.exists()) { cred.delete(); } throw new RefreshTokenException("Creds invalid will retry re allow for the token"); } log.err("Error while geting response with token for folder id : " + folderId, tokenError); nextPageToken = null; } catch (Exception e) { log.err("Error while reading folder id : " + folderId, e); nextPageToken = null; } } return new ArrayList<>(); } 我确信有一种方法可以通过很少的 api 调用(甚至可能是一个调用?)对每个文件(使用文件夹树路径)进行正确的映射,因为在我的版本中,我花了很多时间进行调用 service.files().list().setQ("'" + folderId+ "' in parents and mimeType" + (type == Type.FOLDER ? "=" : "!=") + "'application/vnd.google-apps.folder' and trashed = false").setPageSize(100).setFields("nextPageToken, files(id, name)"); 每个子文件夹至少一次......并且递归搜索所有内容需要很长时间。最后,映射比下载本身花费的时间更多...... 我搜索了文档,也在此处搜索,但没有找到任何内容来列出具有一个库的所有驱动器调用任何想法? 我想使用专用的 java API 来获取共享 GoogleDrive 中的所有文件及其相对路径,但调用次数尽可能少。 提前感谢您的时间和答复 我建议您使用高效的数据结构和逻辑来构建文件夹树并将文件映射到其路径,如下所示 private static void mapDriveContent(String driveId) throws IOException { // HashMap to store folder ID to path mapping HashMap<String, String> idToPath = new HashMap<>(); // HashMap to store files based on their paths HashMap<String, List<File>> pathToFile = new HashMap<>(); // Fetch all files and folders in the drive List<File> allFiles = fetchAllFiles(driveId); // Build folder path mapping and organize files for (File file : allFiles) { String parentId = (file.getParents() != null && !file.getParents().isEmpty()) ? file.getParents().get(0) : null; String path = buildPath(file, parentId, idToPath); if (file.getMimeType().equals("application/vnd.google-apps.folder")) { idToPath.put(file.getId(), path); } else { pathToFile.computeIfAbsent(path, k -> new ArrayList<>()).add(file); } } // Now, pathToFile contains the mapping of paths to files // Your logic to handle these files goes here } private static List<File> fetchAllFiles(String driveId) throws IOException { // Implement fetching all files and folders here // Make sure to handle pagination if necessary // ... } private static String buildPath(File file, String parentId, HashMap<String, String> idToPath) { // Build the file path based on its parent ID and the idToPath mapping // ... }


为什么此代码有时可以工作,但如果我在不同的尝试中输入相同的输入,有时会出错?

随机导入 字母=[ 'a'、'b'、'c'、'd'、'e'、'f'、'g'、'h'、'i'、'j'、'k'、'l'、'm ', '不', “p”、“q”、“r”、“s”、“t”、“u”、“v”、“w”、“x”、“y”、“z”、“A”、“B” ', '光盘', ‘E’、‘F’...


F# 从 while 循环中中断

有什么办法可以像C/C#那样做到吗? 例如(C#风格) 对于 (int i = 0; i < 100; i++) { if (i == 66) break; }


Java 中多维数组的维数顺序影响内存使用

当我在Java中定义一个4d数组时,例如 var f = new float[1000][3][250][250];它仅占用堆内存 797 MB。但是当我将其定义为 var f = new float[1000][250][250][3]; 时它占据 2...


C++:将 std::string 分配给缓冲区数组

在处理必须与 C 代码互操作的代码时,我经常遇到这个问题,其中有一个 std::string ,您需要将其内容复制到普通的 char 缓冲区,如下所示: 结构体T {...


Windows 窗体 Web 浏览器:CTRL+F 搜索未找到任何内容

在我们的 C# 应用程序中,我们有一个弹出的窗体,其中包含 System.Windows.Forms.WebBrowser 控件。当我单击 WebBrowser 控件并按 CTRL+F 时,将打开一个搜索框。 但是当我输入一些...


限制限定符可以用来提示编译器外部函数不会修改你的内存吗?

作为我上一个问题的后续,请考虑以下代码: int f(int *p); 静态内联 int g0(int *p) { *p=0; f(空); // 可能会修改 *p 返回*p==0; } int caller0(int *q) { ret...


在另一个列表中计算一个列表中的元素

df 是这样的: df <- data.frame( groups=I(list(c("a"), c("b","c", "d", "e","f"), c("g","h"), c("i&quo...


背景颜色未正确应用

我有这个自定义控件。 公共类面板:ContentView { 公共静态只读 BindableProperty CaptionProperty = BindableProperty.CreateAttached(nameof(Caption), typeof(string),


合并 argparse.MetavarTypeHelpFormatter、argparse.ArgumentDefaultsHelpFormatter 和 argparse.HelpFormatter

我想显示 --help 的默认值、参数类型和大间距。 但如果我这样做 导入argparse F 类(argparse.MetavarTypeHelpFormatter,argparse.ArgumentDefaultsHelpFormatter,lambda pr...


根据输入参数获取列表

我在Java中有以下方法: 公共列表getList(字符串str,类clazz){ List lst = new ArrayList<>(); String[] arr = str.split(",&quo...


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