懷念過去

文章 评论 浏览 29

懷念過去 2025-02-21 00:24:08

我编写的以下示例显示了如何

  • 处理异步HTTP调用;
  • 等待每个API呼叫的响应;
  • 使用 promise 模式;
  • 使用

这个工作示例是独立的。它将定义一个简单的请求对象,该对象使用窗口 xmlhttprequest 对象进行呼叫。它将定义一个简单的功能,以等待一堆诺言要完成。

语境。该示例是查询 spotify web api 端点以搜索播放列表给定的查询字符串的对象:

[
 "search?type=playlist&q=%22doom%20metal%22",
 "search?type=playlist&q=Adele"
]

对于每个项目,一个新的承诺将发射一个块 - executionBlock ,解析结果,根据结果数组安排一组新的承诺,即Spotify user 对象的列表,并在 executionProfileBlock ynchronChronical中执行新的HTTP调用。

然后,您可以看到一个嵌套的承诺结构,该结构使您可以产生多个和完全异步的嵌套HTTP调用,并通过 Promise.all 从每个呼叫的每个子集中加入每个子集的结果。

注意
最近的Spotify 搜索 API需要在请求标题中指定访问令牌:

-H "Authorization: Bearer {your access token}" 

因此,您要运行以下示例,需要将访问令牌放在请求标题中:

var spotifyAccessToken = "YourSpotifyAccessToken";
var console = {
    log: function(s) {
        document.getElementById("console").innerHTML += s + "<br/>"
    }
}

// Simple XMLHttpRequest
// based on https://davidwalsh.name/xmlhttprequest
SimpleRequest = {
    call: function(what, response) {
        var request;
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            request = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // Internet Explorer
            try {
                request = new ActiveXObject('Msxml2.XMLHTTP');
            }
            catch (e) {
                try {
                  request = new ActiveXObject('Microsoft.XMLHTTP');
                } catch (e) {}
            }
        }

        // State changes
        request.onreadystatechange = function() {
            if (request.readyState === 4) { // Done
                if (request.status === 200) { // Complete
                    response(request.responseText)
                }
                else
                    response();
            }
        }
        request.open('GET', what, true);
        request.setRequestHeader("Authorization", "Bearer " + spotifyAccessToken);
        request.send(null);
    }
}

//PromiseAll
var promiseAll = function(items, block, done, fail) {
    var self = this;
    var promises = [],
                   index = 0;
    items.forEach(function(item) {
        promises.push(function(item, i) {
            return new Promise(function(resolve, reject) {
                if (block) {
                    block.apply(this, [item, index, resolve, reject]);
                }
            });
        }(item, ++index))
    });
    Promise.all(promises).then(function AcceptHandler(results) {
        if (done) done(results);
    }, function ErrorHandler(error) {
        if (fail) fail(error);
    });
}; //promiseAll

// LP: deferred execution block
var ExecutionBlock = function(item, index, resolve, reject) {
    var url = "https://api.spotify.com/v1/"
    url += item;
    console.log( url )
    SimpleRequest.call(url, function(result) {
        if (result) {

            var profileUrls = JSON.parse(result).playlists.items.map(function(item, index) {
                return item.owner.href;
            })
            resolve(profileUrls);
        }
        else {
            reject(new Error("call error"));
        }
    })
}

arr = [
    "search?type=playlist&q=%22doom%20metal%22",
    "search?type=playlist&q=Adele"
]

promiseAll(arr, function(item, index, resolve, reject) {
    console.log("Making request [" + index + "]")
    ExecutionBlock(item, index, resolve, reject);
}, function(results) { // Aggregated results

    console.log("All profiles received " + results.length);
    //console.log(JSON.stringify(results[0], null, 2));

    ///// promiseall again

    var ExecutionProfileBlock = function(item, index, resolve, reject) {
        SimpleRequest.call(item, function(result) {
            if (result) {
                var obj = JSON.parse(result);
                resolve({
                    name: obj.display_name,
                    followers: obj.followers.total,
                    url: obj.href
                });
            } //result
        })
    } //ExecutionProfileBlock

    promiseAll(results[0], function(item, index, resolve, reject) {
        //console.log("Making request [" + index + "] " + item)
        ExecutionProfileBlock(item, index, resolve, reject);
    }, function(results) { // aggregated results
        console.log("All response received " + results.length);
        console.log(JSON.stringify(results, null, 2));
    }

    , function(error) { // Error
        console.log(error);
    })

    /////

  },
  function(error) { // Error
      console.log(error);
  });
<div id="console" />

我已经广泛讨论了此解决方案在这里

The following example I have written shows how to

  • Handle asynchronous HTTP calls;
  • Wait for response from each API call;
  • Use Promise pattern;
  • Use Promise.all pattern to join multiple HTTP calls;

This working example is self-contained. It will define a simple request object that uses the window XMLHttpRequest object to make calls. It will define a simple function to wait for a bunch of promises to be completed.

Context. The example is querying the Spotify Web API endpoint in order to search for playlist objects for a given set of query strings:

[
 "search?type=playlist&q=%22doom%20metal%22",
 "search?type=playlist&q=Adele"
]

For each item, a new Promise will fire a block - ExecutionBlock, parse the result, schedule a new set of promises based on the result array, that is a list of Spotify user objects and execute the new HTTP call within the ExecutionProfileBlock asynchronously.

You can then see a nested Promise structure, that lets you spawn multiple and completely asynchronous nested HTTP calls, and join the results from each subset of calls through Promise.all.

NOTE
Recent Spotify search APIs will require an access token to be specified in the request headers:

-H "Authorization: Bearer {your access token}" 

So, you to run the following example you need to put your access token in the request headers:

var spotifyAccessToken = "YourSpotifyAccessToken";
var console = {
    log: function(s) {
        document.getElementById("console").innerHTML += s + "<br/>"
    }
}

// Simple XMLHttpRequest
// based on https://davidwalsh.name/xmlhttprequest
SimpleRequest = {
    call: function(what, response) {
        var request;
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            request = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // Internet Explorer
            try {
                request = new ActiveXObject('Msxml2.XMLHTTP');
            }
            catch (e) {
                try {
                  request = new ActiveXObject('Microsoft.XMLHTTP');
                } catch (e) {}
            }
        }

        // State changes
        request.onreadystatechange = function() {
            if (request.readyState === 4) { // Done
                if (request.status === 200) { // Complete
                    response(request.responseText)
                }
                else
                    response();
            }
        }
        request.open('GET', what, true);
        request.setRequestHeader("Authorization", "Bearer " + spotifyAccessToken);
        request.send(null);
    }
}

//PromiseAll
var promiseAll = function(items, block, done, fail) {
    var self = this;
    var promises = [],
                   index = 0;
    items.forEach(function(item) {
        promises.push(function(item, i) {
            return new Promise(function(resolve, reject) {
                if (block) {
                    block.apply(this, [item, index, resolve, reject]);
                }
            });
        }(item, ++index))
    });
    Promise.all(promises).then(function AcceptHandler(results) {
        if (done) done(results);
    }, function ErrorHandler(error) {
        if (fail) fail(error);
    });
}; //promiseAll

// LP: deferred execution block
var ExecutionBlock = function(item, index, resolve, reject) {
    var url = "https://api.spotify.com/v1/"
    url += item;
    console.log( url )
    SimpleRequest.call(url, function(result) {
        if (result) {

            var profileUrls = JSON.parse(result).playlists.items.map(function(item, index) {
                return item.owner.href;
            })
            resolve(profileUrls);
        }
        else {
            reject(new Error("call error"));
        }
    })
}

arr = [
    "search?type=playlist&q=%22doom%20metal%22",
    "search?type=playlist&q=Adele"
]

promiseAll(arr, function(item, index, resolve, reject) {
    console.log("Making request [" + index + "]")
    ExecutionBlock(item, index, resolve, reject);
}, function(results) { // Aggregated results

    console.log("All profiles received " + results.length);
    //console.log(JSON.stringify(results[0], null, 2));

    ///// promiseall again

    var ExecutionProfileBlock = function(item, index, resolve, reject) {
        SimpleRequest.call(item, function(result) {
            if (result) {
                var obj = JSON.parse(result);
                resolve({
                    name: obj.display_name,
                    followers: obj.followers.total,
                    url: obj.href
                });
            } //result
        })
    } //ExecutionProfileBlock

    promiseAll(results[0], function(item, index, resolve, reject) {
        //console.log("Making request [" + index + "] " + item)
        ExecutionProfileBlock(item, index, resolve, reject);
    }, function(results) { // aggregated results
        console.log("All response received " + results.length);
        console.log(JSON.stringify(results, null, 2));
    }

    , function(error) { // Error
        console.log(error);
    })

    /////

  },
  function(error) { // Error
      console.log(error);
  });
<div id="console" />

I have extensively discussed this solution here.

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

懷念過去 2025-02-20 18:45:45

尝试使用常规功能而不是箭头功能,应该修复它!

UsersSchema.pre('save', function (next: any)  {
  if (!this.isModified('password')) return next();
  this.password = encrypt(this.password, 10);
  next();
});

try using regular function instead of arrow function, that should fix it!

UsersSchema.pre('save', function (next: any)  {
  if (!this.isModified('password')) return next();
  this.password = encrypt(this.password, 10);
  next();
});

NESTJS加密密码预先保存 @nestjs/mongoose

懷念過去 2025-02-20 16:44:03

这是双向数据绑定商店概念在许多新的JavaScript框架中使用的地方之一,这对您来说非常有用...

因此,如果您使用< a href =“ https://en.wikipedia.org/wiki/angular_(web_framework)” rel =“ noreferrer”> angular href =“ https://en.wikipedia.org/wiki/wiki/react_(web_framework)” rel =“ noreferrer”> react 或任何其他有双向数据绑定或存储概念的其他框架,此问题是简单地为您修复,因此,简单地说,您的结果是在第一阶段,因此您有 result =未定义的在收到数据之前,一旦获得结果,它将被更新并分配给新值AJAX调用的响应...

但是如何在纯JavaScript或例如,正如您在这个问题中提出的那样?

您可以使用回调,承诺并最近可观察到为您处理。例如,在承诺中,我们具有一些功能,例如 success() then(),当您的数据准备就绪时将执行。可观察到的回调或 subscribe 函数相同。

例如,在您正在使用jQuery的情况下,您可以做类似的事情:

$(document).ready(function(){
    function foo() {
        $.ajax({url: "api/data", success: function(data){
            fooDone(data); // After we have data, we pass it to fooDone
        }});
    };

    function fooDone(data) {
        console.log(data); // fooDone has the data and console.log it
    };

    foo(); // The call happens here
});

有关更多信息,研究承诺和观察物是做这种异步工作的新方法。

This is one of the places which two-way data binding or store concept that's used in many new JavaScript frameworks will work great for you...

So if you are using Angular, React, or any other frameworks which do two-way data binding or store concept, this issue is simply fixed for you, so in easy words, your result is undefined at the first stage, so you have got result = undefined before you receive the data, then as soon as you get the result, it will be updated and get assigned to the new value which response of your Ajax call...

But how you can do it in pure JavaScript or jQuery for example as you asked in this question?

You can use a callback, promise and recently observable to handle it for you. For example, in promises we have some function like success() or then() which will be executed when your data is ready for you. The same with callback or the subscribe function on an observable.

For example, in your case which you are using jQuery, you can do something like this:

$(document).ready(function(){
    function foo() {
        $.ajax({url: "api/data", success: function(data){
            fooDone(data); // After we have data, we pass it to fooDone
        }});
    };

    function fooDone(data) {
        console.log(data); // fooDone has the data and console.log it
    };

    foo(); // The call happens here
});

For more information, study promises and observables which are newer ways to do this async stuff.

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

懷念過去 2025-02-20 13:54:06

这是一个热图方法:
每一行都显示模型的预测,每列都是一个实例预测,颜色代表预测的值。

import plotly.express as px
fig = px.imshow(list(data.values()), y = list(data.keys()))
fig.show()

其次,您可以通过比较它们预测相同的速率来彼此比较模型同一实例的类别。

import pandas as pd

df = pd.DataFrame(data)
rate_of_same_prediction = df.apply(lambda x:[ (x== df[ col ]).mean() for col in df.columns], axis=0)
rate_of_same_prediction.index = rate_of_same_prediction.columns 
fig = px.imshow(rate_of_same_prediction)
fig.show()

这里的列和行都代表您的模型。

Here's a heatmap approach:
Each row shows a model's predictions, each column is an instance predicted and the color represents the value predicted.

import plotly.express as px
fig = px.imshow(list(data.values()), y = list(data.keys()))
fig.show()

Heatmap showing predictions from 5 models

Secondly you could compare models with each other, by comparing the rates at which they predict the same category for the same instance.

import pandas as pd

df = pd.DataFrame(data)
rate_of_same_prediction = df.apply(lambda x:[ (x== df[ col ]).mean() for col in df.columns], axis=0)
rate_of_same_prediction.index = rate_of_same_prediction.columns 
fig = px.imshow(rate_of_same_prediction)
fig.show()

Here both columns and rows represent your models.

enter image description here

比较来自不同模型的每个测试数据实例的预测类

懷念過去 2025-02-20 12:22:58
Dt1 = Dt1.AsEnumerable()
         .GroupBy(r => new { filename = r.Field<string>("filename1"), filesize = r.Field<string>("filesizeinkb") })
         .Where(g => g.Count() == 1)
         .Select(g => g.First())
         .CopyToDataTable();

这将丢弃任何一个以上项目的组,然后从其余的第一个(也是唯一的)项目中获取。

Dt1 = Dt1.AsEnumerable()
         .GroupBy(r => new { filename = r.Field<string>("filename1"), filesize = r.Field<string>("filesizeinkb") })
         .Where(g => g.Count() == 1)
         .Select(g => g.First())
         .CopyToDataTable();

That will discard any groups with more than one item, then get the first (and only) item from the rest.

用LINQ从DataTable中删除重复项,而无需保持重复的条目

懷念過去 2025-02-20 12:10:03

您是否尝试使用Sudo读取文件?

sudo cat id_rsa.pub

无论如何我都知道github所需的ssh键是publickey。

为了进一步调试您的问题,您可能需要确保实际上将SSH密钥添加到您的GitHub帐户中并具有正确的权限。
您可以通过按照遵循步骤在这里

调试问题的进一步步骤可能会有用在这里((例如,验证您的用户在验证SSH键后可以建立连接)

Did you try with sudo to read the file?

sudo cat id_rsa.pub

To my knowledge anyways the ssh key needed for GitHub is the publickey.

To further debug your problem, you might want to make sure that the ssh key is actually added to your github account and has the right permissions.
You can debug if your ssh key is being used with your account by following the steps here

further steps of debugging the issue that might be helpful can be found here (e.g. verifying that your user can make connections after verifying the ssh key)

尝试阅读ID_RSA

懷念過去 2025-02-20 09:25:02

区分参数的典型方法是提供一个替代的静态函数来创建实例。这就是某些本地课程的完成方式。例如, array 具有 array.of array.from object code> object.fromentries , object.create ,...

如果我们遵循该模式,则您的示例代码可能会变为:

class MyClass {
  static fromFile(path, isPublic=true) {
    // read key file
    const content = ...
    // Pass the appropriate arguments to constructor
    return isPublic ? new this(null, content) : new this(content);
  }

  static fromSize(size) {
    // Create new key pairs based on the given size
    const privateKey = ...
    const publicKey = ...
    return new this(privateKey, publicKey);
  }

  // Constructor is dumb: it has little logic
  constructor(privateKey, publicKey) {
    // If no public key is given, produce it from the private key
    if (publicKey === undefined) {
        if (privateKey === undefined) throw Error("must provide at least one key");
        // Generate public key instance from private key
        publicKey = ...
    }
    this.privateKey = privateKey ?? null; // turn undefined into null
    this.publicKey = publicKey;
  }
}

// Example calls:
let x = MyClass.fromFile("/testPublic.key");
let y = MyClass.fromSize(5);
let z = new MyClass("a", "b");

A typical way to differentiate between parameters, is to provide an alternative, static function to create an instance. This is how it is done for some native classes. For instance, Array has Array.of, Array.from, and Object has Object.fromEntries, Object.create, ...

If we follow that pattern, your example code could become:

class MyClass {
  static fromFile(path, isPublic=true) {
    // read key file
    const content = ...
    // Pass the appropriate arguments to constructor
    return isPublic ? new this(null, content) : new this(content);
  }

  static fromSize(size) {
    // Create new key pairs based on the given size
    const privateKey = ...
    const publicKey = ...
    return new this(privateKey, publicKey);
  }

  // Constructor is dumb: it has little logic
  constructor(privateKey, publicKey) {
    // If no public key is given, produce it from the private key
    if (publicKey === undefined) {
        if (privateKey === undefined) throw Error("must provide at least one key");
        // Generate public key instance from private key
        publicKey = ...
    }
    this.privateKey = privateKey ?? null; // turn undefined into null
    this.publicKey = publicKey;
  }
}

// Example calls:
let x = MyClass.fromFile("/testPublic.key");
let y = MyClass.fromSize(5);
let z = new MyClass("a", "b");

在JavaScript构造函数中,接受和处理不同选项的最优雅方法是什么?

懷念過去 2025-02-20 08:27:08

无法如 @Scheff的猫所述连接类。

解决方案是不要在 usb2can_driver 中使用QSerialport的继承。如果我想通过插槽(是第二类)连接QSerialport的信号,则必须在USB2CAN_DRIVER的构造函数中创建一个对象。

此对象允许使用信号/插槽机制。

简而
对于第二类(Canview)中的连接,我使用了此语法:

connect(u2c->port_USB2CAN,SIGNAL(readyRead()),this,SLOT(read_u2c()));

感谢Scheff的Cat,您的评论很有帮助。该解决方案正在起作用,但是如果有人看到非标准语法,请警告我。

It is impossible to connect classes as mentioned by @Scheff's Cat.

The solution is do not use inheritance from QSerialPort in the usb2can_driver. If I want connect signal of QSerialPort with slot (which is part of second class), I had to create a object from QSerialPort in the constructor of USB2CAN_driver.

This object to allow use signal/slot mechanism.

So in short: USB2CAN_driver:: was replaced by object port_USB2CAN
For the connection in the second class (canview), i used this syntax:

connect(u2c->port_USB2CAN,SIGNAL(readyRead()),this,SLOT(read_u2c()));

Thank to Scheff's Cat, your comment was helpfully. This solution is working, but if somebody see the non-standard syntax please warning me.

QTCreator:类之间的信号槽机制

懷念過去 2025-02-20 08:01:09

您已经使用了 QuerySelector()方法来访问DOM元素。此方法用于访问单元素。

querySelectorall()方法用于访问与CSS查询匹配的所有元素。 querySelectorall()方法返回 Nodelist

在此片段中,使用了 foreach 循环。
由于由 querySelectorall()选择的Nodelist具有类似 array的结构结构在回调功能中

let tooltips = document.querySelectorAll('.toolhere + section');

document.addEventListener("mousemove", function(e) {
  const posX = `${e.clientX + 3}px`;
  const posY = `${e.clientY + 3}px`;

   tooltips.forEach((tooltip) => {
    tooltip.style.top = posY;
    tooltip.style.left = posX;
  });
});
.toolhere {
  position: relative;
}

.toolhere+section {
  opacity: 0;
  width: fit-content;
  position: fixed;
  font-family: sans-serif;
  background-color: #ECECEC;
  color: #4D4E53;
  border-radius: 5px;
  padding: 4px 8px 4px 9px;
  font-size: 12px;
  transition: opacity .5s;
}

.toolhere:hover+section {
  opacity: 1;
}
<div class="items">
  <div class="sub-content">
    <div class="iconsize toolhere">
      <img src="https://media.istockphoto.com/photos/positive-man-celebrating-success-picture-id1221837116?k=20&m=1221837116&s=612x612&w=0&h=HfTeaCWySduic6zF3kC-jGjWq_JgQUc5BtBjdCzBQzU=" />
    </div>
    <section class="tooltip">this is tooltip</section>
  </div>
  <div class="sub-content">
    <div class="content-name toolhere"></div>
    <section class="tooltip">this is tooltip</section>
  </div>
</div>

You've used querySelector() method to access the DOM element. This method is used to access single element.

querySelectorAll() method is used to access all elements which matches the CSS query. querySelectorAll() method returns a NodeList.

In this Snippet below forEach loop is used.
Since NodeList selected by querySelectorAll() has an array-like structure so you can directly apply forEach method with it and pass element as the first element in the callback function

let tooltips = document.querySelectorAll('.toolhere + section');

document.addEventListener("mousemove", function(e) {
  const posX = `${e.clientX + 3}px`;
  const posY = `${e.clientY + 3}px`;

   tooltips.forEach((tooltip) => {
    tooltip.style.top = posY;
    tooltip.style.left = posX;
  });
});
.toolhere {
  position: relative;
}

.toolhere+section {
  opacity: 0;
  width: fit-content;
  position: fixed;
  font-family: sans-serif;
  background-color: #ECECEC;
  color: #4D4E53;
  border-radius: 5px;
  padding: 4px 8px 4px 9px;
  font-size: 12px;
  transition: opacity .5s;
}

.toolhere:hover+section {
  opacity: 1;
}
<div class="items">
  <div class="sub-content">
    <div class="iconsize toolhere">
      <img src="https://media.istockphoto.com/photos/positive-man-celebrating-success-picture-id1221837116?k=20&m=1221837116&s=612x612&w=0&h=HfTeaCWySduic6zF3kC-jGjWq_JgQUc5BtBjdCzBQzU=" />
    </div>
    <section class="tooltip">this is tooltip</section>
  </div>
  <div class="sub-content">
    <div class="content-name toolhere"></div>
    <section class="tooltip">this is tooltip</section>
  </div>
</div>

如何在鼠标移动上移动工具提示?

懷念過去 2025-02-19 17:24:11

我想您正在尝试做类似以下操作:

class SomeClass {
  obj = {
    functionName: "add",
    args: [10, 20],
  };

  add(a, b) {
    return a + b;
  }

  invokeFunc() {
    const { functionName, args } = this.obj;
    return this[functionName](...args);
  }
}

const instance = new SomeClass();
console.log(instance.invokeFunc());

由于可以从 this 对象访问要调用的函数,因此您可以调用它,并且 vrize(...)所有参数。

对于 async 函数,它是不是清楚地表明它是 async 函数。您可以在对象中具有类型字段,并有条件地等待该功能。

I guess you're trying to do something like the following:

class SomeClass {
  obj = {
    functionName: "add",
    args: [10, 20],
  };

  add(a, b) {
    return a + b;
  }

  invokeFunc() {
    const { functionName, args } = this.obj;
    return this[functionName](...args);
  }
}

const instance = new SomeClass();
console.log(instance.invokeFunc());

Since the function to be invoked is accessible from the this object, you can invoke it and spread (...) all the arguments.

For async functions it's not clear how it's indicated that it's an async function. You can have a type field in the object and conditionally await the function.

如何从包含函数名称的字典中构造函数和参数

懷念過去 2025-02-19 14:16:14

最好使用Bash数组,并在需要时加入CSV字符串:

#!/usr/bin/env bash
readarray -t listofusers < <(cut -d, -f4- file.csv | tr -d '"' | tr ',' 

cut -d,-f4- file.csv | tr -d'''| tr',$'\ n'| sort -u 是重要的位 - 它首先仅打印出CSV输入文件的第四和以下字段进入新线,然后对产生的用户名进行分类,然后删除使用 readarray 内置的输出的重复项。但是,您需要的个别要素。

\n' | sort -u)) IFS=, printf "%s\n" "${listofusers[*]}"

cut -d,-f4- file.csv | tr -d'''| tr',$'\ n'| sort -u 是重要的位 - 它首先仅打印出CSV输入文件的第四和以下字段进入新线,然后对产生的用户名进行分类,然后删除使用 readarray 内置的输出的重复项。但是,您需要的个别要素。

Better to use a bash array, and join it into a CSV string when needed:

#!/usr/bin/env bash
readarray -t listofusers < <(cut -d, -f4- file.csv | tr -d '"' | tr ',' 

cut -d, -f4- file.csv | tr -d '"' | tr ',' $'\n' | sort -u is the important bit - it first only prints out the fourth and following fields of the CSV input file, removes quotes, turns commas into newlines, and then sorts the resulting usernames, removing duplicates. That output is then read into an array with the readarray builtin, and you can manipulate it and the individual elements however you need.

\n' | sort -u)) IFS=, printf "%s\n" "${listofusers[*]}"

cut -d, -f4- file.csv | tr -d '"' | tr ',' $'\n' | sort -u is the important bit - it first only prints out the fourth and following fields of the CSV input file, removes quotes, turns commas into newlines, and then sorts the resulting usernames, removing duplicates. That output is then read into an array with the readarray builtin, and you can manipulate it and the individual elements however you need.

使用bash从CSV文件中的特定行获取最后一个X字段

懷念過去 2025-02-19 01:02:01

这是扑打中的错误。问题是在这里

It is a bug in flutter. Issue is here

如何从动画上删除儿童背景颜色?

懷念過去 2025-02-18 18:41:19

我们可以使用 document> document.queryseleslect /a>选择我们的元素(如果只有一个)

但是在这种情况下,我们需要使用 querySelectorall 用于选择HTML中的所有广告元素

Web 我们可以使用 foreach

使用

foreach 您可以获取其他3个信息,

- 元素本身(您可以使用逻辑或console.log进行逻辑)

- 元素的索引

- 所有元素的数组


使用此顺序(元素,IndexOflement,arrayoflearts)

这是一个例子:

let unfilledAds = document.querySelectorAll(`.adsbygoogle[data-ad-status="unfilled"]`);
let successAds = document.querySelectorAll(`.adsbygoogle[data-ad-status="success"]`);;

/* not success */
unfilledAds.forEach((adElement) => {
    /* your logic */
    console.log(`❌ this Ad is not filled`, adElement);
});

/* success */
successAds.forEach((adElement) => {
    console.log(`✅ this ad is visible to the user`, adElement);
});
<!-- fail -->
    <ins data-ad-status="unfilled" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>
    <ins data-ad-status="unfilled" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>

    <!-- success -->
    <ins data-ad-status="success" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>
    <ins data-ad-status="success" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>


您还可以通过选择所有元素,然后做一个简单的话(检查结果)

来概括 [data-ad-status]

您也可以将此自定义的Google事件用于ADS https> https: //developers.google.com/publisher-tag/samples/ad-event-listeners 而无需重新发明车轮

,如果一段时间后的广告成功,它将起作用。

只需查看 docs

这里一个示例:


we can use document.querySelector to select our element (if there is only one)

but in this case we need to use querySelectorAll for selecting all the ads elements in html (<ins>)

also now we can loop your logic on every element with that status, using forEach

with forEach you can get 3 other information,

- the element itself (which you can do your logic with, or console.log it)

- the index of the element

- the array of all the elements


with this order (element, indexOfElement, ArrayOfAllElements)

this is a example:

let unfilledAds = document.querySelectorAll(`.adsbygoogle[data-ad-status="unfilled"]`);
let successAds = document.querySelectorAll(`.adsbygoogle[data-ad-status="success"]`);;

/* not success */
unfilledAds.forEach((adElement) => {
    /* your logic */
    console.log(`❌ this Ad is not filled`, adElement);
});

/* success */
successAds.forEach((adElement) => {
    console.log(`✅ this ad is visible to the user`, adElement);
});
<!-- fail -->
    <ins data-ad-status="unfilled" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>
    <ins data-ad-status="unfilled" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>

    <!-- success -->
    <ins data-ad-status="success" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>
    <ins data-ad-status="success" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done"></ins>


you can also generalize [data-ad-status] by selecting all the elements and then do a simple if, else (checking the result)

you can also use this custom google event for the ads https://developers.google.com/publisher-tag/samples/ad-event-listeners without reinventing the wheels
so it will work if the ads will be successful after some time.

just see the docs.

here a example: https://googleads.github.io/google-publisher-tag-samples/advanced/ad-event-listeners/demo.html

如何使用JavaScript获取DIV子元素

懷念過去 2025-02-18 13:13:46

按名称组并应用示例(在该组中随机n随机n),其中n是您所需的金额或该组的完整金额,例如:

out = df.groupby('NAME').apply(lambda g: g.sample(min(len(g), target_number_rows)))

否则,请使用第一个N或最后一个,例如:

out = df.groupby('NAME').head(target_number_rows)
# or...
out = df.groupby('NAME').tail(target_number_rows)

Group by the name and apply a sample (that'll take randomly N within that group) where N is either your desired amount or the complete amount for that group, eg:

out = df.groupby('NAME').apply(lambda g: g.sample(min(len(g), target_number_rows)))

Otherwise, take the first N or last N, eg:

out = df.groupby('NAME').head(target_number_rows)
# or...
out = df.groupby('NAME').tail(target_number_rows)

有效地减少数据框中的组大小

懷念過去 2025-02-18 02:31:50

错误 - 无法将值插入列中

上述错误表明 null col2 上有 null

使用下面的命令查看的架构“ test2_dedicated_pool” 表。

SELECT * from sys.schemas where name = “test2_dedicated_pool”

您可能没有在“ COL2” 上发现零约束。然后,只需尝试更改模式并删除无效约束即可。

Error - Cannot insert the value NULL into column

The above error indicates that there is not null constraint on col2.

Use the command below to view schema of “test2_dedicated_pool” table.

SELECT * from sys.schemas where name = “test2_dedicated_pool”

You may find not null constraint on “col2”. Then just try to alter schema and remove not null constraint.

专用的SQL池,无法插入null

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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