问:
mongo query is hanging in filter of mono
I am facing mongo reactive repository hanging issue which cause the whole application hanging.

shipment.getItems().forEach(item -> {
    return deliveryRepository.findById(item.getDeliveryNumber())
        .filter(delivery -> Objects.isNull(delivery.getState()) || !delivery.getState().equals(TrackObjectState.DELIVERED))
        .filter(delivery -> deliveryStatusShouldBeUpdatedToDelivered(delivery, shipment, gamMessage))
        .flatMap(delivery -> {
            delivery.setState(TrackObjectState.DELIVERED);
            return deliveryRepository.save(delivery);
        }).subscribe(delivery -> log.info("delivery: " + delivery.getDeliveryNumber() + " is updated to state delivered"));
});
```
<p>inside method deliveryStatusShouldBeUpdatedToDelivered, I called a another service named incotermLocationService via blow code.</p>
<pre class="lang-java prettyprint-override"><code>var alternativeLocations = incotermLocationService.getAlternativeUnLocationCodesByUnlocationCode(destinationLocation).blockOptional();
</code>```

and this incotermLocationService code as following.

public Mono<Set<String>> getAlternativeUnLocationCodesByUnlocationCode(String unlocationCode) {
    if (log.isDebugEnabled()) {
        log.debug("alternative location get by un-location code is called with un-location code: " + unlocationCode);
    }

    return incotermLocationRepository.getAlternativeLocationsByUnLocationCode(unlocationCode)
        .flatMap(incotermLocation -> Flux.fromIterable(incotermLocation.getUnLocationCodes()))
        .map( unloCode -> { log.debug("unlocationCode: " +  unloCode + " is returned"); return unloCode;})
        .collect(Collectors.toSet());
}
```
<p>but this incotermLocationRepository.getAlternativeLocationsByUnLocationCode() was in hanging for ever.
I checked this method which was called in other place works well. Then I take it out from the filter.</p>
<pre class="lang-java prettyprint-override"><code>shipment.getItems().forEach(item -> {
    var deliveryOptional = deliveryRepository.findById(item.getDeliveryNumber())
        .filter(delivery -> Objects.isNull(delivery.getState()) || !delivery.getState().equals(TrackObjectState.DELIVERED))
        .blockOptional();

    if (deliveryOptional.isPresent() && deliveryStatusShouldBeUpdatedToDelivered(deliveryOptional.get(), shipment, gamMessage)) {
        var delivery = deliveryOptional.get();
        deliveryOptional.get().setState(TrackObjectState.DELIVERED);
        deliveryRepository.save(delivery).subscribe(savedDelivery -> log.info("delivery: " + delivery.getDeliveryNumber() + " is updated to state delivered"));
    }
});
</code>```

Then repository was called and the whole logic works as expected.
Did u face this before that a reactive repository used in a filter method never triggered even it is called with block?

Body:
I am facing mongo reactive repository hanging issue which cause the whole application hanging.

shipment.getItems().forEach(item -> {
    return deliveryRepository.findById(item.getDeliveryNumber())
        .filter(delivery -> Objects.isNull(delivery.getState()) || !delivery.getState().equals(TrackObjectState.DELIVERED))
        .filter(delivery -> deliveryStatusShouldBeUpdatedToDelivered(delivery, shipment, gamMessage))
        .flatMap(delivery -> {
            delivery.setState(TrackObjectState.DELIVERED);
            return deliveryRepository.save(delivery);
        }).subscribe(delivery -> log.info("delivery: " + delivery.getDeliveryNumber() + " is updated to state delivered"));
});

inside method deliveryStatusShouldBeUpdatedToDelivered, I called a another service named incotermLocationService via blow code.

var alternativeLocations = incotermLocationService.getAlternativeUnLocationCodesByUnlocationCode(destinationLocation).blockOptional();

and this incotermLocationService code as following.

public Mono<Set<String>> getAlternativeUnLocationCodesByUnlocationCode(String unlocationCode) {
    if (log.isDebugEnabled()) {
        log.debug("alternative location get by un-location code is called with un-location code: " + unlocationCode);
    }

    return incotermLocationRepository.getAlternativeLocationsByUnLocationCode(unlocationCode)
        .flatMap(incotermLocation -> Flux.fromIterable(incotermLocation.getUnLocationCodes()))
        .map( unloCode -> { log.debug("unlocationCode: " +  unloCode + " is returned"); return unloCode;})
        .collect(Collectors.toSet());
}

but this incotermLocationRepository.getAlternativeLocationsByUnLocationCode() was in hanging for ever.
I checked this method which was called in other place works well. Then I take it out from the filter.

shipment.getItems().forEach(item -> {
    var deliveryOptional = deliveryRepository.findById(item.getDeliveryNumber())
        .filter(delivery -> Objects.isNull(delivery.getState()) || !delivery.getState().equals(TrackObjectState.DELIVERED))
        .blockOptional();

    if (deliveryOptional.isPresent() && deliveryStatusShouldBeUpdatedToDelivered(deliveryOptional.get(), shipment, gamMessage)) {
        var delivery = deliveryOptional.get();
        deliveryOptional.get().setState(TrackObjectState.DELIVERED);
        deliveryRepository.save(delivery).subscribe(savedDelivery -> log.info("delivery: " + delivery.getDeliveryNumber() + " is updated to state delivered"));
    }
});

Then repository was called and the whole logic works as expected.
Did u face this before that a reactive repository used in a filter method never triggered even it is called with block?


来源: stackexchange

问:
Django include template show no data
I am trying to include a html file, into my course page , but when i add the code it show just first tag that is h3 and don't show other data why ?

the code : {% include 'android/side_bar_good_posts.html' %}

note : i have added this code in other pages in my website and it work and show all data but in this page course it don't show anything else ( most read articles ) word

ContentLicense: CC BY-SA 4.0

Title: Django include template show no data


问:
how to find order count in the category sql php
I have tables as below. All I want is for how many orders the category. I tried so hard but I couldn't.

Categories:

ID
Name

1
Shoes

2
Tshirt

Products:

ID
Name
Category

1
Blue Tshirt
2

2
Green Shoes
1

Orders:

ID
ProductID

1
1

2
1

3
2

4
1

5
2

The result I want:

Shoes: 2 order.

Tshirt: 3 order.


问:
How can I detect if there are duplicates in a C# array and can I replace them with another suitable value in the same place in the array?
I'm kind of new to C# and I'm trying to make a sudoku game. I'm using a for loop to loop through the column arrays and add a random number to the spots but I'm using Random and Next() so it allows the numbers to repeat. But because I can't have more than one of a number in each column (array) for it to function, how can I replace the repeated number with another number that isn't repeated? I don't know how to do this.

Also the columns are stored in other arrays that I've called rows just so that I can say Row1[0][2] to access position 3 in column 1 for example.

Here's the method & for loop I'm using to replace add the numbers to the arrays:

```<code>void populateColumns(int[][] arr) // goes through column arrays and replaces the numbers with random ones from Num()
{
    int i;
    int j = 0;

    for (int l = 0; l <= 8; l++)
    {
        for (i = 0; i <= 8; i++)
        {
            arr[j][i] = Num();
            int currentPos = arr[j][i];
            Console.Write(currentPos);
        }

        j = l;
    }
}
</code>```

Body:
I'm kind of new to C# and I'm trying to make a sudoku game. I'm using a for loop to loop through the column arrays and add a random number to the spots but I'm using Random and Next() so it allows the numbers to repeat. But because I can't have more than one of a number in each column (array) for it to function, how can I replace the repeated number with another number that isn't repeated? I don't know how to do this.

Also the columns are stored in other arrays that I've called rows just so that I can say Row1[0][2] to access position 3 in column 1 for example.

Here's the method & for loop I'm using to replace add the numbers to the arrays:

void populateColumns(int[][] arr) // goes through column arrays and replaces the numbers with random ones from Num()
{
    int i;
    int j = 0;

    for (int l = 0; l <= 8; l++)
    {
        for (i = 0; i <= 8; i++)
        {
            arr[j][i] = Num();
            int currentPos = arr[j][i];
            Console.Write(currentPos);
        }

        j = l;
    }
}


问:
Can I configure VSCode to auto copy my file to another file whenever I save?
I am new to VSCode. Is there a way VSCode can auto save all my saves to a sequence of files? For example, my file is named foo.c, after some editing, the first time I save the file, there is a file foo.c_1 generated, the 2nd time foo.c_2, the 3rd foo.c_3, etc.

savevers.vim is what I have been using for vim. It is super convenient, say, when I want to retrieve a version I did the day before.

[Update] Yes, thanks life888888, timeline works great, it saves the history after I close and reopen the project folder.


问:
Why does my PyODBC parameterized date query return too much data?
I have a QODBC query for QuickBooks that generates Profit & Loss report with dynamic columns. The parameterized date value works to return the requested three daily values, AND 300+ more columns of None!

```<code>sql1 = textwrap.dedent("""
    sp_report
        ProfitAndLossStandard
    show
        "AccountNumber",
        "Text",
        "Label",
        "RowType",
        "Amount"   <-- dynamic
    parameters
        DateFrom=?,
        DateTo=?,
        ReportBasis='Accrual',
        SummarizeColumnsBy='Day',
        ReturnRows='All'
    """)

cursor.execute(sql1, date(2022,11,1), date(2022,11,3))
for row in cursor.fetchall():
    print(row)
</code>```

The first row looks like this:

(None, 'Ordinary Income/Expense', None, 'TextRow', 366, None, None, None, None, None, None, None, None, ... (300+), None)

But if I declare the date parameter using the ODBC escape sequence:

```<code>parameters
    DateFrom={d'2022-11-01'},
    DateTo={d'2022-11-03'},
</code>```

Then, I get the sensible results:

(None, 'Ordinary Income/Expense', None, 'TextRow', 4, None, None, None, None)

Why does my PyODBC parameterized date query return too much data?

Bonus: See the additional column (not named in the query) which shows 366 in the first query and 4 in the second--What is this?

Note: The None values are not significant to the problem. It's the number of columns per row that's the issue.

Body:
I have a QODBC query for QuickBooks that generates Profit & Loss report with dynamic columns. The parameterized date value works to return the requested three daily values, AND 300+ more columns of None!

sql1 = textwrap.dedent("""
    sp_report
        ProfitAndLossStandard
    show
        "AccountNumber",
        "Text",
        "Label",
        "RowType",
        "Amount"   <-- dynamic
    parameters
        DateFrom=?,
        DateTo=?,
        ReportBasis='Accrual',
        SummarizeColumnsBy='Day',
        ReturnRows='All'
    """)

cursor.execute(sql1, date(2022,11,1), date(2022,11,3))
for row in cursor.fetchall():
    print(row)

The first row looks like this:

(None, 'Ordinary Income/Expense', None, 'TextRow', 366, None, None, None, None, None, None, None, None, ... (300+), None)

But if I declare the date parameter using the ODBC escape sequence:

parameters
    DateFrom={d'2022-11-01'},
    DateTo={d'2022-11-03'},

Then, I get the sensible results:

(None, 'Ordinary Income/Expense', None, 'TextRow', 4, None, None, None, None)

Why does my PyODBC parameterized date query return too much data?

Bonus: See the additional column (not named in the query) which shows 366 in the first query and 4 in the second--What is this?

Note: The None values are not significant to the problem. It's the number of columns per row that's the issue.


问:
Issues with TS modules (Cannot find module './api/api.js' or its corresponding type )
Yo I am making something with TypeScript and Node and I ran into this issue:

Cannot find module './api/api.js' or its corresponding type declarations.ts(2307)

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es2022",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}
</code>```

Package.json:

```<code>{
  "name": "xmas",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon src/main.ts",
    "build": "tsc -p .",
    "start": "node dist/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/bcryptjs": "^2.4.2",
    "@types/pouchdb": "^6.4.0",
    "@types/uuid": "^9.0.0",
    "bcryptjs": "^2.4.3",
    "pouchdb": "^8.0.0",
    "uuid": "^9.0.0"
  }
}
</code>```

Main.ts:

```<code>import * as API from './api/api.js';
var newacc = API.default.newacc;

newacc("imnotgay", "moveimggay");
</code>```

And /api/api.js:

```<code>import newacc from './newacc.js';
export default {
    newacc
}
</code>```

/api/newacc.js:

```<code>import bcrypt from 'bcryptjs';
import db from 'pouchdb';
var accounts = new db('accounts')
import { v4 as uuidv4 } from 'uuid';
export default (uname, pword) => {
        var uname = uname.toLowerCase()
    return new Promise((resolve, reject) => {

        if(pword.length < 3) {
            resolve( {success: false, errormsg: "Password has to be atleast 2 characters"})
        } else {
        if(/^[\w]+([-_\s]{1}[a-z0-9]+)*$/i.test(uname)) {
            if(uname.length > 3 && uname.length <17) {
                bcrypt.hash(pword, 10).then((hash) => {

                    accounts.get(uname)
                    .then((doc) => {
                        //account exists
                        resolve( {success: false, errormsg: "This account name is already taken"})
                    })
                    .catch((err) => {
                        if(err.status == 404) {
                       var authorization = uuidv4()
                            accounts.put({
                                _id: uname,
                                pword: hash,
                                authorization: authorization,
                                inv: {},
                                bal: 0
                            }).then(() => {
                            resolve({success: true, authorization: authorization, name: uname})
                            })
                            .catch(() => {
                                resolve({success: false, errormsg: "db error"})
                            })

                        } else {
                            console.log(err)
                            resolve( {success: false, errormsg: "db error"})
                        }

                    })

                });
            } else {
                resolve( {success: false, errormsg: "Name has to be bigger than 3 characters, and less than 17"})
            }
        } else {
            resolve( {success: false, errormsg: "Name must only contain Alphanumeric and Space..."})
        }
    }
    })

}
console.log("GOT HERE"); // does not run.
</code>```

I can not figure out what happens. Also, yes, /src and /api are separate folders.

Body:
Yo I am making something with TypeScript and Node and I ran into this issue:

Cannot find module './api/api.js' or its corresponding type declarations.ts(2307)

tsconfig.json

{
  "compilerOptions": {
    "target": "es2022",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}

Package.json:

{
  "name": "xmas",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon src/main.ts",
    "build": "tsc -p .",
    "start": "node dist/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/bcryptjs": "^2.4.2",
    "@types/pouchdb": "^6.4.0",
    "@types/uuid": "^9.0.0",
    "bcryptjs": "^2.4.3",
    "pouchdb": "^8.0.0",
    "uuid": "^9.0.0"
  }
}

Main.ts:

import * as API from './api/api.js';
var newacc = API.default.newacc;

newacc("imnotgay", "moveimggay");

And /api/api.js:

import newacc from './newacc.js';
export default {
    newacc
}

/api/newacc.js:

import bcrypt from 'bcryptjs';
import db from 'pouchdb';
var accounts = new db('accounts')
import { v4 as uuidv4 } from 'uuid';
export default (uname, pword) => {
        var uname = uname.toLowerCase()
    return new Promise((resolve, reject) => {

        if(pword.length < 3) {
            resolve( {success: false, errormsg: "Password has to be atleast 2 characters"})
        } else {
        if(/^[\w]+([-_\s]{1}[a-z0-9]+)*$/i.test(uname)) {
            if(uname.length > 3 && uname.length <17) {
                bcrypt.hash(pword, 10).then((hash) => {

                    accounts.get(uname)
                    .then((doc) => {
                        //account exists
                        resolve( {success: false, errormsg: "This account name is already taken"})
                    })
                    .catch((err) => {
                        if(err.status == 404) {
                       var authorization = uuidv4()
                            accounts.put({
                                _id: uname,
                                pword: hash,
                                authorization: authorization,
                                inv: {},
                                bal: 0
                            }).then(() => {
                            resolve({success: true, authorization: authorization, name: uname})
                            })
                            .catch(() => {
                                resolve({success: false, errormsg: "db error"})
                            })

                        } else {
                            console.log(err)
                            resolve( {success: false, errormsg: "db error"})
                        }

                    })

                });
            } else {
                resolve( {success: false, errormsg: "Name has to be bigger than 3 characters, and less than 17"})
            }
        } else {
            resolve( {success: false, errormsg: "Name must only contain Alphanumeric and Space..."})
        }
    }
    })

}
console.log("GOT HERE"); // does not run.

I can not figure out what happens. Also, yes, /src and /api are separate folders.


问:
pycharm(any IntelliJ product), how to add certain partern to the regex search result
I find what I want by using regex search, let's say I find all the telphone numbers in my file using regex and then I want to  add a string "(+1)" in front of the results I found. What should I put in the "replace" input?

Is this possible? I searched a lot but all I found is that how to use regex and replace the whole stuff.


问:
Creating a model/optimization method to optimize a signal
Suppose I have a system that is driven by a signal comprising 3 voltage levels (let's say -V1, 0, V1). I need to determine the composition of the signal that most accurately produces the desired output. The output is a single number that represents the current state of the system. The number of possible permutations for such a signal are too high to brute-force and find the global minimum i.e. exploring the entirety of the search space is impossible. However, I do have a model that simulates the system so I can still process several possible options. How can I find the best signal to produce the desired output (in other words, the signal that drives the system to the desired state)?

One method that I have right now involves producing a starting set (i.e. a small subset of the search space) of signals that align with a set of constraints, finding the signal that produces output closest to the desired output, and making modifications to this signal (i.e. fine tuning) in order to obtain the desired output. This final step is difficult for me, as I am manually doing this. One idea to automate this final step is to parametrize all possible modifications (for instance, parameter x1 = 1 adds a single -V1 'frame' to the signal, x1 = 2 adds two such frames, x1 = -1 removes a -V1 frame, and so on), and step through the set of possible modifications. But again, there's a lot of possibilities. To improve upon this, I explored the effect that modifications have on the system output. The effects of these modifications look somewhat predictable (the distributions of the changes in output they produce generally follow Gaussian distributions). But I'm not sure how to proceed from here. What models/schemes would you suggest I use? Can I use information from the distributions of changes produced by modifications to intelligently fine-tune the signal? How do I account for outliers (i.e. cases wherein the modification(s) to an initial signal produce a change in output that lies in the tail end of the distribution?

Edit: Forgot to mention, but the constraints on the signal would be length (the number of frames/steps in the signal must be less than or equal to a finite positive integer, N) and total potential (i.e. the sum of the voltages in the signal should equal an integer, V).


问:
How to initialize code modules in workers
I'm a big step further in my attempt to make an image decoder from nodes usable in the browser. the code already works in the program just like its node version. but if that were my goal to only use it in the program, I wouldn't have needed to bring it locally into my program from nodes. I just tested it to see if it works and it does and that was a huge step.
my goal is to be able to use the decoder in workers. I have seen in another decoder that works with workers that the decoder is integrated via a factory function. maybe you are now wondering why i don't use the decoder that works with workers???
the reason is that said decoder can only read 8-bit images. fast-png can read 16 bit images and that's exactly what i need.

but I'm not very familiar with embedding code in factory functions. I have never tried this in connection with imports and therefore my first question:
can factory functions be used at all in connection with import?
if so, I'm obviously doing something wrong, because it doesn't work.
can anyone show me an example of how to do it correctly?

If it is helpful I can also create a repository on github.

```<code>(function(global, factory){
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.png = {}));
})(function (exports) {

import {IOBuffer} from '../resources/libs/fast-png/IOBuffer.js';
import { inflate, Inflate as Inflator } from '../resources/libs/fast-png/pako.js';
import {pngSignature, crc} from '../resources/libs/fast-png/common.js';
import {ColorType, CompressionMethod, FilterMethod, InterlaceMethod} from '../resources/libs/fast-png/internalTypes.js';

class PngDecoder extends IOBuffer {
    constructor(data, options = {}) {
        super(data);

        //many parameters, I have deleted them here so that
        //there are not hundreds of lines of code here and the essentials are not lost
    }//end constructor

    //... many methods, i deleted them to keep track
}//end class

//...
//... many functions, i deleted them to keep track
//...

function decodePng(data, options) {
    const decoder = new PngDecoder(data, options);
    return decoder.decode();
}

exports.decodePng = decodePng;

}));//end of factory function

async function imageLoader() {

    const arrayBuffer = await(await fetch('./resources/textures/depth1.png')).arrayBuffer();

    const imageData = await png.decodePng(arrayBuffer);
    const data = imageData.data;

    postMessage(data);
}

//will call when the worker is called
imageLoader();
</code>```

Body:
I'm a big step further in my attempt to make an image decoder from nodes usable in the browser. the code already works in the program just like its node version. but if that were my goal to only use it in the program, I wouldn't have needed to bring it locally into my program from nodes. I just tested it to see if it works and it does and that was a huge step.
my goal is to be able to use the decoder in workers. I have seen in another decoder that works with workers that the decoder is integrated via a factory function. maybe you are now wondering why i don't use the decoder that works with workers???
the reason is that said decoder can only read 8-bit images. fast-png can read 16 bit images and that's exactly what i need.

but I'm not very familiar with embedding code in factory functions. I have never tried this in connection with imports and therefore my first question:
can factory functions be used at all in connection with import?
if so, I'm obviously doing something wrong, because it doesn't work.
can anyone show me an example of how to do it correctly?

If it is helpful I can also create a repository on github.

(function(global, factory){
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.png = {}));
})(function (exports) {

import {IOBuffer} from '../resources/libs/fast-png/IOBuffer.js';
import { inflate, Inflate as Inflator } from '../resources/libs/fast-png/pako.js';
import {pngSignature, crc} from '../resources/libs/fast-png/common.js';
import {ColorType, CompressionMethod, FilterMethod, InterlaceMethod} from '../resources/libs/fast-png/internalTypes.js';

class PngDecoder extends IOBuffer {
    constructor(data, options = {}) {
        super(data);

        //many parameters, I have deleted them here so that
        //there are not hundreds of lines of code here and the essentials are not lost
    }//end constructor

    //... many methods, i deleted them to keep track
}//end class

//...
//... many functions, i deleted them to keep track
//...

function decodePng(data, options) {
    const decoder = new PngDecoder(data, options);
    return decoder.decode();
}

exports.decodePng = decodePng;

}));//end of factory function

async function imageLoader() {

    const arrayBuffer = await(await fetch('./resources/textures/depth1.png')).arrayBuffer();

    const imageData = await png.decodePng(arrayBuffer);
    const data = imageData.data;

    postMessage(data);
}

//will call when the worker is called
imageLoader();


问:
How to solve the conflict caused by shaded without changing the package name？
My project has two dependencies
flink-kubetnets and flink-kubernrts-operator, Let's call him A, B
The A shaded the kubernets-client into itself and not change package name, and B also dependend  kubernets-client with different version.
So they conflict, how to solve it?

I tried packing again with shaded, but no, It seems that this situation can no longer be solved with shaded.
Because both A and B call kubernets-client, shaded cannot change their internal codes


问:
Can't load an URL using HtmlAgilityPack for particular website in C#(.NET)
I need to web scrape a website so I can download few things off of it. I have noticed that I can load an URL easily from most websites but not the one I need.

Here's a code snippet that works and loads most websites but not this one:

```<code>HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("https://bakerhughesrigcount.gcs-web.com/intl-rig-count/");
</code>```

The program just tries to load it forever and it's stuck.

Body:
I need to web scrape a website so I can download few things off of it. I have noticed that I can load an URL easily from most websites but not the one I need.

Here's a code snippet that works and loads most websites but not this one:

HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("https://bakerhughesrigcount.gcs-web.com/intl-rig-count/");

The program just tries to load it forever and it's stuck.


问:
I still can't delete folders using powershell administrator mode
I still can't delete folders using powershell administrator mode
powershell Delete result

```<code>PS C:\Program Files (x86)> ls .\Sangfor\

    Directory: C:\Program Files (x86)\Sangfor

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----          2022/12/23    22:18                SSL

PS C:\Program Files (x86)\Sangfor\SSL\SangforPWEx> ls

    Directory: C:\Program Files (x86)\Sangfor\SSL\SangforPWEx

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           2021/3/25    10:18         138056 atl100.dll
-a---            2022/5/5    22:05         533664 ECAgentProxy.dll
-a---           2021/3/25    10:18         773968 msvcr100.dll
-a---           2021/7/18    17:35        1610048 SangforPWAlive.dll
-a---            2022/5/6    17:45         440232 SangforPWEx.exe
-a---            2022/5/9     9:37         678312 SangforUDProtectEx_202251723165010.dll
-a---            2022/5/6    17:44        1397160 SangforUDProtectEx.exe
-a---           2021/3/25    10:18        2656360 sangforvpnlibcrypto-1_1.dll
-a---           2021/3/25    10:18         623208 sangforvpnlibssl-1_1.dll
</code>```

I tried to delete the folder in the GUI, but it showed that the folder was occupied, but I could not close the program in the task manager. I also tried to delete using Windows' linux subsystem, but it showed I/O errors. I scanned the folder using anti-virus software and did not find the problem. I hope I can find a way to delete the folder.

Body:
I still can't delete folders using powershell administrator mode
powershell Delete result

PS C:\Program Files (x86)> ls .\Sangfor\

    Directory: C:\Program Files (x86)\Sangfor

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----          2022/12/23    22:18                SSL

PS C:\Program Files (x86)\Sangfor\SSL\SangforPWEx> ls

    Directory: C:\Program Files (x86)\Sangfor\SSL\SangforPWEx

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           2021/3/25    10:18         138056 atl100.dll
-a---            2022/5/5    22:05         533664 ECAgentProxy.dll
-a---           2021/3/25    10:18         773968 msvcr100.dll
-a---           2021/7/18    17:35        1610048 SangforPWAlive.dll
-a---            2022/5/6    17:45         440232 SangforPWEx.exe
-a---            2022/5/9     9:37         678312 SangforUDProtectEx_202251723165010.dll
-a---            2022/5/6    17:44        1397160 SangforUDProtectEx.exe
-a---           2021/3/25    10:18        2656360 sangforvpnlibcrypto-1_1.dll
-a---           2021/3/25    10:18         623208 sangforvpnlibssl-1_1.dll

I tried to delete the folder in the GUI, but it showed that the folder was occupied, but I could not close the program in the task manager. I also tried to delete using Windows' linux subsystem, but it showed I/O errors. I scanned the folder using anti-virus software and did not find the problem. I hope I can find a way to delete the folder.


问:
How to get rid of not existing errors?
Here is my code

```<code>from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework import viewsets, status
from .models import Actor
from .serializers import ActorSerializer

# Create your views here.

class ActorView(viewsets.ModelViewSet):
    model = Actor
    queryset = model.objects.all()
    permission_classes = (AllowAny,)
    serializer_class = ActorSerializer
    http_method_names = ['get', 'post', 'put', 'delete']

    def list(self, request):
        serializer = ActorSerializer(self.queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request):
        serializer = ActorSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            print(serializer.validated_data['name'])
            return Response("OK", status=status.HTTP_200_OK)
        else:
            return Response("nie ok")
</code>```

Pylance thinks that this line:

```<code>print(serializer.validated_data['name'])
</code>```

is incorrect, but it is correct. Code works fine and it doesn't displaying any errors while server is running and request is sent. But it is underlined in red, so something must be wrong. How can i get rid of those "errors"?

```<code>"__getitem__" method not defined on type "empty"
Object of type "None" is not subscriptable

</code>```

I have alredy tried uninstalling Pylance and changing its' version but all for nothing.

Title: How to get rid of not existing errors?

Body:
Here is my code

from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework import viewsets, status
from .models import Actor
from .serializers import ActorSerializer

# Create your views here.

class ActorView(viewsets.ModelViewSet):
    model = Actor
    queryset = model.objects.all()
    permission_classes = (AllowAny,)
    serializer_class = ActorSerializer
    http_method_names = ['get', 'post', 'put', 'delete']

    def list(self, request):
        serializer = ActorSerializer(self.queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request):
        serializer = ActorSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            print(serializer.validated_data['name'])
            return Response("OK", status=status.HTTP_200_OK)
        else:
            return Response("nie ok")

Pylance thinks that this line:

print(serializer.validated_data['name'])

is incorrect, but it is correct. Code works fine and it doesn't displaying any errors while server is running and request is sent. But it is underlined in red, so something must be wrong. How can i get rid of those "errors"?

"__getitem__" method not defined on type "empty"
Object of type "None" is not subscriptable

I have alredy tried uninstalling Pylance and changing its' version but all for nothing.


问:
GCP Python HTTP Cloud Function argument issue
I have written an HTTP Google Cloud Function which works fine with a hard-coded date. When I try to pass in a date, however, the argument always evaluates to None. Here is the code that works:

```<code>import functions_framework
import pymysql
from google.cloud import storage
import sqlalchemy

@functions_framework.http
def hello_http(request):

    request_json = request.get_json(silent=True)
    request_args = request.args
    connection_name = ""
    query_string = dict({"unix_socket": "/cloudsql/{}".format(connection_name)})
    db = sqlalchemy.create_engine(
      sqlalchemy.engine.url.URL(
        drivername="mysql+pymysql",
        username="",
        password="",
        database="",
        query=query_string,
      ),
      pool_size=5,
      max_overflow=2,
      pool_timeout=30,
      pool_recycle=1800
    )
    returnResults = {}
    try:
        with db.connect() as conn:
            results = conn.execute("call mystoredproc('2022-12-22')").fetchall()
            index = 0
            for entry in results:
              returnResults[index] = {'ProductTypeName':results[index][0],'SalePartSkuPrice':results[index][1],'ProductName':results[index][2], 'QuantitySold':results[index][3], 'Subtotal':results[index][4], 'RemainingInStock':results[index][5]}
              index += 1
    except Exception as e:
        return 'Error: {}'.format(str(e))
    return returnResults
</code>```

When I try to pass in a date string in the request: {"report_date": "20221215"} and grab it with the line:

```<code>reportDate = request_args.get("report_date")
</code>```

...and change the stored proc call to

```<code>results = conn.execute("call mystoredproc('{}')".format(reportDate)).fetchall()
</code>```

I get

Error: (pymysql.err.InternalError) (1292, "Incorrect date value:
'None' for column 'reportDate' at row 1")

I don't understand why the value I'm passing in is being evaluated as 'None'.

Body:
I have written an HTTP Google Cloud Function which works fine with a hard-coded date. When I try to pass in a date, however, the argument always evaluates to None. Here is the code that works:

import functions_framework
import pymysql
from google.cloud import storage
import sqlalchemy

@functions_framework.http
def hello_http(request):

    request_json = request.get_json(silent=True)
    request_args = request.args
    connection_name = ""
    query_string = dict({"unix_socket": "/cloudsql/{}".format(connection_name)})
    db = sqlalchemy.create_engine(
      sqlalchemy.engine.url.URL(
        drivername="mysql+pymysql",
        username="",
        password="",
        database="",
        query=query_string,
      ),
      pool_size=5,
      max_overflow=2,
      pool_timeout=30,
      pool_recycle=1800
    )
    returnResults = {}
    try:
        with db.connect() as conn:
            results = conn.execute("call mystoredproc('2022-12-22')").fetchall()
            index = 0
            for entry in results:
              returnResults[index] = {'ProductTypeName':results[index][0],'SalePartSkuPrice':results[index][1],'ProductName':results[index][2], 'QuantitySold':results[index][3], 'Subtotal':results[index][4], 'RemainingInStock':results[index][5]}
              index += 1
    except Exception as e:
        return 'Error: {}'.format(str(e))
    return returnResults

When I try to pass in a date string in the request: {"report_date": "20221215"} and grab it with the line:

reportDate = request_args.get("report_date")

...and change the stored proc call to

results = conn.execute("call mystoredproc('{}')".format(reportDate)).fetchall()

I get

Error: (pymysql.err.InternalError) (1292, "Incorrect date value:
'None' for column 'reportDate' at row 1")

I don't understand why the value I'm passing in is being evaluated as 'None'.


问:
How to obtain Router attribute when handle the Request?
I defines a route with attribute<"id", "demo">:

```<code>route(GET("/demo").and(accept(MediaType.APPLICATION_JSON)), handler::handle)
   .withAttribute("id", "demo")
</code>```

In the handler funaction, how can I obtain the above defined attribute?

```<code>public Mono<ServerResponse> handle(ServerRequest serverRequest) {
   // Here, how to get the attribute<id, demo> ?
}
</code>```

Body:
I defines a route with attribute<"id", "demo">:

route(GET("/demo").and(accept(MediaType.APPLICATION_JSON)), handler::handle)
   .withAttribute("id", "demo")

In the handler funaction, how can I obtain the above defined attribute?

public Mono<ServerResponse> handle(ServerRequest serverRequest) {
   // Here, how to get the attribute<id, demo> ?
}


问:
Firebase deployement of ; react-spw; Node.JS 14; mongoDB
I am trying to host a React application on Firebase, but am having some issues. I have previous experience with Angular and Firebase, as well as some knowledge of different JavaScript interpreters and basic Firebase. I am currently working with Node.js 14 and React, and have been using Firebase tools that are compatible with this version of Node.js.

The issue I am facing is that after building my project with React, it creates a new folder for the build. I am not familiar with this process and am having difficulty understanding how to host my application on Firebase with this new folder structure.

(The basic; npm install -g firebase-tools, firebase login, firebase init, npm run build, firebase deploy. has not worked.)

I have searched for documentation on this issue and have tried looking for any dependency issues, but have not been able to resolve the problem. I would greatly appreciate any help or guidance on how to host my React application on Firebase. Thank you in advance.


问:
Does the f_oneway test for regression from SciPy take the y values and the fitted y values as arguments?
I did a nonlinear regression using curve_fit and wanted an F test on this regression. I wanted to use f_oneway test for regression but I am not sure what to enter into the function. I entered two numpy arrays, y (the actual data for the dependent variable) and yfit the data predicted by the regression equation I received using curve_fit. I am not sure if this will give me an F test for the "Overall Significance" of the independent variables. I do not understand what the Scipy official site is saying about this.

I ran the following code:

```<code>    import scipy.stats as stats
    h = stats.f_oneway(y,yfit)
    print(h)
</code>```

And received the following output:

```<code>F_onewayResult(statistic=1.33717160489312e-19, pvalue=1.0)
</code>```

However, I am not sure that I did the right thing by entering the y and yfit into the f_oneway function, to get an F test for overall significance.

Body:
I did a nonlinear regression using curve_fit and wanted an F test on this regression. I wanted to use f_oneway test for regression but I am not sure what to enter into the function. I entered two numpy arrays, y (the actual data for the dependent variable) and yfit the data predicted by the regression equation I received using curve_fit. I am not sure if this will give me an F test for the "Overall Significance" of the independent variables. I do not understand what the Scipy official site is saying about this.

I ran the following code:

    import scipy.stats as stats
    h = stats.f_oneway(y,yfit)
    print(h)

And received the following output:

F_onewayResult(statistic=1.33717160489312e-19, pvalue=1.0)

However, I am not sure that I did the right thing by entering the y and yfit into the f_oneway function, to get an F test for overall significance.


问:
Suitescript error: TypeError: Cannot set property "JSZipSync" of undefined
I have the following script where I am getting an error message:

org.mozilla.javascript.EcmaError: TypeError: Cannot set property
"JSZipSync" of undefined to
"org.mozilla.javascript.InterpretedFunction@6e57e155"
(/SuiteScripts/Suitelet to Excel.js#17(eval)#2)

According to Netsuite support, there are no issues with the script and they are not getting this error message

/**
 *@NApiVersion 2.x
 *@NScriptType Suitelet
 */

define(["N/search", "N/file", "N/https"], function (search, file, https) {
  function onRequest(context) {

    // Load the xlsx library from the CDN
    var response = https.get({
      url: "https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js",
    });
    var script = response.body;
    eval(script);

    // Replace this with the ID of the saved search you want to run
    var searchId = "customsearch_my_saved_search";

    // Run the search and get the results
    var searchResult = search.load({
      id: searchId,
    });
    var searchRows = searchResult.run().getRange({
      start: 0,
      end: 1000,
    });

    // Create an array to hold the data for the Excel file
    var data = [];

    // Add the column names as the first row
    var columnNames = [];
    searchResult.columns.forEach(function (column) {
      columnNames.push(column.label);
    });
    data.push(columnNames);

    // Add the search results to the data array
    searchRows.forEach(function (row) {
      var rowData = [];
      searchResult.columns.forEach(function (column) {
        rowData.push(
          row.getValue({
            name: column.name,
          })
        );
      });
      data.push(rowData);
    });

    // Create the Excel file
    var ws = XLSX.utils.aoa_to_sheet(data);
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    var binaryData = XLSX.write(wb, {
      type: "binary",
      bookType: "xlsx",
    });
    var fileName = "search_results.xlsx";
    var folderId = -4; // -4 represents the "Home" folder in the file cabinet
    var file = file.create({
      name: fileName,
      fileType: file.Type.EXCEL,
      contents: binaryData,
      folder: folderId,
    });

    // Send the file as a response to the user
      context.response.writeFile({
        file: file,
        isInline: true,
      });
    });
  }
  return {
    onRequest: onRequest,
  };
});

```

I can't tell where I am going wrong?

The JSZipSync is a function in the xlsx.full.min.js library which I believe I have loaded correctly.

I have also tried storing this file in the filing cabinet and referencing that instead of a link to the CDN website.

The same error message is generated in both cases

Body:
I have the following script where I am getting an error message:

org.mozilla.javascript.EcmaError: TypeError: Cannot set property
"JSZipSync" of undefined to
"org.mozilla.javascript.InterpretedFunction@6e57e155"
(/SuiteScripts/Suitelet to Excel.js#17(eval)#2)

According to Netsuite support, there are no issues with the script and they are not getting this error message

/**
 *@NApiVersion 2.x
 *@NScriptType Suitelet
 */

define(["N/search", "N/file", "N/https"], function (search, file, https) {
  function onRequest(context) {

    // Load the xlsx library from the CDN
    var response = https.get({
      url: "https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js",
    });
    var script = response.body;
    eval(script);

    // Replace this with the ID of the saved search you want to run
    var searchId = "customsearch_my_saved_search";

    // Run the search and get the results
    var searchResult = search.load({
      id: searchId,
    });
    var searchRows = searchResult.run().getRange({
      start: 0,
      end: 1000,
    });

    // Create an array to hold the data for the Excel file
    var data = [];

    // Add the column names as the first row
    var columnNames = [];
    searchResult.columns.forEach(function (column) {
      columnNames.push(column.label);
    });
    data.push(columnNames);

    // Add the search results to the data array
    searchRows.forEach(function (row) {
      var rowData = [];
      searchResult.columns.forEach(function (column) {
        rowData.push(
          row.getValue({
            name: column.name,
          })
        );
      });
      data.push(rowData);
    });

    // Create the Excel file
    var ws = XLSX.utils.aoa_to_sheet(data);
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    var binaryData = XLSX.write(wb, {
      type: "binary",
      bookType: "xlsx",
    });
    var fileName = "search_results.xlsx";
    var folderId = -4; // -4 represents the "Home" folder in the file cabinet
    var file = file.create({
      name: fileName,
      fileType: file.Type.EXCEL,
      contents: binaryData,
      folder: folderId,
    });

    // Send the file as a response to the user
      context.response.writeFile({
        file: file,
        isInline: true,
      });
    });
  }
  return {
    onRequest: onRequest,
  };
});

I can't tell where I am going wrong?

The JSZipSync is a function in the xlsx.full.min.js library which I believe I have loaded correctly.

I have also tried storing this file in the filing cabinet and referencing that instead of a link to the CDN website.

The same error message is generated in both cases


问:
How do I maintain transparency when loading WebP format images on iOS?
I have a function to import images from an array of NSItemProvider (passed from a PHPickerViewController) and I need to maintain transparency in the images. Any images in PNG format are correctly maintaining transparency but WebP images are not. The image import code is as follows:

```<code>private func save(itemProviders: [NSItemProvider]) async throws -> Int {
    return try await withCheckedThrowingContinuation({ continuation in
        let group = DispatchGroup()
        var failureCount = 0
        for item in itemProviders {
            // webp format image
            if item.hasItemConformingToTypeIdentifier(UTType.webP.identifier) {
                group.enter()
                item.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier) { data, error in
                    defer {
                        group.leave()
                    }
                    guard let data, let image = UIImage(data: data) else {
                        return
                    }
                    self.saveImage(image)
                }
            }
            else if item.canLoadObject(ofClass: UIImage.self) {
                // other image formats, including PNG
                group.enter()
                item.loadObject(ofClass: UIImage.self) { (image, error) in
                    defer {
                        group.leave()
                    }
                    guard let image = image as? UIImage else {
                        return
                    }

                    self.saveImage(image)
                }
            }
            else {
                failureCount += 1
            }
        }
        group.notify(queue: .main) {
            continuation.resume(returning: failureCount)
        }
    })
}
</code>```

Please note that the saveImage function is a simple resize and save to disk function, and I have been able to verify that transparency is not being lost during that step.

It seems as though transparency is being lost during the call to item.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier) or when the resulting Data is used to instantiate a UIImage. The code in the WebP handling block seems to be irreducibly simple though so I'm not sure how I can possibly fix this issue.

Body:
I have a function to import images from an array of NSItemProvider (passed from a PHPickerViewController) and I need to maintain transparency in the images. Any images in PNG format are correctly maintaining transparency but WebP images are not. The image import code is as follows:

private func save(itemProviders: [NSItemProvider]) async throws -> Int {
    return try await withCheckedThrowingContinuation({ continuation in
        let group = DispatchGroup()
        var failureCount = 0
        for item in itemProviders {
            // webp format image
            if item.hasItemConformingToTypeIdentifier(UTType.webP.identifier) {
                group.enter()
                item.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier) { data, error in
                    defer {
                        group.leave()
                    }
                    guard let data, let image = UIImage(data: data) else {
                        return
                    }
                    self.saveImage(image)
                }
            }
            else if item.canLoadObject(ofClass: UIImage.self) {
                // other image formats, including PNG
                group.enter()
                item.loadObject(ofClass: UIImage.self) { (image, error) in
                    defer {
                        group.leave()
                    }
                    guard let image = image as? UIImage else {
                        return
                    }

                    self.saveImage(image)
                }
            }
            else {
                failureCount += 1
            }
        }
        group.notify(queue: .main) {
            continuation.resume(returning: failureCount)
        }
    })
}

Please note that the saveImage function is a simple resize and save to disk function, and I have been able to verify that transparency is not being lost during that step.

It seems as though transparency is being lost during the call to item.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier) or when the resulting Data is used to instantiate a UIImage. The code in the WebP handling block seems to be irreducibly simple though so I'm not sure how I can possibly fix this issue.


问:
Can't Import SQL Database to phpmyadmin
I have a website that uses phpmyadmin and MySQL for the database

I am currently working on a localhost copy of my website.

The web server is running the following for the website database:
Server: Localhost via UNIX socket
Server type: MySQL
Server connection: SSL is not being used Documentation
Server version: 5.5.62-log - Source distribution
Protocol version: 10
User: sql_indianrivern@localhost
Server charset: UTF-8 Unicode (utf8mb4)

The local host is running the following for its database:
Server: 127.0.0.1 via TCP/IP
Server type: MariaDB
Server connection: SSL is not being used Documentation
Server version: 10.4.22-MariaDB - mariadb.org binary distribution
Protocol version: 10
User: root@localhost
Server charset: UTF-8 Unicode (utf8mb4)

I use the Quick Export function on the web server through phpMyAdmin to export my database.

When I go to import the database to the local host phpmyadmin, I get the following error:

```<code>Error
Static analysis:

11 errors were found during analysis.

Unexpected character. (near "{" at position 345)
Unexpected beginning of statement. (near "doctype" at position 2)
Unexpected beginning of statement. (near "html" at position 10)
Unexpected beginning of statement. (near "html" at position 17)
Unexpected beginning of statement. (near "lang" at position 22)
Unexpected beginning of statement. (near ""en"" at position 27)
Unexpected beginning of statement. (near "dir" at position 32)
Unexpected beginning of statement. (near ""ltr"" at position 36)
Unexpected beginning of statement. (near "head" at position 44)
Unexpected beginning of statement. (near "meta" at position 53)
Unrecognized statement type. (near "charset" at position 58)
SQL query: Copy

<!doctype html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="referrer" content="no-referrer"> <meta name="robots" content="noindex,nofollow"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <style id="cfs-style">html{display: none;

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '<!doctype html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  ...' at line 1
</code>```

That can be possibly causing the error I am getting? How do I fix this so I can import my database to my localhost server.

I have attempted to look at the different export settings to export the database differently. However, I am not very familiar the various settings and I have no idea if they would do anything to fix my issue.

Edit: Here is the link to my exported .sql database: https://indianrivernews.us/advertisements.sql

Title: Can't Import SQL Database to phpmyadmin

Body:
I have a website that uses phpmyadmin and MySQL for the database

I am currently working on a localhost copy of my website.

The web server is running the following for the website database:
Server: Localhost via UNIX socket
Server type: MySQL
Server connection: SSL is not being used Documentation
Server version: 5.5.62-log - Source distribution
Protocol version: 10
User: sql_indianrivern@localhost
Server charset: UTF-8 Unicode (utf8mb4)

The local host is running the following for its database:
Server: 127.0.0.1 via TCP/IP
Server type: MariaDB
Server connection: SSL is not being used Documentation
Server version: 10.4.22-MariaDB - mariadb.org binary distribution
Protocol version: 10
User: root@localhost
Server charset: UTF-8 Unicode (utf8mb4)

I use the Quick Export function on the web server through phpMyAdmin to export my database.

When I go to import the database to the local host phpmyadmin, I get the following error:

Error
Static analysis:

11 errors were found during analysis.

Unexpected character. (near "{" at position 345)
Unexpected beginning of statement. (near "doctype" at position 2)
Unexpected beginning of statement. (near "html" at position 10)
Unexpected beginning of statement. (near "html" at position 17)
Unexpected beginning of statement. (near "lang" at position 22)
Unexpected beginning of statement. (near ""en"" at position 27)
Unexpected beginning of statement. (near "dir" at position 32)
Unexpected beginning of statement. (near ""ltr"" at position 36)
Unexpected beginning of statement. (near "head" at position 44)
Unexpected beginning of statement. (near "meta" at position 53)
Unrecognized statement type. (near "charset" at position 58)
SQL query: Copy

<!doctype html>   <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="referrer" content="no-referrer"> <meta name="robots" content="noindex,nofollow"> <meta http-equiv="X-UA-Compatible" content="IE=Edge">


问:
what kinds of feature need to create biobert-embedding?
I am bit confused regarding  to create biobert embedding. I am just curious what is different between word vector and sentence vector and do I need to use these to extract feature? And about embedding itself, I read somewhere that the BERT embedding itself is concantenation of 3 different features, namely, token, segment and position embedding. I also read somewhere that position doesnt need it for embedding.

Does anyone can give me reference or short explanation about this? Thanks.


问:
How to overcome a overfit problem from Image Steganography problem implemented in Keras?
I am working with Image Steganography where I will hide an image into another image through one model and later, I will extract that hidden image from another model. When I was going to extract that hidden image, my model is overfitted. The training data gives really good results but not for validation and testing data. I have normalized all images from 0 to 1. I am using 'mse' as a loss function and 'Adam' as an optimizer with a 0.0001 learning rate. Batch Size I have tried 16,32 and 64. I have a total of 15000 images. Actual Image Shape: (128,128,3), Hidden Image Shape: (32,32,1)

What should I do to overcome this problem? Also for using dropout and regularization, in which layer I should add those?

Here is the figure for the loss function: Training Loss(Blue), Validation Loss(Red)

Here is the model I have used

I have already tried adding the Dropout layer, and L2 regularization. In that case, at first, both losses are decreasing but after some epochs, training loss and validation loss remain constant. And the output array produces the same value.

Output after using this model


问:
about reconstructing the curve from piecewise polynomial spline
I am self learning the spline used in computer graphical theory. I read one book about interpolation and spline and now would like to try my understanding with Python. I created some random points, build the Bspline with Scipy, and convert the spline pp form, try to reconstruct the function with the breaks and coefficients. From the help of scir about scipy.interpolate.PPoly, I got

The polynomial between x[i] and x[i + 1] is written in the local power basis:

S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1))
where k is the degree of the polynomial.

My understanding is if the coefficients c and breaks x[i] are provided, to reconstruct the function within x[i] and x[i+1], one only have to build the polynomial up to k degree. I try the following code

```<code>from scipy.interpolate import BSpline, CubicSpline
from scipy.interpolate import splrep
from scipy.interpolate import BPoly, PPoly
import numpy as np
x = np.array([-0.5537, 0.5257, 1.3598, 1.8014, 2.4393, 4.0584, 4.9416, 5.4813, 5.9720, 6.6098, 6.9042, 7.3458, 7.8855, 7.9836, 8.2290])
y = np.array([16.5526, 16.4054, 15.6694, 14.1484, 12.5783, 12.9708, 14.1484, 14.9825, 15.9638, 16.6507, 16.6016, 16.0129, 15.2278, 13.7558, 12.0386])
tck = t,c,k = splrep(x, y, s=0.8, k=3)
spl = BSpline(t, c, k)

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
xx = np.linspace(0, 8.5, 500)
ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
ax.plot(x, y, 'ks')

F   = PPoly.from_spline(tck)
i = 0
xxx = np.linspace(x[i], x[i+1], 500)
yyy = sum(F.c[m, i] * (xxx - x[i])**(k-m) for m in range(k+1))
plt.plot(xxx, yyy,'r')
</code>```

Here I only interpret the x variables from x[i=0] to x[i+1=1], it does plot a good fit from x[0] to x[1] as follow

Following the similar idea, I am going to plot the section from x[1] to x[2] with i=1, the code is modified as

```<code>i = 1
xxx = np.linspace(x[i], x[i+1], 500)
yyy = sum(F.c[m, i] * (xxx - x[i])**(k-m) for m in range(k+1))
plt.plot(xxx, yyy,'r')
</code>```

I expect it plot the curve as shown in the magenta but I got the red line instead. Could someone help me out and point out which step I did it wrong. Many thanks.

Someone help to point out the mistake I made

Body:
I am self learning the spline used in computer graphical theory. I read one book about interpolation and spline and now would like to try my understanding with Python. I created some random points, build the Bspline with Scipy, and convert the spline pp form, try to reconstruct the function with the breaks and coefficients. From the help of scir about scipy.interpolate.PPoly, I got

The polynomial between x[i] and x[i + 1] is written in the local power basis:

S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1))
where k is the degree of the polynomial.

My understanding is if the coefficients c and breaks x[i] are provided, to reconstruct the function within x[i] and x[i+1], one only have to build the polynomial up to k degree. I try the following code

from scipy.interpolate import BSpline, CubicSpline
from scipy.interpolate import splrep
from scipy.interpolate import BPoly, PPoly
import numpy as np
x = np.array([-0.5537, 0.5257, 1.3598, 1.8014, 2.4393, 4.0584, 4.9416, 5.4813, 5.9720, 6.6098, 6.9042, 7.3458, 7.8855, 7.9836, 8.2290])
y = np.array([16.5526, 16.4054, 15.6694, 14.1484, 12.5783, 12.9708, 14.1484, 14.9825, 15.9638, 16.6507, 16.6016, 16.0129, 15.2278, 13.7558, 12.0386])
tck = t,c,k = splrep(x, y, s=0.8, k=3)
spl = BSpline(t, c, k)

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
xx = np.linspace(0, 8.5, 500)
ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
ax.plot(x, y, 'ks')

F   = PPoly.from_spline(tck)
i = 0
xxx = np.linspace(x[i], x[i+1], 500)
yyy = sum(F.c[m, i] * (xxx - x[i])**(k-m) for m in range(k+1))
plt.plot(xxx, yyy,'r')

Here I only interpret the x variables from x[i=0] to x[i+1=1], it does plot a good fit from x[0] to x[1] as follow

Following the similar idea, I am going to plot the section from x[1] to x[2] with i=1, the code is modified as

i = 1
xxx = np.linspace(x[i], x[i+1], 500)
yyy = sum(F.c[m, i] * (xxx - x[i])**(k-m) for m in range(k+1))
plt.plot(xxx, yyy,'r')

I expect it plot the curve as shown in the magenta but I got the red line instead. Could someone help me out and point out which step I did it wrong. Many thanks.

Someone help to point out the mistake I made


问:
Swift UITextView Delegate
I am having a problem and have searched all across StackO and did not see a solution.

I have a UITextview extension with TextViewDelegate that I call inside of my VC so that i can have a placeholder label. The problem is i now need to add a func that checks for remaining chars in that same textView which i am able to get to work properly. But i cant grab a label to present it on the VC from that extension. I have been trying delegates but since it is a delegate itself i cant use my normal methods. What is the best route to go about this? Thank You for your help!

Here is the code. The placeholder label code is left out since it will make everything longer and I do not feel its needed for a solution. But I can add if necessary. And i can not move this code straight into VC as i need this extension to stay like this.

```<code>extension UITextView: UITextViewDelegate {

/// When the UITextView change, show or hide the label based on if the UITextView is empty or not

public func textViewDidChange(_ textView: UITextView) {
    if let placeholderLabel = self.viewWithTag(100) as? UILabel {
        placeholderLabel.isHidden = !self.text.isEmpty
    }
    checkRemainingChars(textView: textView)

}

func checkRemainingChars(textView: UITextView) {
    let allowedChars = 140

    if let charsInTextField = textView.text?.count {

        let charsInLabel = charsInTextField

        let remainingChars = charsInLabel

        if remainingChars <= allowedChars {

            //Need to grab this label
           charsLeftLabel.textColor = UIColor.lightGray
        }

        if remainingChars >= 120 {
            //Need to grab this label
            charsLeftLabel.textColor = UIColor.orange

        }

        if remainingChars >= allowedChars {
            //Need to grab this label
            charsLeftLabel.textColor = UIColor.red
        }
        //This prints fine
        print("Remaining chars is \(remainingChars)/140")
        //Need to grab this label
      charsLeftLabel.text = String(remainingChars)

    }

}
</code>```

Thanks again.

Title: Swift UITextView Delegate

Body:
I am having a problem and have searched all across StackO and did not see a solution.

I have a UITextview extension with TextViewDelegate that I call inside of my VC so that i can have a placeholder label. The problem is i now need to add a func that checks for remaining chars in that same textView which i am able to get to work properly. But i cant grab a label to present it on the VC from that extension. I have been trying delegates but since it is a delegate itself i cant use my normal methods. What is the best route to go about this? Thank You for your help!

Here is the code. The placeholder label code is left out since it will make everything longer and I do not feel its needed for a solution. But I can add if necessary. And i can not move this code straight into VC as i need this extension to stay like this.

extension UITextView: UITextViewDelegate {

/// When the UITextView change, show or hide the label based on if the UITextView is empty or not

public func textViewDidChange(_ textView: UITextView) {
    if let placeholderLabel = self.viewWithTag(100) as? UILabel {
        placeholderLabel.isHidden = !self.text.isEmpty
    }
    checkRemainingChars(textView: textView)

}

func checkRemainingChars(textView: UITextView) {
    let allowedChars = 140

    if let charsInTextField = textView.text?.count {

        let charsInLabel = charsInTextField

        let remainingChars = charsInLabel

        if remainingChars <= allowedChars {

            //Need to grab this label
           charsLeftLabel.textColor = UIColor.lightGray
        }

        if remainingChars >= 120 {
            //Need to grab this label
            charsLeftLabel.textColor = UIColor.orange

        }

        if remainingChars >= allowedChars {
            //Need to grab this label
            charsLeftLabel.textColor = UIColor.red
        }
        //This prints fine
        print("Remaining chars is \(remainingChars)/140")
        //Need to grab this label
      charsLeftLabel.text = String(remainingChars)

    }

}

Thanks again.


问:
SetLayeredWindowAttributes not working under certain conditions
I'm making this app in Haxe which compiles to C++ code. I'm using the SetLayeredWindowAttributes() function to set the background of the window to be fully transparent. The problem is that this works completely fine only on certain monitors, but not on others.

If I launch the app on my main monitor, which I believe to be 32-bit (if that matters), the background doesn't change at all, or will flicker and then completely disappear until I focus another window.

However, if I connect another monitor and run the app on that one, the background does become transparent, and the transparency persists even if I move it back to my main monitor. Even with the 2nd monitor connected at the same time. If I launch it on the main one, transparency fails.

I have tried changing the color values between 0xFFffffff/0xffffff, etc, but no combination of these work.

This same problem occurs even on a completely different machine with different hardware than mine. My hardware: Lenovo Ideapad L340-15IRH, i5-9300H, Gpu(s) Gtx 1650, Intel HD 630.

Please help me, what am I doing wrong?

Code to enable transparency, using windows.h inside a C++ function:

```<code>HWND hWnd = GetActiveWindow();
res = SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
SetLayeredWindowAttributes(hWnd, RGB(255, 255, 255), 0, LWA_COLORKEY);
</code>```

Code which creates the transparent background, in main haxe code:

```<code>transparentsquare = new FlxSprite(0, 0).makeGraphic(screenW, screenH, FlxColor.WHITE);
add(transparentsquare);
</code>```

It doesn't matter if I enable transparency before everything has loaded, I can enable it by pressing a key at any time and it still fails if I enable it after the app has fully loaded. Also, obviously graphics are not drawn in the C++ function but in the haxe code, so I can't use any fancy DirectX APIs and what-not.

Body:
I'm making this app in Haxe which compiles to C++ code. I'm using the SetLayeredWindowAttributes() function to set the background of the window to be fully transparent. The problem is that this works completely fine only on certain monitors, but not on others.

If I launch the app on my main monitor, which I believe to be 32-bit (if that matters), the background doesn't change at all, or will flicker and then completely disappear until I focus another window.

However, if I connect another monitor and run the app on that one, the background does become transparent, and the transparency persists even if I move it back to my main monitor. Even with the 2nd monitor connected at the same time. If I launch it on the main one, transparency fails.

I have tried changing the color values between 0xFFffffff/0xffffff, etc, but no combination of these work.

This same problem occurs even on a completely different machine with different hardware than mine. My hardware: Lenovo Ideapad L340-15IRH, i5-9300H, Gpu(s) Gtx 1650, Intel HD 630.

Please help me, what am I doing wrong?

Code to enable transparency, using windows.h inside a C++ function:

HWND hWnd = GetActiveWindow();
res = SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
SetLayeredWindowAttributes(hWnd, RGB(255, 255, 255), 0, LWA_COLORKEY);

Code which creates the transparent background, in main haxe code:

transparentsquare = new FlxSprite(0, 0).makeGraphic(screenW, screenH, FlxColor.WHITE);
add(transparentsquare);

It doesn't matter if I enable transparency before everything has loaded, I can enable it by pressing a key at any time and it still fails if I enable it after the app has fully loaded. Also, obviously graphics are not drawn in the C++ function but in the haxe code, so I can't use any fancy DirectX APIs and what-not.


问:
Flask Dropzone redirect only if upload successful
I have an upload.html file that looks like this:

```<code>{% extends "layout.html" %}
{% block title%}Submissions{% endblock %}

{% block content %}
<div class="container-xxl">

  <div class="col-md-12 d-flex">
    <h1><a href="/submissions/{{submission_items.id}}" style="color:#000"><i class="fa fa-arrow-circle-o-left"></i></a> </h1>
    <div>
      <h2>{{submission_items.submission_name}} <i class="fa fa-angle-right"></i> {{file_type.file_type}}</h2>
      <h6>{{submission_items.package_type}} Package - Property Agent Report Package Details</h6>
    </div>
  </div>

  {{ dropzone.create(action=url_for('views.upload_file', submission_id=submission_items.id, file_type_id=file_type.id)) }}
  {{ dropzone.load_js() }}
  {{ dropzone.config(redirect_url=url_for('views.submission', submission_id=submission_items.id)) }}

</div>
{% endblock %}
</code>```

The views.submission path is uploading the file to an s3 bucket. I've had times when due to network or some other issues, the server logs indicated the transmission failed but the website still redirects. I'd like to condition the redirect to views.submission only if the transmission was successful. How can I do that?

Body:
I have an upload.html file that looks like this:

{% extends "layout.html" %}
{% block title%}Submissions{% endblock %}

{% block content %}

{{submission_items.submission_name}}  {{file_type.file_type}}

{{submission_items.package_type}} Package - Property Agent Report Package Details

  {{ dropzone.create(action=url_for('views.upload_file', submission_id=submission_items.id, file_type_id=file_type.id)) }}
  {{ dropzone.load_js() }}
  {{ dropzone.config(redirect_url=url_for('views.submission', submission_id=submission_items.id)) }}

{% endblock %}

The views.submission path is uploading the file to an s3 bucket. I've had times when due to network or some other issues, the server logs indicated the transmission failed but the website still redirects. I'd like to condition the redirect to views.submission only if the transmission was successful. How can I do that?


问:
How to use MySQL variables in a VB.NET query?
When using a query with MySQL variables from VB.NET I get an error

Fatal error encountered during command execution.

The problem is when trying to use a MySQL variable like @sum in a VB.NET string, this variable is recognized as a parameter of the MySqlCommand and not as part of the string itself.

Here is the code that I use.

```<code>dim query as string = "SET @sum = 0; SELECT @sum := (@sum + debe - haber) AS 'Saldo' from cccustomers WHERE customer = 443"
using con
    If con.State = ConnectionState.Closed Then con.Open()
    Using cmd As New MySqlCommand(query, con)
        Dim adp As New MySqlDataAdapter(cmd)
        Dim dt As New DataTable
        adp.Fill(dt)
        DataGridView1.DataSource = dt
    end using
end using
</code>```

I also tried this with exactly the same result:

```<code>dim sums as string = "@sum"
dim query as string = "SET " & sums & " = 0; SELECT " & sums & " := (" & sums & " + debe - haber) AS 'Saldo' from cccustomers WHERE customer = 443"
</code>```

And I also tried this:

```<code>dim query as string = "SET @sum = 0; SELECT @sum := (@sum + debe - haber) AS 'Saldo' from cccustomers WHERE customer = 443"
using con
    If con.State = ConnectionState.Closed Then con.Open()
    Using cmd As New MySqlCommand(query, con)
        cmd.Parameters.AddWithValue("@sum", "@sum")
        Dim adp As New MySqlDataAdapter(cmd)
        Dim dt As New DataTable
        adp.Fill(dt)
        DataGridView1.DataSource = dt
    end using
end using
</code>```

But in this case, the problem is that it passes me the variable as a string with quotes '@sum' and that gives a different error in the query.

If I make that same query directly in phpmyadmin it works correctly, the problem I have is: How can I use the MySQL variable in VB.net?

I need the variable because in each line I have to show the accumulated balance and not only show the balance of each particular line.

Thanks for your time.

EDIT: Table Definition, Sample Data and expected Output

```<code>CREATE TABLE `stack` (
  `id` int(11) NOT NULL,
  `debe` double NOT NULL,
  `haber` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Volcado de datos para la tabla `stack`
--

INSERT INTO `stack` (`id`, `debe`, `haber`) VALUES
(1, 100, 0),
(2, 100, 0),
(3, 100, 0),
(4, 100, 0),
(5, 0, 50),
(6, 100, 0),
(7, 0, 150),
(8, 100, 0),
(9, 100, 0),
(10, 100, 0),
(11, 0, 100),
(12, 100, 0);

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `stack`
--
ALTER TABLE `stack`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `stack`
--
ALTER TABLE `stack`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
COMMIT;

</code>```

The Query: (works on PhpMyadmin but NOT WORK on VB.NET because the symbol @ in MySqlCommand expects a parameter - I don't want to send a parameter, I want to Send a MySql variable)

```<code>SET @sum = 0;
SELECT debe, haber, @sum := (@sum + debe - haber) AS 'Saldo' from stack;
</code>```

Expected output:

Code on VB.NET with the SAME QUERY:

```<code>dim query as string = "SET @sum = 0; SELECT debe, haber, @sum := (@sum + debe - haber) AS 'Saldo' from stack;"
using con
    If con.State = ConnectionState.Closed Then con.Open()
    Using cmd As New MySqlCommand(query, con)
        Dim adp As New MySqlDataAdapter(cmd)
        Dim dt As New DataTable
        adp.Fill(dt)
        DataGridView1.DataSource = dt
    end using
end using
</code>```

Result on VB.NET

This exception means that @sum is expected to be defined as a parameter, but I don't want to define a parameter, I want to declare a MySQL variable.

Body:
When using a query with MySQL variables from VB.NET I get an error

Fatal error encountered during command execution.

The problem is when trying to use a MySQL variable like @sum in a VB.NET string, this variable is recognized as a parameter of the MySqlCommand and not as part of the string itself.

Here is the code that I use.

dim query as string = "SET @sum = 0; SELECT @sum := (@sum + debe - haber) AS 'Saldo' from cccustomers WHERE customer = 443"
using con
    If con.State = ConnectionState.Closed Then con.Open()
    Using cmd As New MySqlCommand(query, con)
        Dim adp As New MySqlDataAdapter(cmd)
        Dim dt As New DataTable
        adp.Fill(dt)
        DataGridView1.DataSource = dt
    end using
end using

I also tried this with exactly the same result:

dim sums as string = "@sum"
dim query as string = "SET " & sums & " = 0; SELECT " & sums & " := (" & sums & " + debe - haber) AS 'Saldo' from cccustomers WHERE customer = 443"

And I also tried this:

dim query as string = "SET @sum = 0; SELECT @sum := (@sum + debe - haber) AS 'Saldo' from cccustomers WHERE customer = 443"
using con
    If con.State = ConnectionState.Closed Then con.Open()
    Using cmd As New MySqlCommand(query, con)
        cmd.Parameters.AddWithValue("@sum", "@sum")
        Dim adp As New MySqlDataAdapter(cmd)
        Dim dt As New DataTable
        adp.Fill(dt)
        DataGridView1.DataSource = dt
    end using
end using

But in this case, the problem is that it passes me the variable as a string with quotes '@sum' and that gives a different error in the query.

If I make that same query directly in phpmyadmin it works correctly, the problem I have is: How can I use the MySQL variable in VB.net?

I need the variable because in each line I have to show the accumulated balance and not only show the balance of each particular line.

Thanks for your time.

EDIT: Table Definition, Sample Data and expected Output

CREATE TABLE `stack` (
  `id` int(11) NOT NULL,
  `debe` double NOT NULL,
  `haber` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Volcado de datos para la tabla `stack`
--

INSERT INTO `stack` (`id`, `debe`, `haber`) VALUES
(1, 100, 0),
(2, 100, 0),
(3, 100, 0),
(4, 100, 0),
(5, 0, 50),
(6, 100, 0),
(7, 0, 150),
(8, 100, 0),
(9, 100, 0),
(10, 100, 0),
(11, 0, 100),
(12, 100, 0);

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `stack`
--
ALTER TABLE `stack`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `stack`
--
ALTER TABLE `stack`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
COMMIT;

The Query: (works on PhpMyadmin but NOT WORK on VB.NET because the symbol @ in MySqlCommand expects a parameter - I don't want to send a parameter, I want to Send a MySql variable)

SET @sum = 0;
SELECT debe, haber, @sum := (@sum + debe - haber) AS 'Saldo' from stack;

Expected output:

Code on VB.NET with the SAME QUERY:

dim query as string = "SET @sum = 0; SELECT debe, haber, @sum := (@sum + debe - haber) AS 'Saldo' from stack;"
using con
    If con.State = ConnectionState.Closed Then con.Open()
    Using cmd As New MySqlCommand(query, con)
        Dim adp As New MySqlDataAdapter(cmd)
        Dim dt As New DataTable
        adp.Fill(dt)
        DataGridView1.DataSource = dt
    end using
end using

Result on VB.NET

This exception means that @sum is expected to be defined as a parameter, but I don't want to define a parameter, I want to declare a MySQL variable.


问:
How do I reset the Second drop down after I select the first drop down Item?
I have two drop down which second is depends on first.
When i changing the first drop down value after selecting second dropdown value it throws an error as below.

This is the error

This is my code for the drop down

```<code> Container(
                height: 45,
                child: ButtonTheme(
                  alignedDropdown: true,
                  child: DropdownButtonFormField<String>(
                    iconDisabledColor: Colors.black,
                    iconEnabledColor: Colors.black,
                    hint: Text(
                      'Select Country',
                      style: robotoBl12Reg.copyWith(color: Colors.grey),
                    ),
                    decoration: const InputDecoration(
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey),
                        borderRadius: BorderRadius.all(
                          Radius.circular(8.0),
                        ),
                      ),
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(),
                      filled: true,
                      fillColor: Colors.white,
                    ),
                    items: controller.countryCodeList.map((item) {
                      return DropdownMenuItem(
                        value: item["id"].toString(),
                        child: Text(item["country_name"].toString()),
                      );
                    }).toList(),
                    onChanged: (value) {
                      controller.setState(() {
                        print(" value ->>>>>> ${value}");
                        controller.valueCountryCode = value.toString();
                        controller.getStateList(controller.valueCountryCode);
                        // clear the second drop down when the first one is changed
                      });
                    },
                  ),
                ),
              ),
              const SizedBox(height: 12),
              Text('State', style: robotoBl14Med),
              const SizedBox(height: 10),
              Container(
                height: 45,
                child: ButtonTheme(
                  alignedDropdown: true,
                  child: DropdownButtonFormField(
                    iconDisabledColor: Colors.black,
                    iconEnabledColor: Colors.black,
                    hint: Text(
                      'Select State',
                      style: robotoBl12Reg.copyWith(color: Colors.grey),
                    ),
                    decoration: const InputDecoration(
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey),
                        borderRadius: BorderRadius.all(
                          Radius.circular(8.0),
                        ),
                      ),
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(),
                      filled: true,
                      fillColor: Colors.white,
                    ),
                    items: controller.resultList?.map((item) {
                      return DropdownMenuItem(
                        value: item["id"].toString(),
                        child: Text(item["state"].toString()),
                      );
                    }).toList(),
                    onChanged: (newVal) {
                      controller.setState(() {
                        controller.valueState = newVal.toString();
                      });
                    },
                  ),
                ),
              ),
</code>```

And this is how i get the State and the Country Code

```<code>@override
  void initState() {
    instance = this;
    controller = MapTileLayerController();
    mapZoomPanBehavior = MapZoomPanBehavior(zoomLevel: 8);
    getCountryCode();
    setState(() {});
    super.initState();
  }

  @override
  void dispose() => super.dispose();

  @override
  Widget build(BuildContext context) => widget.build(context, this);

  var initialValue = '';

  List countryCodeList = [];
  List testCode = [];

  Future getCountryCode() async {
    var baseUrl = "${Api.baseUrl}/country/getData";

    // var response = await Dio().get(baseUrl);

    http.Response response = await http.get(Uri.parse(baseUrl));

    if (response.body.isNotEmpty) {
      var jsonData = json.decode(response.body);

      setState(() {
        countryCodeList = jsonData['data'];
      });
    }
  }

  List? resultList = [];
  String valueCountryCode = '';
  String valueState = '';

  getStateList(String state) async {
    List stateList = await ServiceCountry().getState(state);
    resultList = stateList;
    setState(() {});
  }

</code>```

I just setState({}) and set the list of the state to 0 after I click the item on the first drop down, I know its wrong. any suggestion?

Body:
I have two drop down which second is depends on first.
When i changing the first drop down value after selecting second dropdown value it throws an error as below.

This is the error

This is my code for the drop down

 Container(
                height: 45,
                child: ButtonTheme(
                  alignedDropdown: true,
                  child: DropdownButtonFormField<String>(
                    iconDisabledColor: Colors.black,
                    iconEnabledColor: Colors.black,
                    hint: Text(
                      'Select Country',
                      style: robotoBl12Reg.copyWith(color: Colors.grey),
                    ),
                    decoration: const InputDecoration(
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey),
                        borderRadius: BorderRadius.all(
                          Radius.circular(8.0),
                        ),
                      ),
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(),
                      filled: true,
                      fillColor: Colors.white,
                    ),
                    items: controller.countryCodeList.map((item) {
                      return DropdownMenuItem(
                        value: item["id"].toString(),
                        child: Text(item["country_name"].toString()),
                      );
                    }).toList(),
                    onChanged: (value) {
                      controller.setState(() {
                        print(" value ->>>>>> ${value}");
                        controller.valueCountryCode = value.toString();
                        controller.getStateList(controller.valueCountryCode);
                        // clear the second drop down when the first one is changed
                      });
                    },
                  ),
                ),
              ),
              const SizedBox(height: 12),
              Text('State', style: robotoBl14Med),
              const SizedBox(height: 10),
              Container(
                height: 45,
                child: ButtonTheme(
                  alignedDropdown: true,
                  child: DropdownButtonFormField(
                    iconDisabledColor: Colors.black,
                    iconEnabledColor: Colors.black,
                    hint: Text(
                      'Select State',
                      style: robotoBl12Reg.copyWith(color: Colors.grey),
                    ),
                    decoration: const InputDecoration(
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey),
                        borderRadius: BorderRadius.all(
                          Radius.circular(8.0),
                        ),
                      ),
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(),
                      filled: true,
                      fillColor: Colors.white,
                    ),
                    items: controller.resultList?.map((item) {
                      return DropdownMenuItem(
                        value: item["id"].toString(),
                        child: Text(item["state"].toString()),
                      );
                    }).toList(),
                    onChanged: (newVal) {
                      controller.setState(() {
                        controller.valueState = newVal.toString();
                      });
                    },
                  ),
                ),
              ),

And this is how i get the State and the Country Code

@override
  void initState() {
    instance = this;
    controller = MapTileLayerController();
    mapZoomPanBehavior = MapZoomPanBehavior(zoomLevel: 8);
    getCountryCode();
    setState(() {});
    super.initState();
  }

  @override
  void dispose() => super.dispose();

  @override
  Widget build(BuildContext context) => widget.build(context, this);

  var initialValue = '';

  List countryCodeList = [];
  List testCode = [];

  Future getCountryCode() async {
    var baseUrl = "${Api.baseUrl}/country/getData";

    // var response = await Dio().get(baseUrl);

    http.Response response = await http.get(Uri.parse(baseUrl));

    if (response.body.isNotEmpty) {
      var jsonData = json.decode(response.body);

      setState(() {
        countryCodeList = jsonData['data'];
      });
    }
  }

  List? resultList = [];
  String valueCountryCode = '';
  String valueState = '';

  getStateList(String state) async {
    List stateList = await ServiceCountry().getState(state);
    resultList = stateList;
    setState(() {});
  }

I just setState({}) and set the list of the state to 0 after I click the item on the first drop down, I know its wrong. any suggestion?


问:
How to properly implement the list component?
I'm trying to write a simple react client that will send a message to the server and receive back a list of all items. I want to output a list of all the items, but something goes wrong

```<code>import React, {Component, ReactNode} from "react";
import "./CommentPage.scss"
import axios from 'axios';
import {Message} from "@material-ui/icons";
import {Box} from "@material-ui/core";

export class CommentPage extends Component<any, any> {

    public render(): ReactNode {
        return (
            <div>
                <Form/>
                <Mlist/>
            </div>
        )
    }
}

interface message {
    name: string,
    value: string
}
let data: message [] = [{name: "a", value: "b"}]

class Form extends Component<{}, { name: string, message: string }> {

    constructor(props: {}) {
        super(props);
        this.state = {name: '', message: ''};

        this.handleChangeName = this.handleChangeName.bind(this);
        this.handleChangeMess = this.handleChangeMess.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChangeName(event: React.ChangeEvent<HTMLInputElement>) {
        this.setState({name: event.target.value, message: this.state.message});
    }

    handleChangeMess(event: React.ChangeEvent<HTMLInputElement>) {
        this.setState({name: this.state.name, message: event.target.value});
    }

    handleSubmit(event: React.ChangeEvent<EventTarget>) {

        axios.post('http://localhost:8080/addComment', {
            author: this.state.name,
            comment: this.state.message
        }).then(r => {
            axios.get('http://localhost:8080/allComments').then(r => {
              r.request.items.map((item: message) =>(data.push(item)));
            })
        }).catch(err => {
            alert(err)
        })
        this.setState({name: this.state.name, message: ''});
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name
                    <input type="text" value={this.state.name} onChange={this.handleChangeName}/>
                    Message
                    <input type="text" value={this.state.message} onChange={this.handleChangeMess}/>
                </label>
                <input type="submit" value="Submit"/>
            </form>
        );
    }
}

class Mlist extends Component<{}, {}> {
    render() {
        return (
                <p>{data.map((m) => (
                    <li>{m.name}</li>
                ))}</p>
        );
    }
}
</code>```

Until I handled the incoming response explicitly, and before I implemented the Mlist everything worked, that is, the data was sent to the server and came what I expected.

I get it:

```<code>TypeScript error in /Users/user/IdeaProjects/namep/front/itmo-hw3/node_modules/@types/babel__traverse/index.d.ts(68,50):
']' expected.  TS1005

    66 | }
    67 |
  > 68 | export type ArrayKeys<T> = keyof { [P in keyof T as T[P] extends any[] ? P : never]: P };
       |                                                  ^
    69 |
    70 | export class Scope {
    71 |     constructor(path: NodePath, parentScope?: Scope);
</code>```

I don't understand much about frontend, so I could use all the help I can get.

Body:
I'm trying to write a simple react client that will send a message to the server and receive back a list of all items. I want to output a list of all the items, but something goes wrong

import React, {Component, ReactNode} from "react";
import "./CommentPage.scss"
import axios from 'axios';
import {Message} from "@material-ui/icons";
import {Box} from "@material-ui/core";

export class CommentPage extends Component<any, any> {

    public render(): ReactNode {
        return (

                <Form/>
                <Mlist/>

        )
    }
}

interface message {
    name: string,
    value: string
}
let data: message [] = [{name: "a", value: "b"}]

class Form extends Component<{}, { name: string, message: string }> {

    constructor(props: {}) {
        super(props);
        this.state = {name: '', message: ''};

        this.handleChangeName = this.handleChangeName.bind(this);
        this.handleChangeMess = this.handleChangeMess.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChangeName(event: React.ChangeEvent<HTMLInputElement>) {
        this.setState({name: event.target.value, message: this.state.message});
    }

    handleChangeMess(event: React.ChangeEvent<HTMLInputElement>) {
        this.setState({name: this.state.name, message: event.target.value});
    }

    handleSubmit(event: React.ChangeEvent<EventTarget>) {

        axios.post('http://localhost:8080/addComment', {
            author: this.state.name,
            comment: this.state.message
        }).then(r => {
            axios.get('http://localhost:8080/allComments').then(r => {
              r.request.items.map((item: message) =>(data.push(item)));
            })
        }).catch(err => {
            alert(err)
        })
        this.setState({name: this.state.name, message: ''});
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>

                    Name
                    <input type="text" value={this.state.name} onChange={this.handleChangeName}/>
                    Message
                    <input type="text" value={this.state.message} onChange={this.handleChangeMess}/>

                <input type="submit" value="Submit"/>
            </form>
        );
    }
}

class Mlist extends Component<{}, {}> {
    render() {
        return (

{data.map((m) => (

{m.name}

                ))}

        );
    }
}

Until I handled the incoming response explicitly, and before I implemented the Mlist everything worked, that is, the data was sent to the server and came what I expected.

I get it:

TypeScript error in /Users/user/IdeaProjects/namep/front/itmo-hw3/node_modules/@types/babel__traverse/index.d.ts(68,50):
']' expected.  TS1005

    66 | }
    67 |
  > 68 | export type ArrayKeys<T> = keyof { [P in keyof T as T[P] extends any[] ? P : never]: P };
       |                                                  ^
    69 |
    70 | export class Scope {
    71 |     constructor(path: NodePath, parentScope?: Scope);

I don't understand much about frontend, so I could use all the help I can get.


问:
How to get user details (email and name) using Azure AD auth token?
We have a web app that has authentication on the front-end (React JS) using Microsoft OAuth, but no authentication at the back end side (Spring Boot), meaning everybody can access the APIs. We want to secure the APIs using the "Access token" generated by the UI (front-end). The idea is that UI passes the token to the back-end in every API call. Since each API call would contain the token, the back-end will use this to validate which user this token belongs to. Is there a way to achieve this using MSAL?

Tl;dr: How to obtain user details (email and user name) from Microsoft OAuth generated token using MSAL?

I did try going through this: https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-overview but to no help