妄想挽回

文章 评论 浏览 29

妄想挽回 2025-02-20 16:33:12

这是Boussadjra Brahim的Reption Api的改进版本。
这种方法使您可以使用有效载荷多次触发事件。
请注意,如果几次触发同一事件时, counter 仅用于触发更改,则使用有效载荷或有效载荷相同。

还要谨慎使用SSR,在这种情况下,总线变量将共享,因此您最终会得到交叉要求的状态污染。为了避免这种情况,您可以将事件总线作为插件实现,并在需要时将其曝光。像这样,将为每个请求初始化总线变量。

useeventbus.js

import { ref, watch } from 'vue';

const bus = ref(new Map());

export function useEventsBus() {
  const emit = (event, props) => {
    const currentValue = bus.value.get(event);
    const counter = currentValue ? ++currentValue[1] : 1;
    bus.value.set(event, [props, counter]);
  };

  const on = (event, callback) => {
    watch(() => bus.value.get(event), (val) => {
      callback(val[0]);
    });
  };

  return {
    emit,
    on,
    bus,
  };
}

PublisherComponent.vue

<script setup lang="ts">
import { useEventsBus } from '~/composables/useEventsBus';
</script>

<template>
  <Button
    @click="useEventsBus().emit('btn-clicked', 'Hello there')"
  >
    Button with payload
  </Button>
  <Button
    @click="useEventsBus().emit('btn-another-clicked')"
  >
    Button without payload
  </Button>
</template>

subscribercomponent.vue

<script setup lang="ts">
import { useEventsBus } from '~/composables/useEventsBus';

useEventsBus().on('btn-clicked', (payload) => {
  console.log(payload); // 'Hello there'
});

useEventsBus().on('btn-another-clicked', (payload) => {
  console.log(payload); // undefined
})
// you can subscribe on the event several times
useEventsBus().on('btn-another-clicked', (payload) => {
  console.log(payload); // undefined
})
</script>

Here is improved version of Boussadjra Brahim's answer with composition API.
This approach allows you to trigger an event multiple times with payload or without it.
Note, that counter is used just to trigger a change if no payload or payload is the same when you trigger same event several times.

Also be careful with SSR, in this case the bus variable will be shared, so you end up with cross-request state pollution. To avoid this you may implement event bus as a plugin and if needed expose it with composable. Like this the bus variable will be initialized for each request.

useEventBus.js

import { ref, watch } from 'vue';

const bus = ref(new Map());

export function useEventsBus() {
  const emit = (event, props) => {
    const currentValue = bus.value.get(event);
    const counter = currentValue ? ++currentValue[1] : 1;
    bus.value.set(event, [props, counter]);
  };

  const on = (event, callback) => {
    watch(() => bus.value.get(event), (val) => {
      callback(val[0]);
    });
  };

  return {
    emit,
    on,
    bus,
  };
}

PublisherComponent.vue

<script setup lang="ts">
import { useEventsBus } from '~/composables/useEventsBus';
</script>

<template>
  <Button
    @click="useEventsBus().emit('btn-clicked', 'Hello there')"
  >
    Button with payload
  </Button>
  <Button
    @click="useEventsBus().emit('btn-another-clicked')"
  >
    Button without payload
  </Button>
</template>

SubscriberComponent.vue

<script setup lang="ts">
import { useEventsBus } from '~/composables/useEventsBus';

useEventsBus().on('btn-clicked', (payload) => {
  console.log(payload); // 'Hello there'
});

useEventsBus().on('btn-another-clicked', (payload) => {
  console.log(payload); // undefined
})
// you can subscribe on the event several times
useEventsBus().on('btn-another-clicked', (payload) => {
  console.log(payload); // undefined
})
</script>

vue.js 3活动巴士

妄想挽回 2025-02-20 11:13:55

tl; dr: 不要在任何地方移动#contextmenu。阅读: 解决方案*


您遇到的错误

dropdown.js:285 Unduck typeError:在'window''上无法执行'getComputedStyle':参数1不是类型的'element'。

// @l62:
const SELECTOR_MENU = '.dropdown-menu'

// @l103:
  constructor(element, config) {
    super(element);
    //...
    this._menu = this._getMenuElement()
    //...
  }

// @l269:
  _getMenuElement() {
    return SelectorEngine.next(this._element, SELECTOR_MENU)[0]
  }

// @l285:
   _getPlacement() {
    // ...
    const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'
    // ...
  }

shere selectorengine.next(this._element,

如您所见,除了BS硬编码的一个,没有办法传递给构造函数另一个元素。 _getMenuelement() 〜Line285。

下一个同胞元素在方法/code>并盲目期望切换下一个同胞元素下拉 - 它实际上尚不存在(尚未)!

我会:

  • 扩展类下拉 手动,或
  • 提出问题并为相关的

所需元素作为this._menu;类似:

  constructor(element, config) {
    //...
    // Fix: allow for custom reusable menu Element
    this._menu = config.menuElement || this._getMenuElement()
    //...
  }

免责声明: 主要分支关于上述剥离代码,我不确定在编写这些问题时是否已解决。


同时,您可以简单地做什么,而无需使用“ Mousedown”事件(要领先BS的“单击”事件 - 就像在此 重复的问题答案 ),并且不使用愚蠢的event.stoppropagation()(除了您不应该使用,除了您,除了您是否真的知道自己在做什么,或用于调试仅目的) - 是:

解决方案:

不要使用ul#contextMenu使用.after()或(使用JS) .insertadjacentelement(),而是,关于扩展的Popper实例的实例化更改预期的bootstrap this._menu属性属性指向所需的可重复使用元素 - 您的 in- in- in-身体“ #contextmenu”喜欢:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test Code</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body>
  <table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th>#</th>
        <th>Document</th>
        <th>Reference</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>General Policies</td>
        <td>GP-01-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc1">Options</button>
          </div>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Training Material</td>
        <td>GP-02-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc2">Options</button>
          </div>
        </td>
      </tr>
    </tbody>
  </table>

  <ul id="contextMenu" class="dropdown-menu">
    <li><button type="button" tabindex="-1" class="dropdown-item downloadLink">Download</button></li>
    <li><button type="button" tabindex="-1" class="dropdown-item propertiesLink">Properties</button></li>
  </ul>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <script>
    // DOM utility functions:
    const el = (sel, par) => (par || document).querySelector(sel);
    const els = (sel, par) => (par || document).querySelectorAll(sel);

    // Task: BS5 Popper fix for single static dropdown menu:
    const elDropdown = el('#contextMenu');
    const elsBtns = els(".optionsButton");
    const dropdownList = [...elsBtns].map(function(elBtn) {
      const instance = new bootstrap.Dropdown(elBtn);
      instance._menu = elDropdown;
      return instance;
    });
    // console.log(dropdownList); 
  </script>

</body>

</html>

以上的好东西是,DOM没有变化会触发回流。 popper代码将计算浮动上下文的最佳位置并将其称为工作。
不是那么 nice thick 是在您将TR元素动态添加到表中的情况下应给予特殊护理;在某种程度上,应在创建时将每个新添加的按钮作为new Bootstrap.dropdown(elbtn)

使用“ Mousedown”使用“ Mousedown”

的另一个(不是那么好的)解决方案,以实例化。不必要地)移动DOM 中的下拉菜单。可以使用“ Mousedown”事件来实现它,以便在BS的“单击” 事件触发器之前移动下拉列表“在这个相关问题的答案)。但这将无法正常工作。单击另一个按钮,一个按钮可以看到内容 /故障(实际下拉列表的)。可能有一些方法可以减轻问题……但是,为什么。无论如何,fyeo这是代码:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test Code</title>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body>
  <table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th>#</th>
        <th>Document</th>
        <th>Reference</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>General Policies</td>
        <td>GP-01-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc1">Options</button>
          </div>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Training Material</td>
        <td>GP-02-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc2">Options</button>
          </div>
        </td>
      </tr>
    </tbody>
  </table>

  <ul id="contextMenu" class="dropdown-menu">
    <li><button type="button" tabindex="-1" class="dropdown-item downloadLink">Download</button></li>
    <li><button type="button" tabindex="-1" class="dropdown-item propertiesLink">Properties</button></li>
  </ul>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <script>
    // DOM utility functions:
    const el = (sel, par) => (par || document).querySelector(sel);
    const els = (sel, par) => (par || document).querySelectorAll(sel);

    // Task: BS5 Popper fix for single static dropdown menu:
    const elDropdown = el('#contextMenu');
    const elsBtns = els(".optionsButton");

    const prepareDropdown = (evt) => {
      const elBtn = evt.currentTarget;
      elBtn.insertAdjacentElement("afterend", elDropdown);
    };

    elsBtns.forEach(elBtn => elBtn.addEventListener("mousedown", prepareDropdown));
  </script>


</body>

</html>

PS:使用始终&lt;按钮类型=“ button”&gt;而不是锚定(如上所述),如果您不需要导航,而只是一个普通的UI交互按钮元素。

BS使用和实施弹出窗口,选择等的方式是破坏的。如果已经打开了弹出窗口(或模态),则单击另一个按钮 - 应立即显示第二个(或同一)弹出窗口 (第二次单击后)。这是设计中的UI/UX缺陷。 Bootstrap通常非常奇怪地实现想法,但不要忘记您可以随时提供拉请求


如果您对如何使用JavaScript从头开始创建(类似的)弹出窗口 - 您可以在此处找到更多:在鼠标位置

TL;DR: Don't move the #contextMenu anywhere. Read: Solution*


The error you're getting

dropdown.js:285 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

is related to the Bootstrap (v5.1.3): dropdown.js code:

// @l62:
const SELECTOR_MENU = '.dropdown-menu'

// @l103:
  constructor(element, config) {
    super(element);
    //...
    this._menu = this._getMenuElement()
    //...
  }

// @l269:
  _getMenuElement() {
    return SelectorEngine.next(this._element, SELECTOR_MENU)[0]
  }

// @l285:
   _getPlacement() {
    // ...
    const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'
    // ...
  }

here: SelectorEngine.next(this._element,

as you can see, there's no way to pass to the constructor another Element .menu-dropdown besides the one that BS hardcoded, and that's a next Sibling element in the Method _getMenuElement() ~line285.

BS assigns a "click" Event to every button with data-bs-toggle="dropdown" and blindly expects to toggle a next sibling Element dropdown — which does not actually exists (yet)!

I would either:

  • extend the class Dropdown manually, or
  • raise an Issue and create a pull-request to the related Bootstrap module

as a way to pass any desired Element as the this._menu; something like:

  constructor(element, config) {
    //...
    // Fix: allow for custom reusable menu Element
    this._menu = config.menuElement || this._getMenuElement()
    //...
  }

Disclaimer: There are some changes in the main branch regarding the above stripped-off code, I'm not sure if at the time of writing those issues were addressed.


In the meantime what you can simply do, without using the "mousedown" Event (to be one step ahead the BS's "click" event - like in this duplicate question's answer), and without using the silly Event.stopPropagation() (which should never be used, besides you really, really know what you're doing, or for debugging purpose only) — is:

Solution:

Don't move the UL#contextMenu using .after() or (with JS) .insertAdjacentElement(), rather, on instantiation of the extended Popper instances change the expected Bootstrap this._menu property to point to the desired reusable Element — your in-body "#contextMenu" like:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test Code</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body>
  <table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th>#</th>
        <th>Document</th>
        <th>Reference</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>General Policies</td>
        <td>GP-01-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc1">Options</button>
          </div>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Training Material</td>
        <td>GP-02-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc2">Options</button>
          </div>
        </td>
      </tr>
    </tbody>
  </table>

  <ul id="contextMenu" class="dropdown-menu">
    <li><button type="button" tabindex="-1" class="dropdown-item downloadLink">Download</button></li>
    <li><button type="button" tabindex="-1" class="dropdown-item propertiesLink">Properties</button></li>
  </ul>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <script>
    // DOM utility functions:
    const el = (sel, par) => (par || document).querySelector(sel);
    const els = (sel, par) => (par || document).querySelectorAll(sel);

    // Task: BS5 Popper fix for single static dropdown menu:
    const elDropdown = el('#contextMenu');
    const elsBtns = els(".optionsButton");
    const dropdownList = [...elsBtns].map(function(elBtn) {
      const instance = new bootstrap.Dropdown(elBtn);
      instance._menu = elDropdown;
      return instance;
    });
    // console.log(dropdownList); 
  </script>

</body>

</html>

The nice thing of the above is that there are no changes in the DOM that would trigger a reflow. The Popper code will calculate the best position of your floating contextMenu and call it job-done.
The not so nice thing is that special care should be given in the case you dynamically add TR elements to the Table; in the means that every newly added Button should be instantiated upon creation as a new bootstrap.Dropdown(elBtn)

Using "mousedown"

Another (not so good) solution to your original idea is to (unnecessarily) move the dropdown in DOM. It can be achieved using the "mousedown" Event, in order to move the dropdown "ahead-of-time" — before the BS's "click" event triggers (as suggested in this related question's answer). But such will not work correctly. Clicking one button after the other, a flash of content / glitch (of the actual dropdown) can be seen. There might be ways to mitigate the issue… but, why. Anyways, FYEO here's the code:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test Code</title>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body>
  <table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th>#</th>
        <th>Document</th>
        <th>Reference</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>General Policies</td>
        <td>GP-01-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc1">Options</button>
          </div>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Training Material</td>
        <td>GP-02-2022</td>
        <td>
          <div class="dropdown">
            <button type="button" class="btn btn-primary optionsButton" data-bs-toggle="dropdown" aria-expanded="false" id="doc2">Options</button>
          </div>
        </td>
      </tr>
    </tbody>
  </table>

  <ul id="contextMenu" class="dropdown-menu">
    <li><button type="button" tabindex="-1" class="dropdown-item downloadLink">Download</button></li>
    <li><button type="button" tabindex="-1" class="dropdown-item propertiesLink">Properties</button></li>
  </ul>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <script>
    // DOM utility functions:
    const el = (sel, par) => (par || document).querySelector(sel);
    const els = (sel, par) => (par || document).querySelectorAll(sel);

    // Task: BS5 Popper fix for single static dropdown menu:
    const elDropdown = el('#contextMenu');
    const elsBtns = els(".optionsButton");

    const prepareDropdown = (evt) => {
      const elBtn = evt.currentTarget;
      elBtn.insertAdjacentElement("afterend", elDropdown);
    };

    elsBtns.forEach(elBtn => elBtn.addEventListener("mousedown", prepareDropdown));
  </script>


</body>

</html>

PS: use always <button type="button"> instead of Anchors (as in the examples above) if you don't need to navigate, but just a plain UI interaction button Element.

The way that BS uses and implements popups, selects etc. is kind of broken anyways. If a popup (or modal) is already opened, by clicking another button — the second (or the same) popup should be shown immediately (not after a second click). It's a UI/UX flaw in the design. Bootstrap often implements ideas quite oddly, but don't forget you can always help the Open Source community by providing a Pull Request.


If you're interested on how to create a (similar) Popup from scratch using JavaScript — you can find out more here: Show custom popup on mouse location.

Bootstrap:下拉次点不用jQuery单击打开

妄想挽回 2025-02-20 06:34:13

希望这个答案对您有用。

queryBuilder.find({ _id: { $in: [...bikesWithNoOrders,...filteredResult] } });

Hope this answer will work for you.!

queryBuilder.find({ _id: { $in: [...bikesWithNoOrders,...filteredResult] } });

如何通过MongoDB中的两个单独的ID阵列匹配?

妄想挽回 2025-02-20 02:57:14

您在正确的轨道上。要注意的1件事是find()返回数组项目,而不是数组项目的属性。

因此,只需简化您的步骤:

  1. 查找阵列项目
  2. 获取alpha3属性在您找到的阵列项目上
 // countries.find() returns the array item
 const matchingCountry = countries.find((obj) => {
    if (obj.country === countryName) {
      return obj;
    }
  })

 // optional but advised: handle a situation where no country is found
 if(!matchingCountry){
    console.warn('no country found');
    return; // this ensures no further code will be executed 
 }

 // now you can safely assume matchingCountry is available 
 const matchingCountryCode = matchingCountry.alpha3;
 console.log('success: ', matchingCountryCode)

You're on the right track. 1 thing to note is that find() returns an array item and not the property of an array item.

So just simplify yours steps:

  1. find array item
  2. get alpha3 property on the array item you found
 // countries.find() returns the array item
 const matchingCountry = countries.find((obj) => {
    if (obj.country === countryName) {
      return obj;
    }
  })

 // optional but advised: handle a situation where no country is found
 if(!matchingCountry){
    console.warn('no country found');
    return; // this ensures no further code will be executed 
 }

 // now you can safely assume matchingCountry is available 
 const matchingCountryCode = matchingCountry.alpha3;
 console.log('success: ', matchingCountryCode)

您如何返回特定的JavaScript对象?

妄想挽回 2025-02-19 17:54:26

您可以使用CSS网格,而不是浮动物品。

对于更广泛的视口,您可以将列定义为
1FR 41.6666%1FR 1FR

FR单元在这种情况下将剩余的可用空间划分为3个相等的部分。

对于较窄的视口,您可以将网格设置为具有3个相等的列,然后将大元素放入第一行,其余的元素进入第二行。

* {
  margin: 0;
  box-sizing: border-box;
}

.container {
  display: grid;
  grid-template-columns: 1fr 41.6666% 1fr 1fr;
  gap: 1vw;
  width: 100vw;
  height: 350px;
}

section {
  border: 1px solid black;
}

@media (max-width: 600px) {
  .container {
    height: 700px;
    grid-template-rows: 1fr 1fr;
    grid-template-columns: 1fr 1fr 1fr;
  }
  .big {
    grid-row: 1;
    grid-column: 1 / span 3;
  }
  .small {
    grid-row: 2;
  }
}
<div class="container">
  <section class="small"></section>
  <section class="big"></section>
  <section class="small"></section>
  <section class="small"></section>
</div>

You could use CSS grid rather than floating the items.

For the wider viewports you could have the columns defined as
1fr 41.6666% 1fr 1fr

The fr units divide up remaining free space, in this case into 3 equal sections.

For the narrower viewports you could set the grid to have 3 equal columns and then put the big element into the first row and the rest into the second row.

* {
  margin: 0;
  box-sizing: border-box;
}

.container {
  display: grid;
  grid-template-columns: 1fr 41.6666% 1fr 1fr;
  gap: 1vw;
  width: 100vw;
  height: 350px;
}

section {
  border: 1px solid black;
}

@media (max-width: 600px) {
  .container {
    height: 700px;
    grid-template-rows: 1fr 1fr;
    grid-template-columns: 1fr 1fr 1fr;
  }
  .big {
    grid-row: 1;
    grid-column: 1 / span 3;
  }
  .small {
    grid-row: 2;
  }
}
<div class="container">
  <section class="small"></section>
  <section class="big"></section>
  <section class="small"></section>
  <section class="small"></section>
</div>

用CSS更改部分的顺序

妄想挽回 2025-02-19 10:59:53

O(n * 2^n)不等于O(2^n),并且比O(2^n)差得多。

O(n * 2^n) is not equal to O(2^n) and is much worse than O(2^n).

o(n * 2^n)与o(2^n)相同吗?

妄想挽回 2025-02-19 08:12:07

这是我设计此游戏的一种方式:

├── backend
│   ├── __init__.py
│   ├── character.py
│   ├── heros.py
│   └── monsters.py
└── main.py

targue.py是英雄和怪物之间的共同类别。

# character.py
class Character:
    def __init__(self):
        self.health = 100

    def attack(self, target):
        target.take_damage(1)

    def take_damage(self, amount):
        self.health -= amount

    def __repr__(self):
        return (
            f"{self.__class__.__name__}("
            f"health={self.health!r}"
            f")"
        )
# heros.py
from .character import Character

class Hero(Character):
    pass
# monsters.py
from .character import Character

class Monster(Character):
    def attack(self, target):
        target.take_damage(5)
# main.py
from backend.heros import Hero
from backend.monsters import Monster

h = Hero()
m = Monster()

h.attack(m)
m.attack(h)

print(h)
print(m)

输出:

Hero(health=95)
Monster(health=99)

此处发生的密钥在Attack方法中发生:它用金额调用target.take_damage()

请注意,Heros.py不导入Monsters.py,反之亦然。这样做可能会导致圆形参考,这是混乱的。

Here is a way for me to design this game:

├── backend
│   ├── __init__.py
│   ├── character.py
│   ├── heros.py
│   └── monsters.py
└── main.py

character.py is the common class between hero and monster.

# character.py
class Character:
    def __init__(self):
        self.health = 100

    def attack(self, target):
        target.take_damage(1)

    def take_damage(self, amount):
        self.health -= amount

    def __repr__(self):
        return (
            f"{self.__class__.__name__}("
            f"health={self.health!r}"
            f")"
        )
# heros.py
from .character import Character

class Hero(Character):
    pass
# monsters.py
from .character import Character

class Monster(Character):
    def attack(self, target):
        target.take_damage(5)
# main.py
from backend.heros import Hero
from backend.monsters import Monster

h = Hero()
m = Monster()

h.attack(m)
m.attack(h)

print(h)
print(m)

Output:

Hero(health=95)
Monster(health=99)

The key here is happening inside the attack method: it calls target.take_damage() with the amount.

Note that heros.py does not import monsters.py and vice versa. Doing so could result in circular reference, which is messy.

如何从两个不同文件中的两个不同类中获得函数以相互通信?

妄想挽回 2025-02-19 05:53:42

我怀疑问题是您正在使用错误的JDBC驱动程序,尽管我无法确认这一点,因为您实际上没有说您正在使用的是哪一个。

您将需要从

我没有这样做的详细步骤,但是我之前撰写过有关连接客户的说明数据集成和DBeaver to Astra DB which is a Cassandra-as-a-服务。这些说明应该让您了解如何配置talend。干杯!

I suspect the problem is that you're using the wrong JDBC driver although I'm unable to confirm that since you didn't actually say which one you're using.

You will need to download the Simba JDBC Driver for Apache Cassandra from DataStax Downloads in order to connect to a Cassandra cluster. Then you'll need to install the driver on to your Talend.

I don't have the detailed steps for doing that but I've previously written instructions for connecting clients like Pentaho Data Integration and DBeaver to Astra DB which is a Cassandra-as-a-service. The instructions for those should give you an idea of how to configure Talend. Cheers!

如何配置Talend Open Studio连接到Cassandra群集?

妄想挽回 2025-02-18 22:43:48

该解决方案可能是可以理解的:

first_inp = int(input("No. of Students"))
no_of_subs = int(input("No. of Subjects :"))
details = {tuple(int(input("Marks")) for i in range(no_of_subs)):input("Name") for i in range(first_inp)}
lis_res = [sum(i) for i in details]
det_val = [v for v in details.values()]
print (det_val[lis_res.index(max(lis_res))])

最终,您可以使用返回关键字来返回该值,如果您定义函数。

This Solution might be an understandable one :

first_inp = int(input("No. of Students"))
no_of_subs = int(input("No. of Subjects :"))
details = {tuple(int(input("Marks")) for i in range(no_of_subs)):input("Name") for i in range(first_inp)}
lis_res = [sum(i) for i in details]
det_val = [v for v in details.values()]
print (det_val[lis_res.index(max(lis_res))])

In the end you can use return keyword to return that value if you are defining a function.

发现哪个人的百分比根据他们的分数最高

妄想挽回 2025-02-18 11:56:58

是的,你可以。
您需要添加第一个控制器:

YourController controller = loader.getController();     
controller.setclient(client);

然后在第二个控制器中声明客户端,然后在控制器的底部:

public void setclien(Client c) {
    this.client = c;
}

Yes you can.
You need to add in the first controller:

YourController controller = loader.getController();     
controller.setclient(client);

Then in the second one declare a client, then at the bottom of your controller:

public void setclien(Client c) {
    this.client = c;
}

传递参数Javafx FXML

妄想挽回 2025-02-18 08:42:25

Moshe回答的动机来自: https://stackoverflow.com/a/3844448106/6459849

我一边的小贡献有一个扩展示例。假设有一个整体操作核心,它包含一个响应成功率,其中包含通用类型。

响应响应

template <class T>
class ResponseSuccess {
public:
    ResponseSuccess(const ResponseStatus responseStatus, const T& data) :
        m_responseStatus(responseStatus),
        m_data(data) {}

    ~ResponseSuccess() = default;

    // Basis requirement, have Copy/Move constructor/delete assignment operator

    ResponseStatus getResponseStatus() const {
        return m_responseStatus;
    }

    T getData() const {
        return m_data;
    };

private:
    ResponseStatus m_responseStatus;

    T m_data;
};

Operationsuccess.h

template <class T>
class OperationResponse {
public:
    explicit OperationResponse(ResponseSuccess<T> responseSuccess) :
        m_responseSuccess(std::move(responseSuccess)) {}

    ~OperationResponse() = default;
    // Basis requirement, have Copy/Move constructor/delete assignment operator

    ResponseSuccess<T> getResponseSuccess() const {
        return m_responseSuccess;
    }

private:
    ResponseSuccess<T> m_responseSuccess;
    // have a failure, in case required
};

用法:

MyObject myObj(<ctor_args>);
    ResponseSuccess<MyObject> responseSuccess(ResponseStatus::SUCCESS, myObj);
    OperationResponse<MyObject> successOperationResponse(responseSuccess);
..
// Fetches the response -> successOperationResponse.getResponseSuccess();

With motivation from Moshe's answer from: https://stackoverflow.com/a/38448106/6459849

A small contribution from my side with an extended example. Let's say there is an overall OperationSuccess and it contains a ResponseSuccess which has a generic type in it.

ResponseSuccess.h

template <class T>
class ResponseSuccess {
public:
    ResponseSuccess(const ResponseStatus responseStatus, const T& data) :
        m_responseStatus(responseStatus),
        m_data(data) {}

    ~ResponseSuccess() = default;

    // Basis requirement, have Copy/Move constructor/delete assignment operator

    ResponseStatus getResponseStatus() const {
        return m_responseStatus;
    }

    T getData() const {
        return m_data;
    };

private:
    ResponseStatus m_responseStatus;

    T m_data;
};

OperationSuccess.h

template <class T>
class OperationResponse {
public:
    explicit OperationResponse(ResponseSuccess<T> responseSuccess) :
        m_responseSuccess(std::move(responseSuccess)) {}

    ~OperationResponse() = default;
    // Basis requirement, have Copy/Move constructor/delete assignment operator

    ResponseSuccess<T> getResponseSuccess() const {
        return m_responseSuccess;
    }

private:
    ResponseSuccess<T> m_responseSuccess;
    // have a failure, in case required
};

Usage:

MyObject myObj(<ctor_args>);
    ResponseSuccess<MyObject> responseSuccess(ResponseStatus::SUCCESS, myObj);
    OperationResponse<MyObject> successOperationResponse(responseSuccess);
..
// Fetches the response -> successOperationResponse.getResponseSuccess();

为什么仅在标题文件中实现模板?

妄想挽回 2025-02-17 20:53:37
In your javascript file use ajax method to call your views.py, 

   $.ajax({
            type: "GET", method GET or POST
            url: "/url_name/", //url of site no need to enter full site

            data: {
                'key': value, // data you want to pass if any
            },

            contentType: 'application/json',

            success: function (response) {
                  console.log(response.flag) // Gives value of flag  
            },

            error: function (data) {
                console.log('error');
            }
        });;

In your views.py you can pass your flag value as JSON response,

    def view_name(response):
        return JsonResponse({'flag': flag }, content_type='application/json')
In your javascript file use ajax method to call your views.py, 

   $.ajax({
            type: "GET", method GET or POST
            url: "/url_name/", //url of site no need to enter full site

            data: {
                'key': value, // data you want to pass if any
            },

            contentType: 'application/json',

            success: function (response) {
                  console.log(response.flag) // Gives value of flag  
            },

            error: function (data) {
                console.log('error');
            }
        });;

In your views.py you can pass your flag value as JSON response,

    def view_name(response):
        return JsonResponse({'flag': flag }, content_type='application/json')

如何将变量从view.py传递到javascript而不使用django中的render()

妄想挽回 2025-02-17 02:51:36

您可以使用 find_in_set()功能

select * 
from table 2 
where FIND_IN_SET(book_id, (select book_ids from table 1 where id=1)) > 0;

阅读我链接到的文档,以获取有关该功能如何工作的详细信息。

但是,只有当您的桌子仍然很小时才这样做。使用此功能会破坏用索引优化查询的任何机会,因此您的桌子越大,性能就会越来越差。

另外,如果您的逗号分隔列表中有空格,则Find_in_set()无法正常工作。

You could use the FIND_IN_SET() function:

select * 
from table 2 
where FIND_IN_SET(book_id, (select book_ids from table 1 where id=1)) > 0;

Read the documentation I linked to for details on how that function works.

But only do this if your table remains small. Using this function spoils any opportunity to optimize the query with an index, so the larger your table gets, the performance will grow worse and worse.

Also FIND_IN_SET() doesn't work the way you expect if there are spaces in your comma-separated list.

mysql选择语句

妄想挽回 2025-02-16 21:10:56

那是因为您将数组索引用作:key。 vue不会在[1,2,3][2,3,1]之间有所不同循环,它与元素没有绑定。

尝试从每个元素绑定相关:键,它应该开始动画。

That's because you use the array index as a :key. Vue won't make a difference between [1, 2, 3] and [2, 3, 1] because the index is generating on the v-for loop, it's not tied to an element.

Try to bind a relevant :key from each element and it should starts animating.

lodash shuffle函数可以在vue.js中进行动画

妄想挽回 2025-02-16 11:39:18
  1. 检查DF是否具有这些列

  2. 您的代码在Antonio_trade之后具有空间,” [[“ NAZIV ARTIKLA”,“ EAN CODE”,]]删除该空间并尝试一下

    antonio_trade_merge = antonio_trade“ space_to_be_remaved ” [[[“ naziv artikla”,“ ean code”,]。 P>

  3. “ 另一个表,你想做什么?

您能显示一个示例输出吗?

  1. Check if the df have those columns

  2. your code has space in it after antonio_trade" "[["NAZIV ARTIKLA","EAN CODE",]] remove that space and give it a try

    Antonio_trade_merge = antonio_trade"space_to_be_removed"[["NAZIV ARTIKLA","EAN CODE",]].append(Dobavljaci[["NAZIV ARTIKLA","EAN CODE"]])

  3. Also there's a difference between merge and append, merge joins 2 tables, append adds all the rows to the other table, so what do you want to do?

Can you show an example output that would be helpful

如何从第一行添加或合并数据FROME FIRST DATAFRAME从11ROW到另一行

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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