RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

全部问题

Martin Hope
Reik
Asked: 2025-02-20 04:27:31 +0000 UTC

C# 字符串变量的字符输出无法正常进行

  • 5

c# 为什么我输入10000时下面的脚本输出97.0K? 100000 时是 145K 吗?

private string Output(int value)
{
        string text, lasttext = "";
        text = value.ToString();
        switch (text.Length)
        {
            case int n when n <= 3:
                lasttext = "";
                return text;
            case int n when n > 3 && n <= 6:
                lasttext = "K";
                break;
            case int n when n > 6 && n <= 9:
                lasttext = "M";
                break;
            case int n when n > 9 && n <= 12:
                lasttext = "B";
                break;
            case int n when n > 12 && n <= 15:
                lasttext = "T";
                break;
            case int n when n > 15 && n <= 18:
                lasttext = "Q";
                break;
        }
        switch (text.Length % 3)
        {
            case 1:
                text = text[0] + "," + text[1] + text[2] + lasttext;
                break;
            case 2:
                text = text[0] + text[1] + "," + text[2] + lasttext;
                break;
            case 0:
                text = text[0] + text[1] + text[2] + lasttext;
                break;
        }
        return text;
    }
c#
  • 3 个回答
  • 104 Views
Martin Hope
Noobie Raccoon
Asked: 2025-02-20 04:14:26 +0000 UTC

如何从 json 文件中获取特定链接?

  • 5

我想制作一个带有我所在大学课程表的 tg 机器人,它每周更新一次,为了不必手动搜索,我决定解析大学网站并在那里寻找带有课程表的 pdf 文件的链接。我设法用包含我需要的链接的 json 文件找到了答案。该文件如下所示:在此处输入图片描述

下面是我实现这一目标的代码:

def get_link(url):
    s = requests.Session()
    response = s.get(url=url, headers=headers)

    data = response.json()
    folders = data.get('folders')

    print(folders)

但是,运行此代码却输出 None,这就是我遇到的困难。也许我做错了什么事情和/或试图过早地输出一些信息?可能值得一提的是,我只研究了网站解析两天,不知道自己在做什么,我只是重复指南中的所有内容,并试图弄清楚到底发生了什么。我如何从上面的截图中获取我需要的链接?

提前致谢!

python
  • 1 个回答
  • 18 Views
Martin Hope
wanderer
Asked: 2025-02-20 03:06:52 +0000 UTC

电报机器人出现 429 错误

  • 3

我遇到一个错误 - “原始描述:请求太多:5 次后重试(此错误的背景信息:https: //core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this)” - 所以我无法通过机器人快速向用户发送消息?出现错误 429。我可以配置机器人,使其每秒发送一条消息,并且不会出现任何错误吗?

python
  • 1 个回答
  • 21 Views
Martin Hope
Alexandr Tsvetkov
Asked: 2025-02-20 02:26:40 +0000 UTC

为什么数据没有到达服务器?

  • 4

我正在 ASP.NET 上制作一个 Web 应用程序。在正在开发的模块中,需要能够以客户的名义添加订单。我会把整个代码发给你。以下是表单视图的代码

@model OrderFlow.Models.OrdersFlowDB.ViewModels.OrderCreateViewModel

@{
    ViewData["Title"] = "Create";
}

<h1>Создать</h1>

<h4>Заказ</h4>
<hr />

<form class="col-md-4" asp-action="Create" method="post">
    <div class="form-group">
        <label>Клиент</label>
        <input type="text" id="clientSearch" class="form-control" placeholder="Введите имя клиента..." />
        <input type="hidden" id="clientId" name="ClientId" />
    </div>

    <div class="form-group">
        <label>Юридическое лицо</label>
        <select id="legalEntitySelect" class="form-control">
            <option value="">Выберите юрлицо</option>
        </select>
        <input type="hidden" id="legalEntityId" name="LegalEntityId">

    </div>

    <div class="form-group">
        <label>Адрес</label>
        <input type="text" name="Address" class="form-control" required />
    </div>

    <div class="form-group">
        <label>Дата начала</label>
        <input type="date" name="DateOfStart" class="form-control" required />
    </div>

    <div class="form-group">
        <label>Дата окончания</label>
        <input type="date" name="DateOfEnd" class="form-control" required />
    </div>

    <div class="form-group">
        <label for="price">Стоимость</label>
        <input type="text" id="price" class="form-control" readonly>
        <input type="hidden" id="priceHidden" name="Price">
    </div>

    <div class="form-group">
        <label for="priceWithNDS">Стоимость с НДС</label>
        <input type="text" id="priceWithNDS" class="form-control" readonly>
        <input type="hidden" id="priceWithNDSHidden" name="PriceWithNDS">
    </div>

    <div class="form-group">
        <label for="productSelect">Товар:</label>
        <select id="productSelect" class="form-control"></select>

        <label for="productQuantity">Количество:</label>
        <input type="number" id="productQuantity" class="form-control" min="1" value="1">

        <button type="button" id="addProduct" class="btn btn-success">Добавить товар</button>

        <ul id="productList"></ul>

    </div>

    <button type="submit" class="btn btn-primary">Сохранить</button>
</form>


<div>
    <a class="text-white" asp-action="Index">К списку заказов</a>
</div>

这是表单的视图模型

public class OrderCreateViewModel
{
    public string ClientId { get; set; }
    public int? LegalEntityId { get; set; }
    public string Address { get; set; }
    public string? Comment { get; set; }
    public DateOnly DateOfStart { get; set; }
    public DateOnly DateOfEnd { get; set; }
    public decimal Price { get; set; }
    public decimal PriceWithNDS { get; set; }

    public List<OrderProductViewModel> Products { get; set; } = new List<OrderProductViewModel>();
}

控制器代码

[HttpGet]
public async Task<IActionResult> Create()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> Create(OrderViewModel model, string products)
{
    Debug.WriteLine($"Received Price: {model.Price}");
    Debug.WriteLine($"Received PriceWithNDS: {model.PriceWithNDS}");
    if (!string.IsNullOrEmpty(products))
    {
        var productList = JsonConvert.DeserializeObject<List<OrderProductViewModel>>(products);

        var order = new Order
        {
            ClientId = model.ClientId,
            LegalEntityId = model.LegalEntityId,
            Address = model.Address,
            Comment = model.Comment,
            DateOfStart = model.DateOfStart,
            DateOfEnd = model.DateOfEnd,
            Price = model.Price,
            PriceWithNDS = model.PriceWithNDS,
            IsComplete = false,
            OrdersProducts = productList.Select(p => new OrdersProduct
            {
                ProductId = p.ProductId,
                Count = p.Quantity
            }).ToList()
        };

        _ordersContext.Orders.Add(order);
        await _ordersContext.SaveChangesAsync();
        return RedirectToAction("List");
    }

    return View(model);
}

[HttpGet]
public async Task<IActionResult> SearchUsers(string term)
{
    if (string.IsNullOrEmpty(term))
    {
        return Json(new { });
    }

    var users = await _userManager.Users
        .Where(u => u.UserName.Contains(term) || u.Email.Contains(term) || u.PhoneNumber.Contains(term))
        .Select(u => new { id = u.Id, userName = u.UserName, email = u.Email, phone = u.PhoneNumber })
        .Take(10) // Ограничиваем кол-во результатов
        .ToListAsync();

    return Json(users);
}


[HttpGet]
public async Task<IActionResult> GetLegalEntities(string userId)
{
    if (string.IsNullOrEmpty(userId))
    {
        return Json(new { });
    }

    var legalEntities = await _identityContext.LegalEntities
        .Where(le => le.UserId == userId)
        .Select(le => new { id = le.Id, companyName = le.CompanyName, inn = le.INN })
        .ToListAsync();

    return Json(legalEntities);
}

[HttpGet]
public async Task<IActionResult> GetProducts()
{
    var products = await _ordersContext.Products
        .Select(p => new { id = p.Id, name = p.Name, price = p.Price, nds = p.NDS })
        .ToListAsync();

    return Json(products);
}

控制器具有获取用户、法人实体和产品列表的方法,因为它们是通过 AJAX 请求获得的。这是 js 代码

$(document).ready(function () {
    // Поиск клиентов
    $("#clientSearch").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Orders/SearchUsers",
                type: "GET",
                dataType: "json",
                data: { term: request.term }, // Текст из инпута
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.userName + " (" + item.email + ")" + " (" + item.phone + ")",
                            value: item.userName,
                            id: item.id
                        };
                    }));
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            $("#clientSearch").val(ui.item.value); // Имя пользователя в инпуте
            $("#clientId").val(ui.item.id).trigger("change");; // ID пользователя в скрытое поле
            return false;
        }
    });

    // Загрузка юрлиц при выборе клиента
    $("#clientId").change(function () {
        var userId = $("#clientId").val();
        var client = $("#clientSearch").val();
        console.log("Выбран клиент ID:", userId)
        if (userId && client) {
            $.getJSON("/Orders/GetLegalEntities", { userId: userId }, function (data) {
                console.log("Полученные юрлица:", data);
                var options = '<option value="">Выберите юрлицо</option>';
                $.each(data, function (index, item) {
                    options += `<option value="${item.id}">${item.companyName} (ИНН: ${item.inn})</option>`;
                });
                $("#legalEntitySelect").html(options);
            });
        } else {
            $("#legalEntitySelect").html('<option value="">Выберите клиента</option>');
        }
    });

    $("#legalEntitySelect").change(function () {
        let selectedValue = $(this).val();
        $("#legalEntityId").val(selectedValue);
    });


    // Добавление товара
    $.ajax({
        url: "/Orders/GetProducts",
        type: "GET",
        success: function (data) {
            let productSelect = $("#productSelect");
            productSelect.empty();
            productSelect.append('<option value="">Выберите товар</option>');

            data.forEach(function (product) {
                productSelect.append(
                    `<option value="${product.id}" data-price="${product.price}" data-nds="${product.nds}">
                        ${product.name} (Цена: ${product.price}, НДС: ${product.nds}%)
                    </option>`
                );
            });
        },
        error: function () {
            console.error("Ошибка загрузки товаров");
        }
    });

    $("#addProduct").click(function (event) {
        event.preventDefault();

        let selectedProduct = $("#productSelect option:selected");
        let productId = selectedProduct.val();
        let productName = selectedProduct.text();
        let productQuantity = $("#productQuantity").val();
        let productPrice = parseFloat(selectedProduct.attr("data-price")) || 0;
        let productNDS = parseFloat(selectedProduct.attr("data-nds")) || 0;

        if (!productId) {
            alert("Выберите товар!");
            return;
        }

        if (productQuantity <= 0) {
            alert("Введите корректное количество!");
            return;
        }

        let totalPrice = productPrice * productQuantity;
        let totalNDS = (totalPrice * productNDS) / 100;
        let totalPriceWithNDS = totalPrice + totalNDS;

        // Проверяем, есть ли уже этот товар в списке
        let existingItem = $(`#productList li[data-id='${productId}']`);
        if (existingItem.length > 0) {
            let currentQuantity = parseInt(existingItem.attr("data-quantity"));
            let newQuantity = currentQuantity + parseInt(productQuantity);
            existingItem.attr("data-quantity", newQuantity);
            existingItem.attr("data-total-price", totalPrice);
            existingItem.attr("data-total-price-nds", totalPriceWithNDS);
            existingItem.find(".product-info").text(`${productName} - ${newQuantity} шт.`);
        } else {
            $("#productList").append(
                `<li data-id="${productId}" data-quantity="${productQuantity}" data-total-price="${totalPrice}" data-total-price-nds="${totalPriceWithNDS}">
                <span class="product-info">${productName} - ${productQuantity} шт.</span> 
                <button type="button" class="removeProduct btn btn-danger btn-sm">Удалить</button>
            </li>`
            );
        }

        updateTotalPrice();
    });


    // Удаление товара
    $(document).on("click", ".removeProduct", function () {
        $(this).parent().remove();
        updateTotalPrice();
    });

    // Отправка формы
    $("form").submit(function () {
        let products = [];
        let price = $("#priceHidden").val();
        let priceWithNDS = $("#priceWithNDSHidden").val();
        let legalEntity = $("#legalEntityId").val();
        $("#productList li").each(function () {
            let productId = $(this).attr("data-id");
            let quantity = $(this).attr("data-quantity");
            products.push({ productId, quantity });
        });

        // Записываем товары в скрытое поле формы
        $("<input>").attr({
            type: "hidden",
            name: "products",
            value: JSON.stringify(products)
        }).appendTo("form");

        if (!price || price <= 0) {
            alert("Ошибка: Итоговая стоимость равна 0. Добавьте товары!");
            return false;
        }

        console.log("Цена:", price);
        console.log("Цена с НДС:", priceWithNDS);
        console.log("Юрлицо:", legalEntity);
    });
});

function updateTotalPrice() {
    let totalPrice = 0;
    let totalPriceWithNDS = 0;

    $("#productList li").each(function () {
        totalPrice += parseFloat($(this).attr("data-total-price"));
        totalPriceWithNDS += parseFloat($(this).attr("data-total-price-nds"));
    });

    $("#price").val(totalPrice.toFixed(2));
    $("#priceHidden").val(totalPrice.toFixed(2));

    $("#priceWithNDS").val(totalPriceWithNDS.toFixed(2));
    $("#priceWithNDSHidden").val(totalPriceWithNDS.toFixed(2));

    console.log("Обновлено в форме: Цена =", totalPrice, "Цена с НДС =", totalPriceWithNDS);
}

而这里的问题是,发送之后的所有数据都记录在数据库中,除了费用和含增值税的费用(Price,PriceWithNDS)。更准确地说,总是用零来代替实数。如您所见,在 js 代码中我创建了一个函数来自动填充这些字段。我还检查了它们是否在同一个函数中更新

console.log("Обновлено в форме: Цена =", totalPrice, "Цена с НДС =", totalPriceWithNDS);

正确的值输出到控制台。 在此处输入图片描述 接下来,在表单提交方法中,我创建了一个检查,以确保成本不为零,并将提交的值输出到控制台。

if (!price || price <= 0) {
            alert("Ошибка: Итоговая стоимость равна 0. Добавьте товары!");
            return false;
        }

        console.log("Цена:", price);
        console.log("Цена с НДС:", priceWithNDS);
        console.log("Юрлицо:", legalEntity);

这里一切也都显示正确。此外,如果价格小于或等于零,我会禁止提交表格。但表格已发送。我进入 DBMS 发现,除了这两个值(Price 和 PriceWithNDS)外,所有内容都记录正确。然后我以为问题出在服务器部分,但事实并非如此。在控制器中的 Create 方法的开头,我检查了在发送表单时会向服务器发送哪些值

[HttpPost]
public async Task<IActionResult> Create(OrderViewModel model, string products)
{
    Debug.WriteLine($"Received Price: {model.Price}");
    Debug.WriteLine($"Received PriceWithNDS: {model.PriceWithNDS}");

然后它输出零。 在此处输入图片描述 但是为什么提交表单时会显示正确的数字?我注意到,当字段自动填写时,服务器会收到 0。但是,当输入中没有只读属性并且用户自己输入数据时,这些数据会被发送到服务器。

javascript
  • 1 个回答
  • 63 Views
Martin Hope
Den
Asked: 2025-02-19 19:28:26 +0000 UTC

std::shared_ptr() 的控制块是如何删除的?

  • 5

有一点我不太明白。

如果我没弄错的话,在使用它时std::weak_ptr()我们如何创建它很重要std::shared_ptr()。

   auto sp1 = std::shared_ptr<int>(new int(10));   // 1
   auto sp2 = std::make_shared<int>(10);           // 2

1和2的区别在于对象和控制块的内存分配(单独还是一起)。当我们使用时,std::weak_ptr()我们可以检查它是否“过期”,即使强链接计数器= 0,只要存在std::weak_ptr()控制块本身,它就会存在,在这里我终于得到了这个问题!

当我们通过 std::make_shared<>() 分配内存时,就只剩下weak_ptr控制块本身了,但是由于我们一起分配了内存,并且对象似乎存在,那么这个对象或分配的内存会发生什么?

c++
  • 2 个回答
  • 103 Views
上一页
下一页

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

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

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5