AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

全部问题(coding)

Martin Hope
Mahesh Kamath - Vendor
Asked: 2025-04-26 17:22:56 +0800 CST

HttpsConnectionPool 错误 Selenium:使用 Selenium 将 3000 个 ID 从 csv 文件的列粘贴到 URL 的输入字段中。对于 200 个 ID 来说效果很好

  • 6

我正在使用 Selenium 自动下载一份报告。为此,我需要将大约 3000 个 ID 以循环方式粘贴到网页的输入字段中,每个 ID 大约有 30 万个,然后点击“下载”按钮,等待大约 40 秒即可下载报告。之后,点击“清除”按钮清除输入字段,再将另外 3000 个值(或 ID)粘贴到输入字段中,再次点击“下载”。重复此步骤,直到提取完数据框中某一列的所有 ID。

ID 之间以逗号分隔。

手动操作大约需要 2 秒来粘贴值(正好 3000 个)并下载,然后等待 40 秒,清除并粘贴另外 3000 个 ID。重复此过程。

但是,在登录 url 后使用 selenium 脚本时,关闭所有弹出窗口并选择精确选项,然后在输入(或使用 input_filed.send_keys(ids) 和 input_field.send_keys(Keys.ENTER))时,120 秒出现超时错误。我没有 120 秒的时间等待,而手动只需 2 秒即可抛出错误。

该脚本对于 200 左右的 ID 运行良好,但对于 3000 左右的 ID 则不行。我希望粘贴 3000 个值,以便加快进程。

请提供解决方案。

下面是我尝试的代码。请看一下最后主要问题在哪里。

from selenium import webdriver
#you have to create instance wait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("MY URL")

wait = WebDriverWait(driver, 10)


try: 
    close_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.toast-close-button")))
    close_button.click()
    print("Popup Closed")
except Exception as e:
    print("No Popup appeared. or popup closed")
    print("Error: ", e)

try:
    username_input = wait.until(EC.presence_of_element_located((By.ID, "username")))
    username_input.send_keys("[email protected]")
    print("UserName Entered")
except Exception as e:
    print("Failed to enter Username")
    print("Error: ", e)


try: 
    password_input = wait.until(EC.presence_of_element_located((By.ID, "password")))
    password_input.send_keys("some_password")
    print("Password Entered")
except Exception as e:
    print("Failed to enter Password")
    print("Error: ",e)

try:
    submit_button = wait.until(EC.element_to_be_clickable((By.ID, "loginSubmit"))) 
    submit_button.click()
    print("Submit Button Clicked")
except Exception as e:
    print("Failed to click submit button")
    print("Error: ",e)


ids_option= WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="root"]/div/div/div[2]/div[2]/div[2]/div/div/div[1]/div/div/div/div/div[1]/div'))
)
ids_option.click()

option = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//div[text()="Option for Id selected"]'))
)
option.click()


input_click_target = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="root"]/div/div/div[2]/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div/div[1]/div[1]'))
)
input_click_target.click()



focused_input = WebDriverWait(driver, 10).until(
    lambda d: d.execute_script("return document.activeElement")
)


from selenium.webdriver.common.keys import Keys
focused_input.send_keys(id_string)        #comma seperated ids
focused_input.send_keys(Keys.ENTER)

大约 120 秒后,它会抛出错误。如果我只输入 15 或 200 个 ID,它会起作用,但输入 3000 个 ID 时则不起作用。

请提供更快的解决方案

我尝试了上面提到的代码,并期望下载每个包含 3000 个 id 的单独 csv 文件,直到 id 结束。

python
  • 1 个回答
  • 57 Views
Martin Hope
bricks96
Asked: 2025-04-26 17:01:35 +0800 CST

异常:由于访问负行导致访问电子表格时服务电子表格失败

  • 8

我最近看到了一篇关于这个错误的帖子,因为无法重现该错误,所以帖子被关闭了。我昨晚也遇到了同样的错误,而且很容易重现。我不确定这两者之间有什么联系,但以下是我遇到的情况。

我试图确定可到达的最远行。例如,即使你的工作表只有默认的 1000 行,你也可以写入=ROW(OFFSET(A1,9999,))reach A10000。它会返回 10000。经过反复试验,我发现可以使用嵌套的 来获取最远行OFFSET。

=row(offset(offset(offset($A$1,B1,),C1,),D1,))

最后可到达的行是第 行2,147,483,647。如果我尝试转到2,147,483,649或更远,就会出现OFFSET 计算结果为超出范围的错误。但就在那之前,我发现了一个虫洞。没错,我尝试2,147,483,648使用到达第 行=row(offset(offset(offset($A$1,700000000,),700000000,),747483647,)),结果返回的是-2,147,483,648。您可以在下面看到结果(E 列包含用于启用或禁用公式的复选框)。

B 碳 D 埃 F 格
7亿 7亿 747483646 真的 2147483647 =if(E1,行(偏移量(偏移量(偏移量($A$1,B1,),C1,),D1,)),)
7亿 7亿 747483647 真的 -2147483648 =if(E2,行(偏移量(偏移量(偏移量($A$1,B2,),C2,),D2,)),)
7亿 7亿 747483648 真的 #参考! =if(E3,行(偏移量(偏移量(偏移量($A$1,B3,),C3,),D3,)),)

它就像虫洞一样,通向纸张宇宙的另一边。我可以在那一行左右移动,甚至可以回到这一边,但我无法在那一边上下移动任何行。确实很奇怪,但没什么危害,我打算报告。

然而,后来当我尝试打开我的个人插件时,出现了以下运行时错误。异常:访问 ID 为 #### 的文档时,服务电子表格失败。[行:77,函数:myGlobalConfig,文件:core/lib/Config。

在费尽心思寻找问题根源之后,我突然冒出个念头,想看看虫洞是不是问题根源。结果也确实如此。我激活那个特定公式时收到了错误提示。禁用那个公式后,问题就消失了。

我甚至在绑定脚本中创建了一个基本函数,用于检索工作表的名称并使用 Toast 显示它。当激活中间那个公式时,出现了相同的错误,得出了负行的值。关闭后,错误就消失了。

这与之前提到的另一篇文章有​​联系吗?有人知道为什么这一行是负数吗?

google-sheets
  • 2 个回答
  • 62 Views
Martin Hope
retpoline
Asked: 2025-04-26 16:31:41 +0800 CST

无法区分两个 Python n 皇后解决方案

  • 6

在阅读回溯相关知识的过程中,我找到了 geeksforgeeks.org 上一个关于 n 皇后问题解决方案的页面。第一个解决方案被称为“朴素方法”,它可以生成所有可能的排列,其效率最低,为 O(n! * n)。第二个解决方案是“我们不是生成所有可能的排列,而是逐步构建解决方案,这样做可以确保每一步部分解决方案都有效。如果发生冲突,我们会立即回溯,这有助于避免不必要的计算。” 据说它的复杂度是 O(n!)。

分析代码时,除了注释、一些变量名、对角线冲突的计算/记录方式以及其他一些没有区别的琐碎事情(例如使用 [:] 而不是 .copy())之外,我根本看不出两者之间的区别(在递归/回溯/修剪方面)。

第一个解决方案(效率最低):

#Python program to find all solution of N queen problem 
#using recursion

# Function to check if placement is safe
def isSafe(board, currRow, currCol):
    for i in range(len(board)):
        placedRow = board[i]
        placedCol = i + 1
        
        # Check diagonals
        if abs(placedRow - currRow) == \
           abs(placedCol - currCol):
            return False # Not safe
          
    return True # Safe to place

# Recursive utility to solve N-Queens
def nQueenUtil(col, n, board, res, visited):
  
    # If all queens placed, add to res
    if col > n:
        res.append(board.copy())
        return
      
    # Try each row in column
    for row in range(1, n+1):
      
        # If row not used
        if not visited[row]:
          
            # Check safety
            if isSafe(board, row, col):
              
                # Mark row
                visited[row] = True
                
                # Place queen
                board.append(row)
                
                # Recur for next column
                nQueenUtil(col+1, n, board, res, visited)
                
                # Backtrack
                board.pop()
                visited[row] = False

# Main N-Queen solver
def nQueen(n):
    res = []
    board = []
    visited = [False] * (n + 1)
    nQueenUtil(1, n, board, res, visited)
    return res

if __name__ == "__main__":
    n = 4
    res = nQueen(n)
    for row in res:
        print(row)

第二种解决方案(通过修剪进行回溯,据称效率更高):

# Python program to find all solutions of the N-Queens problem
# using backtracking and pruning

def nQueenUtil(j, n, board, rows, diag1, diag2, res):

    if j > n:
        # A solution is found
        res.append(board[:])
        return

    for i in range(1, n + 1):
        if not rows[i] and not diag1[i + j] and not diag2[i - j + n]:

            # Place queen
            rows[i] = diag1[i + j] = diag2[i - j + n] = True
            board.append(i)

            # Recurse to the next column
            nQueenUtil(j + 1, n, board, rows, diag1, diag2, res)

            # Remove queen (backtrack)
            board.pop()
            rows[i] = diag1[i + j] = diag2[i - j + n] = False

def nQueen(n):
    res = []
    board = []

    # Rows occupied
    rows = [False] * (n + 1)

    # Major diagonals (row + j) and Minor diagonals (row - col + n)
    diag1 = [False] * (2 * n + 1)
    diag2 = [False] * (2 * n + 1)

    # Start solving from the first column
    nQueenUtil(1, n, board, rows, diag1, diag2, res)
    return res

if __name__ == "__main__":
    n = 4
    res = nQueen(n)

    for temp in res:
        print(temp)
python
  • 1 个回答
  • 75 Views
Martin Hope
test testb
Asked: 2025-04-26 16:03:34 +0800 CST

Razor - 在 JavaScript 中将 DataTable 转换为数组

  • 5

我在 Razor Project 中有一个数据表,其中包含 id、name、title、parent 和其他字段。我需要动态绑定一个 JavaScript 数组,但我尝试了以下代码却报错。请帮忙。

它能很好地处理如下所示的静态数据,并且我的组织结构图显示没有错误。

var testData = [
    { id: 1, name: "John", title: "CEO", parent: 0 }, 
    { id: 2, name: "Tom", title: "SellManager", parent: 1 }, 
    { id: 3, name: "Jerry", title: "SupportManager", parent: 1 }, 
    { id: 4, name: "Robert", title: "SellExpert", parent: 2 },
];

使用 JSON 生成的数据不起作用并显示错误:

未捕获的 TypeError:无法读取未定义的属性(读取“render”)jquery-3.7.1.min.js:2 jQuery.Deferred 异常:无法读取未定义的属性(读取“render”)TypeError:无法读取未定义的属性(读取“render”)

<script type="text/javascript">        
/////////////////////   Chart Script Start   /////////////////////
    var jq = jQuery.noConflict();

    (function (jq) {
        jq.fn.orgChart = function (options) {
            var opts = jq.extend({}, jq.fn.orgChart.defaults, options);
            return new OrgChart(jq(this), opts);
        }

        jq.fn.orgChart.defaults = {
            data: [{ id: 1, name: 'Root', title: 'Amount', parent: 0, hierarchy: 0 }],
            showControls: false,
            allowEdit: false,
            onAddNode: null,
            onDeleteNode: null,
            onClickNode: null,
            newNodeText: 'Add',
            delNodeText: 'del'
        };

        function OrgChart(jqcontainer, opts) {
            var data = opts.data;
            var nodes = {};
            var rootNodes = [];
            this.opts = opts;
            this.jqcontainer = jqcontainer;
            var self = this;

            this.draw = function () {
                jqcontainer.empty().append(rootNodes[0].render(opts));
                //document.getElementsByClassName('org-del-button')[0].style.display = 'none';
                jqcontainer.find('.node').click(function () {
                    if (self.opts.onClickNode !== null) {
                        self.opts.onClickNode(nodes[jq(this).attr('node-id')]);
                    }
                });

                if (opts.allowEdit) {
                    jqcontainer.find('.node h2').click(function (e) {
                        var thisId = jq(this).parent().attr('node-id');
                        self.startEdit(thisId);
                        e.stopPropagation();
                    });
                    jqcontainer.find('.node h3').click(function (e) {
                        var thisId = jq(this).parent().attr('node-id');
                        self.startEdith3(thisId);
                        e.stopPropagation();
                    });
                }

                // add "add button" listener
                jqcontainer.find('.org-add-button').click(function (e) {
                    var thisId = jq(this).parent().attr('node-id');

                    if (self.opts.onAddNode !== null) {
                        self.opts.onAddNode(nodes[thisId]);
                    }
                    else {
                        self.newNode(thisId);
                    }
                    e.stopPropagation();
                });

                jqcontainer.find('.org-del-button').click(function (e) {
                    var thisId = jq(this).parent().attr('node-id');

                    if (self.opts.onDeleteNode !== null) {
                        self.opts.onDeleteNode(nodes[thisId]);
                    }
                    else {
                        self.deleteNode(thisId);
                    }
                    e.stopPropagation();
                });
            }

            this.startEdit = function (id) {
                var inputElement = jq('<input class="org-input" type="text" value="'+nodes[id].data.name+'"/>');
                jqcontainer.find('div[node-id=' + id + '] h2').replaceWith(inputElement);
                var commitChange = function () {
                    var h2Element = jq('<h2>' + nodes[id].data.name + '</h2>');
                    if (opts.allowEdit) {
                        h2Element.click(function () {
                            self.startEdit(id);
                        })
                    }
                    inputElement.replaceWith(h2Element);
                }
                inputElement.focus();
                inputElement.keyup(function (event) {
                    if (event.which == 13) {
                        commitChange();
                    }
                    else {
                        nodes[id].data.name = inputElement.val();
                    }
                });
                inputElement.blur(function (event) {
                    commitChange();
                })
            }

            //////////////////////title field//////////////////////////////
            this.startEdith3 = function (id) {
                var inputElement = jq('<input class="org-input" type="text" value="' + nodes[id].data.title + '"/>');
                jqcontainer.find('div[node-id=' + id + '] h3').replaceWith(inputElement);
                var commitChange = function () {
                    var h3Element = jq('<h3>' + nodes[id].data.title + '</h3>');
                    if (opts.allowEdit) {
                        h3Element.click(function () {
                            self.startEdith3(id);
                        })
                    }
                    inputElement.replaceWith(h3Element);
                }
                inputElement.focus();
                inputElement.keyup(function (event) {
                    if (event.which == 13) {
                        commitChange();
                    }
                    else {
                        nodes[id].data.title = inputElement.val();
                    }
                });
                inputElement.blur(function (event) {
                    commitChange();
                })
            }
            //////////////////////title field ends////////////////////////
            this.newNode = function (parentId) {
                var nextId = Object.keys(nodes).length;
                while (nextId in nodes) {
                    nextId++;
                }

                self.addNode({ id: nextId, name: '(New name)', title: '0.0', hierarchy: parentId, parent: parentId });
            }

            this.addNode = function (data) {
                var newNode = new Node(data);
                nodes[data.id] = newNode;
                nodes[data.parent].addChild(newNode);
                self.draw();
                self.startEdit(data.id);
                self.startEdith3(data.id);
            }

            this.deleteNode = function (id) {
                for (var i = 0; i < nodes[id].children.length; i++) {
                    self.deleteNode(nodes[id].children[i].data.id);
                }
                nodes[nodes[id].data.parent].removeChild(id);
                delete nodes[id];
                self.draw();
            }

            this.getData = function () {
                var outData = [];
                for (var i in nodes) {
                    outData.push(nodes[i].data);
                }
                return outData;
            }

            // constructor
            for (var i in data) {
                var node = new Node(data[i]);
                nodes[data[i].id] = node;
            }

            // generate parent child tree
            for (var i in nodes) {
                if (nodes[i].data.parent == 0) {
                    rootNodes.push(nodes[i]);
                }
                else {
                    nodes[nodes[i].data.parent].addChild(nodes[i]);
                }
            }

            // draw org chart
            jqcontainer.addClass('orgChart');
            self.draw();
        }

        function Node(data) {
            this.data = data;
            this.children = [];
            var self = this;

            this.addChild = function (childNode) {
                this.children.push(childNode);
            }

            this.removeChild = function (id) {
                for (var i = 0; i < self.children.length; i++) {
                    if (self.children[i].data.id == id) {
                        self.children.splice(i, 1);
                        return;
                    }
                }
            }

            this.render = function (opts) {
                var childLength = self.children.length,
                    mainTable;

                mainTable = "<table cellpadding='0' cellspacing='0' border='0'>";
                var nodeColspan = childLength > 0 ? 2 * childLength : 2;
                mainTable += "<tr><td colspan='" + nodeColspan + "'>" + self.formatNode(opts) + "</td></tr>";

                if (childLength > 0) {
                    var downLineTable = "<table cellpadding='0' cellspacing='0' border='0'><tr class='lines x'><td class='line left half'></td><td class='line right half'></td></table>";
                    mainTable += "<tr class='lines'><td colspan='" + childLength * 2 + "'>" + downLineTable + '</td></tr>';

                    var linesCols = '';
                    for (var i = 0; i < childLength; i++) {
                        if (childLength == 1) {
                            linesCols += "<td class='line left half'></td>";    // keep vertical lines aligned if there's only 1 child
                        }
                        else if (i == 0) {
                            linesCols += "<td class='line left'></td>";     // the first cell doesn't have a line in the top
                        }
                        else {
                            linesCols += "<td class='line left top'></td>";
                        }

                        if (childLength == 1) {
                            linesCols += "<td class='line right half'></td>";
                        }
                        else if (i == childLength - 1) {
                            linesCols += "<td class='line right'></td>";
                        }
                        else {
                            linesCols += "<td class='line right top'></td>";
                        }
                    }
                    mainTable += "<tr class='lines v'>" + linesCols + "</tr>";

                    mainTable += "<tr>";
                    for (var i in self.children) {
                        mainTable += "<td colspan='2'>" + self.children[i].render(opts) + "</td>";
                    }
                    mainTable += "</tr>";
                }
                mainTable += '</table>';
                return mainTable;
            }

            this.formatNode = function (opts) {
                var nameString = '',
                    descString = '';
                titleString = '';
                if (typeof data.name !== 'undefined') {
                    nameString = '<h2>' + self.data.name + '</h2>';
                }
                if (typeof data.title !== 'undefined') {
                    titleString = '<h3>' + self.data.title + '</h3>';
                }
                if (typeof data.description !== 'undefined') {
                    descString = '<p>' + self.data.description + '</p>';
                }
                if (opts.showControls) {
                    var buttonsHtml = "<div class='org-add-button'>" + opts.newNodeText + "</div><div class='org-del-button'>" + opts.delNodeText + "</div>";
                }
                else {
                    buttonsHtml = '';
                }
                return "<div class='node' node-id='" + this.data.id + "'>" + nameString + titleString + descString + buttonsHtml + "</div>";
            }
        }

    })(jQuery);
    var data1 = @Html.Raw(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(Model.Table_Public)));
    testData = JSON.stringify(data1);
    alert(testData);

    jq(function () {
        org_chart = jq('#orgChart').orgChart({
            data: testData,
            showControls: false,
            allowEdit: false,
            onAddNode: function (node) {
                log('Created new node on node ' + 
                   node.data.id);
                org_chart.newNode(node.data.id);
            },
            onDeleteNode: function (node) {
                log('Deleted node ' + node.data.id);
                org_chart.deleteNode(node.data.id);
            },
            onClickNode: function (node) {
                log('Clicked node ' + node.data.id);
            }        
        });
    });
</script>
javascript
  • 1 个回答
  • 48 Views
Martin Hope
Sophia
Asked: 2025-04-26 14:59:59 +0800 CST

在 Python 中检查一个字符串是否可以由另一个字符串组成

  • 2

我想检查一个字符串是否可以由另一个字符串组成,例如,在下面的例子中,我想检查列表中有多少个字符串targets可以由字符串组成chars。 中的每个字符chars只能使用一次。

targets = ["cat","bt","hat","tree"], chars = "atach"

我的代码如下:

 ans = 0
 chars_freq = Counter(chars)
 for word in targets:
     word_freq = Counter(word)
     for char in word:
         if word_freq[char] > chars_freq[char]:
             break
     ans += 1
 return ans

例如,答案应该是2,但我得到的是4。谁能帮忙?谢谢。

python-3.x
  • 2 个回答
  • 52 Views
Martin Hope
ryuma
Asked: 2025-04-26 14:31:36 +0800 CST

Tailwind CSS 自定义颜色和标准颜色在 Next.js 15 项目中不起作用

  • 6

Tailwind CSS 自定义颜色和标准颜色在 Next.js 15 项目中无法正常工作。我正在使用 Tailwind CSS v4 开发一个 Next.js 15 项目,但在使用任何 Tailwind 背景颜色(包括自定义颜色和标准颜色,例如)时都遇到了问题bg-red-500。

我尝试过的方法

我在 globals.css 中定义了自定义颜色:

@theme {
  --colors-suki-light: #f6fdff;
}

我正尝试在我的组件中使用它:

export default function Home() {
  return <div className="bg-suki-light">aaaaaaaaaaaaaa</div>;
}

但是背景颜色没有应用。标准的 Tailwind 颜色bg-red-500也不起作用。

我的设置

tailwind.config.ts:

import type { Config } from "tailwindcss";

const config: Config = {
  content: [
    "./app/**/*.{ts,tsx}",
    "./app/*.{ts,tsx}",
    "./components/**/*.{ts,tsx}",
  ],
  plugins: [],
};
export default config;

全局.css:

@import "tailwindcss";

:root {
  --background: #ffffff;
  --foreground: #171717;
}

@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --font-sans: var(--font-geist-sans);
  --font-mono: var(--font-geist-mono);
}

@media (prefers-color-scheme: dark) {
  :root {
    --background: #0a0a0a;
    --foreground: #ededed;
  }
}

body {
  background: var(--background);
  color: var(--foreground);
  font-family: Arial, Helvetica, sans-serif;
}

@theme {
  --colors-suki-light: #f6fdff;
}

package.json 依赖项:

"dependencies": {
  "react": "^19.0.0",
  "react-dom": "^19.0.0",
  "next": "15.3.1"
},
"devDependencies": {
  "typescript": "^5",
  "@types/node": "^20",
  "@types/react": "^19",
  "@types/react-dom": "^19",
  "@tailwindcss/postcss": "^4",
  "tailwindcss": "^4",
  "eslint": "^9",
  "eslint-config-next": "15.3.1",
  "@eslint/eslintrc": "^3"
}

任何帮助都将不胜感激,因为我已经被这个问题困扰了好几个小时。

next.js
  • 1 个回答
  • 28 Views
Martin Hope
user3161924
Asked: 2025-04-26 14:31:17 +0800 CST

在 C# 类成员变量中保存对结构的引用?

  • 5

我想知道在 C# 中,如何正确地实现与这段 C++ 代码相同的功能,这段代码中保存了一个指向类对象或结构体的指针(引用)。由于 C# 处理结构体/类对象的方式不同,因此我将在此示例中使用结构体。

struct sMyStruct { .. blah .. };

class MyClass { 
  sMyStruct *RefToStruct=nullptr;

  MyClass(sMyStruct *reftostruct)
  { 
    RefToStruct=reftostruct;
  }
};

int main(void)
{
  sMyStruct *mystruct = new sMyStruct( .. blah .. );
  MyClass *c=new MyClass(mystruct);

  delete c;
  delete mystruct;
}

实际上,这个结构体是在其他地方创建的(作为框架的一部分,在我的控制范围之外,并且会动态更新),并且每个结构体的行为都不同。MyClass 只需要使用正确的那个(程序员的选择),这就是为什么我希望将对象的引用保留在类本身中,而不必将其传递给为该类创建的每个函数/方法。

c#
  • 2 个回答
  • 68 Views
Martin Hope
DevQt
Asked: 2025-04-26 12:50:13 +0800 CST

Flutter 中的 Wrap 与 Column

  • 6

有趣的是,如果我必须使用这些小部件列出详细信息:

Row(
  mainAxisAlignment:
      MainAxisAlignment.spaceBetween,
  children: [
    Text('some label'),
    Text('some value'),
  ],
),
Row(
  mainAxisAlignment:
      MainAxisAlignment.spaceBetween,
  children: [
    Text('some label'),
    Text('some value'),
  ],
),

每次我都用一种更简单的方式将它们包裹Wrap起来Column。

如果我使用,我永远无法达到我预期的效果Wrap,就像这样:

Wrap(
  direction: Axis.vertical,
  spacing: 8.0,
  children: [
    Row(
      mainAxisAlignment:
          MainAxisAlignment
              .spaceBetween,
      children: [
        Text('some label'),
        Text('some value'),
      ],
    ),
    Row(
      mainAxisAlignment:
          MainAxisAlignment
              .spaceBetween,
      children: [
        Text('some label'),
        Text('some value'),
      ],
    ),
  ],
),

意外的输出:

使用_of_wrap

问题是内容放在了左侧。即使我Wrap用SizedBox(width: double.infinity, child: ...)

Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [...],)我仅通过这种方法实现了我想要的(即,因为我在这里使用):

使用Column()widget而不是Wrap()widget

Column(
  spacing: 8.0,
  children: [
    Row(
      mainAxisAlignment:
          MainAxisAlignment
              .spaceBetween,
      children: [
        Text('some label'),
        Text('some value'),
      ],
    ),
    Row(
      mainAxisAlignment:
          MainAxisAlignment
              .spaceBetween,
      children: [
        Text('some label'),
        Text('some value'),
      ],
    ),
  ],
),

预期输出:

使用列

请注意,SizedBox(width: double.infinity, child: Column(...))对于这种情况而言是多余的,除非有用例建议这样做。

有人能更详细地解释一下为什么会发生这种情况吗?如果我们倾向于使用这种布局结果,更好地理解这一点可以避免实施错误的设置。

PS 如果在DartPad中执行,行为保持不变

这是最小的、可重复的示例:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(colorSchemeSeed: Colors.blue),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({super.key, required this.title});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.0),
        child: Column(
          spacing: 8.0,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [Text('some label'), Text('some value')],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [Text('some label'), Text('some value')],
            ),
          ],
        ),
      ),
    );
  }
}
flutter
  • 3 个回答
  • 65 Views
Martin Hope
user25521292
Asked: 2025-04-26 11:57:21 +0800 CST

当我们已经有 PooledConnectionLifetime 时,为什么还要使用 .SetHandlerLifetime(...)

  • 8

假设我们有代码片段

builder.Services.AddHttpClient("typicode", c =>
    {
        c.BaseAddress = new Uri("https://xxx");
        c.DefaultRequestHeaders.Add(
            "accept", "application/json");
    })
    .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler()
    {
        PooledConnectionLifetime = TimeSpan.FromMinutes(5),
    })
    .SetHandlerLifetime(TimeSpan.FromMinutes(10));

我不太明白为什么需要调用它SetHandlerLifetime(TimeSpan.FromMinutes(10),或者调用它有什么好处?我知道它控制着实例(及其连接池)在“处理程序级别”的重用SetHandlerLifetime时长,以及在“连接级别”的重用时长。SocketsHttpHandlerPooledConnectionLifetime = TimeSpan.FromMinutes(5)

但使用还不够吗PooledConnectionLifetime = TimeSpan.FromMinutes(5),想象一下我使用这个 HttpClient 对不同的 url 进行多个请求,例如 foo1.com、foo2.com......foo10.com,我希望在连接级别上使用 5 分钟的 PooledConnectionIdleTimeout,例如 foo1.com 的连接在 5 分钟后过期,但 foo2.com 仍然处于活动状态并且我想稍后重新使用它,但是 SetHandlerLifetime 会在 10 分钟后清除所有池?

c#
  • 2 个回答
  • 68 Views
Martin Hope
oemer ok
Asked: 2025-04-26 11:51:36 +0800 CST

postgresql无法将text[]转换为uuid

  • 6

我有一个这样的数组:

["f383224c-aa95-40c9-a4e4-fa41747f49c5","c783234c-aa95-40c9-a4e4-fa41747f49c6"]

我想选择任意但我收到错误无法将文本[]转换为uuid

SELECT c.name FROM cars c 

LEFT JOIN location_orders_cars loc ON loc.car_id = c.id 

WHERE loc.user_id = ANY($1::uuid) AND loc.location_orders_id = $2 AND loc.is_back = NULL 

LIMIT 10;

$1 = 上述 UUID 数组

2美元=355

我在这里做错了什么?

sql
  • 2 个回答
  • 53 Views
上一页
下一页

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve