小编phi*_*her的帖子

数据结构 - 随机队列

我目前正在研究普林斯顿的算法第一部分.其中一项任务是实现一个随机队列.这是关于使用不同数据结构的实现和权衡的问题.

题:

随机队列类似于堆栈或队列,除了从数据结构中的项目随机均匀地选择移除的项目.创建实现以下API的通用数据类型RandomizedQueue:

public class RandomizedQueue<Item> implements Iterable<Item> {
    public RandomizedQueue() // construct an empty randomized queue
    public boolean isEmpty() // is the queue empty?
    public int size() // return the number of items on the queue
    public void enqueue(Item item) // add the item
    public Item dequeue() // remove and return a random item
    public Item sample() // return (but do not remove) a random item
    public Iterator<Item> iterator() // return an independent iterator over items in random order …
Run Code Online (Sandbox Code Playgroud)

java random queue data-structures

22
推荐指数
2
解决办法
1万
查看次数

获取 API:在请求完成后“await res.json()”能否失败?

fetch API 请求只会在出现网络或服务器错误时失败。因此,例如,如果我执行以下代码,假设它通过try块没有错误,我将有一个有效的填充res.

try {
    const res = await fetch('/createurl', { 
        method: 'POST',
        body: 'testData',
        headers: {
            'Content-Type': 'application/json'
        }
    })

    if (res.ok) {
        alert('Resource created!')
    } else {
        alert('Error creating resource!')
    }

    flashResponseToUser(res)
} catch(e) {
    alert('A server or network error occurred during the request!')
}
Run Code Online (Sandbox Code Playgroud)

我正在处理res向用户显示使用该功能的必要信息errorsuccess消息flashResponseToUser(res)。由于res.json()返回 a PromiseflashResponseToUser必须是一个异步函数。

const flashResponseToUser = async(res) => {
    const jsonRes = await res.json() // Get …
Run Code Online (Sandbox Code Playgroud)

javascript promise fetch-api

10
推荐指数
1
解决办法
4282
查看次数

如何在 NodeJS 中测试服务器发送事件 (SSE) 路由?

我的 NodeJS 应用程序上有一个 Server Sent Events 路由,客户端可以订阅该路由以从服务器获取实时更新。它看起来像这样:

router.get('/updates', (req, res) => {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    })

    const triggered = (info) => {
        res.write(`\ndata: ${JSON.stringify(info)}\n\n`)
    }

    eventEmitter.addListener(constants.events.TRIGGERED, triggered)

    req.on('close', () => {
        eventEmitter.removeListener(constants.events.TRIGGERED, triggered)
    })
})
Run Code Online (Sandbox Code Playgroud)

supertest在节点中使用测试传统路由非常简单:

test('Should get and render view', async() => {
    const res = await request(app)
        .get('/')
        .expect(200)

    expect(res.text).not.toBeUndefined()
})
Run Code Online (Sandbox Code Playgroud)

但是,这在测试 SSE 路由时不起作用。

有没有人对如何使用 Node 测试 SSE 路由有任何想法?它不一定必须使用supertest. 只是寻找有关如何测试它supertest或其他方式的想法。

编辑: 我有一个关于如何集成测试的想法。基本上,必须在测试前启动服务器,在测试期间订阅它并在测试后关闭它。但是,当我使用 beforeEach() 和 afterEach() 启动服务器时,它在 Jest 中无法按预期工作。

node.js server-sent-events supertest

7
推荐指数
1
解决办法
1804
查看次数

使用 Jest 测试框架调用 fetch(url) 时,如何根据 url 模拟变量响应?

我有一个如下所示的模块:

计算平均值.js

const fetch = require('node-fetch')
const stats = require('stats-lite')
const BASE_URL = 'https://www.example.com/api'

const calculateAverage = async(numApiCalls) => {
  const importantData = []

  for (let i = 0; i < numApiCalls; i++) {
      const url = `${BASE_URL}/${i}` // will make requests to https://www.example.com/api/0, https://www.example.com/api/1 and so on....
      const res = await fetch(url)
      const jsonRes = await res.json()

      importantData.push(jsonRes.importantData)
  }

  return stats.mean(importantData)
}

module.exports = calculateAverage
Run Code Online (Sandbox Code Playgroud)

我尝试按照以下方式测试它,但我显然离解决方案还很远:

计算平均值.test.js

const calculateAverage = require('../calculate-average')

jest.mock(
    'node-fetch',
    () => {
        return jest.fn(() => …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocking fetch node.js jestjs

6
推荐指数
1
解决办法
9051
查看次数

仅使用 css/bootstrap 粘性多个表头 (thead) 行

我试图在<thead>标签下粘贴多行,而表格的其余部分是可滚动的。

SO 上的这个答案显示了如何使用标签将标题粘贴到顶部position: sticky,但没有显示如何在<thead>.

使用链接中提到的 CSS 代码thead th { position: sticky; top: 0; }只会粘贴 中的第一行<thead>

谢谢您的帮助!

html css bootstrap-4

5
推荐指数
1
解决办法
7191
查看次数

服务器发送事件 (SSE) 路由的 Heroku H12 请求超时

我有一个 NodeJS 应用程序,它使用服务器发送事件 (SSE) 路由将更新从服务器发送到客户端。在我的本地开发环境中,这非常有效,因为客户端始终保持与 SSE 路由的连接,并在断开连接时尝试立即重新连接。

\n\n

然而,当我将应用程序部署到 Heroku 后,一切都出了问题。在不通过 SSE 路由发送任何数据的几秒钟内,我503 Service Unavailable在客户端收到错误,并且客户端失去了与服务器的连接,因此无法接收更多实时更新。查看 Heroku 服务器日志,它给了我一个H12 Request Timeout错误。

\n\n

经过进一步研究,我在 Heroku 网站上看到了这篇文章:

\n\n
\n

如果您\xe2\x80\x99 正在发送流式响应,例如服务器发送\n 事件,则\xe2\x80\x99 将需要检测客户端何时挂起,并确保\n 您的应用服务器关闭及时连接。如果服务器\n 使连接保持打开状态55 秒而不发送任何数据,\n 您\n\xe2\x80\x99 将看到请求超时。

\n
\n\n

但是,它没有提及如何解决该问题。

\n\n
    \n
  1. 有没有办法将超时设置为无穷大?
  2. \n
  3. 或者这是否意味着我必须不断从服务器向客户端发送心跳才能保持 SSE 路由连接处于活动状态?这似乎乏味且不必要,因为我想始终保持连接。
  4. \n
\n

heroku node.js server-sent-events

3
推荐指数
1
解决办法
1086
查看次数