黑凤梨

文章 评论 浏览 27

黑凤梨 2025-02-21 00:24:08

使用承诺

对此问题的最完美答案是使用Promise

function ajax(method, url, params) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      resolve(this.responseText);
    };
    xhr.onerror = reject;
    xhr.open(method, url);
    xhr.send(params);
  });
}

用法

ajax("GET", "/test", "acrive=1").then(function(result) {
    // Code depending on result
})
.catch(function() {
    // An error occurred
});

,但等等...!

使用承诺有问题!

我们为什么要使用自己的自定义承诺?

我已经使用了一段时间,直到我发现旧浏览器存在错误:

未介绍的参考:未定义承诺

因此我决定将自己的诺言类实施 es3的承诺类,如果未定义,请 javascript编译器。只需在主代码之前添加此代码,然后安全地使用Promise!

if(typeof Promise === "undefined"){
    function _typeof(obj) { "@babel/helpers - typeof"; return 

    _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
    function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
    function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
    function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
    function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
    function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
    function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
    function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
    function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
    function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
    function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
    var Promise = /*#__PURE__*/function () {
  "use strict";

  function Promise(main) {
    _classCallCheck(this, Promise);
    this.main = main;
    this.mainExecuted = false;
    this.resolved = false;
    this.rejected = false;
    this.promiseChain = [];
    this.handleError = function () {};
    this.onResolve = this.onResolve.bind(this);
    this.onReject = this.onReject.bind(this);
  }
  _createClass(Promise, [{
    key: "then",
    value: function then(handleSuccess) {
      if (this.resolved) {
        if (!this.rejected) {
          this.args = handleSuccess(this.args);
        }
      } else {
        this.promiseChain.push(handleSuccess);
        this.main(this.onResolve, this.onReject);
        this.thenExecuted = true;
      }
      return this;
    }
  }, {
    key: "catch",
    value: function _catch(handleError) {
      this.handleError = handleError;
      if (!this.mainExecuted) {
        this.main(this.onResolve, this.onReject);
        this.thenExecuted = true;
      }
      return this;
    }
  }, {
    key: "onResolve",
    value: function onResolve() {
      var _this = this;
      this.resolved = true;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      this.args = args;
      try {
        this.promiseChain.forEach(function (nextFunction) {
          _this.args = nextFunction.apply(void 0, _toConsumableArray(_this.args));
        });
      } catch (error) {
        this.promiseChain = [];
        this.onReject(error);
      }
    }
  }, {
    key: "onReject",
    value: function onReject(error) {
      this.rejected = true;
      this.handleError(error);
    }
  }]);
  return Promise;
}();
}

Using Promise

The most perfect answer to this question is using Promise.

function ajax(method, url, params) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      resolve(this.responseText);
    };
    xhr.onerror = reject;
    xhr.open(method, url);
    xhr.send(params);
  });
}

Usage

ajax("GET", "/test", "acrive=1").then(function(result) {
    // Code depending on result
})
.catch(function() {
    // An error occurred
});

But wait...!

There is a problem with using promises!

Why should we use our own custom Promise?

I was using this solution for a while until I figured out there is an error in old browsers:

Uncaught ReferenceError: Promise is not defined

So I decided to implement my own Promise class for ES3 to below JavaScript compilers if it's not defined. Just add this code before your main code and then safely use Promise!

if(typeof Promise === "undefined"){
    function _typeof(obj) { "@babel/helpers - typeof"; return 

    _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
    function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
    function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
    function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
    function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
    function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
    function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
    function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
    function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
    function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
    function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
    var Promise = /*#__PURE__*/function () {
  "use strict";

  function Promise(main) {
    _classCallCheck(this, Promise);
    this.main = main;
    this.mainExecuted = false;
    this.resolved = false;
    this.rejected = false;
    this.promiseChain = [];
    this.handleError = function () {};
    this.onResolve = this.onResolve.bind(this);
    this.onReject = this.onReject.bind(this);
  }
  _createClass(Promise, [{
    key: "then",
    value: function then(handleSuccess) {
      if (this.resolved) {
        if (!this.rejected) {
          this.args = handleSuccess(this.args);
        }
      } else {
        this.promiseChain.push(handleSuccess);
        this.main(this.onResolve, this.onReject);
        this.thenExecuted = true;
      }
      return this;
    }
  }, {
    key: "catch",
    value: function _catch(handleError) {
      this.handleError = handleError;
      if (!this.mainExecuted) {
        this.main(this.onResolve, this.onReject);
        this.thenExecuted = true;
      }
      return this;
    }
  }, {
    key: "onResolve",
    value: function onResolve() {
      var _this = this;
      this.resolved = true;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      this.args = args;
      try {
        this.promiseChain.forEach(function (nextFunction) {
          _this.args = nextFunction.apply(void 0, _toConsumableArray(_this.args));
        });
      } catch (error) {
        this.promiseChain = [];
        this.onReject(error);
      }
    }
  }, {
    key: "onReject",
    value: function onReject(error) {
      this.rejected = true;
      this.handleError(error);
    }
  }]);
  return Promise;
}();
}

如何从异步电话中返回响应?

黑凤梨 2025-02-20 23:27:56

https://dev.mysql.com/doc/com/doc/ refman/8.0/en/sql pargreed-statement.html 说:

sql语法用于准备的语句不支持多条件(也就是说,单字符串中的多个语句被; targue)。

)。

如果您使用准备,则必须一次运行语句。

无需将滴扳机包括在您准备的语句中。您可以在无需准备就绪&amp;的情况下运行下降扳机。执行,因为其中没有动态部分。然后将创建触发器格式化为单个语句,然后准备并执行它。

https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html says:

SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters).

You have to run the statements one at a time if you use PREPARE.

There's no need to include the DROP TRIGGER in your prepared statement. You can run the DROP TRIGGER without prepare & execute, since there is no dynamic part in it. Then format the CREATE TRIGGER as a single statement and prepare and execute it.

执行此MySQL SP的错误,以使通过触发刷新在日志表中的字段进行刷新,但我没有请参见错误

黑凤梨 2025-02-20 20:54:20

它只是更新数据库代码路径未使用的一般参数,

请参见源: https://github.com/dotnet/efcore/blob/main/src/src/efcore.design/design/internal/migrationsoperations.cs#l197

It is just a general parameter not used by the Update database code path

See source here: https://github.com/dotnet/efcore/blob/main/src/EFCore.Design/Design/Internal/MigrationsOperations.cs#L197

什么是dotnet EF数据库更新中的项目?

黑凤梨 2025-02-20 19:55:54

我在JupyterHub服务器的工作(旧)部署。我检查了两个服务器的PIP列表,并找到了一些Python模块的版本差异。 NBClassic模块是新鲜的(还有其他一些模块,但是嘿,嘿,没有影响服务器)。

我检查了NBClassic,新版本昨天发布:
https://github.com/jupyter/nbclassic/commits/commits/main
我降低了模块,对我有用。

I had a working(old) deployment of jupyterhub server. I check pip list for both servers and found version differences for some python modules. nbclassic module was fresh(and some other modules too, but hey did not affect the server) on nonworking server.

I checked nbclassic and the new version was released yesterday:
https://github.com/jupyter/nbclassic/commits/main
I downgraded the module and it worked for me.

JupyterHub无法使用名为Ipythonhandler的模块来催生新的会话。

黑凤梨 2025-02-20 10:57:04

您应该这样做,您有一个agmulticolumnfilter(假设agsetColumnFilter是第二个过滤器)过滤器:

 filterInstance.setModel({
    filterType: 'multi',
    filterModels: [null, { filterType: 'set', values: ['Brazil','France'] }],
  });

有一个简单的agsetColumnFilter extract filter:

     filterInstance.setModel({
        values: ['Brazil','France'] }],
      });

或者,如果您 AG网格中的数据应具有过滤器的值。

You should do like this you have a agMultiColumnFilter (assuming agSetColumnFilter is the second filter) filter:

 filterInstance.setModel({
    filterType: 'multi',
    filterModels: [null, { filterType: 'set', values: ['Brazil','France'] }],
  });

or if you have a simple agSetColumnFilter filter:

     filterInstance.setModel({
        values: ['Brazil','France'] }],
      });

Your data in the ag-grid should have the value of the filter.

Ag网格Angulr-setModel不适用于多个值

黑凤梨 2025-02-20 01:19:24

正如错误所提到的那样,您正在混合数据类型。在cocece功能中,您需要先将sales_rep_id转换为varchar。

SELECT ORDER_ID, ORDER_DATE,
coalesce (to_char(SALES_REP_ID), 'NA') REP
FROM ORDERS

As the error mentions, you are mixing data types. Inside the coalesce function you need to convert sales_rep_id to a varchar first.

SELECT ORDER_ID, ORDER_DATE,
coalesce (to_char(SALES_REP_ID), 'NA') REP
FROM ORDERS

如何使用cocece函数用字符串替换零值?

黑凤梨 2025-02-19 13:51:02

不幸的是,仅安装了扩展安全更新的Windows 7 SP1。同一陈述也适用于Net6。

我设法通过从Microsoft Update目录中安装这些更新来使其正常工作(NET6):

  • Windows6.1-kb3063858-x64.msu
  • Windows6.1-kb299999926-x644.mmsu
  • win7andw2k8r2

这是Windows管理框架5.1

  • Microsoft Visual C ++ 2015-2019重新分布(X64)-14.29.30135

此外,在某些安装中,我还必须安装PowerShell v7.2.1。

我无法以任何方式在Windows 7 SP1的新安装上运行该应用程序。

Unfortunately Windows 7 SP1 is supported only with Extended Security Updates installed. The same statement also applies to net6.

I managed to get it to work (with net6) by installing those updates from the Microsoft Update Catalog:

  • Windows6.1-KB3063858-x64.msu
  • Windows6.1-KB2999226-x64.msu
  • Win7AndW2K8R2-KB3191566-x64.zip

this is Windows Management Framework 5.1

  • Microsoft Visual C++ 2015-2019 Redistributable (x64) - 14.29.30135

In addition, in some installation, I had to also install PowerShell v7.2.1 .

I was unable to run the application on a fresh install of Windows 7 SP1 in any way.

在Windows 7中发布便携式和独立的.NET应用程序

黑凤梨 2025-02-19 08:22:15

您可以使用此虚拟数据dfcoltoadd列以检查是否不存在添加

df <- data.frame(A = rnorm(5) , B = rnorm(5) , C = rnorm(5))

colToAdd <- c("B" , "D")

,然后应用该列是否存在null产生的您的列Eg rnorm(5)

add <- sapply(colToAdd , \(x) if(!(x %in% colnames(df))) rnorm(5))

data.frame(do.call(cbind , c(df , add)))

  • 输出
           A          B          C          D
1  1.5681665 -0.1767517  0.6658019 -0.8477818
2 -0.5814281 -1.0720196  0.5343765 -0.8259426
3 -0.5649507 -1.1552189 -0.8525945  1.0447395
4  1.2024881 -0.6584889 -0.1551638  0.5726059
5  0.7927576  0.5340098 -0.5139548 -0.7805733

You can use this dummy data df and colToAdd columns to check if not exists to add

df <- data.frame(A = rnorm(5) , B = rnorm(5) , C = rnorm(5))

colToAdd <- c("B" , "D")

then apply the check if the column exists NULL produced else add your column e.g. rnorm(5)

add <- sapply(colToAdd , \(x) if(!(x %in% colnames(df))) rnorm(5))

data.frame(do.call(cbind , c(df , add)))

  • output
           A          B          C          D
1  1.5681665 -0.1767517  0.6658019 -0.8477818
2 -0.5814281 -1.0720196  0.5343765 -0.8259426
3 -0.5649507 -1.1552189 -0.8525945  1.0447395
4  1.2024881 -0.6584889 -0.1551638  0.5726059
5  0.7927576  0.5340098 -0.5139548 -0.7805733

检查是否存在列,如果不添加

黑凤梨 2025-02-19 01:26:32
  • 我创建了一个类blink,其中包含用于闪烁效果的CSS。
  • 然后,我正在检查Counter是否奇怪甚至是偶数。
  • 如果是这样,我将添加blink类,如果不是我检查它是否包含blink类。如果这样做,我将删除blink类,否则什么都不做。
const text = document.querySelector("#wait-text");
let counter = 0;
const updateText = () => {
  counter++;
  text.innerHTML = counter;
  if (counter % 2 == 0) {
    text.classList.add("blink");
  } else {
    if (text.classList.contains("blink")) {
      text.classList.remove("blink");
    }
  }
}
.blink {
  animation: blinkIt 1s infinite;
}

@keyframes blinkIt {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<div id="wait-text"> </div>
<button onclick="updateText()">Click</button>

  • I have created a class blink which contains CSS for blinking effect.
  • then I am checking whether counter is odd or even.
  • if it's even then I am adding blink class and if it's not than I am checking whether it's contains blink class or not. If it does then I am removing blink class otherwise do nothing.

const text = document.querySelector("#wait-text");
let counter = 0;
const updateText = () => {
  counter++;
  text.innerHTML = counter;
  if (counter % 2 == 0) {
    text.classList.add("blink");
  } else {
    if (text.classList.contains("blink")) {
      text.classList.remove("blink");
    }
  }
}
.blink {
  animation: blinkIt 1s infinite;
}

@keyframes blinkIt {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<div id="wait-text"> </div>
<button onclick="updateText()">Click</button>

如何使用Java脚本有条件地使文本闪烁

黑凤梨 2025-02-18 23:20:34
$(document).on('click', "a[href$='.pdf']", function(e){
    e.preventDefault();
    var href_val = $(this).attr('href');
    window.open(href_val, '', ["width=" + 600,"height=" + 600, 'status=1', 'toolbar=0'].join(','));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com/presentation-1.pdf" target="_blank">Download</a>
<a href="https://example.com/presentation-2.pdf" target="_blank">Download</a>

注意 - 新窗口不会在此处打开,因为该请求是在未设置“允许popups”权限的沙盒框架中提出的。

$(document).on('click', "a[href$='.pdf']", function(e){
    e.preventDefault();
    var href_val = $(this).attr('href');
    window.open(href_val, '', ["width=" + 600,"height=" + 600, 'status=1', 'toolbar=0'].join(','));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com/presentation-1.pdf" target="_blank">Download</a>
<a href="https://example.com/presentation-2.pdf" target="_blank">Download</a>

Note - New window will not open here because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.

将HREF放入OnClick活动

黑凤梨 2025-02-17 18:06:16

这可以缩短为:

(?:(?=ab|bc|cd|de|ef|fg|gh|hi|ij|jk|kl|lm|mn|no|op|pq|qr|rs|st|tu|uv|vw|wx|xy|yz).){2,}.

在线查看 demo


  • (:) - 打开一个非捕捉组;
    • (?= ab | bc | cd ...)。 - 嵌套的正面lookahead to sossert to noveAhead具有正确的继任者;
  • ){2,} - 关闭非捕捉组并匹配2次;
  • - 匹配最终字符以结束子字符串。

This can be shortened to:

(?:(?=ab|bc|cd|de|ef|fg|gh|hi|ij|jk|kl|lm|mn|no|op|pq|qr|rs|st|tu|uv|vw|wx|xy|yz).){2,}.

See an online demo


  • (?: - Open a non-capture group;
    • (?=ab|bc|cd...). - A nested positive lookahead to assert character after lookahead has it's correct successor;
  • ){2,} - Close non-capture group and match 2+ times;
  • . - Match the final character to conclude the substring.

三个或多个连续字母的正则表达式

黑凤梨 2025-02-17 15:15:37

我找到了解决方案。有一种明确指定上下文目录的方法;在这种情况下,也需要明确指定Dockerfile。

在docker-compose.yml中,一个应该具有以下结构:

services:
  php:
    build:
      context: .
      dockerfile: ./php/Dockerfile

在这种情况下,src是“可见的”,因为它在上下文中!然后,在该码头中,复制命令将起作用!

更新:还有另一种方法可以通过命令实现这一目标。但是,对于我来说,当我在最后添加./时,它开始工作。因此,完整命令是:

docker cp ./src/./ $(docker-compose ps|grep php|awk '{print $1}'):/var/www/html/

I found the solution. There is a way of specifying the context directory explicitly; in that case the dockerfile also need to be specified explicitly too.

In the docker-compose.yml one should have the following structure:

services:
  php:
    build:
      context: .
      dockerfile: ./php/Dockerfile

In this case the src is "visible" because it is inside the context! Then in that Dockerfile the COPY command will work!

Update: There is another way to achieve this via the command as well. However for me it started to work when I've added the ./ at the end. So the full command is:

docker cp ./src/./ $(docker-compose ps|grep php|awk '{print $1}'):/var/www/html/

有没有办法将目录的内容复制到Docker容器中?

黑凤梨 2025-02-17 12:58:48

您的意思是“不可伸缩100万请求/秒”? jmeter可以启动到 2147483647主要在您的应用程序响应时间上(请参阅 文章有关更多详细信息)

当然,您需要关注 jmeter最佳实践

如果您没有足够强大的机器每秒产生100万个请求,请注意,您可以在分布式模式下运行jmeter ,因此负载将来自几台计算机。

What do you mean by "not scalable to have 1 million requests/sec."? JMeter can kick off as many as 2147483647 threads and whether you can have million request per second will depend mainly on your application response time (see article for more details)

Of course you need to follow JMeter Best Practices.

If you don't have a machine which is powerful enough to generate 1 million requests per second be aware that you can run JMeter in distributed mode so the load would come from several machines.

http post API映射到EventHubs的性能负载测试

黑凤梨 2025-02-17 06:11:15

在此行中,

rtn[key] = valueObject[key].value;

您正在尝试将valueObject的值字符串分配给type tcar,该期望类型的对象{value> {value:“ sosited” sometss'} ,这就是为什么您会遇到此错误的原因。

尝试简单地删除对value的访问,以便将整个对象分配给您的rtn变量。

const parseCarValueObject = (valueObject: TValueCar): TCar => {
  const ObjectKeys = Object.keys(valueObject) as TCarKey[];

  const rtn = {} as TCar;
  ObjectKeys.forEach((key) => {
    // It should works now
    rtn[key] = valueObject[key];
  });

  return rtn;
};

See the example on typescript playground

In this line

rtn[key] = valueObject[key].value;

You are trying to assign the string of value from valueObject to the type TCar that expects an object of type { value: "something" }, this is why you're getting this error.

try to simply remove the access to value in order to assign the whole object to your rtn variable.

const parseCarValueObject = (valueObject: TValueCar): TCar => {
  const ObjectKeys = Object.keys(valueObject) as TCarKey[];

  const rtn = {} as TCar;
  ObjectKeys.forEach((key) => {
    // It should works now
    rtn[key] = valueObject[key];
  });

  return rtn;
};

See the example on typescript playground

打字稿 - 迭代以解析/完善对象

黑凤梨 2025-02-17 02:04:24

这是使用上面评论中概述的逻辑的示例。您可以看到一个dataframe(yx_df)初始化了每个新的y,x值,然后将新列与yx_df = pd串联到它的不同股票值中。 。 。

编辑:添加窗口yx_df dataframe的初始化。当获得新的y,x值时,该列只需要分配一次。

def rolling_reg():
    tickers = ['FDX', 'BRK']
    iterable = zip(range(5), range(50, 55))

    total_df = pd.DataFrame()

    for y, x in iterable:
        yx_df = pd.DataFrame({'window': [f'{y}-{x}']})

        for t in tickers:
            res = pd.DataFrame(
                {t: np.random.randint(0, 10), f"{t}_2": np.random.randn(1)}
            )
            yx_df = pd.concat([yx_df, res], axis = 1)

        total_df = pd.concat([total_df, yx_df], axis = 0, ignore_index=True)

    return total_df

rolling_reg()

#   window  FDX     FDX_2   BRK      BRK_2
# 0   0-50    7  0.232365     6  -1.491573
# 1   1-51    9  0.302536     1   0.871351
# 2   2-52    6  0.233803     9  -1.306058
# 3   3-53    7 -0.203941     8   0.454480
# 4   4-54    7 -0.618590     7   0.810528

Here is an example using the logic outlined in my comment above. You can see one dataframe (yx_df) is initialized for every new y, x values, then new columns are concatenated to it for different ticker values with yx_df = pd.concat([yx_df, res], axis = 1), and finally a full row is concatenated to the total_df after the loop over all tickers is done with total_df = pd.concat([total_df, yx_df], axis = 0, ignore_index=True).

Edit: Added window column to the initialization of the yx_df dataframe. That column only needs to have its value assigned once when new y, x values are obtained.

def rolling_reg():
    tickers = ['FDX', 'BRK']
    iterable = zip(range(5), range(50, 55))

    total_df = pd.DataFrame()

    for y, x in iterable:
        yx_df = pd.DataFrame({'window': [f'{y}-{x}']})

        for t in tickers:
            res = pd.DataFrame(
                {t: np.random.randint(0, 10), f"{t}_2": np.random.randn(1)}
            )
            yx_df = pd.concat([yx_df, res], axis = 1)

        total_df = pd.concat([total_df, yx_df], axis = 0, ignore_index=True)

    return total_df

rolling_reg()

#   window  FDX     FDX_2   BRK      BRK_2
# 0   0-50    7  0.232365     6  -1.491573
# 1   1-51    9  0.302536     1   0.871351
# 2   2-52    6  0.233803     9  -1.306058
# 3   3-53    7 -0.203941     8   0.454480
# 4   4-54    7 -0.618590     7   0.810528

我如何连接滚动回归结果| Python

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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