ゃ懵逼小萝莉

文章 评论 浏览 29

ゃ懵逼小萝莉 2025-02-20 06:33:51

我可能会误解您的逻辑,但是看起来您想获得所有false的 gg 值。

如果是这种情况,则不需要使用 shift 列,只需 ffill 数据:

df['gg_shift'] = df['gg'].where(df['bool']).ffill().mask(df['bool'])

输出:

     gg   bool  shift  gg_shift
0  0.88  False      0       NaN
1  0.87   True      0       NaN
2  0.94  False      1      0.87
3  0.17  False      2      0.87
4  0.92   True      0       NaN
5  0.51  False      1      0.92
6  0.10   True      0       NaN
7  0.88  False      1      0.10
8  0.36  False      2      0.10
9  0.14   True      0       NaN

I might be misinterpreting your logic, but it looks like you want to get the gg values of the previous True for all False.

If this is the case you do not need to use the shift column, simply ffill and mask the data:

df['gg_shift'] = df['gg'].where(df['bool']).ffill().mask(df['bool'])

output:

     gg   bool  shift  gg_shift
0  0.88  False      0       NaN
1  0.87   True      0       NaN
2  0.94  False      1      0.87
3  0.17  False      2      0.87
4  0.92   True      0       NaN
5  0.51  False      1      0.92
6  0.10   True      0       NaN
7  0.88  False      1      0.10
8  0.36  False      2      0.10
9  0.14   True      0       NaN

如何将另一列的值用作DF的参数

ゃ懵逼小萝莉 2025-02-20 06:27:00

大o符号只是告诉我们,随着输入大小,算法所花费的时间如何增长。

它只告诉我们花费的时间如何渐近。这意味着您甚至无法得出与另一个输入大小所花费的时间相比,对于一个输入大小所花费的时间。给定一个实现的函数

Big O notation just tells us how the time taken by an algorithm grows as we increase the input size.

It only tells us how the time taken grows asymptotically. This means you cannot even make conclusions about the time taken for one input size compared to the time taken for another input size. Given an implemented function ????, a run of ????(????=100) may even be faster than a run of ????(n=90), whatever the time complexity of that function is.

We can compare only algorithms from two different classes and not from the same class i.e; we can compare O(n^2) with O(n) but not with O(n^2) of some other algorithm.

If you are comparing execution times, then again, the given time complexities tell us nothing concerning the actual execution times of two algorithms. The difference in asymptotic behaviour may only become noticeable in their execution times for input sizes that are impractically large.

We omit the constants as we are only considered about growth.

It is not really about growth -- a function may temporarily show a descending slope for increasing input sizes -- but asymptotic behaviour. When the input size increases towards infinity, a constant eventually becomes irrelevant.

We know that O(10n) is slower than O(n^2) for n<10.

No, we do not know that.

For instance, compare these two algorithms:

Func1(n):
    for i = 1 to 10 * n:
        sleep(1 millisecond)
        
Func2(n):
    for i = 1 to n*n:
        sleep(1 second)

Here Fun1 is O(10????) = O(????) and Func2 is O(????²). Func1 will never be slower than Func2.

One cannot compare two time complexities in terms of "slower".

Then how can we say that the algorithm of order O(n) is always best than O(n^2) without actually considering the constants?

We don't say that. On the contrary, this overhead of constants (and linear coefficients, ...etc) does play a role in deciding which algorithm to use. For instance, this is why quick sort is quite popular, even though there are sorting algorithms whose worst case time complexity is better.

How can we state that the algorithm of time complexity O(n) is always best?

We don't state that. And don't forget there are sub-lineair algorithms, whose time complexity is O(log????), or even O(1).

If we have f(n)=10n^2+5n+6, we omit 10 as the function always increase by a constant 10. But why do we also omit 5n+6 (not constant)? Isn't it significant in function growth?

The part that the lower graded terms play in the function becomes less and less important the higher the value of ????. For instance, when ???? is 10000, the terms 5????+6 only influence the value by 0.005%, and it becomes more and more negligible as we increase ????. Asymptotically it has lost all its impact. And so all that remains is ????²

我们可以使用Big Oh比较算法吗?

ゃ懵逼小萝莉 2025-02-20 03:05:20

不确定我需要做什么。请尝试过滤器proke == 1,groupby and count;

df.query("Stroke==1").groupby('Residence_type')['Stroke'].agg('count').to_frame('Stroke_Count')

          

                   Stroke_Count
Residence_type              
Rural                      3
Urban                      2

如果您需要类别之间的差异,可以尝试以下操作

 df1 =df.query("Stroke==1").groupby('Residence_type')['Stroke'].agg('count').to_frame('Stroke_Count')
df1.loc['Diff'] = abs(df1.loc['Rural']-df1.loc['Urban'])
print(df1)
    

                    Stroke_Count
Residence_type              
Rural                      3
Urban                      2
Diff                       1

Not sure I got what you need done. Please try filter stroke==1, groupby and count;

df.query("Stroke==1").groupby('Residence_type')['Stroke'].agg('count').to_frame('Stroke_Count')

          

                   Stroke_Count
Residence_type              
Rural                      3
Urban                      2

You could try the following if you need the differences between categories

 df1 =df.query("Stroke==1").groupby('Residence_type')['Stroke'].agg('count').to_frame('Stroke_Count')
df1.loc['Diff'] = abs(df1.loc['Rural']-df1.loc['Urban'])
print(df1)
    

                    Stroke_Count
Residence_type              
Rural                      3
Urban                      2
Diff                       1

AttributeError:&#x27; SeriesGroupby&#x27;对象没有属性&#x27; tolist&#x27;

ゃ懵逼小萝莉 2025-02-20 02:05:27

Typescript只是不允许使用对象类型出于类型的安全原因将对象类型索引。

我会提供 colorStomood 一个明确的类型来解决此问题。

const colorsToMood: Partial<Record<TColor, string>> = {
  Red: "Hunger",
  Blue: "Calm"
}

这告诉Typescript, colorStomood 可以用任何 tcolor 成员索引。但是结果可能是未定义的

const resultingMood = colorsToMood[myColor];
//    ^? const resultingMood: string | undefined

游乐场

TypeScript just does not allow indexing of object types with keys that the object type can not have for type safety reasons.

I would give colorsToMood an explicit type to solve this problem.

const colorsToMood: Partial<Record<TColor, string>> = {
  Red: "Hunger",
  Blue: "Calm"
}

This tells TypeScript, that colorsToMood can be indexed with any TColor member. But the result may be undefined.

const resultingMood = colorsToMood[myColor];
//    ^? const resultingMood: string | undefined

Playground

元素隐式具有AN&#x27;任何&#x27;类型是因为类型的表达可以用于索引类型

ゃ懵逼小萝莉 2025-02-19 07:48:54

请修改您的Namesuffix文件:

nameSuffix:
  - path: spec/tls/secretName
    kind: Ingress

此解决问题

Please modify your nameSuffix file to this:

nameSuffix:
  - path: spec/tls/secretName
    kind: Ingress

this fix the problem

kustomize前缀/后缀变压器用于Ingress对象的自定义变量

ゃ懵逼小萝莉 2025-02-18 20:05:29

问题是在Chrome(和基于Chrome的浏览器)中 - 出于某种原因,有时会向我的服务器,有时向其他人提出请求。也许问题是DNS令人耳目一新,但是奇怪的是,即使Firefox已经获得了正确的信息,这种行为也可以连接几个小时。

The trouble was in Chrome (and chrome-based browsers) - for somewhat reason it was make requests sometimes to my server, sometimes to other. Maybe problem was in DNS refreshing, but strange that this behavior cointinues for few hours even after Firefox already get correct info.

nginx不时向我展示404页

ゃ懵逼小萝莉 2025-02-17 18:53:26

→有关使用不同示例的异步行为的更一般说明,请参见 为什么我的变量是在我的变量之后不变的,为什么我将其修改在功能中吗? - 异步代码参考

→如果您已经理解了问题,请跳到以下可能的解决方案。

→如果您已经了解了问题

a in

这是一个类比,希望能使同步和异步流更清晰地之间有所不同:

同步

想象您打电话给朋友,并要求他为您寻找东西。尽管可能需要一段时间,但您在电话上等待太空,直到您的朋友给您所需的答案。

当您进行包含“正常”代码的函数调用时,也会发生同样的情况:

function findItem() {
    var item;
    while(item_not_found) {
        // search
    }
    return item;
}

var item = findItem();

// Do something with item
doSomethingElse();

即使 FindItem 可能需要很长时间才能执行, var item = var item = findItem(); 必须等待,直到函数返回结果。

异步

出于同样的原因, 您再次致电您的朋友。但是这次您告诉他您很着急,他应该在手机上给您回电。您挂断电话,离开房子,做您计划做的任何事情。一旦您的朋友给您回电,您就会处理他给您的信息。

这就是您执行AJAX请求时发生的事情。

findItem(function(item) {
    // Do something with the item
});
doSomethingElse();

执行并没有等待响应,而是立即继续执行,并且执行AJAX调用后的语句。为了最终获得响应,您提供了一个函数,一旦收到响应,a challback (请注意某件事?回电?)。在调用回调之前执行该呼叫之后的任何语句。


解决方案

包含JavaScript!的异步性质,而某些异步操作提供同步的对应物(“ Ajax”也是如此),通常不愿意使用它们,尤其是在浏览器上下文中。

你为什么问不好?

JavaScript在浏览器的UI线程中运行,任何长期运行的过程都会锁定UI,从而使其无反应。此外,JavaScript的执行时间有一个上限,浏览器将询问用户是否继续执行。

所有这些都导致了非常糟糕的用户体验。用户将无法分辨出一切工作正常。此外,对于连接缓慢的用户而言,效果会更糟。

在以下内容中,我们将查看三种彼此之间建立的不同解决方案:

  • 承诺 ynnc/等待 (ES2017++,如果您使用的话,可在较旧的浏览器中使用transpiler或recenerator)
  • 回调(在节点中流行)
  • 承诺 then() (ES2015++)(如果您使用众多浏览器之一)承诺库)

所有这三个都在当前浏览器中可用,节点7+。


es2017+: async/等待

2017年发布的eCmascript版本引入了 stytax-level支持 sandtax-level support s syynchronigonous函数。借助 async 等待,您可以以“同步样式”编写异步。该代码仍然具有异步,但是阅读/理解更容易。

异步/等待在承诺之上构建: async 函数始终返回承诺。 等待“取消包裹”的承诺,并且如果拒绝承诺,则可以解决承诺的价值或丢弃错误。

重要:您只能在 async 函数或 en-us/doc/web/javaScript/guide/模块“ rel =“ noreferrer”> javascript模块。顶级等待在模块之外不支持,因此您可能必须制作一个异步(立即调用函数表达式)启动 async 上下文,如果不使用模块。

您可以阅读有关 noreferrer“> async 等待等待 在MDN上。

这是详细列出 delay 函数 finditem()上面的示例:

// Using 'superagent' which will return a promise.
var superagent = require('superagent')

// This is isn't declared as `async` because it already returns a promise
function delay() {
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {
    // Only `delay` is able to resolve or reject the promise
    setTimeout(function() {
      resolve(42); // After 3 seconds, resolve the promise with value 42
    }, 3000);
  });
}

async function getAllBooks() {
  try {
    // GET a list of book IDs of the current user
    var bookIDs = await superagent.get('/user/books');
    // wait for 3 seconds (just for the sake of this example)
    await delay();
    // GET information about each book
    return superagent.get('/books/ids='+JSON.stringify(bookIDs));
  } catch(error) {
    // If any of the awaited promises was rejected, this catch block
    // would catch the rejection reason
    return null;
  }
}

// Start an IIFE to use `await` at the top level
(async function(){
  let books = await getAllBooks();
  console.log(books);
})();

当前浏览器异步/等待。您还可以在 recenererator 的帮助下,通过将代码转换为ES5来支持旧环境。 ,例如 babel )。


让函数接受回调

一个回调是当函数1传递给函数2时。函数2可以在准备就绪时调用函数1。在异步过程的上下文中,每当完成异步过程时,都会调用回调。通常,结果将传递给回调。

在问题的示例中,您可以进行 foo 接受回调,并将其用作 Success 回调。因此,这

var result = foo();
// Code that depends on 'result'

将成为

foo(function(result) {
    // Code that depends on 'result'
});

这里定义“内联”函数,但是您可以传递任何函数参考:

function myCallback(result) {
    // Code that depends on 'result'
}

foo(myCallback);

foo 本身定义如下:

function foo(callback) {
    $.ajax({
        // ...
        success: callback
    });
}

callback 将参考我们传递给<<<的函数。代码> foo 我们调用它,然后将其传递给 Success 。即,一旦AJAX请求成功, $。ajax 将调用回调,然后将响应传递给回调(可以使用 result> Result 来参考。 ,因为这就是我们定义回调的方式)。

您还可以在将响应传递给回调之前处理:

function foo(callback) {
    $.ajax({
        // ...
        success: function(response) {
            // For example, filter the response
            callback(filtered_response);
        }
    });
}

使用回调编写代码比看起来更容易。毕竟,浏览器中的JavaScript是事件驱动的(DOM事件)。接收Ajax响应只是事件。
当您必须使用第三方代码时,可能会出现困难,但是只要考虑应用程序流程,就可以解决大多数问题。


ES2015+:

the a href =“ https://developer.mozilla.org/en-us/docs/web/javascript/Reference/global_object/global_objects/promise” rel =“ noreferrer”> Promise api ES2015),但它具有良好的浏览器支持也有许多库可以实现标准承诺API并提供其他方法来减轻异步功能的使用和组成(例如,)。

承诺是未来值的容器。当承诺收到值(已解决的)或取消(拒绝)时,它会通知所有想访问此值的“听众”。

比普通回调的优势在于,它们允许您将代码解除,并且更容易撰写。

这是使用承诺的示例:

function delay() {
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {
    // Only `delay` is able to resolve or reject the promise
    setTimeout(function() {
      resolve(42); // After 3 seconds, resolve the promise with value 42
    }, 3000);
  });
}

delay()
  .then(function(v) { // `delay` returns a promise
    console.log(v); // Log the value once it is resolved
  })
  .catch(function(v) {
    // Or do something else if it is rejected
    // (it would not happen in this example, since `reject` is not called).
  });
.as-console-wrapper { max-height: 100% !important; top: 0; }

应用于我们的Ajax电话,我们可以使用这样的承诺:

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

ajax("https://jsonplaceholder.typicode.com/todos/1")
  .then(function(result) {
    console.log(result); // Code depending on result
  })
  .catch(function() {
    // An error occurred
  });
.as-console-wrapper { max-height: 100% !important; top: 0; }

描述承诺提供的所有优势超出了此答案的范围,但是如果您编写新代码,则应认真考虑它们。它们提供了很好的抽象和您的代码分离。

有关承诺的更多信息: html5 rocks -javascript Promises promises

旁注:jQuery的延期对象

延迟对象标准化)。他们的行为几乎像承诺,但暴露了略有不同的API。

jQuery的每种AJAX方法已经返回一个“递延对象”(实际上是递延对象的承诺),您可以从函数中返回:

function ajax() {
    return $.ajax(...);
}

ajax().done(function(result) {
    // Code depending on result
}).fail(function() {
    // An error occurred
});

侧面注意:promise gotchas new Chep

牢记承诺和递延对象只是容器 /em>对于未来的价值,它们不是价值本身。例如,假设您有以下内容:

function checkPassword() {
    return $.ajax({
        url: '/password',
        data: {
            username: $('#username').val(),
            password: $('#password').val()
        },
        type: 'POST',
        dataType: 'json'
    });
}

if (checkPassword()) {
    // Tell the user they're logged in
}

此代码误解了上述异步问题。具体来说, $。ajax()在检查服务器上的“/密码”页面时不会冻结代码 - 它将请求发送到服务器,并且在等待时,它立即返回jQuery AJAX递延对象,而不是服务器的响应。这意味着如果语句将始终获取此延期对象,请将其视为 true ,然后继续以用户登录。不好。

但是修复程序很容易:

checkPassword()
.done(function(r) {
    if (r) {
        // Tell the user they're logged in
    } else {
        // Tell the user their password was bad
    }
})
.fail(function(x) {
    // Tell the user something bad happened
});

不推荐:我提到的同步“ ajax”调用

,一些(!)异步操作具有同步的对应物。我不主张他们的用法,但为了完整的缘故,这是您执行同步呼叫的方式:

如果

直接使用 xmlhttprequest 对象,将 false 作为第三个参数作为 .open

jQuery

如果您使用 jquery ,您可以设置 async 选项 false 。请注意,由于jQuery 1.8,此选项是弃用
然后,您可以仍然使用成功回调,或访问 ResponseText jqxhr对象

function foo() {
    var jqXHR = $.ajax({
        //...
        async: false
    });
    return jqXHR.responseText;
}

如果您使用任何其他jQuery ajax方法,例如 $。get , $。 ,您必须将其更改为 $。ajax (因为您只能将配置参数传递到 $。ajax )。

抬头!无法同步 jsonp 请求。 JSONP本质上总是异步的(甚至不考虑此选项的另一个原因)。

→ For a more general explanation of asynchronous behaviour with different examples, see Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

→ If you already understand the problem, skip to the possible solutions below.

The problem

The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.

Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer:

Synchronous

Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer that you needed.

The same is happening when you make a function call containing "normal" code:

function findItem() {
    var item;
    while(item_not_found) {
        // search
    }
    return item;
}

var item = findItem();

// Do something with item
doSomethingElse();

Even though findItem might take a long time to execute, any code coming after var item = findItem(); has to wait until the function returns the result.

Asynchronous

You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house, and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.

That's exactly what's happening when you do an Ajax request.

findItem(function(item) {
    // Do something with the item
});
doSomethingElse();

Instead of waiting for the response, the execution continues immediately and the statement after the Ajax call is executed. To get the response eventually, you provide a function to be called once the response was received, a callback (notice something? call back ?). Any statement coming after that call is executed before the callback is called.


Solution(s)

Embrace the asynchronous nature of JavaScript! While certain asynchronous operations provide synchronous counterparts (so does "Ajax"), it's generally discouraged to use them, especially in a browser context.

Why is it bad do you ask?

JavaScript runs in the UI thread of the browser and any long-running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not.

All of this results in a really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore, the effect will be worse for users with a slow connection.

In the following we will look at three different solutions that are all building on top of each other:

  • Promises with async/await (ES2017+, available in older browsers if you use a transpiler or regenerator)
  • Callbacks (popular in node)
  • Promises with then() (ES2015+, available in older browsers if you use one of the many promise libraries)

All three are available in current browsers, and node 7+.


ES2017+: Promises with async/await

The ECMAScript version released in 2017 introduced syntax-level support for asynchronous functions. With the help of async and await, you can write asynchronous in a "synchronous style". The code is still asynchronous, but it's easier to read/understand.

async/await builds on top of promises: an async function always returns a promise. await "unwraps" a promise and either result in the value the promise was resolved with or throws an error if the promise was rejected.

Important: You can only use await inside an async function or in a JavaScript module. Top-level await is not supported outside of modules, so you might have to make an async IIFE (Immediately Invoked Function Expression) to start an async context if not using a module.

You can read more about async and await on MDN.

Here is an example that elaborates the delay function findItem() above:

// Using 'superagent' which will return a promise.
var superagent = require('superagent')

// This is isn't declared as `async` because it already returns a promise
function delay() {
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {
    // Only `delay` is able to resolve or reject the promise
    setTimeout(function() {
      resolve(42); // After 3 seconds, resolve the promise with value 42
    }, 3000);
  });
}

async function getAllBooks() {
  try {
    // GET a list of book IDs of the current user
    var bookIDs = await superagent.get('/user/books');
    // wait for 3 seconds (just for the sake of this example)
    await delay();
    // GET information about each book
    return superagent.get('/books/ids='+JSON.stringify(bookIDs));
  } catch(error) {
    // If any of the awaited promises was rejected, this catch block
    // would catch the rejection reason
    return null;
  }
}

// Start an IIFE to use `await` at the top level
(async function(){
  let books = await getAllBooks();
  console.log(books);
})();

Current browser and node versions support async/await. You can also support older environments by transforming your code to ES5 with the help of regenerator (or tools that use regenerator, such as Babel).


Let functions accept callbacks

A callback is when function 1 is passed to function 2. Function 2 can call function 1 whenever it is ready. In the context of an asynchronous process, the callback will be called whenever the asynchronous process is done. Usually, the result is passed to the callback.

In the example of the question, you can make foo accept a callback and use it as success callback. So this

var result = foo();
// Code that depends on 'result'

becomes

foo(function(result) {
    // Code that depends on 'result'
});

Here we defined the function "inline" but you can pass any function reference:

function myCallback(result) {
    // Code that depends on 'result'
}

foo(myCallback);

foo itself is defined as follows:

function foo(callback) {
    $.ajax({
        // ...
        success: callback
    });
}

callback will refer to the function we pass to foo when we call it and we pass it on to success. I.e. once the Ajax request is successful, $.ajax will call callback and pass the response to the callback (which can be referred to with result, since this is how we defined the callback).

You can also process the response before passing it to the callback:

function foo(callback) {
    $.ajax({
        // ...
        success: function(response) {
            // For example, filter the response
            callback(filtered_response);
        }
    });
}

It's easier to write code using callbacks than it may seem. After all, JavaScript in the browser is heavily event-driven (DOM events). Receiving the Ajax response is nothing else but an event.
Difficulties could arise when you have to work with third-party code, but most problems can be solved by just thinking through the application flow.


ES2015+: Promises with then()

The Promise API is a new feature of ECMAScript 6 (ES2015), but it has good browser support already. There are also many libraries which implement the standard Promises API and provide additional methods to ease the use and composition of asynchronous functions (e.g., bluebird).

Promises are containers for future values. When the promise receives the value (it is resolved) or when it is canceled (rejected), it notifies all of its "listeners" who want to access this value.

The advantage over plain callbacks is that they allow you to decouple your code and they are easier to compose.

Here is an example of using a promise:

function delay() {
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {
    // Only `delay` is able to resolve or reject the promise
    setTimeout(function() {
      resolve(42); // After 3 seconds, resolve the promise with value 42
    }, 3000);
  });
}

delay()
  .then(function(v) { // `delay` returns a promise
    console.log(v); // Log the value once it is resolved
  })
  .catch(function(v) {
    // Or do something else if it is rejected
    // (it would not happen in this example, since `reject` is not called).
  });
.as-console-wrapper { max-height: 100% !important; top: 0; }

Applied to our Ajax call we could use promises like this:

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

ajax("https://jsonplaceholder.typicode.com/todos/1")
  .then(function(result) {
    console.log(result); // Code depending on result
  })
  .catch(function() {
    // An error occurred
  });
.as-console-wrapper { max-height: 100% !important; top: 0; }

Describing all the advantages that promise offer is beyond the scope of this answer, but if you write new code, you should seriously consider them. They provide a great abstraction and separation of your code.

More information about promises: HTML5 rocks - JavaScript Promises.

Side note: jQuery's deferred objects

Deferred objects are jQuery's custom implementation of promises (before the Promise API was standardized). They behave almost like promises but expose a slightly different API.

Every Ajax method of jQuery already returns a "deferred object" (actually a promise of a deferred object) which you can just return from your function:

function ajax() {
    return $.ajax(...);
}

ajax().done(function(result) {
    // Code depending on result
}).fail(function() {
    // An error occurred
});

Side note: Promise gotchas

Keep in mind that promises and deferred objects are just containers for a future value, they are not the value itself. For example, suppose you had the following:

function checkPassword() {
    return $.ajax({
        url: '/password',
        data: {
            username: $('#username').val(),
            password: $('#password').val()
        },
        type: 'POST',
        dataType: 'json'
    });
}

if (checkPassword()) {
    // Tell the user they're logged in
}

This code misunderstands the above asynchronous issues. Specifically, $.ajax() doesn't freeze the code while it checks the '/password' page on your server - it sends a request to the server and while it waits, it immediately returns a jQuery Ajax Deferred object, not the response from the server. That means the if statement is going to always get this Deferred object, treat it as true, and proceed as though the user is logged in. Not good.

But the fix is easy:

checkPassword()
.done(function(r) {
    if (r) {
        // Tell the user they're logged in
    } else {
        // Tell the user their password was bad
    }
})
.fail(function(x) {
    // Tell the user something bad happened
});

Not recommended: Synchronous "Ajax" calls

As I mentioned, some(!) asynchronous operations have synchronous counterparts. I don't advocate their use, but for completeness' sake, here is how you would perform a synchronous call:

Without jQuery

If you directly use a XMLHttpRequest object, pass false as third argument to .open.

jQuery

If you use jQuery, you can set the async option to false. Note that this option is deprecated since jQuery 1.8.
You can then either still use a success callback or access the responseText property of the jqXHR object:

function foo() {
    var jqXHR = $.ajax({
        //...
        async: false
    });
    return jqXHR.responseText;
}

If you use any other jQuery Ajax method, such as $.get, $.getJSON, etc., you have to change it to $.ajax (since you can only pass configuration parameters to $.ajax).

Heads up! It is not possible to make a synchronous JSONP request. JSONP by its very nature is always asynchronous (one more reason to not even consider this option).

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

ゃ懵逼小萝莉 2025-02-17 13:26:39

您可以按以下方式使用Invoke-Command

Invoke-Command -ComputerName $env:COMPUTERNAME  -ScriptBlock { [Security.Principal.WindowsIdentity]::GetCurrent().Name} -Credential domain\user

,该行可以使您可以运行此脚本

[Security.Principal.WindowsIdentity]::GetCurrent().Name

You can use the invoke-command as follows

Invoke-Command -ComputerName $env:COMPUTERNAME  -ScriptBlock { [Security.Principal.WindowsIdentity]::GetCurrent().Name} -Credential domain\user

by the way, the line gives you the user to run this script

[Security.Principal.WindowsIdentity]::GetCurrent().Name

使用PowerShell登录自动化

ゃ懵逼小萝莉 2025-02-17 07:20:35

您可以通过将元标记更改为以下内容来添加不安全inline 。但是,我建议将其保持相同,只是通过单独的文件加载JS,因为更改标签会增加一些安全风险。由于某种原因,它被称为不安全

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
    <title>Hello World!</title>
  </head>
  <body>
    <script>
      console.log("Hello World"); // <-- this is the line causing problems
    </script>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

You can add unsafe-inline by changing your meta tag to the following. However I'd suggest keeping it the same and just load JS via a separate file since changing the tag adds some security risks. It's called unsafe for a reason.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
    <title>Hello World!</title>
  </head>
  <body>
    <script>
      console.log("Hello World"); // <-- this is the line causing problems
    </script>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

如何添加不安全的内线&#x27;运行内联JavaScript的关键字?

ゃ懵逼小萝莉 2025-02-16 21:36:18

选择合适的技术高度取决于与您的SLA相关的事物。诸如您的查询能有延迟多少?您的查询类型是什么?您的数据是否归类为大数据?数据可更新吗?我们期待晚期事件吗?我们将来是否需要历史数据,还是可以使用越野等技术?和这样的事情。为了澄清我的答案,可能是使用窗口功能可以解决问题。例如,您可以将数据存储在您提到的任何工具上,并使用Presto SQL引擎,您可以查询并获得所需的结果。但是并非所有人都是最佳的。此外,通常无法使用单个工具来解决这类问题。一组工具可以满足所有要求。

tl; dr。在下文中,我们找不到解决方案。它介绍了一种思考数据建模和选择工具的方法。

让我尝试对问题进行建模以选择单个工具。我认为您的数据无法更新,您需要一个较低的延迟响应时间,我们不会期望任何迟到事件,我们将面临必须将其保存为原始数据的大量数据流。

  • 根据第一个和第二个要求,至关重要的是随机访问(似乎您想在特定ID上查询),因此诸如Parquet或orc文件之类的解决方案不是一个不错的选择。
  • 基于最后的要求,必须基于ID对数据进行分区。第一个和第二个要求和最后的要求,都将ID视为标识符部分,看来没有其他字段(例如时间)像加入和全局订购一样。因此,我们可以选择ID作为分区器(物理或逻辑)和 atime 作为群集部分;对于每个ID,根据时间订购事件。
  • 第三个要求有点模糊。您想产生所有数据吗?还是每个ID?
  • 为了计算前三个条件,我们需要一个支持窗口功能的工具。

根据上述注释,似乎我们应该选择一个对随机访问查询有良好支持的工具。 Cassandra,Postgres,Druid,MongoDB和Elasticsearch等工具是我记得的事物。让我们检查一下:

  • Cassandra:在随机访问查询上的响应时间非常好,可以轻松处理大量数据,并且没有单个失败点。但是可悲的是,它不支持窗口功能。另外,您应该仔细设计数据模型,似乎这不是我们可以选择的好工具(由于未来需要原始数据)。我们可以通过与卡桑德拉(Cassandra)一起使用Spark绕过其中的一些限制,但是目前,我们更喜欢避免在堆栈中添加新工具。
  • Postgres:在随机访问查询和索引列上很棒。它支持窗口功能。我们可以将多个服务器的数据(水平分区)分解(通过选择ID作为碎片键,我们可以在计算上具有数据位置)。但是有一个问题:ID并非唯一;因此,我们不能选择ID作为主键,并且我们在随机访问中遇到了一些问题(我们可以选择ID和 atime 列(作为时间戳列)作为复合主键,但没有拯救我们)。
  • 德鲁伊:这是一个很棒的OLAP工具。根据DRUID的存储方式(段文件),通过选择正确的数据模型,您可以在子秒中对大量数据进行分析查询。它不支持窗口功能,但是使用汇总和其他功能(例如最早的),我们可以回答我们的问题。但是,通过使用汇总,我们会丢失原始数据,我们需要它们。
  • MongoDB:它支持随机访问查询和碎片。另外,我们可以在其计算框架上具有某种类型的窗口函数,我们可以定义某种用于进行聚合的管道。它支持上限收集,如果ID列的基数不高,我们可以使用它来存储每个ID的最后10个事件。看来此工具可以涵盖我们的所有要求。
  • Elasticsearch:这对于随机访问非常好,也许是最伟大的。使用某种过滤器聚合,我们可以具有一种窗口函数。它可以通过碎片处理大量数据。但是它的查询语言很难。我可以想象我们可以用ES回答第一个和第二个问题,但是就目前而言,我无法在我的脑海中进行查询。与之找到正确的解决方案需要时间。

因此,MongoDB和Elasticsearch似乎可以回答我们的要求,但是有很多'如果在路上。我认为我们找不到使用单个工具的直接解决方案。也许我们应该选择多种工具,并使用复制数据之类的技术来找到最佳解决方案。

Choosing the right technology is highly dependent on things related to your SLA. things like how much can your query have latency? what are your query types? is your data categorized as big data or not? Is data updateable? Do we expect late events? Do we need historical data in the future or we can use techniques like rollup? and things like that. To clarify my answer, probably by using window functions you can solve your problems. For example, you can store your data on any of the tools you mentioned and by using the Presto SQL engine you can query and get your desired result. But not all of them are optimal. Furthermore, usually, these kinds of problems can not be solved with a single tool. A set of tools can cover all requirements.

tl;dr. In the below text we don't find a solution. It introduces a way to think about data modeling and choosing tools.

Let me take try to model the problem to choose a single tool. I assume your data is not updatable, you need a low latency response time, we don't expect any late event and we face a large volume data stream that must be saved as raw data.

  • Based on the first and second requirements, it's crucial to have random access (it seems you wanna query on a particular ID), so solutions like parquet or ORC files are not a good choice.
  • Based on the last requirement, data must be partitioned based on the ID. Both the first and second requirements and the last requirement, count on ID as an identifier part and it seems there is nothing like join and global ordering based on other fields like time. So we can choose ID as the partitioner (physical or logical) and atime as the cluster part; For each ID, events are ordered based on the time.
  • The third requirement is a bit vague. You wanna result on all data? or for each ID?
  • For computing the first three conditions, we need a tool that supports window functions.

Based on the mentioned notes, it seems we should choose a tool that has good support for random access queries. Tools like Cassandra, Postgres, Druid, MongoDB, and ElasticSearch are things that currently I can remember them. Let's check them:

  • Cassandra: It's great on response time on random access queries, can handle a huge amount of data easily, and does not have a single point of failure. But sadly it does not support window functions. Also, you should carefully design your data model and it seems it's not a good tool that we can choose (because of future need for raw data). We can bypass some of these limitations by using Spark alongside Cassandra, but for now, we prefer to avoid adding a new tool to our stack.
  • Postgres: It's great on random access queries and indexed columns. It supports window functions. We can shard data (horizontal partitioning) across multiple servers (and by choosing ID as the shard key, we can have data locality on computations). But there is a problem: ID is not unique; so we can not choose ID as the primary key and we face some problems with random access (We can choose the ID and atime columns (as a timestamp column) as a compound primary key, but it does not save us).
  • Druid: It's a great OLAP tool. Based on the storing manner (segment files) that Druid follows, by choosing the right data model, you can have analytic queries on a huge volume of data in sub-seconds. It does not support window functions, but with rollup and some other functions (like EARLIEST), we can answer our questions. But by using rollup, we lose raw data and we need them.
  • MongoDB: It supports random access queries and sharding. Also, we can have some type of window function on its computing framework and we can define some sort of pipelines for doing aggregations. It supports capped collections and we can use it to store the last 10 events for each ID if the cardinality of the ID column is not high. It seems this tool can cover all of our requirements.
  • ElasticSearch: It's great on random access, maybe the greatest. With some kind of filter aggregations, we can have a type of window function. It can handle a large amount of data with sharding. But its query language is hard. I can imagine we can answer the first and second questions with ES, but for now, I can't make a query in my mind. It takes time to find the right solution with it.

So it seems MongoDB and ElasticSearch can answer our requirements, but there is a lot of 'if's on the way. I think we can't find a straightforward solution with a single tool. Maybe we should choose multiple tools and use techniques like duplicating data to find an optimal solution.

我如何找到正确的数据设计和正确的工具/数据库/查询以下要求

ゃ懵逼小萝莉 2025-02-16 20:10:27

是否可以从Azure Portal给我的Azure函数访问权限以从Azure Pipeline访问管道伪像?

?如文档

IE

- task: AzureWebApp@1
  inputs:
    azureSubscription: '<Azure service connection>'
    appType: 'webAppLinux'
    appName: '<Name of web app>'
    package: '$(System.DefaultWorkingDirectory)/**/*.zip'

Is it possible to give access permissions to my Azure function from Azure Portal to access the pipeline artifacts from Azure Pipeline?

No.

Typically, you don't use an ARM template to deploy your application, you use a continuous delivery pipeline that pushes the changes out to the site, as explained in the documentation.

i.e.

- task: AzureWebApp@1
  inputs:
    azureSubscription: '<Azure service connection>'
    appType: 'webAppLinux'
    appName: '<Name of web app>'
    package: '$(System.DefaultWorkingDirectory)/**/*.zip'

从Azure功能中访问Devops Azure管道工件

ゃ懵逼小萝莉 2025-02-16 04:57:11

$ ordersponse 包含运输地址: print_r($ ordersponse-&gt;结果

- var_dump(); 当项目离主要一个太远时,它将“ ...”:

因为这是我发现的唯一 address> array/object narray/object在 $ unerizationResponse 中,但仅包含 country_code

The $orderResponse contains the shipping address : print_r($orderResponse->result->purchase_units[0]->shipping->address);

I was using var_dump(); which when the item is too far from the main one puts "..." :

Because of that the only address array/object I found was in the $authorizationResponse but it would of contain only the country_code.

使用PayPal签到PHP SDK时,是否可以获取买家的地址?

ゃ懵逼小萝莉 2025-02-16 04:37:02

我发现了最终如何做!
感谢您的所有有用的评论,它可以帮助我找到解决问题的解决方案。
这是我的代码:

#define VIDEO_MEMORY 0xb8000

void PrintS(char *text, char color)
{
    char *currentAddressVRAM = (char *)VIDEO_MEMORY;
    for (int i = 0; 1; i++)
    {
        if (text[i] == '\0')
        {
            break;
        }
        *currentAddressVRAM++ = text[i];
        *currentAddressVRAM++ = color;
    }
}

唯一的问题是我不知道如何在功能的使用之间保存当前地址。如果有人知道,请告诉我!

I found out how to do it finally!
Thanks for all of your helpful comments, it help me find the solution to my problem.
Here is my code :

#define VIDEO_MEMORY 0xb8000

void PrintS(char *text, char color)
{
    char *currentAddressVRAM = (char *)VIDEO_MEMORY;
    for (int i = 0; 1; i++)
    {
        if (text[i] == '\0')
        {
            break;
        }
        *currentAddressVRAM++ = text[i];
        *currentAddressVRAM++ = color;
    }
}

The only problem with this is that I don't know how to save the current address between the uses of the function. If somebody knows, please let me know!

C:写入视频公羊

ゃ懵逼小萝莉 2025-02-15 16:27:57

您可以使用案例

 创建table2(column1 int,column2 varchar(10))
 
 插入表2值(1,'value1'),(2,'value1'),(13,'value2'),(44,'value2')
 
 创建table1(column1 int)
 
 插入表1值(1),(2),(13),(44)
 
 选择 * 
  来自Table1 T1 
       加入T1.Column1 = T2.Column1上的Table2 T2
 在哪里 
 当t1.column1在1到10和t2.column2之间的情况下
  当t1.column1在11到20和T2.Column2中像'value2'一样
 否则错误的结尾
 
 column1 |列1 |列2
------:| ------:| :-------
      1 | 1 | Value1 
      2 | 2 | Value1 
     13 | 13 | Value2 

db&lt;&gt;&gt;

You could use a case when aproach

CREATE tABLE table2(column1 int, column2 varchar(10))
INSERT INTO table2 VALUEs(1,'value1'),(2,'value1'),(13,'value2'),(44,'value2')
CREATE tABLE table1(column1 int)
INSERT INTO table1 VALUES (1),(2),(13),(44)
select * 
  from table1 t1 
       join table2 t2 on t1.column1=t2.column1
 where 
 CASE WHEN t1.column1 between 1 and 10 AND t2.column2 like 'value1' THEN TRUE
  WHEN t1.column1 between 11 and 20 AND t2.column2 like 'value2' THEN TRUE
 ELSE FALSE END
column1 | column1 | column2
------: | ------: | :------
      1 |       1 | value1 
      2 |       2 | value1 
     13 |      13 | value2 

db<>fiddle here

如果sql中的条件

ゃ懵逼小萝莉 2025-02-15 14:49:31

您可以通过在脚本区域中添加以下cdn来使用同位JS库:

      <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>

您仍然可以使用嵌套的画廊结构并使用同位素使用数据过滤器,也可以使用同位素,也可以正确地显示一个旁边的图像,当然也可以显示一个extrestope。仍将具有不会受到影响的相同网格结构。

<div class="container text-center pt-5">
<div class="row">
<div class="col-md-12">
  <div class="filters">
    <h4>Featured categories</h4>
    <ul>
      <li data-filter=".idea">Furniture <img class="dot" src="./images/dot.svg" 
      alt=""></li>
      <li data-filter=".ui">lighting <img class="dot" src="./images/dot.svg" 
      alt=""></li>
      <li data-filter=".ux">Accessories <img class="dot" src="./images/dot.svg" 
      alt=""></li>
      <li data-filter=".code">Tailor-made objects <img class="dot" 
      src="./images/dot.svg" alt=""></li>
      <li class="is-checked fp" data-filter="*">All</li>
    </ul>
  </div>
</div>

<div class="col-md-12">
  <div class="rows grid data-isotope='{ "itemSelector": ".grid-item", "masonry": 
    { "columnWidth": 200 } }'">
    <div class="col-md-12 grid-item code">
      <img class="img-fluid" src="./images/01.jpg" alt="">
    </div>
       <div class="col-md-4 grid-item ux ">
      <img class="img-fluid img-grid" src="./images/02.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ui">
      <img class="img-fluid img-grid" src="./images/03.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item idea">
      <img class="img-fluid img-grid" src="./images/04.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ux ">
      <img class="img-fluid img-grid" src="./images/02.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ui">
      <img class="img-fluid img-grid" src="./images/03.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item idea">
      <img class="img-fluid img-grid" src="./images/04.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ux ">
      <img class="img-fluid img-grid" src="./images/02.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ui">
      <img class="img-fluid img-grid" src="./images/03.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item idea">
      <img class="img-fluid img-grid" src="./images/04.jpg" alt="">
    </div>
  </div>
</div>

并使用以下脚本以及

var $grid = $('.grid').isotope({
// options
itemSelector: '.grid-item',
layoutMode: 'fitRows',
});

 // change is-checked class on buttons
 var $buttonGroup = $('.filters');
 $buttonGroup.on( 'click', 'li', function( event ) {
 $buttonGroup.find('.is-checked').removeClass('is-checked');
 var $button = $( event.currentTarget );
 $button.addClass('is-checked');
 var filterValue = $button.attr('data-filter');
 $grid.isotope({ filter: filterValue });
 });

好运

You can simply use isotop js library by adding the following cdn to your script area :

      <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>

You can still have the nested gallery structure and use the data filter by using isotope, also the filtered images will show properly one beside the other, and of course you will still have the same grid structure that will not be affected.

<div class="container text-center pt-5">
<div class="row">
<div class="col-md-12">
  <div class="filters">
    <h4>Featured categories</h4>
    <ul>
      <li data-filter=".idea">Furniture <img class="dot" src="./images/dot.svg" 
      alt=""></li>
      <li data-filter=".ui">lighting <img class="dot" src="./images/dot.svg" 
      alt=""></li>
      <li data-filter=".ux">Accessories <img class="dot" src="./images/dot.svg" 
      alt=""></li>
      <li data-filter=".code">Tailor-made objects <img class="dot" 
      src="./images/dot.svg" alt=""></li>
      <li class="is-checked fp" data-filter="*">All</li>
    </ul>
  </div>
</div>

<div class="col-md-12">
  <div class="rows grid data-isotope='{ "itemSelector": ".grid-item", "masonry": 
    { "columnWidth": 200 } }'">
    <div class="col-md-12 grid-item code">
      <img class="img-fluid" src="./images/01.jpg" alt="">
    </div>
       <div class="col-md-4 grid-item ux ">
      <img class="img-fluid img-grid" src="./images/02.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ui">
      <img class="img-fluid img-grid" src="./images/03.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item idea">
      <img class="img-fluid img-grid" src="./images/04.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ux ">
      <img class="img-fluid img-grid" src="./images/02.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ui">
      <img class="img-fluid img-grid" src="./images/03.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item idea">
      <img class="img-fluid img-grid" src="./images/04.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ux ">
      <img class="img-fluid img-grid" src="./images/02.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item ui">
      <img class="img-fluid img-grid" src="./images/03.jpg" alt="">
    </div>
    <div class="col-md-4 grid-item idea">
      <img class="img-fluid img-grid" src="./images/04.jpg" alt="">
    </div>
  </div>
</div>

and use the following script as well

var $grid = $('.grid').isotope({
// options
itemSelector: '.grid-item',
layoutMode: 'fitRows',
});

 // change is-checked class on buttons
 var $buttonGroup = $('.filters');
 $buttonGroup.on( 'click', 'li', function( event ) {
 $buttonGroup.find('.is-checked').removeClass('is-checked');
 var $button = $( event.currentTarget );
 $button.addClass('is-checked');
 var filterValue = $button.attr('data-filter');
 $grid.isotope({ filter: filterValue });
 });

Best of luck

是否可以将数据过滤器调整到定义的网格中,以便所有图像出现在COL-12中或特定尺寸?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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