玩心态

文章 评论 浏览 30

玩心态 2025-02-20 22:51:42

转到Android> app> build.gradle并删除'apply插件:'kotlin android'''

Go to android>app>build.gradle and delete 'apply plugin: 'kotlin-android''

flutter执行失败的任务':app:dexbuilderdebug'

玩心态 2025-02-20 13:43:24

正确的不符合事件是抓住一个人加入您的不和谐的是:

async def on_member_join(member: discord.Member):

而不是 on_message_join

轻松删除您可以首先使其成为字符串的消息:

msg = await channel.send(embed=embed)

然后获取ID:然后获取它:

msg_id = msg.id

然后删除它:

msg_todel = await channel.fetch_message(int(msg_id))

将其删除:

await msg_todel.delete()

The correct discord event to catch that a person joins your discord is:

async def on_member_join(member: discord.Member):

rather than on_message_join

To easily delete the message you can first make it a string:

msg = await channel.send(embed=embed)

then get it's id by:

msg_id = msg.id

then fetch it:

msg_todel = await channel.fetch_message(int(msg_id))

then delete it:

await msg_todel.delete()

您如何制作一个机器人,在几秒钟后,在Discord.py中删除了受欢迎的嵌入并删除嵌入的嵌入

玩心态 2025-02-20 11:17:35

我喜欢将调度表用于此类事情。从本质上讲,这是一个哈希,其中键是有效的选项,而键的值是一个子例程,在提供有效的选项时可以执行您想做的事情。这样做会消除长长的if/else语句链。

您可以将子例程内联排列在表本身中,也可以引用其他地方定义的子例程。这里的示例显示了这两个:

use warnings;
use strict;

my %table = (
    0   => sub { print "A\n"; },
    1   => sub { print "B\n"; },
    2   => sub { print "C\n"; },
    3   => sub { print "D\n"; },
    4   => \&code_reference_example,
);

for my $pl (0..5) {
    if (exists $table{$pl}) {
        # Put the option into the table and execute
        # the assigned subroutine

        $table{$pl}->();

    } else {
        print "'$pl' is not a valid option\n";
    }
}

sub code_reference_example {
    print "E\n";
}

输出:

A
B
C
D
E
'5' is not a valid option

I like to use dispatch tables for things like this. Essentially it's a hash where the keys are the valid options, and the value of the key is a subroutine that does what you want to do when a valid option is supplied. Doing it this way eliminates a long chain of if/else statements.

You can put the subroutines inline in the table itself, or reference a subroutine defined elsewhere. The example here shows both:

use warnings;
use strict;

my %table = (
    0   => sub { print "A\n"; },
    1   => sub { print "B\n"; },
    2   => sub { print "C\n"; },
    3   => sub { print "D\n"; },
    4   => \&code_reference_example,
);

for my $pl (0..5) {
    if (exists $table{$pl}) {
        # Put the option into the table and execute
        # the assigned subroutine

        $table{$pl}->();

    } else {
        print "'$pl' is not a valid option\n";
    }
}

sub code_reference_example {
    print "E\n";
}

Output:

A
B
C
D
E
'5' is not a valid option

如何重写给定/何时消除“实验”警告使用

玩心态 2025-02-20 09:33:05

(这不是 dt - 特定的,目前尚不清楚这是否是必要的。)

您可以分组或拆分并分配:

library(dplyr)
set.seed(2)
dat <- data.frame(fmt = sample(c("PCT","DOLLAR","NUMBER"), 10, replace = TRUE), value = round(runif(10, 10, 9999), 2))

dat %>%
  group_by(fmt) %>%
  mutate(value2 = switch(fmt[1],
    PCT=scales::percent(value),
    DOLLAR=scales::dollar(value),
    NUMBER=scales::percent(value),
    as.character(value))
  )
# # A tibble: 10 x 3
# # Groups:   fmt [3]
#    fmt    value value2   
#    <chr>  <dbl> <chr>    
#  1 PCT    1816. 181 621% 
#  2 NUMBER 4058. 405 836% 
#  3 DOLLAR 8536. $8,536.10
#  4 DOLLAR 9763. $9,763.24
#  5 PCT    2266. 226 577% 
#  6 PCT    4453. 445 320% 
#  7 PCT     759. 75 897%  
#  8 PCT    6622. 662 171% 
#  9 PCT    3881. 388 123% 
# 10 DOLLAR 8370. $8,369.69

替代方案是使用 case_when 和它会产生非常相似的结果,但一次将工作一个字符串。此方法调用格式函数一次,每组 ,也许更有效。 (如果有必要,请给您。)

(This is not DT-specific, it wasn't clear if that was a requirement.)

You can group or split and assign:

library(dplyr)
set.seed(2)
dat <- data.frame(fmt = sample(c("PCT","DOLLAR","NUMBER"), 10, replace = TRUE), value = round(runif(10, 10, 9999), 2))

dat %>%
  group_by(fmt) %>%
  mutate(value2 = switch(fmt[1],
    PCT=scales::percent(value),
    DOLLAR=scales::dollar(value),
    NUMBER=scales::percent(value),
    as.character(value))
  )
# # A tibble: 10 x 3
# # Groups:   fmt [3]
#    fmt    value value2   
#    <chr>  <dbl> <chr>    
#  1 PCT    1816. 181 621% 
#  2 NUMBER 4058. 405 836% 
#  3 DOLLAR 8536. $8,536.10
#  4 DOLLAR 9763. $9,763.24
#  5 PCT    2266. 226 577% 
#  6 PCT    4453. 445 320% 
#  7 PCT     759. 75 897%  
#  8 PCT    6622. 662 171% 
#  9 PCT    3881. 388 123% 
# 10 DOLLAR 8370. $8,369.69

An alternative would be to use case_when and it would come up with very similar results, but it will be working one string at a time; this method calls the format function once per group, perhaps a bit more efficient. (Over to you if that's necessary.)

r dt(dataTable)中货币,数字和百分比的条件(行)形成(划分)

玩心态 2025-02-19 17:38:14

您可以比较键代码并返回false如果键不是数字,那么在键上您可以验证最小值和最大值,因此可以修改输入的值

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script>
      function handleKeyDown(e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
          e.preventDefault();
          return false;
        }
      }
      function handleKeyUp(e) {
        const v = e?.target?.value || 0;
        if (parseInt(v) === NaN || parseInt(v) < 1) {
          e.target.value = 1;
        } else if (parseInt(v) > 100) {
          e.target.value = 100;
        }
      }
    </script>
  </head>

  <body>
    <input
      type="number"
      min="1"
      max="100"
      onkeydown="handleKeyDown(event)"
      onkeyup="handleKeyUp(event)"
    />
  </body>
</html>

You can compare keyCode and return false if key is not a number, then on key up you can validate min and max value, accordingly modify value of input

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script>
      function handleKeyDown(e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
          e.preventDefault();
          return false;
        }
      }
      function handleKeyUp(e) {
        const v = e?.target?.value || 0;
        if (parseInt(v) === NaN || parseInt(v) < 1) {
          e.target.value = 1;
        } else if (parseInt(v) > 100) {
          e.target.value = 100;
        }
      }
    </script>
  </head>

  <body>
    <input
      type="number"
      min="1"
      max="100"
      onkeydown="handleKeyDown(event)"
      onkeyup="handleKeyUp(event)"
    />
  </body>
</html>

JavaScript输入类型编号检查输入是否为数字

玩心态 2025-02-19 07:32:13

你可以这样做

<script src="https://cdn.tailwindcss.com"></script>
<div class="relative bg-slate-100 flex min-h-screen flex-col justify-center overflow-hidden bg-gray-50 py-6 sm:py-12 space-y-9">
<div class="relative bg-white px-6 pt-10 pb-8 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10">
    <div class="mx-auto max-w-md">
      
      <div class="divide-y divide-gray-300/50">
        <div class="space-y-6 py-8 text-base">
          <p>White Card with all black links:</p>
          <ul class="space-y-4">
            <li class="flex items-center">
              
              <a href="https://tailwindcss.com"> First Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Second Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Third Link</a>
            </li>
          </ul>
          </div>
       
      </div>
    </div>
  </div>


  <div class="relative bg-orange-700 px-6 pt-10 pb-8 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10">
    <div class="mx-auto max-w-md">
      
      <div class="divide-y divide-gray-300/50">
        <div class="space-y-6 py-8 text-base text-white">
          <p>Orange Card with all white links:</p>
          <ul class="space-y-4">
            <li class="flex items-center">
              
              <a href="https://tailwindcss.com"> First Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Second Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Third Link</a>
            </li>
          </ul>
          </div>
       
      </div>
    </div>
  </div>
</div>

YOu can do this way

<script src="https://cdn.tailwindcss.com"></script>
<div class="relative bg-slate-100 flex min-h-screen flex-col justify-center overflow-hidden bg-gray-50 py-6 sm:py-12 space-y-9">
<div class="relative bg-white px-6 pt-10 pb-8 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10">
    <div class="mx-auto max-w-md">
      
      <div class="divide-y divide-gray-300/50">
        <div class="space-y-6 py-8 text-base">
          <p>White Card with all black links:</p>
          <ul class="space-y-4">
            <li class="flex items-center">
              
              <a href="https://tailwindcss.com"> First Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Second Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Third Link</a>
            </li>
          </ul>
          </div>
       
      </div>
    </div>
  </div>


  <div class="relative bg-orange-700 px-6 pt-10 pb-8 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10">
    <div class="mx-auto max-w-md">
      
      <div class="divide-y divide-gray-300/50">
        <div class="space-y-6 py-8 text-base text-white">
          <p>Orange Card with all white links:</p>
          <ul class="space-y-4">
            <li class="flex items-center">
              
              <a href="https://tailwindcss.com"> First Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Second Link</a>
            </li>
            <li class="flex items-center">
              
               <a href="https://tailwindcss.com"> Third Link</a>
            </li>
          </ul>
          </div>
       
      </div>
    </div>
  </div>
</div>

如何使用Tailwind CSS根据父级为嵌套元素样式?

玩心态 2025-02-19 05:48:34

更改

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @EntityGraph(value = "User.profilePic", type = EntityGraphType.FETCH)
    @Query("SELECT u FROM User u WHERE u.email="email")
    User findByEmail(String email);
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @EntityGraph(value = "User.profilePic", type = EntityGraphType.LOAD)
    @Query("SELECT u FROM User u WHERE u.email="email")
    User findByEmail(String email);
}

Change

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @EntityGraph(value = "User.profilePic", type = EntityGraphType.FETCH)
    @Query("SELECT u FROM User u WHERE u.email="email")
    User findByEmail(String email);
}

to

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @EntityGraph(value = "User.profilePic", type = EntityGraphType.LOAD)
    @Query("SELECT u FROM User u WHERE u.email="email")
    User findByEmail(String email);
}

Spring EntityGraphType.Fetch不起作用

玩心态 2025-02-18 23:53:39

准备元素不会使其容器的 scrollleft 增加元素的宽度。

相反, scrollleft 的值保持不变,因此新框有效地“ pops”到视图中:

此处您提到的是, scrollleft 在插入后保持零,鼠标轮的移动不会导致容器的滚动,因此 scroll 未触发,因此框未评估插入逻辑。

例如,可以通过收听 <代码来解决。 >车轮 事件而不是滚动。问题是, scrollleft 仍然保持在零,因此盒子只会一一出现在视图中,而不是让用户滚动到它们上。 demo 。另外,鼠标车轮不是滚动的唯一方法。

因此,根据问题的定义,我们需要手动调整滚动位置,以使视图保持与插入之前相同的元素。在这种情况下,此数量仅仅是 /code> 框的,因此解决方案可以如下:

demo

const boxWidth = document.getElementById("element-0").offsetWidth;
if (element.scrollLeft < 100) {
  element.scrollBy(boxWidth, 0);
  prepend();
}
else if (/*...*/) { 

I hope this answers your question. :)

Prepending an element doesn't make its container's scrollLeft increase by as much as the element's width.

enter image description here

Instead, the scrollLeft's value remains the same, and so the new box effectively "pops" into the view:

enter image description here

Since, as you mentioned, the scrollLeft remains at zero after insertion, further mouse wheel movement doesn't result in the container's scroll, so the scroll event is not fired, and hence the box insertion logic is not evaluated.

That can be solved, for example, by listening for the wheel event rather than the scroll. The problem is, that the scrollLeft would still stay at zero, so the boxes would just appear in the view one by one rather than letting the user scroll onto them. Demo. Plus, the mouse wheel is not the only way to scroll.

As such, by the very definition of the problem, we need to manually adjust the scroll position so that the view remains at the same element as before the insertion. In this case, this amount is simply the offsetWidth of the box, so the solution could be as follows:

Demo

const boxWidth = document.getElementById("element-0").offsetWidth;
if (element.scrollLeft < 100) {
  element.scrollBy(boxWidth, 0);
  prepend();
}
else if (/*...*/) { 

I hope this answers your question. :)

滚动在元素中滚动时跳跃内容/不自然移动的宽度增加

玩心态 2025-02-18 12:52:47

一个可能的解决方案:

m <- matrix(1:9, 3, 3)

sum(colSums(m <= 5) != 0)

#> [1] 2

A possible solution:

m <- matrix(1:9, 3, 3)

sum(colSums(m <= 5) != 0)

#> [1] 2

如何找到包含大于或等于给定数字的值的R矩阵的列数?

玩心态 2025-02-18 12:02:17

我认为通过Web Buddy不可能。

您要做的就是使用网站更新Oneignl中的字段。我认为这不是一个信号,让您做。

I think it's not possible through web buddy.

What you are trying to do is to update a field in onesignl using website. Which i don't think one signal let's you do.

如何使用Web(JS)在OneSignal中设置external_user_id?

玩心态 2025-02-18 08:17:17

您可以精心打印JSON文件,并将其作为参数传递给 YQ 。由于 mikefarah/yq 允许您更新YAML多行,您可以做。

style 对于 appsettings.k8s.k8s.jsons.json 文字上,因此不必修改它,

JSON="$(yq -o=json json_file)" yq '.data."appsettings.k8s.json" = strenv(JSON)' yaml

请使用 -i - Inplace flag即可更新文件Inploph。在版本 4.25.3 上测试

You can pretty-print the JSON file and pass that as an argument to yq. Since mikefarah/yq allows you to update YAML multi-line, you could just do.

The style for the appsettings.k8s.json is already at literal, so it doesn't have to be modified

JSON="$(yq -o=json json_file)" yq '.data."appsettings.k8s.json" = strenv(JSON)' yaml

Use the -i or --inplace flag to update the file inplace. Tested on version 4.25.3

将多行JSON插入YAML

玩心态 2025-02-18 08:08:22

如果您使用的是承诺,则此答案适合您。

这意味着Angularjs,jQuery(带延迟),本机 xhr“> xhr”> xhr href =“ https://en.wikipedia.org/wiki/ember.js” rel =“ noreferrer”> ember.js , backbone.js 's保存或任何 noreferrer“ .js 返回承诺的库。

您的代码应该与此相似:

function foo() {
    var data;
    // Or $.get(...).then, or request(...).then, or query(...).then
    fetch("/echo/json").then(function(response){
        data = response.json();
    });
    return data;
}

var result = foo(); // 'result' is always undefined no matter what.

Felix Kling做得很好为使用jQuery和回调的人写答案。我有一个本地XHR的答案。这个答案是用于对前端或后端上承诺的一般用法。


核心问题

在浏览器和服务器上使用node.js/io.js在服务器中的JavaScript并发模型是 asynchronous 反应性

每当您调用返回诺言的方法时,然后处理程序始终异步执行 - 也就是说, 下方的代码不是在中。然后处理程序。

这意味着,当您返回数据 处理程序尚未执行。反过来,这意味着您要返回的值尚未设置为正确的值。

这是一个简单的类比:

    function getFive(){
        var data;
        setTimeout(function(){ // Set a timer for one second in the future
           data = 5; // After a second, do this
        }, 1000);
        return data;
    }
    document.body.innerHTML = getFive(); // `undefined` here and not 5

data 的值是不确定的,因为 data = 5 零件尚未执行。它可能会在一秒钟内执行,但是到那时,它与返回的值无关。

由于该操作尚未发生(AJAX,服务器调用,I/O和计时器),您在请求有机会告诉您的代码是什么值之前返回值。

解决此问题的一种可能解决方案是代码 ,告诉您的程序完成计算后该怎么办。承诺通过本质上是暂时的(时间敏感)来积极实现这一目标。

快速回顾承诺的

承诺是随时间的价值。承诺有状态。他们从没有价值的待审开始,可以安定下来:

  • 实现意味着计算成功完成。
  • 拒绝意味着计算失败。

诺言只能改变状态 之后,它将永远保持在同一状态。您可以将附加处理程序附加,以承诺提取其价值并处理错误。 然后处理程序允许 chaning> chaning> chaning 。承诺由使用返回它们。例如,更现代的AJAX替换 Fetch 或jQuery的 $。get 返回承诺。

当我们调用。如果我们回报另一个诺言,我们会得到令人惊奇的事情,但让我们握住马匹。

有了承诺,

让我们看看如何通过承诺解决上述问题。首先,让我们通过使用 Promise构造函数用于创建延迟函数:

function delay(ms){ // Takes amount of milliseconds
    // Returns a new promise
    return new Promise(function(resolve, reject){
        setTimeout(function(){ // When the time is up,
            resolve(); // change the promise to the fulfilled state
        }, ms);
    });
}

现在,在我们转换的settimeout 要使用诺言,我们可以使用然后来计算:

function delay(ms){ // Takes amount of milliseconds
  // Returns a new promise
  return new Promise(function(resolve, reject){
    setTimeout(function(){ // When the time is up,
      resolve(); // change the promise to the fulfilled state
    }, ms);
  });
}

function getFive(){
  // We're RETURNING the promise. Remember, a promise is a wrapper over our value
  return delay(100).then(function(){ // When the promise is ready,
      return 5; // return the value 5. Promises are all about return values
  })
}
// We _have_ to wrap it like this in the call site, and we can't access the plain value
getFive().then(function(five){
   document.body.innerHTML = five;
});

基本上,而不是返回 value ,我们由于并发模型而无法做,而是我们返回a wrapper ,以获取我们可以 unwrap <的值/em>带有<代码>然后。就像一个框,您可以使用然后打开。

在原始API调用中应用

此信息相同,您可以:

function foo() {
    // RETURN the promise
    return fetch("/echo/json").then(function(response){
        return response.json(); // Process it inside the `then`
    });
}

foo().then(function(response){
    // Access the value inside the `then`
})

这样也可以。我们已经了解到,我们无法从已经异步的调用中返回值,但是我们可以使用诺言并将其链接来执行处理。现在,我们知道如何从异步呼叫中返回响应。

ES2015(ES6)

ES6引入是可以在中间返回然后恢复其点的功能。例如,这通常对于序列很有用,例如:

function* foo(){ // Notice the star. This is ES6, so new browsers, Nodes.js, and io.js only
    yield 1;
    yield 2;
    while(true) yield 3;
}

是一个函数,该函数可以通过序列返回序列 1,2,3,3,3,3,.... 可以迭代。尽管这本身很有趣,并为很多可能性打开了空间,但有一个特别的案例。

如果我们要产生的序列是一系列动作,而不是数字 - 我们可以在恢复函数之前等待动作并等待该功能。因此,我们需要一个 future 值的序列,而不是数字序列,也就是说:承诺。

这有点棘手,但非常有力的技巧让我们以同步的方式编写异步代码。有几个“跑步者”为您做到这一点。写一条是几行代码,但它超出了该答案的范围。我将在此处使用Bluebird的 Promise.coroutine ,但是还有其他包装器,例如 co <​​/code>或 q.async

var foo = coroutine(function*(){
    var data = yield fetch("/echo/json"); // Notice the yield
    // The code here only executes _after_ the request is done
    return data.json(); // 'data' is defined
});

此方法返回了一个承诺本身,我们可以从其他coroutines中消费。例如:

var main = coroutine(function*(){
   var bar = yield foo(); // Wait our earlier coroutine. It returns a promise
   // The server call is done here, and the code below executes when done
   var baz = yield fetch("/api/users/" + bar.userid); // Depends on foo's result
   console.log(baz); // Runs after both requests are done
});
main();

ES7中的ES2016(ES7)

,这是进一步标准化的。现在有几个建议,但是在所有建议中,您都可以等待承诺。这只是上述ES6提案的“糖”(较好的语法),通过添加 async 等待关键字。进行上面的示例:

async function foo(){
    var data = await fetch("/echo/json"); // Notice the await
    // code here only executes _after_ the request is done
    return data.json(); // 'data' is defined
}

它仍然返回承诺同样的示例:)

If you're using promises, this answer is for you.

This means AngularJS, jQuery (with deferred), native XHR's replacement (fetch), Ember.js, Backbone.js's save or any Node.js library that returns promises.

Your code should be something along the lines of this:

function foo() {
    var data;
    // Or $.get(...).then, or request(...).then, or query(...).then
    fetch("/echo/json").then(function(response){
        data = response.json();
    });
    return data;
}

var result = foo(); // 'result' is always undefined no matter what.

Felix Kling did a fine job writing an answer for people using jQuery with callbacks for Ajax. I have an answer for native XHR. This answer is for generic usage of promises either on the frontend or backend.


The core issue

The JavaScript concurrency model in the browser and on the server with Node.js/io.js is asynchronous and reactive.

Whenever you call a method that returns a promise, the then handlers are always executed asynchronously - that is, after the code below them that is not in a .then handler.

This means when you're returning data the then handler you've defined did not execute yet. This in turn means that the value you're returning has not been set to the correct value in time.

Here is a simple analogy for the issue:

    function getFive(){
        var data;
        setTimeout(function(){ // Set a timer for one second in the future
           data = 5; // After a second, do this
        }, 1000);
        return data;
    }
    document.body.innerHTML = getFive(); // `undefined` here and not 5

The value of data is undefined since the data = 5 part has not executed yet. It will likely execute in a second, but by that time it is irrelevant to the returned value.

Since the operation did not happen yet (Ajax, server call, I/O, and timer) you're returning the value before the request got the chance to tell your code what that value is.

One possible solution to this problem is to code re-actively, telling your program what to do when the calculation completed. Promises actively enable this by being temporal (time-sensitive) in nature.

Quick recap on promises

A Promise is a value over time. Promises have state. They start as pending with no value and can settle to:

  • fulfilled meaning that the computation completed successfully.
  • rejected meaning that the computation failed.

A promise can only change states once after which it will always stay at the same state forever. You can attach then handlers to promises to extract their value and handle errors. then handlers allow chaining of calls. Promises are created by using APIs that return them. For example, the more modern Ajax replacement fetch or jQuery's $.get return promises.

When we call .then on a promise and return something from it - we get a promise for the processed value. If we return another promise we'll get amazing things, but let's hold our horses.

With promises

Let's see how we can solve the above issue with promises. First, let's demonstrate our understanding of promise states from above by using the Promise constructor for creating a delay function:

function delay(ms){ // Takes amount of milliseconds
    // Returns a new promise
    return new Promise(function(resolve, reject){
        setTimeout(function(){ // When the time is up,
            resolve(); // change the promise to the fulfilled state
        }, ms);
    });
}

Now, after we converted setTimeout to use promises, we can use then to make it count:

function delay(ms){ // Takes amount of milliseconds
  // Returns a new promise
  return new Promise(function(resolve, reject){
    setTimeout(function(){ // When the time is up,
      resolve(); // change the promise to the fulfilled state
    }, ms);
  });
}

function getFive(){
  // We're RETURNING the promise. Remember, a promise is a wrapper over our value
  return delay(100).then(function(){ // When the promise is ready,
      return 5; // return the value 5. Promises are all about return values
  })
}
// We _have_ to wrap it like this in the call site, and we can't access the plain value
getFive().then(function(five){
   document.body.innerHTML = five;
});

Basically, instead of returning a value which we can't do because of the concurrency model - we're returning a wrapper for a value that we can unwrap with then. It's like a box you can open with then.

Applying this

This stands the same for your original API call, you can:

function foo() {
    // RETURN the promise
    return fetch("/echo/json").then(function(response){
        return response.json(); // Process it inside the `then`
    });
}

foo().then(function(response){
    // Access the value inside the `then`
})

So this works just as well. We've learned we can't return values from already asynchronous calls, but we can use promises and chain them to perform processing. We now know how to return the response from an asynchronous call.

ES2015 (ES6)

ES6 introduces generators which are functions that can return in the middle and then resume the point they were at. This is typically useful for sequences, for example:

function* foo(){ // Notice the star. This is ES6, so new browsers, Nodes.js, and io.js only
    yield 1;
    yield 2;
    while(true) yield 3;
}

Is a function that returns an iterator over the sequence 1,2,3,3,3,3,.... which can be iterated. While this is interesting on its own and opens room for a lot of possibility, there is one particular interesting case.

If the sequence we're producing is a sequence of actions rather than numbers - we can pause the function whenever an action is yielded and wait for it before we resume the function. So instead of a sequence of numbers, we need a sequence of future values - that is: promises.

This somewhat a tricky, but very powerful trick let’s us write asynchronous code in a synchronous manner. There are several "runners" that do this for you. Writing one is a short few lines of code, but it is beyond the scope of this answer. I'll be using Bluebird's Promise.coroutine here, but there are other wrappers like co or Q.async.

var foo = coroutine(function*(){
    var data = yield fetch("/echo/json"); // Notice the yield
    // The code here only executes _after_ the request is done
    return data.json(); // 'data' is defined
});

This method returns a promise itself, which we can consume from other coroutines. For example:

var main = coroutine(function*(){
   var bar = yield foo(); // Wait our earlier coroutine. It returns a promise
   // The server call is done here, and the code below executes when done
   var baz = yield fetch("/api/users/" + bar.userid); // Depends on foo's result
   console.log(baz); // Runs after both requests are done
});
main();

ES2016 (ES7)

In ES7, this is further standardized. There are several proposals right now, but in all of them you can await promise. This is just "sugar" (nicer syntax) for the ES6 proposal above by adding the async and await keywords. Making the above example:

async function foo(){
    var data = await fetch("/echo/json"); // Notice the await
    // code here only executes _after_ the request is done
    return data.json(); // 'data' is defined
}

It still returns a promise just the same :)

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

玩心态 2025-02-17 19:41:07

我的应用程序, wsa sideloader 是使用Nuitka编译的Pysimplegui程序。这是我使用的命令:

nuitka --standalone sideloader.py --enable-plugin=tk-inter --windows-disable-console

当然,您的主python文件的名称应在standalone之后使用。

请注意,如果需要其他文件才能函数,则需要在编译后将它们添加到DIST文件夹中。

My application, WSA Sideloader is a PySimpleGUI program compiled using Nuitka. This is the command I used:

nuitka --standalone sideloader.py --enable-plugin=tk-inter --windows-disable-console

Of course the name of your main Python file should be used after --standalone.

Note that if it requires other files to function you will need to add them to the dist folder once it's compiled.

nuitka do do do call_function_with_args14&#x27&#x27;错误

玩心态 2025-02-17 15:23:45

您可以简单地做类似的事情:

mapOfPatternCharsIndex.computeIfPresent(listOfPatternChars.get(i), (k,v) -> {v.add(i); return v;} );

You can simply do something like:

mapOfPatternCharsIndex.computeIfPresent(listOfPatternChars.get(i), (k,v) -> {v.add(i); return v;} );

将项目添加到hashmap中的阵列列表中

玩心态 2025-02-17 15:16:42

新的Promise(executor)

执行程序,构造函数要执行的函数。它接收两个函数作为参数:ResolutionFunc和repoctionFunc。执行者中犯下的任何错误都将导致承诺被拒绝,并且返回值将被忽略。执行人的语义在下面详细介绍。

// a promise
let promise1 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved1')}, 4000); 
});
let promise2 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved2')}, 4000); 
});


// async function
async function asyncFunc() {

    // wait until the promise resolves 
    let result1 = await promise1(); 
    console.log(result1);
    let result2 = await promise2(); 
    console.log(result2);

}

// calling the async function
asyncFunc();

承诺1&amp;声明时2已经运行。如果您希望您期望的结果,则应如上所述编码。

new Promise(executor)

executor, A function to be executed by the constructor. It receives two functions as parameters: resolutionFunc and rejectionFunc. Any errors thrown in the executor will cause the promise to be rejected, and the return value will be neglected. The semantics of executor are detailed below.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise

// a promise
let promise1 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved1')}, 4000); 
});
let promise2 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved2')}, 4000); 
});


// async function
async function asyncFunc() {

    // wait until the promise resolves 
    let result1 = await promise1(); 
    console.log(result1);
    let result2 = await promise2(); 
    console.log(result2);

}

// calling the async function
asyncFunc();

The promise 1 & 2 is already running when you declared. If you want result that you expect, you should code as above.

我和异步 - 瓦特混淆了

更多

推荐作者

佚名

文章 0 评论 0

今天

文章 0 评论 0

゛时过境迁

文章 0 评论 0

达拉崩吧

文章 0 评论 0

呆萌少年

文章 0 评论 0

孤者何惧

文章 0 评论 0

更多

友情链接

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