羁客

文章 评论 浏览 26

羁客 2025-02-21 02:17:49

正如 @heikotheißen所建议的那样,您应该使用单个帖子请求处理服务器上操作的逻辑:

const express = require('express');
const app = express();
const Items = require('./Items');
const connection = require('./connection');
const Port = process.env.Port || 1337;
const cors = require('cors');

app.use(cors());
connection();

app.use(express.json());

app.post('/items', async (req, res) => {
  try {
    let item = await Items.findById(req.body.id);
    if (!item) {
      item = await Items.create(req.body);
    } else {
      item.quantity++;
      await item.save();
    }
    res.json({ succcess: true, item });
  } catch (err) {
    res.json({ succcess: false });
  }
});

app.listen(Port, () => {
  console.log(`App running on port ${Port}`);
});

您应将客户端代码简化为:

async function addToCart(state, product) {
  try {
    const { data } = await axios.post('http://localhost:1337/items', product);

    // Add new product to card if necessary
    if (!state.cart.some((p) => p.id === data.item.id)) {
      state.cart.push(data.item);
    }
  } catch (err) {
    console.log(err);
  }
}

As @HeikoTheißen suggested, you should handle the logic of the operation on the server, using a single POST request:

const express = require('express');
const app = express();
const Items = require('./Items');
const connection = require('./connection');
const Port = process.env.Port || 1337;
const cors = require('cors');

app.use(cors());
connection();

app.use(express.json());

app.post('/items', async (req, res) => {
  try {
    let item = await Items.findById(req.body.id);
    if (!item) {
      item = await Items.create(req.body);
    } else {
      item.quantity++;
      await item.save();
    }
    res.json({ succcess: true, item });
  } catch (err) {
    res.json({ succcess: false });
  }
});

app.listen(Port, () => {
  console.log(`App running on port ${Port}`);
});

You should simplify your client code as:

async function addToCart(state, product) {
  try {
    const { data } = await axios.post('http://localhost:1337/items', product);

    // Add new product to card if necessary
    if (!state.cart.some((p) => p.id === data.item.id)) {
      state.cart.push(data.item);
    }
  } catch (err) {
    console.log(err);
  }
}

如何在集合中创建新项目(如果不存在),否则,将添加到购物车时更新价格和数量

羁客 2025-02-21 01:06:07

linq

in .NET,LINQ经常用于排序,它在比较函数上提供了更好的语法,尤其是当需要通过多个字段对对象进行排序时。 LINQ的几个端口都到PHP,包括 yalinqo library*。有了它,可以用一条线对数组进行排序,而无需编写复杂的比较功能。

$sortedByName         = from($objects)->orderBy('$v->name');
$sortedByCount        = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');

可以通过将回调作为第二个参数来进一步定制比较,例如:

$sortedByFilenameNat  = from($objects)->orderBy('$v->filename', 'strnatcmp');

'$ v-> count'function($ v){返回$ v的速记 - > count; }(可以使用任何一种)。这些方法链返回迭代器,可以通过在需要时添加- > toarray()将迭代器转换为数组。

内部,orderby和相关方法调用适当的数组排序函数(uasortkrsortMultisortusort等)。

LINQ包含更多受SQL启发的方法:过滤,分组,加入,汇总等。它最适合在不依赖数据库的情况下需要执行数组和对象的复杂转换的情况。

*由我开发的,请参见Readme,以获取更多详细信息和与其他LINQ端口的比较

LINQ

In .NET, LINQ is frequently used for sorting, which provides a much nicer syntax over comparison functions, especially when objects need to be sorted by multiple fields. There're several ports of LINQ to PHP, including YaLinqo library*. With it, arrays can be sorted with a single line without writing complex comparison functions.

$sortedByName         = from($objects)->orderBy('$v->name');
$sortedByCount        = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');

Comparisons can be further customized by passing a callback as a second argument, for example:

$sortedByFilenameNat  = from($objects)->orderBy('$v->filename', 'strnatcmp');

Here, '$v->count' is a shorthand for function ($v) { return $v->count; } (either can be used). These method chains return iterators, iterators can be transformed to arrays by adding ->toArray() in the end if needed.

Internally, orderBy and related methods call appropriate array sorting functions (uasort, krsort, multisort, usort etc.).

LINQ contains many more methods inspired by SQL: filtering, grouping, joining, aggregating etc. It's best suited for cases when complex transformations on arrays and objects need to be performed without relying on databases.

* developed by me, see readme for more details and comparison with other LINQ ports

如何在PHP中对数组和数据进行排序?

羁客 2025-02-21 00:19:51

我猜您要寻找的是“前端编辑” - 它可作为扩展程序可用,可以在此处找到: https://extensions.typo3.org/extension/frontend_editing

I guess what you are looking for is called "frontend editing" - it is available as an extension that can be found here: https://extensions.typo3.org/extension/frontend_editing

如何使Typo3为后端用户生成不同的输出?

羁客 2025-02-20 05:03:34

试试看,您可以构建一个嵌套的案例语句,而不是实现,但是,如果您对枢轴结构的意图确实如此,请告诉我,我会相应地更新答案

CREATE OR REPLACE VIEW curorigination.opportunitiespresentationV3
AS
WITH numbering AS (
    SELECT CompanyOwner, CurrentOpportunityStatus, LastDateStatusChanged,
           rank() OVER (PARTITION BY CompanyOwner, CurrentOpportunityStatus ORDER BY  LastDateStatusChanged DESC) AS rank
    FROM   enrorigination.opportunities_hv
)

SELECT CompanyOwner, 
       CASE
         WHEN CurrentOpportunityStatus = 'Action - 1. Analysing'      THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 2. Trying to meet' THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 3. Date agreed'    THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 4. Post meeting'   THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 5. Chopped'        THEN LastDateStatusChanged 
       END AS CurrentOpportunityStatus,
      LastDateStatusChanged
FROM  numbering
WHERE  rank = 1
ORDER BY CompanyOwner, CurrentOpportunityStatus, LastDateStatusChanged
;

Try this instead , you can build a nested case statement rather than your implementation , however if your intention is towards a pivot structure do , let me know , I ll update the answere accordingly

CREATE OR REPLACE VIEW curorigination.opportunitiespresentationV3
AS
WITH numbering AS (
    SELECT CompanyOwner, CurrentOpportunityStatus, LastDateStatusChanged,
           rank() OVER (PARTITION BY CompanyOwner, CurrentOpportunityStatus ORDER BY  LastDateStatusChanged DESC) AS rank
    FROM   enrorigination.opportunities_hv
)

SELECT CompanyOwner, 
       CASE
         WHEN CurrentOpportunityStatus = 'Action - 1. Analysing'      THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 2. Trying to meet' THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 3. Date agreed'    THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 4. Post meeting'   THEN LastDateStatusChanged 
         WHEN CurrentOpportunityStatus = 'Action - 5. Chopped'        THEN LastDateStatusChanged 
       END AS CurrentOpportunityStatus,
      LastDateStatusChanged
FROM  numbering
WHERE  rank = 1
ORDER BY CompanyOwner, CurrentOpportunityStatus, LastDateStatusChanged
;

无法使用CTE使用Databrick创建或替换视图

羁客 2025-02-20 01:38:46

检查您的$ perpage变量。我认为您有5个。
更改它将为您提供正确的结果。

Check your $perpage variable. I think you are getting 5 in it.
Changing it will give you correct result.

我应该更改我想通过PHP(codeigniter)增加页面上的新闻数

羁客 2025-02-19 18:53:19

这看起来像是一个错误,值得向苹果提交反馈。

同时,这是可能的解决方法。用Xcode 14B2 / iOS测试16

Button {
    UIView.setAnimationsEnabled(false)

        nav = [.a]

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
        UIView.setAnimationsEnabled(true)
    }
} label: {
  // ...

This looks like a bug and worth submitting feedback to Apple.

Meanwhile here is a possible workaround. Tested with Xcode 14b2 / iOS 16

Button {
    UIView.setAnimationsEnabled(false)

        nav = [.a]

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
        UIView.setAnimationsEnabled(true)
    }
} label: {
  // ...

如何禁用NavigationStack推动动画

羁客 2025-02-19 13:59:39

GET是旧的XLM宏观语言命令。这些可能会在您使用的机器上阻塞。

来自 Microsoft文档关于#Blocked!错误:

用XLM宏函数用Excel 4.0(XLM)阻止函数
由于以下一个或多个原因,无法评估宏:

Excel 4.0(XLM)宏因宏设置而关闭。

Excel 4.0(XLM)宏不支持Excel的当前版本。

有关更多信息,请参阅使用Excel 4.0宏。

Get is an old XLM macro language command. These may be blocked on the machine you are using.

From the Microsoft documentation about the #BLOCKED! error:

Functions with XLM macros are blocked Functions with Excel 4.0 (XLM)
macros can't be evaluated for one or more of the following reasons:

Excel 4.0 (XLM) macros are turned off because of macro settings.

Excel 4.0 (XLM) macros aren't supported in current version of Excel.

For more information, see Working with Excel 4.0 macros.

什么会导致#Blocked!当我将Excel文件复制到计算机时出错

羁客 2025-02-19 08:44:30

您可以使用max窗口函数代替last_value窗口函数:

SELECT app, 
       people, 
       MAX(login) OVER (PARTITION BY app, people ORDER BY login DESC)
FROM tab

检查demo 在这里


相反,如果要汇总您的“ app ”和“ people ”值,上次登录值,也可以使用max contregation功能:

SELECT app, 
       people, 
       MAX(login)
FROM tab
GROUP BY app, 
         people

检查演示在这里

You can use the MAX window function in place of the LAST_VALUE window function:

SELECT app, 
       people, 
       MAX(login) OVER (PARTITION BY app, people ORDER BY login DESC)
FROM tab

Check the demo here.


Instead, if you want to aggregate your "app" and "people" values on the last login value, you can also use the MAX aggregation function:

SELECT app, 
       people, 
       MAX(login)
FROM tab
GROUP BY app, 
         people

Check the demo here.

postgresql提取到每个组的最后一行

羁客 2025-02-19 04:39:06

在控制器方法中,您设置文件名

 HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData(filename, filename);
            headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

和响应实体中

 return ResponseEntity.ok()
                .headers(headers)
                .contentLength(fileLength)
                .body(resource);

In the controller method you set the filename

 HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData(filename, filename);
            headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

and in the response entity

 return ResponseEntity.ok()
                .headers(headers)
                .contentLength(fileLength)
                .body(resource);

将名称添加到春季资源对象

羁客 2025-02-19 04:22:15

错误指出您的应用不允许向另一个起源提出请求。检查相同的原始策略完整说明 - https:httpps> https:https://开发人员。 mozilla.org/en-us/docs/web/security/same-origin_policy

很可能是您的安全配置。检查您是否正在使用头盔项目中的某个地方(最有可能在您的Express Server中),如果您这样做,检查contentsecuritypolicy配置。

如果您启用了相同的原始策略,则意味着您必须明确指定要向其提出的所有域,与网站的来源不同,因此可以满足策略。

The error states that your app doesn't allow making requests to another origins. Check the same origin policy full description - https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

Most likely the issue is with your security configuration. Check if you are using Helmet somewhere in the project (most likely in your express server), and if you do, check the contentSecurityPolicy configuration.

If you enabled same origin policy, that means you have to explicitly specify all domains you want to make requests to that are not the same origin that your site, so the policy is satisfied.

mapbox-gl-j给出`消息:未发现的“错误与状态(null),因此cors

羁客 2025-02-18 02:29:10

您可以使用表中的表格填充数据

from tabulate import tabulate

result = open("results.txt","r")
res = result.readlines()
final = []
for line in res:
    temp_list = line.split(';')[:-1]
    total = int(temp_list[1]) + int(temp_list[2]) + int(temp_list[3])
    average = round(int(total) / 3.0, 2)
    temp_list.append(total)
    temp_list.append(average)
    final.append(temp_list)

print(tabulate(final, headers=["Name", "Lap1", "Lap2", "Lap3", "In Total", "Average"]))

以上的Python中的表格,将提供以下输出:

<” img src =“ https://i.sstatic.net/xpgwh.png” alt =“在此处输入图像说明”>

You can use tabulate instead to populate your data in a tabular format in python

from tabulate import tabulate

result = open("results.txt","r")
res = result.readlines()
final = []
for line in res:
    temp_list = line.split(';')[:-1]
    total = int(temp_list[1]) + int(temp_list[2]) + int(temp_list[3])
    average = round(int(total) / 3.0, 2)
    temp_list.append(total)
    temp_list.append(average)
    final.append(temp_list)

print(tabulate(final, headers=["Name", "Lap1", "Lap2", "Lap3", "In Total", "Average"]))

Above code will give the following output:

enter image description here

显示;用Python分离表格格式的值

羁客 2025-02-17 19:36:36

除非出于某种原因,您需要确保您只有一个共享实例并且它被突变(提示:您真的不应该),只需在需要时创建新的日期对象即可。 GC会照顾好旧的。

Unless for some reason you need to make sure that you have only a single shared instance and that it gets mutated (hint: you really shouldn't), just create new date objects whenever you need them. GC will take care of the old ones just fine.

更新日期对象为现在()

羁客 2025-02-17 17:52:45

定界符之后,我在管道中添加了另一个阶段。这是一个aql,带有keepnull = false和return @param ==“”“?null:@param的Querystring。如果有人有更简单的建议,我很感兴趣。

I added another stage in the pipeline after the delimiters. It's an aql with keepNull=false and queryString of return @param==""?null:@param. If someone has a simpler suggestion I'm interested.

如何在自定义Arangosearch Analyzer中删除空字符串

羁客 2025-02-17 17:04:06

这取决于您在gitlab-ci.yml中使用的图像。

例如,在文章中,“ 如何为Google Cloud App Engine设置Gitlab CI管道?”来自 nofollow noreferrer“>他正在使用:

image: google/cloud-sdk:alpine

deploy_production:
  stage: deploy
  environment: Production
  only:
  - master
  script:
  - echo $SERVICE_ACCOUNT > /tmp/$CI_PIPELINE_ID.json
  - gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
  - gcloud --quiet --project $PROJECT_ID app deploy app.yaml dispatch.yaml

这意味着gcloud已经安装在$ path中。

It depends on the image you are using in your gitlab-ci.yml.

For instance, in the article "How to Setup Gitlab CI Pipeline For Google Cloud App Engine?" from Tapendra Dev, he is using:

image: google/cloud-sdk:alpine

deploy_production:
  stage: deploy
  environment: Production
  only:
  - master
  script:
  - echo $SERVICE_ACCOUNT > /tmp/$CI_PIPELINE_ID.json
  - gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
  - gcloud --quiet --project $PROJECT_ID app deploy app.yaml dispatch.yaml

Which means gcloud is already installed and in the $PATH.

gcloud:找不到命令

羁客 2025-02-17 05:24:25

根据我的经验,这个问题可能出于多种原因而发生。最常见的是,因为当数据来自API时,您没有正确访问Checker的数据。有时,我们在浏览器中看不到的事情,但是部署时会出现这种错误。

例如:

const response = fetch("some_url");
const companyId = response.data.companyId; ❌
const companyId = response?.data?.companyId; ✔️

From my experience, this problem can happen for multiple reasons. The most common one is because you didn't put the data accessing checker properly when data comes from an API. Sometimes this things we don't see in browser but it gives such error when you deploy.

For example:

const response = fetch("some_url");
const companyId = response.data.companyId; ❌
const companyId = response?.data?.companyId; ✔️

NextJS-应用程序错误:客户端异常发生

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文