问:
Is it possible to save a File object in LocalStorage and then reload a File via FileReader when a user comes back to a page?
For example, say the user loads some very large images or media files in to your web app. When they return you want your app to show what they've previously loaded, but can't keep the actual file data in LocalStorage because the data is too large. </p>

答:
Yes, this is possible. You can insert whatever information about the file you want into LocalStorage, provided you serialize it to one of the primitive types supported. You can also serialize the whole file into LocalStorage and retrieve that later if you want, but there are limitations on the size of the file depending on browser.

The following shows how to achieve this using two different approaches:

```<code>(function () {
// localStorage with image
var storageFiles = JSON.parse(localStorage.getItem("storageFiles")) || {},
    elephant = document.getElementById("elephant"),
    storageFilesDate = storageFiles.date,
    date = new Date(),
    todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();

// Compare date and create localStorage if it's not existing/too old
if (typeof storageFilesDate === "undefined" || storageFilesDate < todaysDate) {
    // Take action when the image has loaded
    elephant.addEventListener("load", function () {
        var imgCanvas = document.createElement("canvas"),
            imgContext = imgCanvas.getContext("2d");

        // Make sure canvas is as big as the picture
        imgCanvas.width = elephant.width;
        imgCanvas.height = elephant.height;

        // Draw image into canvas element
        imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);

        // Save image as a data URL
        storageFiles.elephant = imgCanvas.toDataURL("image/png");

        // Set date for localStorage
        storageFiles.date = todaysDate;

        // Save as JSON in localStorage
        try {
            localStorage.setItem("storageFiles", JSON.stringify(storageFiles));
        }
        catch (e) {
                console.log("Storage failed: " + e);
        }
    }, false);

    // Set initial image src
    elephant.setAttribute("src", "elephant.png");
}
else {
    // Use image from localStorage
    elephant.setAttribute("src", storageFiles.elephant);
}

// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob
var rhinoStorage = localStorage.getItem("rhino"),
    rhino = document.getElementById("rhino");
if (rhinoStorage) {
    // Reuse existing Data URL from localStorage
    rhino.setAttribute("src", rhinoStorage);
}
else {
    // Create XHR, BlobBuilder and FileReader objects
    var xhr = new XMLHttpRequest(),
        blob,
        fileReader = new FileReader();

    xhr.open("GET", "rhino.png", true);
    // Set the responseType to arraybuffer. "blob" is an option too, rendering BlobBuilder unnecessary, but the support for "blob" is not widespread enough yet
    xhr.responseType = "arraybuffer";

    xhr.addEventListener("load", function () {
        if (xhr.status === 200) {
            // Create a blob from the response
            blob = new Blob([xhr.response], {type: "image/png"});

            // onload needed since Google Chrome doesn't support addEventListener for FileReader
            fileReader.onload = function (evt) {
                // Read out file contents as a Data URL
                var result = evt.target.result;
                // Set image src to Data URL
                rhino.setAttribute("src", result);
                // Store Data URL in localStorage
                try {
                    localStorage.setItem("rhino", result);
                }
                catch (e) {
                    console.log("Storage failed: " + e);
                }
            };
            // Load blob as Data URL
            fileReader.readAsDataURL(blob);
        }
    }, false);
    // Send XHR
    xhr.send();
}
})();
</code>```

Source

Body:
Yes, this is possible. You can insert whatever information about the file you want into LocalStorage, provided you serialize it to one of the primitive types supported. You can also serialize the whole file into LocalStorage and retrieve that later if you want, but there are limitations on the size of the file depending on browser.

The following shows how to achieve this using two different approaches:

(function () {
// localStorage with image
var storageFiles = JSON.parse(localStorage.getItem("storageFiles")) || {},
    elephant = document.getElementById("elephant"),
    storageFilesDate = storageFiles.date,
    date = new Date(),
    todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();

// Compare date and create localStorage if it's not existing/too old
if (typeof storageFilesDate === "undefined" || storageFilesDate < todaysDate) {
    // Take action when the image has loaded
    elephant.addEventListener("load", function () {
        var imgCanvas = document.createElement("canvas"),
            imgContext = imgCanvas.getContext("2d");

        // Make sure canvas is as big as the picture
        imgCanvas.width = elephant.width;
        imgCanvas.height = elephant.height;

        // Draw image into canvas element
        imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);

        // Save image as a data URL
        storageFiles.elephant = imgCanvas.toDataURL("image/png");

        // Set date for localStorage
        storageFiles.date = todaysDate;

        // Save as JSON in localStorage
        try {
            localStorage.setItem("storageFiles", JSON.stringify(storageFiles));
        }
        catch (e) {
                console.log("Storage failed: " + e);
        }
    }, false);

    // Set initial image src
    elephant.setAttribute("src", "elephant.png");
}
else {
    // Use image from localStorage
    elephant.setAttribute("src", storageFiles.elephant);
}

// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob
var rhinoStorage = localStorage.getItem("rhino"),
    rhino = document.getElementById("rhino");
if (rhinoStorage) {
    // Reuse existing Data URL from localStorage
    rhino.setAttribute("src", rhinoStorage);
}
else {
    // Create XHR, BlobBuilder and FileReader objects
    var xhr = new XMLHttpRequest(),
        blob,
        fileReader = new FileReader();

    xhr.open("GET", "rhino.png", true);
    // Set the responseType to arraybuffer. "blob" is an option too, rendering BlobBuilder unnecessary, but the support for "blob" is not widespread enough yet
    xhr.responseType = "arraybuffer";

    xhr.addEventListener("load", function () {
        if (xhr.status === 200) {
            // Create a blob from the response
            blob = new Blob([xhr.response], {type: "image/png"});

            // onload needed since Google Chrome doesn't support addEventListener for FileReader
            fileReader.onload = function (evt) {
                // Read out file contents as a Data URL
                var result = evt.target.result;
                // Set image src to Data URL
                rhino.setAttribute("src", result);
                // Store Data URL in localStorage
                try {
                    localStorage.setItem("rhino", result);
                }
                catch (e) {
                    console.log("Storage failed: " + e);
                }
            };
            // Load blob as Data URL
            fileReader.readAsDataURL(blob);
        }
    }, false);
    // Send XHR
    xhr.send();
}
})();

Source


来源: stackexchange

问:
Using MATIC with Web3 and MetaMask: "Error: Returned error: unknown account"
I have a server-client DApp that I've tested working fine on an Ethereum test network. But due to gas fees, I want to use a L2, in this case I chose Polygon (MATIC). Basic app is reading and writing text posts to a website, the smart contract stores them.

I have successfully deployed on MATIC using remix.ethereum.org, and from Remix I can write transactions to the contract. On my localhost web app, I can read transactions, but my writing is not working from the client.

Here is the server.js

```<code>const WEB3_PROVIDER = "https://polygon-rpc.com"
// https://blog.polygon.technology/polygon-rpc-gateway-will-provide-a-free-high-performance-connection-to-the-polygon-pos-blockchain/

//"https://cloudflare-eth.com"; //"HTTP://127.0.0.1:7545"
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
    console.log("web3 already initialized.");
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider(WEB3_PROVIDER));
    console.log("New web3 object initialized.");
}

app.post('/add-post', async (req, res) => {
    const post = req.body;

    try {
        console.log(post);

        MyContract.methods.addNewPost(post['name'], post['post'], post['date']).send({from: post['addr'], gas:3000000}).then(function(result) {
            const output_response = "add-post successful :: ";//+String(result);
            res.send(output_response);
        }).catch(function(err) {
            const output_response = "add-post failed :: "+String(err);
            res.send(output_response);
        });

    } catch (e) { throw e; }
});
</code>```

And here is the snippet in client.js where I am adding a post, by grabbing the html input form and then passing to the following:

```<code>const web3 = new Web3(window.ethereum);

async function addPost(post_input) {
    stringify_post_input = JSON.stringify(post_input);
    const post_response = await fetch('/add-post', {method: 'POST', body: stringify_post_input, headers: { "content-type": "application/json" } });
    var post_response_text = await post_response.text();
    console.log(post_response_text);
}
</code>```

Now this usually works flawlessly on ethereum test network, where all I change is the web3 initialization in server.js. But now on the MATIC network I get, in my client browser,

```<code>add-post failed :: Error: Returned error: unknown account
</code>```

This is really confusing to me, because

I can manually add posts in remix.ethereum.org, where I deployed this exact same MyContract

I have other server-side calls that read from MyContract and work fine (i.e. I can read existing posts I added from Remix).

So my client can read but not write, i.e. no MetaMask pop-up asking me to confirm to pay gas fees.

This is my first time trying to use a L2, so I have no idea if all the web3 code should be the same. I've been under the impression that I only need to swap the networks and log into my MetaMask and it should all be fine. But I don't really understand web3 that deeply, so I'm not sure.

Help much appreciate - ideally when I try and write with MyContract.methods...(), I should get a MetaMask pop-up in my client browser asking me to confirm paying gas fees.

答:
```<code>MyContract.methods.addNewPost(...).send({from: post['addr'], gas:3000000})
</code>```

This snippet generates a transaction from the post['addr'] address, and sends the generated transaction to the node. When web3 instance holds the corresponding private key to this address, it signs the transaction before sending.

When web3 doesn't hold the private key, it sends the transaction unsigned. Which is useful only in dev environment (e.g. the Remix VM emulator, Ganache, Hardhat, ...) where the node might hold the private key and still sign the transaction. But in this case, the node doesn't have the corresponding private key and returns the "unknown account" error.

Your question already suggests a solution - request MetaMask (or another wallet software holding the user's private key) to sign the transaction instead of signing it with web3 or on the node.

This requires moving the transaction generating logic to a frontend app (in your case client.js), so that the frontend app can communicate with the MetaMask API available throuth the window.ethereum object (docs), which is logically not available in the backend app.

client.js:

```<code>// containing the contract `addPost` function definition
const abiJson = [{
    "inputs": [
        {"internalType": "string", "name": "_name", "type": "string"},
        {"internalType": "string", "name": "_post", "type": "string"},
        {"internalType": "string", "name": "_date", "type": "string"}
    ],
    "name": "addPost", "outputs": [], "stateMutability": "nonpayable", "type": "function"
}];
const contractAddress = "0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF";

let accounts, web3, contract;

async function init() {
    // popup - get the user's address
    accounts = await ethereum.request({ method: 'eth_requestAccounts' });

    // using web3 just as a helper to generate the transaction
    // (see the `data` field and `encodeABI`) - not to sign it
    web3 = new Web3();
    contract = new web3.eth.Contract(abiJson);
}

async function addPost(postInput) {
    const transactionParameters = {
        from: accounts[0],
        to: contractAddress,
        data: contract.methods.addPost(
            postInput.name,
            postInput.post,
            postInput.date
        ).encodeABI(),
        gasPrice: '0x09184e72a000', // custom gas price
    };
    // popup - request the user to sign and broadcast the transaction
    await ethereum.request({
        method: 'eth_sendTransaction',
        params: [transactionParameters],
    });
}

async function run() {
    await init();
    await addPost({
        name: "This is a post name",
        post: "Hello world",
        date: "date"
    });
}

run();
</code>```

Now you can safely remove the endpoint, as it's not needed anymore.

ContentLicense: CC BY-SA 4.0

Body:
I have a server-client DApp that I've tested working fine on an Ethereum test network. But due to gas fees, I want to use a L2, in this case I chose Polygon (MATIC). Basic app is reading and writing text posts to a website, the smart contract stores them.

I have successfully deployed on MATIC using remix.ethereum.org, and from Remix I can write transactions to the contract. On my localhost web app, I can read transactions, but my writing is not working from the client.

Here is the server.js

const WEB3_PROVIDER = "https://polygon-rpc.com"
// https://blog.polygon.technology/polygon-rpc-gateway-will-provide-a-free-high-performance-connection-to-the-polygon-pos-blockchain/

//"https://cloudflare-eth.com"; //"HTTP://127.0.0.1:7545"
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
    console.log("web3 already initialized.");
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider(WEB3_PROVIDER));
    console.log("New web3 object initialized.");
}

app.post('/add-post', async (req, res) => {
    const post = req.body;

    try {
        console.log(post);

        MyContract.methods.addNewPost(post['name'], post['post'], post['date']).send({from: post['addr'], gas:3000000}).then(function(result) {
            const output_response = "add-post successful :: ";//+String(result);
            res.send(output_response);
        }).catch(function(err) {
            const output_response = "add-post failed :: "+String(err);
            res.send(output_response);
        });

    } catch (e) { throw e; }
});

And here is the snippet in client.js where I am adding a post, by grabbing the html input form and then passing to the following:

const web3 = new Web3(window.ethereum);

async function addPost(post_input) {
    stringify_post_input = JSON.stringify(post_input);
    const post_response = await fetch('/add-post', {method: 'POST', body: stringify_post_input, headers: { "content-type": "application/json" } });
    var post_response_text = await post_response.text();
    console.log(post_response_text);
}

Now this usually works flawlessly on ethereum test network, where all I change is the web3 initialization in server.js. But now on the MATIC network I get, in my client browser,

add-post failed :: Error: Returned error: unknown account

This is really confusing to me, because

I can manually add posts in remix.ethereum.org, where I deployed this exact same MyContract

I have other server-side calls that read from MyContract and work fine (i.e. I can read existing posts I added from Remix).

So my client can read but not write, i.e. no MetaMask pop-up asking me to confirm to pay gas fees.

This is my first time trying to use a L2, so I have no idea if all the web3 code should be the same. I've been under the impression that I only need to swap the networks and log into my MetaMask and it should all be fine. But I don't really understand web3 that deeply, so I'm not sure.

Help much appreciate - ideally when I try and write with MyContract.methods...(), I should get a MetaMask pop-up in my client browser asking me to confirm paying gas fees.

Body:
MyContract.methods.addNewPost(...).send({from: post['addr'], gas:3000000})

This snippet generates a transaction from the post['addr'] address, and sends the generated transaction to the node. When web3 instance holds the corresponding private key to this address, it signs the transaction before sending.

When web3 doesn't hold the private key, it sends the transaction unsigned. Which is useful only in dev environment (e.g. the Remix VM emulator, Ganache, Hardhat, ...) where the node might hold the private key and still sign the transaction. But in this case, the node doesn't have the corresponding private key and returns the "unknown account" error.

Your question already suggests a solution - request MetaMask (or another wallet software holding the user's private key) to sign the transaction instead of signing it with web3 or on the node.

This requires moving the transaction generating logic to a frontend app (in your case client.js), so that the frontend app can communicate with the MetaMask API available throuth the window.ethereum object (docs), which is logically not available in the backend app.

client.js:

// containing the contract `addPost` function definition
const abiJson = [{
    "inputs": [
        {"internalType": "string", "name": "_name", "type": "string"},
        {"internalType": "string", "name": "_post", "type": "string"},
        {"internalType": "string", "name": "_date", "type": "string"}
    ],
    "name": "addPost", "outputs": [], "stateMutability": "nonpayable", "type": "function"
}];
const contractAddress = "0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF";

let accounts, web3, contract;

async function init() {
    // popup - get the user's address
    accounts = await ethereum.request({ method: 'eth_requestAccounts' });

    // using web3 just as a helper to generate the transaction
    // (see the `data` field and `encodeABI`) - not to sign it
    web3 = new Web3();
    contract = new web3.eth.Contract(abiJson);
}

async function addPost(postInput) {
    const transactionParameters = {
        from: accounts[0],
        to: contractAddress,
        data: contract.methods.addPost(
            postInput.name,
            postInput.post,
            postInput.date
        ).encodeABI(),
        gasPrice: '0x09184e72a000', // custom gas price
    };
    // popup - request the user to sign and broadcast the transaction
    await ethereum.request({
        method: 'eth_sendTransaction',
        params: [transactionParameters],
    });
}

async function run() {
    await init();
    await addPost({
        name: "This is a post name",
        post: "Hello world",
        date: "date"
    });
}

run();

Now you can safely remove the endpoint, as it's not needed anymore.


问:
How to use PostgreSQL test database in async FastAPI tests?
I'm working on an async FastAPI project and I want to connect to the database during tests. Coming from Django, my instinct was to create pytest fixtures that take care of creating/dropping the test database. However, I couldn't find much documentation on how to do this. The most complete instructions I could find were in this tutorial, but they don't work for me because they are all synchronous. I'm somewhat new to async development so I'm having trouble adapting the code to work async. This is what I have so far:

import pytest
from sqlalchemy.ext.asyncio import create_async_engine, session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database

from fastapi.testclient import TestClient

from app.core.db import get_session
from app.main import app

Base = declarative_base()

@pytest.fixture(scope="session")
def db_engine():
    default_db = (
        "postgresql+asyncpg://postgres:postgres@postgres:5432/postgres"
    )
    test_db = "postgresql+asyncpg://postgres:postgres@postgres:5432/test"
    engine = create_async_engine(default_db)
    if not database_exists(test_db):  # <- Getting error on this line
        create_database(test_db)

    Base.metadata.create_all(bind=engine)
    yield engine

@pytest.fixture(scope="function")
def db(db_engine):
    connection = db_engine.connect()

    # begin a non-ORM transaction
    connection.begin()

    # bind an individual Session to the connection
    Session = sessionmaker(bind=connection)
    db = Session()
    # db = Session(db_engine)

    yield db

    db.rollback()
    connection.close()

@pytest.fixture(scope="function")
def client(db):
    app.dependency_overrides[get_session] = lambda: db

    PREFIX = "/api/v1/my-endpoint"
    with TestClient(PREFIX, app) as c:
        yield c

```
<p>And this is the error I'm getting:</p>
```E           sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)

/usr/local/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py:67: MissingGreenlet
```

Any idea what I have to do to fix it?

答:
You try to use sync engine with async session. Try to use:

```<code>from sqlalchemy.ext.asyncio import AsyncSession
Session = sessionmaker(bind= connection, class_=AsyncSession)
</code>```

https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html

Body:
I'm working on an async FastAPI project and I want to connect to the database during tests. Coming from Django, my instinct was to create pytest fixtures that take care of creating/dropping the test database. However, I couldn't find much documentation on how to do this. The most complete instructions I could find were in this tutorial, but they don't work for me because they are all synchronous. I'm somewhat new to async development so I'm having trouble adapting the code to work async. This is what I have so far:

import pytest
from sqlalchemy.ext.asyncio import create_async_engine, session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database

from fastapi.testclient import TestClient

from app.core.db import get_session
from app.main import app

Base = declarative_base()

@pytest.fixture(scope="session")
def db_engine():
    default_db = (
        "postgresql+asyncpg://postgres:postgres@postgres:5432/postgres"
    )
    test_db = "postgresql+asyncpg://postgres:postgres@postgres:5432/test"
    engine = create_async_engine(default_db)
    if not database_exists(test_db):  # <- Getting error on this line
        create_database(test_db)

    Base.metadata.create_all(bind=engine)
    yield engine

@pytest.fixture(scope="function")
def db(db_engine):
    connection = db_engine.connect()

    # begin a non-ORM transaction
    connection.begin()

    # bind an individual Session to the connection
    Session = sessionmaker(bind=connection)
    db = Session()
    # db = Session(db_engine)

    yield db

    db.rollback()
    connection.close()

@pytest.fixture(scope="function")
def client(db):
    app.dependency_overrides[get_session] = lambda: db

    PREFIX = "/api/v1/my-endpoint"
    with TestClient(PREFIX, app) as c:
        yield c

And this is the error I'm getting:

E           sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)

/usr/local/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py:67: MissingGreenlet

Any idea what I have to do to fix it?

Body:
You try to use sync engine with async session. Try to use:

from sqlalchemy.ext.asyncio import AsyncSession
Session = sessionmaker(bind= connection, class_=AsyncSession)

https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html


问:
How to merge two dependant models in django and get count of each type
I'm new to django, how to relate two model classes and extract total count of it

```<code>class FoodBatch(models.Model):
    batch_code = models.CharField(max_length=200, blank=False, null=False)
    expiry = models.DateField()
    price = models.FloatField()

class FoodItem(models.Model):
    seller_code = models.CharField(max_length=200, blank=False, null=False)
    brand = models.CharField(max_length=200, blank=False, null=False)
    quantity = models.IntegerField()
    batch = models.ManytoMany(FoodBatch)

</code>```

FoodBatch has to be unique for each FoodItem. FoodItem can map to multiple FoodBatch.

Also, need to total count of quantity from all the FoodBatch for each FoodItem.

Thanks in advance.

答:
I don't know what you want to do!!

But this is steps to explain your code:

1- must be change :

batch = models.ManytoMany(FoodBatch)

to this code:

batch = models.ManyToManyField(FoodBatch)

2- create dump data for testing:

```<code>fb1 = FoodBatch(batch_code = "100",expiry ="2022-02-02",price = 100)
fb1.save()

fb2 = FoodBatch(batch_code = "200",expiry ="2022-02-02",price = 200)
fb2.save()

fb3 = FoodBatch(batch_code = "300",expiry ="2022-02-02",price = 300)
fb3.save()

# create FoodItem instance and set tow FoodBatch instances only for it.
fi1 = FoodItem(seller_code="111",brand="A",quantity=10)
fi1.save()
fi1.batch.set([fb1,fb2])

</code>```

# to extra total count:

```<code>FoodBatch.objects.annotate(item_total = models.Sum('fooditem__quantity')).values()
</code>```

# result like these:

<QuerySet [

{'id': 1, 'batch_code': '100', 'expiry':
datetime.date(2022, 2, 2), 'price': 100.0, 'item_total': 10},

{'id': 2, 'batch_code': '200', 'expiry': datetime.date(2022, 2, 2),
'price': 200.0, 'item_total': 10},

{'id': 3, 'batch_code': '300', 'expiry': datetime.date(2022, 2, 2),
'price': 300.0, 'item_total': None}]>

Body:
I'm new to django, how to relate two model classes and extract total count of it

class FoodBatch(models.Model):
    batch_code = models.CharField(max_length=200, blank=False, null=False)
    expiry = models.DateField()
    price = models.FloatField()

class FoodItem(models.Model):
    seller_code = models.CharField(max_length=200, blank=False, null=False)
    brand = models.CharField(max_length=200, blank=False, null=False)
    quantity = models.IntegerField()
    batch = models.ManytoMany(FoodBatch)

FoodBatch has to be unique for each FoodItem. FoodItem can map to multiple FoodBatch.

Also, need to total count of quantity from all the FoodBatch for each FoodItem.

Thanks in advance.

Body:
I don't know what you want to do!!

But this is steps to explain your code:

1- must be change :

batch = models.ManytoMany(FoodBatch)

to this code:

batch = models.ManyToManyField(FoodBatch)

2- create dump data for testing:

fb1 = FoodBatch(batch_code = "100",expiry ="2022-02-02",price = 100)
fb1.save()

fb2 = FoodBatch(batch_code = "200",expiry ="2022-02-02",price = 200)
fb2.save()

fb3 = FoodBatch(batch_code = "300",expiry ="2022-02-02",price = 300)
fb3.save()

# create FoodItem instance and set tow FoodBatch instances only for it.
fi1 = FoodItem(seller_code="111",brand="A",quantity=10)
fi1.save()
fi1.batch.set([fb1,fb2])

# to extra total count:

FoodBatch.objects.annotate(item_total = models.Sum('fooditem__quantity')).values()

# result like these:

<QuerySet [

{'id': 1, 'batch_code': '100', 'expiry':
datetime.date(2022, 2, 2), 'price': 100.0, 'item_total': 10},

{'id': 2, 'batch_code': '200', 'expiry': datetime.date(2022, 2, 2),
'price': 200.0, 'item_total': 10},

{'id': 3, 'batch_code': '300', 'expiry': datetime.date(2022, 2, 2),
'price': 300.0, 'item_total': None}]>


问:
Send empty body in POST request in Retrofit
My api expects an empty json body ({ }) when making post requests. How do I set this up in Retrofit and Jackson?

I tried passing null, and empty string, and "{}" but could not get this to work.

```<code>@POST(my/url)
Call<MyResponse> createPostRequest(@Body Object empty);
</code>```

How can I set an empty JSON body?

答:
Heres the answer in Kotlin:</p>
```<code>    @POST("CountriesList")
fun getCountriesNew(@Body body: HashMap<String, String>) : Call<CountryModel>

      val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My api expects an empty json body ({ }) when making post requests. How do I set this up in Retrofit and Jackson?

I tried passing null, and empty string, and "{}" but could not get this to work.

@POST(my/url)
Call<MyResponse> createPostRequest(@Body Object empty);

How can I set an empty JSON body?

Body:
Heres the answer in Kotlin:

    @POST("CountriesList")
fun getCountriesNew(@Body body: HashMap<String, String>) : Call<CountryModel>

      val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())


问:
How to move a glTF model in the direction it is facing in A-frame?
I have a gltf model of my robot loaded in A-frame scene version 1.0.4. So far I can turn the robot about its x,y, z axes, but when I try to move it forward it still moves in its initial direction rather than the direction it's facing. I want to be able to control its movements with my keyboard without using any external libraries. I believe I have to use Quaternions, but I haven't figured out how to use them yet. Here is my A-frame code so far.

```
</div>
</div>
</p>
<p>And here is my script</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const robot = document.getElementById('robot');

const update = () => {
   if (keys.forward) {
       let {x,y,z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z += Math.cos(ry * Math.PI/180)/12;
       x += Math.sin(ry * Math.PI/180)/12;
       robot.object3D.position.set(x, y, z);
}
   else if (keys.backwards) {
       let {x, y, z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z -= Math.cos(ry * Math.PI/180)/10;
       x -= Math.sin(ry * Math.PI/180)/10;
       robot.object3D.position.set(x, y, z);
}
 if (keys.turnLeft) {
       let {x, y, z} = robot.getAttribute('rotation');
       y += 0.25;
       robot.setAttribute('rotation',{x,y,z});
}
    else if (keys.turnRight) {
        let {x, y, z} = robot.getAttribute('rotation');
        y -= 0.25;
        robot.setAttribute('rotation',{x,y,z});
}
}</code>```

答:
You can use Quaternions and many other ways, but Object3D has some usesful and more simple alternatives to move object in local coordinates:

I think the most simple one is to use https://threejs.org/docs/#api/en/core/Object3D.translateZ

```<code>robot.object3D.translateZ(amountToMoveForward);
</code>```

Also https://threejs.org/docs/#api/en/core/Object3D.localToWorld can be used to transform vectors.

Body:
I have a gltf model of my robot loaded in A-frame scene version 1.0.4. So far I can turn the robot about its x,y, z axes, but when I try to move it forward it still moves in its initial direction rather than the direction it's facing. I want to be able to control its movements with my keyboard without using any external libraries. I believe I have to use Quaternions, but I haven't figured out how to use them yet. Here is my A-frame code so far.

And here is my script

const robot = document.getElementById('robot');

const update = () => {
   if (keys.forward) {
       let {x,y,z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z += Math.cos(ry * Math.PI/180)/12;
       x += Math.sin(ry * Math.PI/180)/12;
       robot.object3D.position.set(x, y, z);
}
   else if (keys.backwards) {
       let {x, y, z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z -= Math.cos(ry * Math.PI/180)/10;
       x -= Math.sin(ry * Math.PI/180)/10;
       robot.object3D.position.set(x, y, z);
}
 if (keys.turnLeft) {
       let {x, y, z} = robot.getAttribute('rotation');
       y += 0.25;
       robot.setAttribute('rotation',{x,y,z});
}
    else if (keys.turnRight) {
        let {x, y, z} = robot.getAttribute('rotation');
        y -= 0.25;
        robot.setAttribute('rotation',{x,y,z});
}
}

Body:
You can use Quaternions and many other ways, but Object3D has some usesful and more simple alternatives to move object in local coordinates:

I think the most simple one is to use https://threejs.org/docs/#api/en/core/Object3D.translateZ

robot.object3D.translateZ(amountToMoveForward);

Also https://threejs.org/docs/#api/en/core/Object3D.localToWorld can be used to transform vectors.


问:
Is there a way to declare a type for a value that possibly extends some other type?
In Typescript, can we create a type Possibly<T> that only accepts values that maybe, but not necessarily, extend T? Or in other words, values that could be asserted as T without a "neither type sufficiently overlaps with the other" error?

Alternative ways of constraining the parameter that are not describable as a utility type are also fine. However, they must work at compile time (this is a Typescript question after all, not Javascript).

```<code>// NOTE: AliveCat and DeadCat are examples, not actual types that can be modified.
//       Assume that asserting (casting) a DeadCat to AliveCat is a compile error.
declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: AliveCat | DeadCat;

function feed(cat: Possibly<AliveCat>) {
    if (unspecifiedAliveCheck(cat)) {
        unspecifiedCastOrUnwrap(cat).food++;
    } else {
        throw new Error(" :( ");
    }
}

garfield as Alive; // obviously works, probably warns about being useless
feed(garfield); // so should also work

schrodingersCat as AliveCat; // compiles
feed(schrodingersCat); // so should also compile

tom as AliveCat; // doesn't compile: "neither type sufficiently overlaps with the other"
feed(tom); // so should not compile either
</code>```

Not solutions, because they accept a DeadCat:

```<code>declare function feed(cat: AliveCat | DeadCat);
declare function feed(cat: unknown);
declare function feed(cat: any); // yuk!
</code>```

Or for a more mundane example:

```<code>// NOTE: the type guard return type is nice to have but optional
function isArray(a: Possibly<any[]>): a is any[] { ... }
isArray([]); // well yeah, but okay, double-checking is fine
isArray(true); // of course not!
isArray(... as true | number); // let's see and find out!
</code>```

答:
Updated

In response to your new information, I interpret your question to be that you need to either

only accept a type which extends AliveCat, or

discriminate an unknown type at runtime before acting on the discriminated type. I'll show examples of both.

Given these types/values for both examples:

type Cat<IsAlive extends boolean = boolean> = {
  isAlive: IsAlive;
};

type AliveCat = Cat<true> & { food: number };
type DeadCat = Cat<false>;

declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: unknown;
```
<h3>Using a generic to only accept a type that extends <code>AliveCat</code></h3>
<p>TS Playground</p>
<pre class="lang-ts prettyprint-override"><code>function feed <T extends AliveCat>(cat: T) {
  cat.food++;
}

feed(garfield); // ok
feed({isAlive: true, food: 5, extraProp: 'value'}); // ok, extends AliveCat

feed(tom); /*
     ^^^
Argument of type 'DeadCat' is not assignable to parameter of type 'AliveCat'.
  Type 'DeadCat' is not assignable to type 'Cat<true>'.
    Types of property 'isAlive' are incompatible.
      Type 'false' is not assignable to type 'true'.(2345) */

feed(schrodingersCat); /*
     ^^^^^^^^^^^^^^^
Argument of type 'unknown' is not assignable to parameter of type 'AliveCat'.
  Type 'unknown' is not assignable to type 'Cat<true>'.(2345) */

</code>```

Discriminate an unknown type at runtime (using a predicate)

Here, runtime validation of the unknown value is performed to ensure that its shape/properties align with the type that is asserted. Doing this gives confidence that the value can be safely acted on according to the type you think it will be in the code block:

TS Playground

function isType <T = never>(value: unknown, typeValidator: (value: unknown) => boolean): value is T {
  return typeValidator(value);
}

function feed (something: unknown) {
  const isAliveCat = isType<AliveCat>(something, u => (
    typeof u === 'object'
    && (u as any).isAlive === true
    && typeof (u as any).food === 'number'
  ));

  if (isAliveCat) {
    something; // AliveCat
    something.food++; // ok
  }
  else {
    something; // unknown
  }
}

feed(garfield); // ok, gets fed
feed(tom); // ok, might get fed if is an AliveCat (but won't because it isn't)
feed(schrodingersCat); // ok, might get fed if is an AliveCat

```
<hr />
<h2>Original answer</h2>
<p>I think you are looking for a discriminated union:</p>
<p>TS Playground</p>
<pre class="lang-ts prettyprint-override"><code>type Cat<IsAlive extends boolean = boolean> = {
  isAlive: IsAlive;
};

type AliveCat = Cat<true> & {
  food: number;
};

type DeadCat = Cat<false>;
type YetToBeDeterminedCat = AliveCat | DeadCat;

declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: YetToBeDeterminedCat;

function feed(cat: YetToBeDeterminedCat) {
  if (cat.isAlive) {
    cat.food++;
  } else {
    cat.food++; /*
        ^^^^
    Property 'food' does not exist on type 'DeadCat'.(2339) */

    throw new Error(" :( ");
  }
}

feed(schrodingersCat); // ok
feed(schrodingersCat as AliveCat); // ok
feed(schrodingersCat as DeadCat); // ok

feed(tom as AliveCat); /*
     ^^^^^^^^^^^^^^^
Conversion of type 'DeadCat' to type 'AliveCat' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type 'DeadCat' is not comparable to type 'Cat<true>'.
    Types of property 'isAlive' are incompatible.
      Type 'false' is not comparable to type 'true'.(2352) */

</code>```

Body:
In Typescript, can we create a type Possibly<T> that only accepts values that maybe, but not necessarily, extend T? Or in other words, values that could be asserted as T without a "neither type sufficiently overlaps with the other" error?

Alternative ways of constraining the parameter that are not describable as a utility type are also fine. However, they must work at compile time (this is a Typescript question after all, not Javascript).

// NOTE: AliveCat and DeadCat are examples, not actual types that can be modified.
//       Assume that asserting (casting) a DeadCat to AliveCat is a compile error.
declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: AliveCat | DeadCat;

function feed(cat: Possibly<AliveCat>) {
    if (unspecifiedAliveCheck(cat)) {
        unspecifiedCastOrUnwrap(cat).food++;
    } else {
        throw new Error(" :( ");
    }
}

garfield as Alive; // obviously works, probably warns about being useless
feed(garfield); // so should also work

schrodingersCat as AliveCat; // compiles
feed(schrodingersCat); // so should also compile

tom as AliveCat; // doesn't compile: "neither type sufficiently overlaps with the other"
feed(tom); // so should not compile either

Not solutions, because they accept a DeadCat:

declare function feed(cat: AliveCat | DeadCat);
declare function feed(cat: unknown);
declare function feed(cat: any); // yuk!

Or for a more mundane example:

// NOTE: the type guard return type is nice to have but optional
function isArray(a: Possibly<any[]>): a is any[] { ... }
isArray([]); // well yeah, but okay, double-checking is fine
isArray(true); // of course not!
isArray(... as true | number); // let's see and find out!

Body:
Updated

In response to your new information, I interpret your question to be that you need to either

only accept a type which extends AliveCat, or

discriminate an unknown type at runtime before acting on the discriminated type. I'll show examples of both.

Given these types/values for both examples:

type Cat<IsAlive extends boolean = boolean> = {
  isAlive: IsAlive;
};

type AliveCat = Cat<true> & { food: number };
type DeadCat = Cat<false>;

declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: unknown;

Using a generic to only accept a type that extends AliveCat

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true&ssl=12&ssc=1&pln=30&pc=1#code/C4TwDgpgBAwghsAPASQM4EEA2BLAbtCAD2AgDsATVKAIwHtbMI5SoBeG+x5gPjagG8AUFCjYMOfAC4oaLHggBuQQF8lg0JChz88YH12JgAJwCuEXgDIBUAGb1y00iYC21CEair14aABEm5Lr6CIg2cJio5mrkEADGmHBG0LG0pKh6AOaJNtgQmA5aEhC6SjHxicmp6VDAtM7S-nCBCKVxCUlQKWl6qLEAFka05NikGe6outImpADWpLQA7qRqNtOxwNipthAQ5FCIACpQRCQUVNrFCNwAFLEI0gcAlALCnQgAdHZDANTfSsqCQQ2Hbka5ZIw5PLkR4KKAAejhUFoMyBIOu-DEF2kxjMABpbPZpABWfEnIxwAAKgzA0gA5LhwmZacoYfDEcjScQyJRCvJdIDgbtrrVnKy4QAqV4iKAAPTlgnQRgyLjIeloNhqPigtMazWAtNEVHmejgqFQ2AypDg1EYNVoUDAiTgzggJA86s1mlpF10tPerwOWp1AV9hqgxqgpvNlutttqnugtIMOPMfqlUEDkCoHrA1PcoG1mKKBoqolIKWcjo2Nog-ul0szibCEQgBrE4doJrNFqtNbtCe1Kb91wATABmAAsROe4rhArRvQGQxGYyMEwQYsl9dlct3e-3CqVKtIao1GkT0zmi1IbaNncj3ZjffjjvJLrdSLPQZ9CDTIkb2qXvMSy3h2XbRr2cb2ue2rJqYqbvKOk7TlAs6CEAA" rel="nofollow noreferrer">TS Playground

function feed <T extends AliveCat>(cat: T) {
  cat.food++;
}

feed(garfield); // ok
feed({isAlive: true, food: 5, extraProp: 'value'}); // ok, extends AliveCat

feed(tom); /*
     ^^^
Argument of type 'DeadCat' is not assignable to parameter of type 'AliveCat'.
  Type 'DeadCat' is not assignable to type 'Cat<true>'.
    Types of property 'isAlive' are incompatible.
      Type 'false' is not assignable to type 'true'.(2345) */

feed(schrodingersCat); /*
     ^^^^^^^^^^^^^^^
Argument of type 'unknown' is not assignable to parameter of type 'AliveCat'.
  Type 'unknown' is not assignable to type 'Cat<true>'.(2345) */

Discriminate an unknown type at runtime (using a predicate)

Here, runtime validation of the unknown value is performed to ensure that its shape/properties align with the type that is asserted. Doing this gives confidence that the value can be safely acted on according to the type you think it will be in the code block:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/C4TwDgpgBAwghsAPASQM4EEA2BLAbtCAD2AgDsATVKAIwHtbMI5SoBeG+x5gPjagG8AUFCjYMOfAC4oaLHggBuQQF8lg0JChz88YH12JgAJwCuEXgDIBUAGb1y00iYC21CEair14aABEm5Lr6CIg2cJio5mrkEADGmHBG0LG0pKh6AOaJNtgQmA5aEhC6SjHxicmp6VDAtM7S-nCBCKVxCUlQKWl6qLEAFka05NikGe6outImpADWpLQA7qRqNtOxwNipoqgAKj5QiDt8pBD4RtwAFLjhZlOz80sANDU+AGrh2OQItEbSVzcQO5zRakACUbF4dAYTDB0mumDM2ygRyEIiSwBMRhYGgg7xwX1qRn+CIgoKUykEglWpHWmxYNggEHIUAuqDqEGAfRGGSBDzBAmEnSqejE2mKCD4Yj2kEQYt0lzZzg5XNGzxMEJZgpEONoNig6tYhqgAHJaNQAFZxYDGrVQCxWC7quBUZggUEAOlFRTYRuMZlt9pekF1LKdLtIbvddiGPvYxqcrncNpEoLJlJE2D1Fy98l04NRIigiuV3IUUAA9OXCrmELbi5zuVH7ABqZtlytQWgzQUUkR5SICwtF9kN0btqvTYFLHsqSkMpkXLJGHJ5chkitVrvPMbAKgM8hUxnkC61ZzrjtbqDObAZPqZDm2JmiPViKDMas6CUXagmPQLVLGnobixHAJgDtgIqoKQgGgoeC69AMQzcuMebjp2MzPNet73no+7Pki75yrWQA" rel="nofollow noreferrer">TS Playground

function isType <T = never>(value: unknown, typeValidator: (value: unknown) => boolean): value is T {
  return typeValidator(value);
}

function feed (something: unknown) {
  const isAliveCat = isType<AliveCat>(something, u => (
    typeof u === 'object'
    && (u as any).isAlive === true
    && typeof (u as any).food === 'number'
  ));

  if (isAliveCat) {
    something; // AliveCat
    something.food++; // ok
  }
  else {
    something; // unknown
  }
}

feed(garfield); // ok, gets fed
feed(tom); // ok, might get fed if is an AliveCat (but won't because it isn't)
feed(schrodingersCat); // ok, might get fed if is an AliveCat

Original answer

I think you are looking for a discriminated union:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/C4TwDgpgBAwghsAPASQM4EEA2BLAbtCAD2AgDsATVKAIwHtbMI5SoBeG+x5gPjagG8AUFCjYMOfAC4oaLHggBuQQF8lg0JChz88YH12JgAJwCuEXgDIBwqADN65aaRMBbahCNLVg9eGgARJnJdfQREWzhMVHMlDWgATQhgABVaACEIQJIjF2xSCGCEPm0IEIAfKEC4QuA1cggAY0w4I2gG2lJUPQBzFttsCExHLQlShCV6ppa2jq6oYFoXaSqaicbm1qh2zr1UBoALI1pyPO6PVF1pRJT0zKSPXPzVn1sTUgbgbA67CAKACgaCCuSVSGSyDzyBV0AEprCJsLYoACEAA6MQlWFCEQiQHAFH2Y4AakJShEyigg2icOxuPxDmJCigAHoAFQ2bHYgB63M57KgAAUjpAjKAoAByAnkMVQci0CBUUi0PREMR6b5xcUrXRilF-ABMAGYDQBOWEspk+DnAQ60ADuUHy9oAokYjkY-gAiKCSP5QD3Q0lQZQqF6-ch-PY2k6kM5GC4IAPMplQWgAa0EtjDEYOR2jsfjejgVBKMMZTOTaYzWcjudO5xCRcqQVLSZT6ar-wWLigjZLCbLbI5UB5I9HPMEMA6+DjXxYtERGrFWoQ0oW8z84r7wGlLjgIBo0DgUFyXTgqeg7kBJip+Ww1o8680qBMtn6DQGpGAmH3tGnzTAVC2ne+zzPs0BKmBRgojIC77GIUC2o2eQkJ+s6RAANFsU4eHo94UoQYCtKgqCzvMtDim8qaKrapDSv0cZ4jYyQbkuzYrqICpKlhLhgC0cDUIwZGPtAYoGMYZjcDqfLMZAVDzlAhG0MKopiuiozStMojvIsvGfAJEAonyIgySJERRBA0rwYqejtDxfH6UJi7iRZuqGgArHqZoWkAA" rel="nofollow noreferrer">TS Playground

type Cat<IsAlive extends boolean = boolean> = {
  isAlive: IsAlive;
};

type AliveCat = Cat<true> & {
  food: number;
};

type DeadCat = Cat<false>;
type YetToBeDeterminedCat = AliveCat | DeadCat;

declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: YetToBeDeterminedCat;

function feed(cat: YetToBeDeterminedCat) {
  if (cat.isAlive) {
    cat.food++;
  } else {
    cat.food++; /*
        ^^^^
    Property 'food' does not exist on type 'DeadCat'.(2339) */

    throw new Error(" :( ");
  }
}

feed(schrodingersCat); // ok
feed(schrodingersCat as AliveCat); // ok
feed(schrodingersCat as DeadCat); // ok

feed(tom as AliveCat); /*
     ^^^^^^^^^^^^^^^
Conversion of type 'DeadCat' to type 'AliveCat' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type 'DeadCat' is not comparable to type 'Cat<true>'.
    Types of property 'isAlive' are incompatible.
      Type 'false' is not comparable to type 'true'.(2352) */


问:
How to make WebView OSX Xcode project load a URL on launch?
Okay, well I am trying to learn how to develop mac apps. I have done making a web browser and all, but I really want to know how to make the WebView load a URL (lets say http://google.com/) when the apps start. How do I do that?</p>

答:
You could just put </p>

```<code>[webview setMainFrameURL:@"http://www.google.com/"];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You could just put

[webview setMainFrameURL:@"http://www.google.com/"];


问:
How to create dynamic selection field base on condition?
I'm learning to develop something with ODOO 11CE.
   I'd like to filling the "filelds.Selection" with the condition.

So for example:
       If I change the stage of CRM lead the x_status select field will also change.

Here is my tried, But I does not working.

class MYLead(models.Model):
    _inherit = ['crm.lead']

```<code>def _get_status_list(self):
    vals = []
    for rec in self:
        #New
        if rec.stage_id == 1:
            vals.extend([('0', 'Pending'), ('1', 'Ready')])
        #Qualified
        elif rec.stage_id == 2:
            vals.extend([('0', 'Pending'), ('1', 'Waiting])
        #Proposition
        elif rec.stage_id == 3:
        else:
            vals.extend([('0', 'Processing'), ('1', 'Approve'), ('2', 'Pending'), ('-1', 'Reject')])
    return vals

x_status = fields.Selection(selection=_get_status_list, string='Status')
</code>```

答:
This can approached by 3 patterns. they are all used in Odoo code. what makes your code to not work. is that your method definition is in class so it doesn't get called. so to fix it your method must be outside the class definition. your code has to be something like

def _get_status_list(self):
    vals = []
    for rec in self:
        #New
        if rec.stage_id == 1:
            vals.extend([('0', 'Pending'), ('1', 'Ready')])
        #Qualified
        elif rec.stage_id == 2:
            vals.extend([('0', 'Pending'), ('1', 'Waiting])
        #Proposition
        elif rec.stage_id == 3:
        else:
            vals.extend([('0', 'Processing'), ('1', 'Approve'), ('2', 'Pending'), ('-1', 'Reject')])
    return vals

class ModelName(models.Model):
    _name = 'model.name'

    x_status = fields.Selection(selection=_get_status_list, string='Status')
```
<p>another example</p>
<pre class="lang-py prettyprint-override"><code>def _get_purchase_order_states(self):
    return self.env['purchase.order']._fields['state'].selection

class PurchaseReport(models.Model):
    _name = 'purchase.report'

    state = fields.Selection(_get_purchase_order_states, string='Order States')
</code>```

to know about the other 2 patterns you could check the following:
https://dev.to/kerbrose/dynamic-selection-list-in-odoo-for-selection-fields-16h8

Body:
I'm learning to develop something with ODOO 11CE.
   I'd like to filling the "filelds.Selection" with the condition.

So for example:
       If I change the stage of CRM lead the x_status select field will also change.

Here is my tried, But I does not working.

class MYLead(models.Model):
    _inherit = ['crm.lead']

def _get_status_list(self):
    vals = []
    for rec in self:
        #New
        if rec.stage_id == 1:
            vals.extend([('0', 'Pending'), ('1', 'Ready')])
        #Qualified
        elif rec.stage_id == 2:
            vals.extend([('0', 'Pending'), ('1', 'Waiting])
        #Proposition
        elif rec.stage_id == 3:
        else:
            vals.extend([('0', 'Processing'), ('1', 'Approve'), ('2', 'Pending'), ('-1', 'Reject')])
    return vals

x_status = fields.Selection(selection=_get_status_list, string='Status')

Body:
This can approached by 3 patterns. they are all used in Odoo code. what makes your code to not work. is that your method definition is in class so it doesn't get called. so to fix it your method must be outside the class definition. your code has to be something like

def _get_status_list(self):
    vals = []
    for rec in self:
        #New
        if rec.stage_id == 1:
            vals.extend([('0', 'Pending'), ('1', 'Ready')])
        #Qualified
        elif rec.stage_id == 2:
            vals.extend([('0', 'Pending'), ('1', 'Waiting])
        #Proposition
        elif rec.stage_id == 3:
        else:
            vals.extend([('0', 'Processing'), ('1', 'Approve'), ('2', 'Pending'), ('-1', 'Reject')])
    return vals

class ModelName(models.Model):
    _name = 'model.name'

    x_status = fields.Selection(selection=_get_status_list, string='Status')

another example

def _get_purchase_order_states(self):
    return self.env['purchase.order']._fields['state'].selection

class PurchaseReport(models.Model):
    _name = 'purchase.report'

    state = fields.Selection(_get_purchase_order_states, string='Order States')

to know about the other 2 patterns you could check the following:
https://dev.to/kerbrose/dynamic-selection-list-in-odoo-for-selection-fields-16h8


问:
Java console explorer RPG game
This is more of a general question not a specific coding one, but in school we got this assignment to make our own dungeon RPG console explorer game you know the one with tons of text where you type where to go, etc. My question here to the more experienced programmers is what would be the best way to fundamentally approach this like read the text from a file and store the play options into an array, etc. I am open to having to learn anything new. Thanks in advance.</p>

答:
Objected Oriented programming is Java's forte. If you are going with Java, try to take advantage of these primitives.

For example, reading everything from a file and having a user select inputs with his keyboard would be something more akin to scripting, which you could perfectly do with something like Python and would therefore be a situation of using a rocket launcher to kill a mouse.

The array thing, not sure what you mean, but generally storing such information statically in an array is generally not a good idea, especially if the information is already stored in files (unless you're going to be using them all of the time).

Title: Java console explorer RPG game


问:
asp.net: how to do data validation?
i am enabling the user using my asp.net application to add data into a sql server 2008 database.

what is the best way to insert data and be able to validate things like empty fields, integers vs strings?

i am currently using formview to insert the data. how do i validate user input?

答:
I'd get comfortable with asp.net validators first...  After that, there are some really nice ones with jquery, etc.

Here is a great place to get an overview, as well as see them in action.  It has a sandbox area, where you can test it out too.
http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp

Title: asp.net: how to do data validation?


问:
Compute difference between weekly values b country
I need to find out what is the excess death (defined as the difference between deaths that occurred  in a specific week) / country

my table looks something like this:

```<code>Country Dates Death_in_2020 Death_in_2021

Germany 01.01 1700          1800

Germany 01.08 1800          1900

Finland 01.06 1346          1448

Finland 08.06 1444          1555
</code>```

My first idea was to sort the data frame by date and country.

答:
If you want to subtract values in one column from another column, you can do so like this:

df['Excess_Death'] = df['Death_in_2021'] - df['Death_in_2020']
```

Body:
I need to find out what is the excess death (defined as the difference between deaths that occurred  in a specific week) / country

my table looks something like this:

Country Dates Death_in_2020 Death_in_2021

Germany 01.01 1700          1800

Germany 01.08 1800          1900

Finland 01.06 1346          1448

Finland 08.06 1444          1555

My first idea was to sort the data frame by date and country.


问:
VBA Code to Save As .XLSM
Need assistance to add command to save as .xlsm :-</p>

```<code>Private Sub cmdSaveForm1_Click()
    Dim strFolder As String
    Dim i As Long

    'Find the position of the period in the file name
    i = InStr(ActiveWorkbook.Name, ".")

    'Create a default file name by concatenating the file name without the extention _
        plus the current date and time, and plus the xlsm extention
    Filename = Left(ActiveWorkbook.Name, i - 1) & "_" & Format(Now, "yyyy-mm-dd_hh mm") & ".xlsm"

    'Open Save As dialog to a default folder with default file name
    With Application.FileDialog(msoFileDialogSaveAs)
        .AllowMultiSelect = False
        .InitialFileName = "P:\EU Funds Management - Treasury\TRS3_Abstract of Payments\TRS3_Authorisation_L1\" & Filename
        .InitialView = msoFileDialogViewDetails
        If .Show = -1 Then strFolder = .SelectedItems(1) Else Exit Sub
        .Execute
    End With
End Sub
</code>```

答:
Different Fileformats for excel are:

.xlsx = 51 '(52 for Mac)

.xlsm = 52 '(53 for Mac)

.xlsb = 50 '(51 for Mac)

.xls = 56 '(57 for Mac)

```<code>ActiveWorkbook.SaveAs FileFormat:=52   '=.xlsm in Windows
</code>```

Title: VBA Code to Save As .XLSM

Body:
Need assistance to add command to save as .xlsm :-

Private Sub cmdSaveForm1_Click()
    Dim strFolder As String
    Dim i As Long

    'Find the position of the period in the file name
    i = InStr(ActiveWorkbook.Name, ".")

    'Create a default file name by concatenating the file name without the extention _
        plus the current date and time, and plus the xlsm extention
    Filename = Left(ActiveWorkbook.Name, i - 1) & "_" & Format(Now, "yyyy-mm-dd_hh mm") & ".xlsm"

    'Open Save As dialog to a default folder with default file name
    With Application.FileDialog(msoFileDialogSaveAs)
        .AllowMultiSelect = False
        .InitialFileName = "P:\EU Funds Management - Treasury\TRS3_Abstract of Payments\TRS3_Authorisation_L1\" & Filename
        .InitialView = msoFileDialogViewDetails
        If .Show = -1 Then strFolder = .SelectedItems(1) Else Exit Sub
        .Execute
    End With
End Sub

Body:
Different Fileformats for excel are:

.xlsx = 51 '(52 for Mac)

.xlsm = 52 '(53 for Mac)

.xlsb = 50 '(51 for Mac)

.xls = 56 '(57 for Mac)

ActiveWorkbook.SaveAs FileFormat:=52   '=.xlsm in Windows


问:
Promise { <pending> } LOG
i was making meme.js file/command and i got this error idk how to resolve this problem, Can you help me?

so this is my code:

```<code>const fetch = require('node-fetch');
const randomPuppy = require("random-puppy");

module.exports = {
    name: "meme",
    description: "Sends an epic meme",
    execute(message) {
        const subReddits = ["dankmeme", "meme", "me_irl"];
        const random = subReddits[Math.floor(Math.random() * subReddits.length)];

        const img = await randomPuppy(random);
        console.log(img)
        const memeEmbed = new MessageEmbed()
            .setColor("#fa0557")
          //  .setImage(`${img}`)
            .setTitle(`From /r/${random}`)
            .setURL(`https://reddit.com/r/${random}`);

        message.channel.send({ embeds: [memeEmbed] });
    }
}
</code>```

And this is the log i got:

```<code>Promise { <pending> }
</code>```

答:
The posted code throws a syntax error that await can only be used inside an async function - which `module.exports.execute' has not been declared as.

Try declaring execute as an async function

```<code>module.exports = {
    name: "meme",
    description: "Sends an epic meme",
    async execute(message) { . . .
</code>```

If the log in the post does show

```<code>Promise { <pending> }
</code>```

on the console, please update the post with necessary code to reproduce the problem.

Title: Promise { <pending> } LOG

Body:
i was making meme.js file/command and i got this error idk how to resolve this problem, Can you help me?

so this is my code:

const fetch = require('node-fetch');
const randomPuppy = require("random-puppy");

module.exports = {
    name: "meme",
    description: "Sends an epic meme",
    execute(message) {
        const subReddits = ["dankmeme", "meme", "me_irl"];
        const random = subReddits[Math.floor(Math.random() * subReddits.length)];

        const img = await randomPuppy(random);
        console.log(img)
        const memeEmbed = new MessageEmbed()
            .setColor("#fa0557")
          //  .setImage(`${img}`)
            .setTitle(`From /r/${random}`)
            .setURL(`https://reddit.com/r/${random}`);

        message.channel.send({ embeds: [memeEmbed] });
    }
}

And this is the log i got:

Promise { <pending> }

Body:
The posted code throws a syntax error that await can only be used inside an async function - which `module.exports.execute' has not been declared as.

Try declaring execute as an async function

module.exports = {
    name: "meme",
    description: "Sends an epic meme",
    async execute(message) { . . .

If the log in the post does show

Promise { <pending> }

on the console, please update the post with necessary code to reproduce the problem.


答:
Your code as shown will not run.  You show await randomPuppy(random), but await is NOT allowed there because it's not inside an async function.  So, I suspect that your real code does not have the await and that's why you show Promise { <pending> } in your console.  You have to use either await or .then() on the promise that randomPuppy(random) returns.

If I fix your code so that it will run by adding async to the execute() definition, then the console.log(img) actually works just fine:

```<code>const randomPuppy = require("random-puppy");

module.exports = {
    name: "meme",
    description: "Sends an epic meme",
    async execute(message) {
        const subReddits = ["dankmeme", "meme", "me_irl"];
        const random = subReddits[Math.floor(Math.random() * subReddits.length)];

        const img = await randomPuppy(random);
        console.log(img)
    }
}

module.exports.execute().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});
</code>```

And, I get in my console this:

```<code>http://imgur.com/FFkL628.gif
done
</code>```

So, my conclusion is that the code you posted in your question is not the code you're actually running.  This code shown here will work just fine.

Title: Promise { <pending> } LOG

Body:
Your code as shown will not run.  You show await randomPuppy(random), but await is NOT allowed there because it's not inside an async function.  So, I suspect that your real code does not have the await and that's why you show Promise { <pending> } in your console.  You have to use either await or .then() on the promise that randomPuppy(random) returns.

If I fix your code so that it will run by adding async to the execute() definition, then the console.log(img) actually works just fine:

const randomPuppy = require("random-puppy");

module.exports = {
    name: "meme",
    description: "Sends an epic meme",
    async execute(message) {
        const subReddits = ["dankmeme", "meme", "me_irl"];
        const random = subReddits[Math.floor(Math.random() * subReddits.length)];

        const img = await randomPuppy(random);
        console.log(img)
    }
}

module.exports.execute().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

And, I get in my console this:

http://imgur.com/FFkL628.gif
done

So, my conclusion is that the code you posted in your question is not the code you're actually running.  This code shown here will work just fine.


问:
How to copy Youtube text by using pyautogui?
```<code>import pyautogui

pyautogui.moveTo(x=100,y=100,duration=10)

keyDown = ('cntrl')

pyautogui.press('c')
</code>```

step 1 :#importing pyautogui module.
step 2:#moving mouse to the youtube text i want to copy
step 3:#pressing control to copy the text
step 4:#pressing c to copy the text.
In simple words I dont want to do my work of copying youtube title to text file,I wanna automate it,cause its work from free intership.

答:
You might want to try double clicking the text or drag selecting it before ctrl-c.

Also, the pyautogui documentation uses "ctrl" and not "cntrl."

```<code>import pyautogui

ytx = 100
yty = 100

npx = 600
npy = 100

pyautogui.moveTo(x=ytx,y=yty,duration=2)

pyautogui.doubleClick()

pyautogui.hotkey('ctrl', 'c')

pyautogui.moveTo(x=npx,y=npy,duration=2)

pyautogui.click()

pyautogui.hotkey('ctrl', 'v')
</code>```

Body:
import pyautogui

pyautogui.moveTo(x=100,y=100,duration=10)

keyDown = ('cntrl')

pyautogui.press('c')

step 1 :#importing pyautogui module.
step 2:#moving mouse to the youtube text i want to copy
step 3:#pressing control to copy the text
step 4:#pressing c to copy the text.
In simple words I dont want to do my work of copying youtube title to text file,I wanna automate it,cause its work from free intership.

Body:
You might want to try double clicking the text or drag selecting it before ctrl-c.

Also, the pyautogui documentation uses "ctrl" and not "cntrl."

import pyautogui

ytx = 100
yty = 100

npx = 600
npy = 100

pyautogui.moveTo(x=ytx,y=yty,duration=2)

pyautogui.doubleClick()

pyautogui.hotkey('ctrl', 'c')

pyautogui.moveTo(x=npx,y=npy,duration=2)

pyautogui.click()

pyautogui.hotkey('ctrl', 'v')


问:
Find event frequency based on nested object value - MongoDB aggregate
I have the following data schema and trying to find frequency of 'eventType' based on 'country' field. I'm using Mongoose in a Nodejs app.

```<code>{
    username: "jack",
    events: [
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            location: {
                      country: 'US'
                     }
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-30T10:26:11.214Z",
       visitorInfo: {
            location: {
                      country: 'US'
                     }
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-29T10:26:11.214Z",
       visitorInfo: {
             location: {
                      country: 'US'
                     }
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-29T10:26:11.214Z",
       visitorInfo: {
             location: {
                      country: 'US'
                     }
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-31T10:16:11.214Z",
       visitorInfo: {
             location: {
                      country: 'GB'
                     }
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-31T10:16:11.214Z",
       visitorInfo: {
             location: {
                      country: 'GB'
                     }
           }
     },
   {
       eventType: "party",
       createdAt: "2022-01-31T10:16:10.214Z",
       visitorInfo: {
             location: {
                      country: 'GB'
                     }
           }
     }
       ]

    }
</code>```

What I'm trying so far:

```<code> db.collection.aggregate([
  {
   $match: {
   username: "jack"
   }
   },
   {
    $unwind: "$events"
   },
   {
    $match: {
       "events.eventType": "party"
    }
   },

   countries: [
   {
    $group: {
       _id: "$events.visitorInfo.location.country",
       frequency: { $sum: 1 },
       },
     }

    {
      $project: {
        _id: 0,
       countries: "$countries"
       }
     }
    ]
   }
 ])
</code>```

I'm trying to match on event types here and then group on country.
Another approach could be to first get a list of unique countries then find event frequency on each of those countries. Any feedback is appreciated on these approaches.

Basically what I'm hoping to get as result:

```<code>countryAndEventFrequency: [
   {
    country: 'US',
    party: 3,
    meeting: 1
   },
  {
    country: 'GB',
    party: 2,
    meeting: 1
   },
]
</code>```

Appreciate any help or guidance. Thanks!

答:
```<code> db.collection.aggregate([
 {
  $unwind: "$events"
 },
 {
 $project: {
  party: {
    $cond: [
      {
        $eq: [
          "$events.eventType",
          "party"
        ]
      },
      1,
      0
    ]
    },
    meeting: {
     $cond: [
      {
        $eq: [
          "$events.eventType",
          "meeting"
        ]
      },
      1,
      0
       ]
     },
     country: "$events.visitorInfo.location.country"
    }
  },
  {
   $group: {
     _id: "$country",
     meeting: {
       $sum: "$meeting"
     },
    party: {
       $sum: "$party"
     }
   }
  },
  {
   $project: {
    country: "$_id",
    meeting: 1,
     party: 1
   }
   },
   {
   $group: {
    _id: "cc",
     countryAndEventFrequency: {
      $push: "$$ROOT"
    }
   }
   },
   {
    $project: {
  _id: 0,
  countryAndEventFrequency: 1
  }
  }
  ])
</code>```

explained:

unwind the events array

project to split party & meeting from eventType

group to count the meetings & party by country

project the necessary fields.

Move the documents to the countryAndEventFrequency array

playground

Body:
I have the following data schema and trying to find frequency of 'eventType' based on 'country' field. I'm using Mongoose in a Nodejs app.

{
    username: "jack",
    events: [
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            location: {
                      country: 'US'
                     }
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-30T10:26:11.214Z",
       visitorInfo: {
            location: {
                      country: 'US'
                     }
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-29T10:26:11.214Z",
       visitorInfo: {
             location: {
                      country: 'US'
                     }
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-29T10:26:11.214Z",
       visitorInfo: {
             location: {
                      country: 'US'
                     }
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-31T10:16:11.214Z",
       visitorInfo: {
             location: {
                      country: 'GB'
                     }
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-31T10:16:11.214Z",
       visitorInfo: {
             location: {
                      country: 'GB'
                     }
           }
     },
   {
       eventType: "party",
       createdAt: "2022-01-31T10:16:10.214Z",
       visitorInfo: {
             location: {
                      country: 'GB'
                     }
           }
     }
       ]

    }

What I'm trying so far:

 db.collection.aggregate([
  {
   $match: {
   username: "jack"
   }
   },
   {
    $unwind: "$events"
   },
   {
    $match: {
       "events.eventType": "party"
    }
   },

   countries: [
   {
    $group: {
       _id: "$events.visitorInfo.location.country",
       frequency: { $sum: 1 },
       },
     }

    {
      $project: {
        _id: 0,
       countries: "$countries"
       }
     }
    ]
   }
 ])

I'm trying to match on event types here and then group on country.
Another approach could be to first get a list of unique countries then find event frequency on each of those countries. Any feedback is appreciated on these approaches.

Basically what I'm hoping to get as result:

countryAndEventFrequency: [
   {
    country: 'US',
    party: 3,
    meeting: 1
   },
  {
    country: 'GB',
    party: 2,
    meeting: 1
   },
]

Appreciate any help or guidance. Thanks!

Body:
 db.collection.aggregate([
 {
  $unwind: "$events"
 },
 {
 $project: {
  party: {
    $cond: [
      {
        $eq: [
          "$events.eventType",
          "party"
        ]
      },
      1,
      0
    ]
    },
    meeting: {
     $cond: [
      {
        $eq: [
          "$events.eventType",
          "meeting"
        ]
      },
      1,
      0
       ]
     },
     country: "$events.visitorInfo.location.country"
    }
  },
  {
   $group: {
     _id: "$country",
     meeting: {
       $sum: "$meeting"
     },
    party: {
       $sum: "$party"
     }
   }
  },
  {
   $project: {
    country: "$_id",
    meeting: 1,
     party: 1
   }
   },
   {
   $group: {
    _id: "cc",
     countryAndEventFrequency: {
      $push: "$$ROOT"
    }
   }
   },
   {
    $project: {
  _id: 0,
  countryAndEventFrequency: 1
  }
  }
  ])

explained:

unwind the events array

project to split party & meeting from eventType

group to count the meetings & party by country

project the necessary fields.

Move the documents to the countryAndEventFrequency array

playground


问:
3rd Person POV for Game Ursina
I am trying to make an rpg-style game with ursina. I want to have the camera always follow the back of the character. I tried using camera.look_at(player) but I couldn't get the camera to rotate to the back of the character when it rotated.</p>
```<code>app = Ursina()

class character(Entity):
    def __init__(self):
        super().__init__(
            model = load_model('cube'),
            color = color.red,
            position = (-0, -3, -8)
        )

player = character()

print(player.forward)

print(player.forward)
camera.look_at(player)
player.rotation_y =180
def update():
    if held_keys['a']:
        player.rotation_y -= 2
    if held_keys['d']:
        player.rotation_y += 2

app.run()```
</code>```

答:
If anyone wants to use FirstPersonController, I found out how to move the camera away from the player, while keeping all physics interactions!

After creating the FirstPersonController, modify the position of its camera_pivot (default is (0,2,0)).

player = FirstPersonController(model="cube", color=color.orange, origin_y=-.5,z=-10)

# the default camera_pivot is (0,2,0)
player.camera_pivot.z = -3.5  # move the camera behind the player model
player.camera_pivot.y = 2.5  # move the camera a little higher
```
<hr />
<p>Full example (q to quit)</p>
<pre class="lang-py prettyprint-override"><code>from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
from ursina.shaders import lit_with_shadows_shader

app = Ursina()

Entity.default_shader = lit_with_shadows_shader

ground = Entity(model='plane', collider='box', scale=64, color=color.green)
player = FirstPersonController(model="cube", color=color.orange, origin_y=-.5,z=-10)

# the default camera_pivot is (0,2,0)
player.camera_pivot.z = -3.5  # move the camera behind the player model
player.camera_pivot.y = 2.5  # move the camera a little higher

# setting collider and making it visible for debugging
player.collider = BoxCollider(player, Vec3(0,1,0), Vec3(1,2,1))
player.collider.visible=True

# adding some objects to collide with
for i in range(16):
    Entity(model='cube', origin_y=-.5, scale=2, texture='brick', texture_scale=(1,2),
        x=random.uniform(-8,8),
        z=random.uniform(-8,8) + 8,
        collider='box',
        scale_y = random.uniform(2,3),
        color=color.hsv(0, 0, random.uniform(.9, 1))
    )

sun = DirectionalLight()
sun.look_at(Vec3(1,-1,-1))
Sky()

def input(key):
    if key == 'q':
        exit()

app.run()
</code>```

Title: 3rd Person POV for Game Ursina

Body:
I am trying to make an rpg-style game with ursina. I want to have the camera always follow the back of the character. I tried using camera.look_at(player) but I couldn't get the camera to rotate to the back of the character when it rotated.

app = Ursina()

class character(Entity):
    def __init__(self):
        super().__init__(
            model = load_model('cube'),
            color = color.red,
            position = (-0, -3, -8)
        )

player = character()

print(player.forward)

print(player.forward)
camera.look_at(player)
player.rotation_y =180
def update():
    if held_keys['a']:
        player.rotation_y -= 2
    if held_keys['d']:
        player.rotation_y += 2

app.run()```

Body:
If anyone wants to use FirstPersonController, I found out how to move the camera away from the player, while keeping all physics interactions!

After creating the FirstPersonController, modify the position of its camera_pivot (default is (0,2,0)).

player = FirstPersonController(model="cube", color=color.orange, origin_y=-.5,z=-10)

# the default camera_pivot is (0,2,0)
player.camera_pivot.z = -3.5  # move the camera behind the player model
player.camera_pivot.y = 2.5  # move the camera a little higher

Full example (q to quit)

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
from ursina.shaders import lit_with_shadows_shader

app = Ursina()

Entity.default_shader = lit_with_shadows_shader

ground = Entity(model='plane', collider='box', scale=64, color=color.green)
player = FirstPersonController(model="cube", color=color.orange, origin_y=-.5,z=-10)

# the default camera_pivot is (0,2,0)
player.camera_pivot.z = -3.5  # move the camera behind the player model
player.camera_pivot.y = 2.5  # move the camera a little higher

# setting collider and making it visible for debugging
player.collider = BoxCollider(player, Vec3(0,1,0), Vec3(1,2,1))
player.collider.visible=True

# adding some objects to collide with
for i in range(16):
    Entity(model='cube', origin_y=-.5, scale=2, texture='brick', texture_scale=(1,2),
        x=random.uniform(-8,8),
        z=random.uniform(-8,8) + 8,
        collider='box',
        scale_y = random.uniform(2,3),
        color=color.hsv(0, 0, random.uniform(.9, 1))
    )

sun = DirectionalLight()
sun.look_at(Vec3(1,-1,-1))
Sky()

def input(key):
    if key == 'q':
        exit()

app.run()


问:
Yarn 3 and Node 17: file extension resolution fails?
After upgrading to Yarn 3.0 with Yarn Plug'n'Play (throw out node_modules), I started having issues with filename resolution when starting Node.

After successfully starting server.js it tries to resolve the first imported file in the project, called util.js, but path resolution fails unless I explicitly add .js to the filename. I would prefer to not have to update all paths project-wide.

Can I make Yarn and Node resolve the .js file extensions automatically?

Yarn 3.1.0, Node 17.0.1.

yarn node server.js # Automatically uses Yarn's .pnp.cjs, right?
```
<pre class="lang-js prettyprint-override"><code>// server.js excerpt
import util from "/tools/util"; // <--  No worky
import util from "/tools/util.js"; // <-- ✅ Worky
</code>```

The error message:

```<code>/Users/me/repo/.pnp.cjs:22839
  return Object.defineProperties(new Error(message), {
                                 ^

Error: Qualified path resolution failed - none of those files can be found on the disk.

Source path: /Users/me/repo/server/util
Not found: /Users/me/repo/server/util

    at internalTools_makeError (/Users/me/repo/.pnp.cjs:22839:34)
    at resolveUnqualified (/Users/me/repo/.pnp.cjs:24238:13)
    at resolveRequest (/Users/me/repo/.pnp.cjs:24271:14)
    at Object.resolveRequest (/Users/me/repo/.pnp.cjs:24343:26)
    at resolve$1 (file:///Users/me/repo/.pnp.loader.mjs:205:25)
    at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36)
</code>```

答:
I was able to get past this, but not without giving up PnP. Here's how I did it:

First, add --experimental-specifier-resolution=node to the node command that actually runs your code. I'm using typescript, so my final command looks like:

```<code>tsc-watch --onSuccess \"node --experimental-specifier-resolution=node ./lib/index.js\"
</code>```

I was hoping this flag would work with PnP but it didn't. So I went into .yarnrc.yml and added the following line:

```<code>nodeLinker: node-modules
</code>```

After re-running yarn, I was able to yarn dev and run my app. I'm really not sure why PnP didn't work here, but I'm OK sacrificing this "purity" of my local configuration for something that, you know, actually works.

The final piece for those running yarn workspaces and typescript: make sure that your package.json files point towards the compiled javascript, not the typescript files, e.g. for a lib/ output dir:

```<code>  "type": "module",
  "main": "lib/index.js",
  "types": "lib/index.d.ts",
</code>```

Body:
After upgrading to Yarn 3.0 with Yarn Plug'n'Play (throw out node_modules), I started having issues with filename resolution when starting Node.

After successfully starting server.js it tries to resolve the first imported file in the project, called util.js, but path resolution fails unless I explicitly add .js to the filename. I would prefer to not have to update all paths project-wide.

Can I make Yarn and Node resolve the .js file extensions automatically?

Yarn 3.1.0, Node 17.0.1.

yarn node server.js # Automatically uses Yarn's .pnp.cjs, right?

// server.js excerpt
import util from "/tools/util"; // <--  No worky
import util from "/tools/util.js"; // <-- ✅ Worky

The error message:

/Users/me/repo/.pnp.cjs:22839
  return Object.defineProperties(new Error(message), {
                                 ^

Error: Qualified path resolution failed - none of those files can be found on the disk.

Source path: /Users/me/repo/server/util
Not found: /Users/me/repo/server/util

    at internalTools_makeError (/Users/me/repo/.pnp.cjs:22839:34)
    at resolveUnqualified (/Users/me/repo/.pnp.cjs:24238:13)
    at resolveRequest (/Users/me/repo/.pnp.cjs:24271:14)
    at Object.resolveRequest (/Users/me/repo/.pnp.cjs:24343:26)
    at resolve$1 (file:///Users/me/repo/.pnp.loader.mjs:205:25)
    at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36)

Body:
I was able to get past this, but not without giving up PnP. Here's how I did it:

First, add --experimental-specifier-resolution=node to the node command that actually runs your code. I'm using typescript, so my final command looks like:

tsc-watch --onSuccess \"node --experimental-specifier-resolution=node ./lib/index.js\"

I was hoping this flag would work with PnP but it didn't. So I went into .yarnrc.yml and added the following line:

nodeLinker: node-modules

After re-running yarn, I was able to yarn dev and run my app. I'm really not sure why PnP didn't work here, but I'm OK sacrificing this "purity" of my local configuration for something that, you know, actually works.

The final piece for those running yarn workspaces and typescript: make sure that your package.json files point towards the compiled javascript, not the typescript files, e.g. for a lib/ output dir:

  "type": "module",
  "main": "lib/index.js",
  "types": "lib/index.d.ts",


问:
Python's unittest `assertCouldNotTest`?
I am using Python's unittest module to do some testing that some probability density functions that I have implemented integrate to 1. To test this I am using Scipy's quad function:

integral, err = integrate.quad(my_pdf, -float('inf'), float('inf'))
self.assertTrue(isclose(integral, 1))
```
<p>where <code>isclose</code> is from Python's math. For some PDFs it happens that <code>err</code> is > 1 and <code>integral</code> is "very far from 1" such as I would consider this a fail. However this is not a fail of <code>my_pdf</code> but a fail of the testing method. To avoid flagging  this as a fail I can do</p>
```if err > 1:
    continue
```
<p>but in this case I completely skipping this case without any clue that it happened.</p>
<p>Is it possible to somehow flag this kind of failure within <code>unittest</code>? Somthing like</p>
<pre class="lang-py prettyprint-override"><code>if err > 1:
    self.couldNotTest()
</code>```

such that in the end unittest will tell me the number of tests that could not be performed?

答:
This sound sketchy overall (If pdfs with integrals very far from 1 are unsupported, and that's expected, then why are you attempting to test them, in the first place?)

In any case, I think you're looking for TestCase.skipTest

Title: Python's unittest `assertCouldNotTest`?

Body:
I am using Python's unittest module to do some testing that some probability density functions that I have implemented integrate to 1. To test this I am using Scipy's quad function:

integral, err = integrate.quad(my_pdf, -float('inf'), float('inf'))
self.assertTrue(isclose(integral, 1))

where isclose is from Python's math. For some PDFs it happens that err is > 1 and integral is "very far from 1" such as I would consider this a fail. However this is not a fail of my_pdf but a fail of the testing method. To avoid flagging  this as a fail I can do

if err > 1:
    continue

but in this case I completely skipping this case without any clue that it happened.

Is it possible to somehow flag this kind of failure within unittest? Somthing like

if err > 1:
    self.couldNotTest()

such that in the end unittest will tell me the number of tests that could not be performed?


问:
Get an access token to Sharepoint and GraphAPI
I'd like to access both the Sharepoint Rest API and the GraphAPI using an access token acquired using the MSAL.js library.

I always get Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown.
On Sharepoint though.

How can I acquire 2 access tokens (one for Sharepoint one for Graph)?

This is my current authentication flow:

This is my current config in Azure:

答:
You need to swap your graph auth token for one that will work with the SharePoint REST API.

I detailed the process here: https://stackoverflow.com/a/63386756/26843


问:
How to have cursor change with buttonclick
I have set up a switcher on my website to toggle between normal mouse / pointer & a Lego hand as a cursor and a head as pointer. However, I can only get the cursor to show when clicking the switcher. How can I also add this pointer

(cursor: url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/pointer.png?v=1644096049), pointer;)

It should be assigned to the following classes:

a, button, input, input, button, a, input, .slider, .round

I have then also added a snippet, which lets the switcher / checkbox stay on checked...
(You can see that on this video [password is 12345678]: https://easyupload.io/gknxoi)

However after a reload of the page for example, the switcher stays on checked, but the cursor doesn't show up...

var cbs = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < cbs.length; i++) {
  cbs[i].addEventListener('change', function() {
    if (this.checked) {
      document.body.style.cursor = "url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto";
    } else {
      document.body.style.cursor = "default";
    }
  });
}

$(function() {
  var test = localStorage.input === 'true' ? true : false;
  $('input').prop('checked', test || false);
});

$('input').on('change', function() {
  localStorage.input = $(this).is(':checked');
  console.log($(this).is(':checked'));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.switcheronheader {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
  margin-bottom: 2px;
}

.mouseswitcher {
  /*   border-left: 1px solid #248751; */
  padding-left: 20px;
}

.switcheronheader input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #248751;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}</code>```

                     <input type="checkbox" id="overheaderswitch">

```

答:
Use document.querySelector('html') instead of document.body will make it work.

Also, use cursor: auto instead of cursor: default

var cbs = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < cbs.length; i++) {
  cbs[i].addEventListener('change', function() {
    if (this.checked) {
      document.querySelector('html').style.cursor= ' url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto'
      document.querySelector('label').style.cursor = ' url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto'
    } else {
       document.querySelector('html').style.cursor = "auto";
      document.querySelector('label').style.cursor = 'auto'
    }

  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.switcheronheader {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
  margin-bottom: 2px;
}

.mouseswitcher {
  /*   border-left: 1px solid #248751; */
  padding-left: 20px;
}

.switcheronheader input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #248751;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}</code>```

                        <input type="checkbox" id="overheaderswitch">

                 ```

Body:
I have set up a switcher on my website to toggle between normal mouse / pointer & a Lego hand as a cursor and a head as pointer. However, I can only get the cursor to show when clicking the switcher. How can I also add this pointer

(cursor: url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/pointer.png?v=1644096049), pointer;)

It should be assigned to the following classes:

a, button, input, input, button, a, input, .slider, .round

I have then also added a snippet, which lets the switcher / checkbox stay on checked...
(You can see that on this video [password is 12345678]: https://easyupload.io/gknxoi)

However after a reload of the page for example, the switcher stays on checked, but the cursor doesn't show up...

var cbs = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < cbs.length; i++) {
  cbs[i].addEventListener('change', function() {
    if (this.checked) {
      document.body.style.cursor = "url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto";
    } else {
      document.body.style.cursor = "default";
    }
  });
}

$(function() {
  var test = localStorage.input === 'true' ? true : false;
  $('input').prop('checked', test || false);
});

$('input').on('change', function() {
  localStorage.input = $(this).is(':checked');
  console.log($(this).is(':checked'));
});

.switcheronheader {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
  margin-bottom: 2px;
}

.mouseswitcher {
  /*   border-left: 1px solid #248751; */
  padding-left: 20px;
}

.switcheronheader input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #248751;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

                     <input type="checkbox" id="overheaderswitch">

Body:
Use document.querySelector('html') instead of document.body will make it work.

Also, use cursor: auto instead of cursor: default

var cbs = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < cbs.length; i++) {
  cbs[i].addEventListener('change', function() {
    if (this.checked) {
      document.querySelector('html').style.cursor= ' url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto'
      document.querySelector('label').style.cursor = ' url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto'
    } else {
       document.querySelector('html').style.cursor = "auto";
      document.querySelector('label').style.cursor = 'auto'
    }

  });
}

.switcheronheader {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
  margin-bottom: 2px;
}

.mouseswitcher {
  /*   border-left: 1px solid #248751; */
  padding-left: 20px;
}

.switcheronheader input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #248751;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mouseswitcher">

  <label class="switcheronheader">
                        <input type="checkbox" id="overheaderswitch">
                     <span class="slider round"></span>
                </label>

</div>


问:
Filter out records that exceed certain count
was hoping someone could advise on the following problem.

I have a table similar to below and am trying to filter out all IDs that have the same subject and date (not just dedupe but remove complete) from my output.

ID
Date
Subject
Type

abc
1/22/22
Welcome>
Email

def
1/23/22
Offer!
Call

xyz
1/22/22
Welcome>
Email

So in the example above we would want to remove both rows with subject, "Welcome>"

I am able to write a query that shows me the count of IDs per subject and date, but stuck finding a way to remove these from my final output.

```<code>  select distinct
  activitydate,
  name,
  subject,
  count (id)
  from activity
  where activity.activitydate between X and Y'
  and type IN ('Email')
  group by 1,2,3
  having count (id) > 30
  order by count (id) desc
</code>```

Please let me know if any further details are needed and thank you in advance!

答:
```<code>-- Filter out all IDs that have the same subject and date
SELECT
    Date,
    Subject,
    COUNT(*)
FROM
    activity
GROUP BY
    Date,
    Subject
HAVING
    COUNT(*) < 2
</code>```

Body:
was hoping someone could advise on the following problem.

I have a table similar to below and am trying to filter out all IDs that have the same subject and date (not just dedupe but remove complete) from my output.

ID
Date
Subject
Type

abc
1/22/22
Welcome>
Email

def
1/23/22
Offer!
Call

xyz
1/22/22
Welcome>
Email

So in the example above we would want to remove both rows with subject, "Welcome>"

I am able to write a query that shows me the count of IDs per subject and date, but stuck finding a way to remove these from my final output.

  select distinct
  activitydate,
  name,
  subject,
  count (id)
  from activity
  where activity.activitydate between X and Y'
  and type IN ('Email')
  group by 1,2,3
  having count (id) > 30
  order by count (id) desc

Please let me know if any further details are needed and thank you in advance!


问:
How important is it to check for malloc failures?
Is always protecting mallocs important? By protecting I mean:

```<code>char *test_malloc = malloc(sizeof(char) * 10000);

if (!test_malloc)
  exit(EXIT_FAILURE);
</code>```

I mean, in electronic devices, I don't doubt it's essential.
But in programs I'm running on my own machine that I'm sure my allocation size will be positive and that the size will not be astronomical.
Some people say, "Ah imagine there’s not enough memory in your computer at this moment."

答:
The other reason it's a good idea to check for malloc failures (and why I always do) is: to catch programming mistakes.

It's true, memory is effectively infinite on many machines today, so malloc almost never fails because it ran out of memory.  But it often fails (for me, at least) because I screwed up and overwrote memory in some way, screwing up the heap, and the next call to malloc often returns NULL to let you know it noticed the corruption.  And that's something I really want to know about, and fix.

Over the years, probably 10% of the time malloc has returned NULL on me was because it was out of memory, and the other 90% was because of those other problems, my problems, that I really needed to know about.

So, to this day, I still maintain a pretty religious habit of always checking malloc.

Body:
Is always protecting mallocs important? By protecting I mean:

char *test_malloc = malloc(sizeof(char) * 10000);

if (!test_malloc)
  exit(EXIT_FAILURE);

I mean, in electronic devices, I don't doubt it's essential.
But in programs I'm running on my own machine that I'm sure my allocation size will be positive and that the size will not be astronomical.
Some people say, "Ah imagine there’s not enough memory in your computer at this moment."


问:
hide items in xcode app?
I am newbie to iPhone development. I have a Root.plist under Settings.bundl like below image.
While doing Adhoc testing with users. we used Item 0, Item 1, Item 2 for testing. because there is web service url in item1. Now we are planning to move this app to app store. So we dont need show this information settings to user. How can I hide these items to user? but we still need this info for app usage.

答: You need to store your URL elsewhere in your app, not in a Settings bundle. You could hard-code the string as a variable, use NSUserDefaults, or a database.</p>

Title: hide items in xcode app?