问:
Submitting form is resetting city dropDown javascript
i made two dynamic dropdown list State and city

City dropdown will depend of selected option of state

problem is when all is good and okay to submit .it resets the city drop down
and does not submit

javascript code for making those dynamic drop down is

these function are onchange events

```<code>
    // remove all previous options
    function removeOptions(selectbox) {
        for (let i = selectbox.options.length - 1; i >= 0; i--) {
            selectbox.remove(i);
        }
    }
    // function to make city drop down according to selected state
    function cityFunction(){
    // get input value and text
    const stateobj = document.getElementById('stateDropDown');
    const valueState = stateobj.options[stateobj.selectedIndex].text;
    const selectedOption = stateobj.options[stateobj.selectedIndex].value;

    // making required arrays

    let sindhArray = [ 'Select City', 'Karachi', 'Hyderabad', 'Mirpur khas', 'Sukkhar', 'Shikarpur' ];
    let KhyberArray = [ 'Select City', 'gilgit', 'Qalat', 'Balakoot', 'Sawat', 'Peshwar' ];
    let punjabArray = [ 'Select City', 'Lahore', 'Fasialabad', 'Qasoor', 'SheikhuPura', 'Gujrat' ];
    let balochArray = [ 'Select City', 'Quetta', 'Chaman', 'Khuzdar', 'Turbat', 'Gawdar' ];

    // if value is punjab or any select cities according to that state
    if (valueState == 'Punjab') {
    // removing all previous present options
        removeOptions(document.getElementById('cityDropDown'));

        let cityD = document.querySelector('#cityDropDown');
        let index = 0;

        for (let ele of punjabArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has
            document.getElementById('cityDropDown').value = cityD.appendChild(opt);

            index++;
        }
    }
    if (valueState == 'Sindh') {
        removeOptions(document.getElementById('cityDropDown'));
        let cityD = document.querySelector('#cityDropDown');
        let index = 0;

        for (let ele of sindhArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has

            document.getElementById('cityDropDown').value = cityD.appendChild(opt);

            index++;
        }
    }
    if (valueState == 'Balochistan') {
        removeOptions(document.getElementById('cityDropDown'));

        let cityD = document.querySelector('#cityDropDown');
        let index = 0;

        for (let ele of balochArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has

            document.getElementById('cityDropDown').value = cityD.appendChild(opt);

            index++;
        }
    }

    if (valueState == 'khyber Pakhtunkhwa') {
        removeOptions(document.getElementById('cityDropDown'));

        let cityD = document.getElementById('cityDropDown');

        let index = 0;

        for (let ele of KhyberArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has

            document.getElementById('cityDropDown').value = cityD.appendChild(opt);
    index++;
        }
    }
    }
</code>```

for city form validation onchange event is

```<code>function cityDown() {
    const cityObj = document.getElementById('cityDropDown');
    const cityText = cityObj.options[cityObj.selectedIndex].text;

    const valueOfCity = cityObj.options[cityObj.selectedIndex].value;

    let citiesArray = [
        'Quetta',
        'Chaman',
        'Khuzdar',
        'Turbat',
        'Gawdar',
        'Lahore',
        'Fasialabad',
        'Qasoor',
        'SheikhuPura',
        'Gujrat',
        'gilgit',
        'Qalat',
        'Balakoot',
        'Sawat',
        'Peshwar',
        'Karachi',
        'Hyderabad',
        'Mirpur khas',
        'Sukkhar',
        'Shikarpur'
    ];

    if ( valueOfCity == 0) {
        document.getElementById('cityErr').innerText = 'City is required';
        document.getElementById('cityDropDown').focus();
        return valueOfCity;
    }
    if (citiesArray.indexOf(cityText) < 0) {
        document.getElementById('cityErr').innerText = 'Select City';
        document.getElementById('cityDropDown').focus();
        return valueOfCity;
    } else {
        document.getElementById('cityErr').innerText = '';
        return valueOfCity;
    };
}
</code>```

main function is

```<code>

        // validation f0rm function

        function validateForm() {
            // creating variable then sanitize them

            isTrueorFalse = false;
        document.getElementById('Address').disabled = isTrueorFalse;
            document.getElementById('stateDropDown').disabled = isTrueorFalse;
            document.getElementById('stateDropDown').style.background = '#FFF';
            document.getElementById('cityDropDown').disabled = isTrueorFalse;
            document.getElementById('cityDropDown').style.background = '#FFF';
            const stateVal = stateDrag();
            const cityV = cityDown();
            const userAddress = form.Address.value;
            //States must not be unselected
            if (stateVal == 0 || stateVal == '') {
                document.getElementById('stateErr').innerText = 'State is required.';
                document.getElementById('stateDropDown').focus();
                return false;
            }
            if (stateVal < 0) {
                document.getElementById('stateErr').innerText = 'State is required.';
                document.getElementById('stateDropDown').focus();
                return false;
            }

            document.getElementById('addressErr').innerText = '';
            document.getElementById('cityDropDown').focus();
        console.log(cityV);
            if (cityV == 0 || cityV == '') {
                document.getElementById('cityErr').innerText = 'State is required.';
                document.getElementById('cityDropDown').focus();
                return false;

    }

            document.getElementById('cityErr').innerText = '';
        document.getElementById('signupForm').submit();
}
</code>```

here that demo

https://jsbin.com/jeguwakolo/1/edit?html,css,js,console,output

答:
onsubmit was calling that function again and was resetting the city dropdown.

To solve this i just removed that function from stateDrag() and
in html i did this

```<code><select oninput ="return stateDrag()" onchange="return cityFunction()">
</code>```

after this i didnt get same problem and scripting was working fine thank you for everyone

Body:
i made two dynamic dropdown list State and city

City dropdown will depend of selected option of state

problem is when all is good and okay to submit .it resets the city drop down
and does not submit

javascript code for making those dynamic drop down is

these function are onchange events

    // remove all previous options
    function removeOptions(selectbox) {
        for (let i = selectbox.options.length - 1; i >= 0; i--) {
            selectbox.remove(i);
        }
    }
    // function to make city drop down according to selected state
    function cityFunction(){
    // get input value and text
    const stateobj = document.getElementById('stateDropDown');
    const valueState = stateobj.options[stateobj.selectedIndex].text;
    const selectedOption = stateobj.options[stateobj.selectedIndex].value;

    // making required arrays

    let sindhArray = [ 'Select City', 'Karachi', 'Hyderabad', 'Mirpur khas', 'Sukkhar', 'Shikarpur' ];
    let KhyberArray = [ 'Select City', 'gilgit', 'Qalat', 'Balakoot', 'Sawat', 'Peshwar' ];
    let punjabArray = [ 'Select City', 'Lahore', 'Fasialabad', 'Qasoor', 'SheikhuPura', 'Gujrat' ];
    let balochArray = [ 'Select City', 'Quetta', 'Chaman', 'Khuzdar', 'Turbat', 'Gawdar' ];

    // if value is punjab or any select cities according to that state
    if (valueState == 'Punjab') {
    // removing all previous present options
        removeOptions(document.getElementById('cityDropDown'));

        let cityD = document.querySelector('#cityDropDown');
        let index = 0;

        for (let ele of punjabArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has
            document.getElementById('cityDropDown').value = cityD.appendChild(opt);

            index++;
        }
    }
    if (valueState == 'Sindh') {
        removeOptions(document.getElementById('cityDropDown'));
        let cityD = document.querySelector('#cityDropDown');
        let index = 0;

        for (let ele of sindhArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has

            document.getElementById('cityDropDown').value = cityD.appendChild(opt);

            index++;
        }
    }
    if (valueState == 'Balochistan') {
        removeOptions(document.getElementById('cityDropDown'));

        let cityD = document.querySelector('#cityDropDown');
        let index = 0;

        for (let ele of balochArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has

            document.getElementById('cityDropDown').value = cityD.appendChild(opt);

            index++;
        }
    }

    if (valueState == 'khyber Pakhtunkhwa') {
        removeOptions(document.getElementById('cityDropDown'));

        let cityD = document.getElementById('cityDropDown');

        let index = 0;

        for (let ele of KhyberArray) {
            var opt = document.createElement('option');
            opt.value = index;
            opt.innerHTML = ele; // whatever property it has

            document.getElementById('cityDropDown').value = cityD.appendChild(opt);
    index++;
        }
    }
    }

for city form validation onchange event is

function cityDown() {
    const cityObj = document.getElementById('cityDropDown');
    const cityText = cityObj.options[cityObj.selectedIndex].text;

    const valueOfCity = cityObj.options[cityObj.selectedIndex].value;

    let citiesArray = [
        'Quetta',
        'Chaman',
        'Khuzdar',
        'Turbat',
        'Gawdar',
        'Lahore',
        'Fasialabad',
        'Qasoor',
        'SheikhuPura',
        'Gujrat',
        'gilgit',
        'Qalat',
        'Balakoot',
        'Sawat',
        'Peshwar',
        'Karachi',
        'Hyderabad',
        'Mirpur khas',
        'Sukkhar',
        'Shikarpur'
    ];

    if ( valueOfCity == 0) {
        document.getElementById('cityErr').innerText = 'City is required';
        document.getElementById('cityDropDown').focus();
        return valueOfCity;
    }
    if (citiesArray.indexOf(cityText) < 0) {
        document.getElementById('cityErr').innerText = 'Select City';
        document.getElementById('cityDropDown').focus();
        return valueOfCity;
    } else {
        document.getElementById('cityErr').innerText = '';
        return valueOfCity;
    };
}

main function is

        // validation f0rm function

        function validateForm() {
            // creating variable then sanitize them

            isTrueorFalse = false;
        document.getElementById('Address').disabled = isTrueorFalse;
            document.getElementById('stateDropDown').disabled = isTrueorFalse;
            document.getElementById('stateDropDown').style.background = '#FFF';
            document.getElementById('cityDropDown').disabled = isTrueorFalse;
            document.getElementById('cityDropDown').style.background = '#FFF';
            const stateVal = stateDrag();
            const cityV = cityDown();
            const userAddress = form.Address.value;
            //States must not be unselected
            if (stateVal == 0 || stateVal == '') {
                document.getElementById('stateErr').innerText = 'State is required.';
                document.getElementById('stateDropDown').focus();
                return false;
            }
            if (stateVal < 0) {
                document.getElementById('stateErr').innerText = 'State is required.';
                document.getElementById('stateDropDown').focus();
                return false;
            }

            document.getElementById('addressErr').innerText = '';
            document.getElementById('cityDropDown').focus();
        console.log(cityV);
            if (cityV == 0 || cityV == '') {
                document.getElementById('cityErr').innerText = 'State is required.';
                document.getElementById('cityDropDown').focus();
                return false;

    }

            document.getElementById('cityErr').innerText = '';
        document.getElementById('signupForm').submit();
}

here that demo

https://jsbin.com/jeguwakolo/1/edit?html,css,js,console,output

Body:
onsubmit was calling that function again and was resetting the city dropdown.

To solve this i just removed that function from stateDrag() and
in html i did this

<select oninput ="return stateDrag()" onchange="return cityFunction()">

after this i didnt get same problem and scripting was working fine thank you for everyone


来源: stackexchange

问:
EOF error with staticmethod for xlworkbook class
I'm trying to open password protected excel workbooks and found the code I've posted below on this page but when I try to impliment it I'm getting a sytaxError and an indentationEorror

xlpassword.py

```<code>
import xlwings as xw
from autoit.autoit import AutoItError
import autoit
import threading

class _WB(object):

  def __init__(self, path, password=None):
    self.path = path
    self.password = password
    self.name = path

  @staticmethod
  def _handlepassword(password):#this line is giving the error
    if password:
      autoit.win_wait_active("[TITLE:Excel]", 5)
      autoit.send(password)
      autoit.send("{ENTER}")

  def op(self):
    try: # If already opened
      autoit.win_activate("%s - Excel"%self.name)
      self.book = xw.Book(self.path)
    except AutoItError: # Else
      t = threading.Thread(target=self._handlepassword, args=(self.password,))
      t.start()
      self.book = xw.Book(self.path)
      t.join()
    finally:
      return self

  def _wait(self):
      autoit.win_wait_active("%s - Excel"%self.name, 1)

  def close(self):
      self._wait()
      self.book.close()
      autoit.win_close("Excel")
</code>```

when I get to the def _handlepassword line I get the output

```<code>SyntaxError: unexpected EOF while parsing (<string>, line 1)
IndentationError: unexpected indent (<string>, line 1)
</code>```

Which means when I import xlpassword.py into another python script, that new script fails to run

test_run.py

```<code>import pandas as pd
from xlpassword import * #I know this isn't best practice

PATH = "C:\\Path\\to\\my\\file.xlsx"

print(PATH)
wb = _WB(path=PATH, password='MyP8ssw0rd')

</code>```

I'm using python 3.8.1 on a windows 10 machine, and I have tried to run the code in spyder, sublime, and Rstudio (I normally work in Rstudio but I thought that might be what's causing the problem.)

I have read up on classes, class methods, and static methods and I can't see what I'm doing wrong here so if anyone could provide assistance it would help a lot.

答:
Since v0.16.1, xlwings supports opening of password protected workbooks out of the box:

```<code>import xlwings as xw
wb = xw.Book(password='mypassword')
</code>```

See also the API Reference: https://docs.xlwings.org/en/stable/api.html#xlwings.Book

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to open password protected excel workbooks and found the code I've posted below on this page but when I try to impliment it I'm getting a sytaxError and an indentationEorror

xlpassword.py

import xlwings as xw
from autoit.autoit import AutoItError
import autoit
import threading

class _WB(object):

  def __init__(self, path, password=None):
    self.path = path
    self.password = password
    self.name = path

  @staticmethod
  def _handlepassword(password):#this line is giving the error
    if password:
      autoit.win_wait_active("[TITLE:Excel]", 5)
      autoit.send(password)
      autoit.send("{ENTER}")

  def op(self):
    try: # If already opened
      autoit.win_activate("%s - Excel"%self.name)
      self.book = xw.Book(self.path)
    except AutoItError: # Else
      t = threading.Thread(target=self._handlepassword, args=(self.password,))
      t.start()
      self.book = xw.Book(self.path)
      t.join()
    finally:
      return self

  def _wait(self):
      autoit.win_wait_active("%s - Excel"%self.name, 1)

  def close(self):
      self._wait()
      self.book.close()
      autoit.win_close("Excel")

when I get to the def _handlepassword line I get the output

SyntaxError: unexpected EOF while parsing (<string>, line 1)
IndentationError: unexpected indent (<string>, line 1)

Which means when I import xlpassword.py into another python script, that new script fails to run

test_run.py

import pandas as pd
from xlpassword import * #I know this isn't best practice

PATH = "C:\\Path\\to\\my\\file.xlsx"

print(PATH)
wb = _WB(path=PATH, password='MyP8ssw0rd')

I'm using python 3.8.1 on a windows 10 machine, and I have tried to run the code in spyder, sublime, and Rstudio (I normally work in Rstudio but I thought that might be what's causing the problem.)

I have read up on classes, class methods, and static methods and I can't see what I'm doing wrong here so if anyone could provide assistance it would help a lot.

Body:
Since v0.16.1, xlwings supports opening of password protected workbooks out of the box:

import xlwings as xw
wb = xw.Book(password='mypassword')

See also the API Reference: https://docs.xlwings.org/en/stable/api.html#xlwings.Book


问:
Reshape distance matrix in pandas
I have a dataframe in the shape of df1

```<code>import pandas as pd

df1 = pd.DataFrame({
    'From': ['A','B','C'],
    'To': ['X','Y','Z'],
    'Price': [1,2,3]
})
</code>```

What I am trying to do is reshape df1 to have the form of df2. The desired end result would be this:

```<code>df2 = pd.DataFrame({
    'Location': ['A','X','B','Y','C','Z'],
    'Direction': ['Origin','Destination','Origin','Destination','Origin','Destination'],
    'Price': [1,1,2,2,3,3]
})
</code>```

I would like to achieve that with pandas stack(), pivot(), melt(), etc., but I cannot figure out how it's done.

答:
First rename columns, then reshape by DataFrame.set_index and DataFrame.stack:

```<code>df = (df1.rename(columns={'From':'Origin','To':'Destination'})
         .set_index('Price')
         .rename_axis('Direction', axis=1)
         .stack()
         .reset_index(name='Location')
         .reindex(['Location','Direction','Price'], axis=1))
print (df)
  Location    Direction  Price
0        A       Origin      1
1        X  Destination      1
2        B       Origin      2
3        Y  Destination      2
4        C       Origin      3
5        Z  Destination      3
</code>```

If order is not important:

```<code>df2 = (df1.rename(columns={'From':'Origin','To':'Destination'})
          .melt('Price',var_name='Direction',value_name='Location')
          .reindex(['Location','Direction','Price'], axis=1)
         )
print (df2)
  Location    Direction  Price
0        A       Origin      1
1        B       Origin      2
2        C       Origin      3
3        X  Destination      1
4        Y  Destination      2
5        Z  Destination      3
</code>```

Title: Reshape distance matrix in pandas

Body:
I have a dataframe in the shape of df1

import pandas as pd

df1 = pd.DataFrame({
    'From': ['A','B','C'],
    'To': ['X','Y','Z'],
    'Price': [1,2,3]
})

What I am trying to do is reshape df1 to have the form of df2. The desired end result would be this:

df2 = pd.DataFrame({
    'Location': ['A','X','B','Y','C','Z'],
    'Direction': ['Origin','Destination','Origin','Destination','Origin','Destination'],
    'Price': [1,1,2,2,3,3]
})

I would like to achieve that with pandas stack(), pivot(), melt(), etc., but I cannot figure out how it's done.

Body:
First rename columns, then reshape by DataFrame.set_index and DataFrame.stack:

df = (df1.rename(columns={'From':'Origin','To':'Destination'})
         .set_index('Price')
         .rename_axis('Direction', axis=1)
         .stack()
         .reset_index(name='Location')
         .reindex(['Location','Direction','Price'], axis=1))
print (df)
  Location    Direction  Price
0        A       Origin      1
1        X  Destination      1
2        B       Origin      2
3        Y  Destination      2
4        C       Origin      3
5        Z  Destination      3

If order is not important:

df2 = (df1.rename(columns={'From':'Origin','To':'Destination'})
          .melt('Price',var_name='Direction',value_name='Location')
          .reindex(['Location','Direction','Price'], axis=1)
         )
print (df2)
  Location    Direction  Price
0        A       Origin      1
1        B       Origin      2
2        C       Origin      3
3        X  Destination      1
4        Y  Destination      2
5        Z  Destination      3


问:
Entity Framework: Improving Performance when inserting a record in a table with many records
I want to insert a single record into a table with 60 columns (some of them are not required) and 2 million records. It takes about 20 seconds.

var package = new Package()
      {
          DestinationCityId = city.Id,
          OriginCityId = RequestDetails.User.Retailer.CityId,
          State = state,
          CreatedOn = RequestDetails.DateTime,
          CreatedByUserId = RequestDetails.User.Id,
          OrderedOn = RequestDetails.DateTime,
          CustomerName = "a",
          CustomerAddress = "a",
          CustomerEmail = "a",
          CustomerPostalCode = "a",
          CustomerLandPhone = "a",
          CustomerCellPhone = "aa",
          CustomerMessage = "a",
          CustomerSubstitute = "a",
          RetailerPackageDiscount = 0,
          Barcode = "2",
          InternalBarcode = "11111",
          PackagingWeight = 10,
          DeliveryType = PackageDeliveryType.ByPostExpress,
          ProvidedByWarehouse = false,
          NeedReview = false,
          NeedReviewType = NeedReviewType.Unknown,
          RetailerId = retailer.Id,
          Retailer = retailer
      };

DbContext.ZPackages.Add(package);
DbContext.SaveChanges();
```

Any Idea to improve performance?

答: Partitions, Indexes, Async CRUD operations where it possible. This is not EF problem</p>

Body:
I want to insert a single record into a table with 60 columns (some of them are not required) and 2 million records. It takes about 20 seconds.

var package = new Package()
      {
          DestinationCityId = city.Id,
          OriginCityId = RequestDetails.User.Retailer.CityId,
          State = state,
          CreatedOn = RequestDetails.DateTime,
          CreatedByUserId = RequestDetails.User.Id,
          OrderedOn = RequestDetails.DateTime,
          CustomerName = "a",
          CustomerAddress = "a",
          CustomerEmail = "a",
          CustomerPostalCode = "a",
          CustomerLandPhone = "a",
          CustomerCellPhone = "aa",
          CustomerMessage = "a",
          CustomerSubstitute = "a",
          RetailerPackageDiscount = 0,
          Barcode = "2",
          InternalBarcode = "11111",
          PackagingWeight = 10,
          DeliveryType = PackageDeliveryType.ByPostExpress,
          ProvidedByWarehouse = false,
          NeedReview = false,
          NeedReviewType = NeedReviewType.Unknown,
          RetailerId = retailer.Id,
          Retailer = retailer
      };

DbContext.ZPackages.Add(package);
DbContext.SaveChanges();

Any Idea to improve performance?


问:
Two excel sheets with BIRT 2.6.2
I am using BIRT 2.6.2.
Into a report I have two cross tabs, and I want that each cross tab to be on a separate excel sheet.

I set to first cross tab the page break property, After = Always, also I set to second cross tab the page break property, Before = Always. But the reports is generated only to one excel sheet.

Can anyone help with this?

Thanks!

答:
I think you should change the excel emitter to have this capability. I'm using spudsoft :

https://bitbucket.org/yaytay/spudsoft-birt-excel-emitters/wiki/

you should delete the birt default excel emitter and add the spudsoft, then with page break you can have the separated sheets and a lot of useful capability for excel.

ContentLicense: CC BY-SA 3.0

Title: Two excel sheets with BIRT 2.6.2


问:
Bash Script with multiple variables
Here's what I'm trying to do:

Ask for username, database, and password for SQL

Attempt SQLDUMP

If failed due to specific table, ask for which table, once entered, add it to script.

Run again automatically after adding table

If failed again, ask for new table, add table to list

Continue this process until successful

Here's what I've made so far:

```<code>#!/bin/bash

:dbase
echo "What is the Database name?"
read db1
goto :PW

:PW
echo "what is the password?"

read p1

PASSWORD=${p1}
HOST=mysql
USER=root
DATABASE=${db1}
DB_FILE=SQLDump.sql
EXCLUDED_TABLES=(
)

IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines --extended-insert=false --max_allowed_packet=2048M ${DATABASE} > ${DB_FILE}

echo "Dump content"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --extended-insert=false --max_allowed_packet=2048M ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
pause
alias ll='ls -lah'
ll *.sql

:choice
set /P c=Do you see your file[Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice

:yes

echo "Awesome, I'll delete this script now."
rm -rf /srv/SQLDump
echo "I have successfully deleted SQLDUMP."
pause
exit

:no
echo "What was the name of the table that failed?"
read $table1
set /P c=Was there another?[Y/N]?
if /I "%c%" EQU "Y" goto :t2
if /I "%c%" EQU "N" goto :continue

PASSWORD=${p1}
HOST=mysql
USER=root
DATABASE=${db1}
DB_FILE=SQLDump.sql
EXCLUDED_TABLES=(
${table1}
)

IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines --extended-insert=false --max_allowed_packet=2048M ${DATABASE} > ${DB_FILE}

echo "Dump content"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --extended-insert=false --max_allowed_packet=2048M ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
pause
alias ll='ls -lah'
ll *.sql

:choice
set /P c=Do you see your file[Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice
</code>```

It's obviously not finished. I ran into an issue where i'm calling the script over and over again in order to add multiple tables. I know there's a workaround, but as I'm self taught, I haven't been able to figure it out. Ideas?

答:
To restart your script it have to support options, so i'd suggest this approach</p>

```<code>#!/bin/bash

# get options if restarter
while [[ $@ ]]; do
    case $1 in
        --name) name="$2";;
        --pass) pass="$2";;
        --tabl) tables+=("$2");;
    esac
    shift
done

# get initial data when started first time
[[ $pass ]] || read -p 'What is the password? '      pass
[[ $name ]] || read -p 'What is the Database name? ' name

options=( --name "$name" --pass "$pass" )

# your code here
# add tables to tables to options array like this
# options+=(--tabl "table name")

# and restart script with options like this

$0 "${options[@]}"
</code>```

Title: Bash Script with multiple variables

Body:
Here's what I'm trying to do:

Ask for username, database, and password for SQL

Attempt SQLDUMP

If failed due to specific table, ask for which table, once entered, add it to script.

Run again automatically after adding table

If failed again, ask for new table, add table to list

Continue this process until successful

Here's what I've made so far:

#!/bin/bash

:dbase
echo "What is the Database name?"
read db1
goto :PW

:PW
echo "what is the password?"

read p1

PASSWORD=${p1}
HOST=mysql
USER=root
DATABASE=${db1}
DB_FILE=SQLDump.sql
EXCLUDED_TABLES=(
)

IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines --extended-insert=false --max_allowed_packet=2048M ${DATABASE} > ${DB_FILE}

echo "Dump content"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --extended-insert=false --max_allowed_packet=2048M ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
pause
alias ll='ls -lah'
ll *.sql

:choice
set /P c=Do you see your file[Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice

:yes

echo "Awesome, I'll delete this script now."
rm -rf /srv/SQLDump
echo "I have successfully deleted SQLDUMP."
pause
exit

:no
echo "What was the name of the table that failed?"
read $table1
set /P c=Was there another?[Y/N]?
if /I "%c%" EQU "Y" goto :t2
if /I "%c%" EQU "N" goto :continue

PASSWORD=${p1}
HOST=mysql
USER=root
DATABASE=${db1}
DB_FILE=SQLDump.sql
EXCLUDED_TABLES=(
${table1}
)

IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines --extended-insert=false --max_allowed_packet=2048M ${DATABASE} > ${DB_FILE}

echo "Dump content"
mysqldump --compress --host=${HOST} --user=${USER} --password=${PASSWORD} --extended-insert=false --max_allowed_packet=2048M ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
pause
alias ll='ls -lah'
ll *.sql

:choice
set /P c=Do you see your file[Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice

It's obviously not finished. I ran into an issue where i'm calling the script over and over again in order to add multiple tables. I know there's a workaround, but as I'm self taught, I haven't been able to figure it out. Ideas?

Body:
To restart your script it have to support options, so i'd suggest this approach

#!/bin/bash

# get options if restarter
while [[ $@ ]]; do
    case $1 in
        --name) name="$2";;
        --pass) pass="$2";;
        --tabl) tables+=("$2");;
    esac
    shift
done

# get initial data when started first time
[[ $pass ]] || read -p 'What is the password? '      pass
[[ $name ]] || read -p 'What is the Database name? ' name

options=( --name "$name" --pass "$pass" )

# your code here
# add tables to tables to options array like this
# options+=(--tabl "table name")

# and restart script with options like this

$0 "${options[@]}"


问:
The HTTP request was forbidden with client authentication scheme 'Anonymous'. returning 403
I'm getting the error while make call to the service "The HTTP request was forbidden with client authentication scheme 'Anonymous'."

actually im hosting this service in plesk, and in the plesk Anonymous authentication is enabled.

WCF Config

```<code><?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="SampleService.ServiceContracts.SampleService" behaviorConfiguration="mexBehaviour">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpConfig" contract="SampleService.ServiceContracts.ISampleService"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="basicHttpConfig" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" receiveTimeout="00:00:10">
          <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"></serviceDebug>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpBinding" scheme="https"  />
    </protocolMapping>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>
</code>```

Client

```<code><system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_ISampleService">
          <security mode="Transport" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://samplewcf.packletsgo.com/ServiceContracts/SampleService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISampleService"
        contract="ServiceReference1.ISampleService" name="BasicHttpBinding_ISampleService" />
    </client>
  </system.serviceModel>
</code>```

答:
This error typically occurred when the server authenticates the client with a certificate, nothing business with your current scenario. If the certificate's trust relationship between the client and server is not established, this error will occur.

I doubt whether the client configuration is automatically generated by using the above server configuration. In the above configuration, we should add an https bind to the website on the server-side in order to suit the Basichttpbinding with transport security mode. On the client-side, we should trust the server certificate before calling the service, or we will get the below similar error.

“The underlying connection is closed: trust cannot be established for
  the SSL/TLS security channel”.

In short, we need to validate whether the remote certificate is valid before communicating with the server.

At last, why does the service contain the following fragment, and do you use the virtual path?

https://localhost/SampleService/AuthService/AuthService.svc

I would like to know more details about how the error occurred. Feel free to let me know if there is anything I can help with.

Body:
I'm getting the error while make call to the service "The HTTP request was forbidden with client authentication scheme 'Anonymous'."

actually im hosting this service in plesk, and in the plesk Anonymous authentication is enabled.

WCF Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="SampleService.ServiceContracts.SampleService" behaviorConfiguration="mexBehaviour">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpConfig" contract="SampleService.ServiceContracts.ISampleService"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="basicHttpConfig" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" receiveTimeout="00:00:10">
          <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"></serviceDebug>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpBinding" scheme="https"  />
    </protocolMapping>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

Client

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_ISampleService">
          <security mode="Transport" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://samplewcf.packletsgo.com/ServiceContracts/SampleService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISampleService"
        contract="ServiceReference1.ISampleService" name="BasicHttpBinding_ISampleService" />
    </client>
  </system.serviceModel>


问:
using terraform .12.10+ templatefile function to populate local_secrets to s3 bucket
Can anyone help me on how i can use templatefile function in terraform .12.10+ to populate local_secrets to S3 bucket .

```<code>locals {
  prefix = join("-", [var.prefix, "core"])
  common_tags = merge(var.common_tags, map("Stack", "ipolls-core"))
  core_secrets = merge(var.secrets, map("AWS_REGION", data.aws_region.current.name,
      "AWS_STORAGE_BUCKET_NAME", aws_s3_bucket.assets.bucket,
      "AWS_S3_FQDN", join(".", [aws_s3_bucket.assets.bucket, "s3", data.aws_region.current.name, "amazonaws", "com"]),
      "AWS_STATIC_ASSETS_LOCATION", element(var.s3_objects, index(var.s3_objects,"static")),
      "AWS_MEDIA_ASSETS_LOCATION", element(var.s3_objects, index(var.s3_objects,"media")),
      "STATIC_URL", join("", ["https://", local.core_secrets["AWS_S3_FQDN"], "/", local.core_secrets["AWS_STATIC_ASSETS_LOCATION"], "/"]),
      "MEDIA_URL", join("", ["https://", local.core_secrets["AWS_S3_FQDN"], "/", local.core_secrets["AWS_MEDIA_ASSETS_LOCATION"], "/"]),
      "AWS_DEFAULT_ACL", "None"))
  images_dir = join("/", [path.module, "images"])
}
</code>```

```<code>resource "aws_s3_bucket_object" "envs" {
  bucket = var.s3_settings["bucket"]
  key = join("/", [local.prefix, "env"])
  acl = "private"
  for_each = local.core_secrets
  content = templatefile(join("/", [path.module, "templates", "envs.tpl"]), { each.key = each.value })
}
</code>```

can I use for_each function to iterate the secrets map, and how i can configure envs.tpl file to read each.key and each.value

答:
A new approach is used to activate the same thing populate APP secrets to app container
So, in here I created an AWS_SECRET_MANAGER to store the SECRETS from local.core_secrets and on the container, I will retrieve the Keys via the entrypoint

```<code>resource "aws_secretsmanager_secret" "secrets" {
  name = join("-", [local.prefix, "secret"])
  description = "secret store to store app secrets"
  kms_key_id = var.kms
  tags  = merge(local.common_tags, map("Type", "SecretManager"))
}

resource "aws_secretsmanager_secret_version" "secrets" {
  secret_id = aws_secretsmanager_secret.secrets.arn
  secret_string = jsonencode(local.core_secrets)
}
</code>```

Body:
Can anyone help me on how i can use templatefile function in terraform .12.10+ to populate local_secrets to S3 bucket .

locals {
  prefix = join("-", [var.prefix, "core"])
  common_tags = merge(var.common_tags, map("Stack", "ipolls-core"))
  core_secrets = merge(var.secrets, map("AWS_REGION", data.aws_region.current.name,
      "AWS_STORAGE_BUCKET_NAME", aws_s3_bucket.assets.bucket,
      "AWS_S3_FQDN", join(".", [aws_s3_bucket.assets.bucket, "s3", data.aws_region.current.name, "amazonaws", "com"]),
      "AWS_STATIC_ASSETS_LOCATION", element(var.s3_objects, index(var.s3_objects,"static")),
      "AWS_MEDIA_ASSETS_LOCATION", element(var.s3_objects, index(var.s3_objects,"media")),
      "STATIC_URL", join("", ["https://", local.core_secrets["AWS_S3_FQDN"], "/", local.core_secrets["AWS_STATIC_ASSETS_LOCATION"], "/"]),
      "MEDIA_URL", join("", ["https://", local.core_secrets["AWS_S3_FQDN"], "/", local.core_secrets["AWS_MEDIA_ASSETS_LOCATION"], "/"]),
      "AWS_DEFAULT_ACL", "None"))
  images_dir = join("/", [path.module, "images"])
}

resource "aws_s3_bucket_object" "envs" {
  bucket = var.s3_settings["bucket"]
  key = join("/", [local.prefix, "env"])
  acl = "private"
  for_each = local.core_secrets
  content = templatefile(join("/", [path.module, "templates", "envs.tpl"]), { each.key = each.value })
}

can I use for_each function to iterate the secrets map, and how i can configure envs.tpl file to read each.key and each.value

Body:
A new approach is used to activate the same thing populate APP secrets to app container
So, in here I created an AWS_SECRET_MANAGER to store the SECRETS from local.core_secrets and on the container, I will retrieve the Keys via the entrypoint

resource "aws_secretsmanager_secret" "secrets" {
  name = join("-", [local.prefix, "secret"])
  description = "secret store to store app secrets"
  kms_key_id = var.kms
  tags  = merge(local.common_tags, map("Type", "SecretManager"))
}

resource "aws_secretsmanager_secret_version" "secrets" {
  secret_id = aws_secretsmanager_secret.secrets.arn
  secret_string = jsonencode(local.core_secrets)
}


问:
Problems with AuthenticateAsync with Facebook login in ASP.NET Core
I have a problem enabling Facebook auth in my ASP.NET Core web app. I'm using ASP.NET Core Authentication but not Identity. The auth is configured in Startup like this:

services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddFacebook(options =>
    {
        options.ClientId = "clientid";
        options.ClientSecret = "secret";
        options.CallbackPath = "/signinfacebookcallback";
    });
```

<p>As shown in the code, I want to use cookie auth, but also allow people to sign in with Facebook. Once they have been successfully signed in, I want to set the auth cookie.</p>

<p>To show the challenge, I have the following action:</p>

<pre class="lang-cs prettyprint-override"><code>[HttpGet]
[Route("signinfacebook")]
public ActionResult SignInFacebook()
{
    return Challenge(FacebookDefaults.AuthenticationScheme);
}
</code>```

This redirects the user to the Facebook login screen. Once they sign in, the user is redirected to the URL specified in config:

[HttpGet]
[Route("signinfacebookcallback")]
public async Task<ActionResult> SignInFacebookCallback()
{
    var result = await HttpContext.AuthenticateAsync();
    if (!result.Succeeded) return Redirect("/login/");

    ...
}
```

When I debug the code, result.Succeeded returns false and the AuthenticationResult object doesn't contain more information on why Succeeded is false.

I verified that the app id and secret are correct.

What could be the issue here?

答:
The CallbackPath  in the OpenID Connect middleware is internal path that are used for the authentication flow of the OpenID Connect protocol. After Identity provider redirect user to that url in your application , middeware will handle token valiation ,token decode,exchange token and finally fill the user principle , and that process is fired before your controller gets involved .

Since CallbackPath is internal and will handled by OpenID Connect middleware automatically , you don't need to care about , make sure the callback is registered in facebook's allowed redirect url and let middleware handle the callback .If you want to redirect user to specific route/page after authentication , put the url to AuthenticationProperties :

```<code>if (!User.Identity.IsAuthenticated)
{
    return Challenge(new AuthenticationProperties() { RedirectUri = "/home/Privacy" } ,FacebookDefaults.AuthenticationScheme);
}
</code>```

And you should remove the callback path route (signinfacebookcallback) in your application .

UPDATE

If you want to access database and manage local user , you can use built-in events in middleware, for AddFacebook middleware , you can use OnTicketReceived to add access database , manage users and add claims to user's princple  :

```<code>.AddFacebook(options =>
{
    options.ClientId = "xxxxxxxxxxxxx";
    options.ClientSecret = "xxxxxxxxxxxxxxxxxxxx";
    options.CallbackPath = "/signinfacebookcallback";
    options.Events = new OAuthEvents
    {
        OnTicketReceived = ctx =>
        {

            //query the database to get the role
            var db = ctx.HttpContext.RequestServices.GetRequiredService<YourDbContext>();
            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});
</code>```

Body:
I have a problem enabling Facebook auth in my ASP.NET Core web app. I'm using ASP.NET Core Authentication but not Identity. The auth is configured in Startup like this:

services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddFacebook(options =>
    {
        options.ClientId = "clientid";
        options.ClientSecret = "secret";
        options.CallbackPath = "/signinfacebookcallback";
    });

As shown in the code, I want to use cookie auth, but also allow people to sign in with Facebook. Once they have been successfully signed in, I want to set the auth cookie.

To show the challenge, I have the following action:

[HttpGet]
[Route("signinfacebook")]
public ActionResult SignInFacebook()
{
    return Challenge(FacebookDefaults.AuthenticationScheme);
}

This redirects the user to the Facebook login screen. Once they sign in, the user is redirected to the URL specified in config:

[HttpGet]
[Route("signinfacebookcallback")]
public async Task<ActionResult> SignInFacebookCallback()
{
    var result = await HttpContext.AuthenticateAsync();
    if (!result.Succeeded) return Redirect("/login/");

    ...
}

When I debug the code, result.Succeeded returns false and the AuthenticationResult object doesn't contain more information on why Succeeded is false.

I verified that the app id and secret are correct.

What could be the issue here?

Body:
The CallbackPath  in the OpenID Connect middleware is internal path that are used for the authentication flow of the OpenID Connect protocol. After Identity provider redirect user to that url in your application , middeware will handle token valiation ,token decode,exchange token and finally fill the user principle , and that process is fired before your controller gets involved .

Since CallbackPath is internal and will handled by OpenID Connect middleware automatically , you don't need to care about , make sure the callback is registered in facebook's allowed redirect url and let middleware handle the callback .If you want to redirect user to specific route/page after authentication , put the url to AuthenticationProperties :

if (!User.Identity.IsAuthenticated)
{
    return Challenge(new AuthenticationProperties() { RedirectUri = "/home/Privacy" } ,FacebookDefaults.AuthenticationScheme);
}

And you should remove the callback path route (signinfacebookcallback) in your application .

UPDATE

If you want to access database and manage local user , you can use built-in events in middleware, for AddFacebook middleware , you can use OnTicketReceived to add access database , manage users and add claims to user's princple  :

.AddFacebook(options =>
{
    options.ClientId = "xxxxxxxxxxxxx";
    options.ClientSecret = "xxxxxxxxxxxxxxxxxxxx";
    options.CallbackPath = "/signinfacebookcallback";
    options.Events = new OAuthEvents
    {
        OnTicketReceived = ctx =>
        {

            //query the database to get the role
            var db = ctx.HttpContext.RequestServices.GetRequiredService<YourDbContext>();
            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});


问:
Tensorflow.keras: AlreadyExistsError
I am building a model using tensorflow. I trained my model and it worked normally. Then, I modified my code and when I try to train my model, I am getting a AlreadyExistError. I restart my Jupyter Notebook but I’m still getting the same error. I need some help please.
here is my piece of code where I build the network and train it. The problem occurs in the last line.

```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, Dropout, Dense, Flatten, LSTM, MaxPooling1D, Bidirectional
from tensorflow.keras.optimizers import Adam
from keras.callbacks import EarlyStopping, TensorBoard

model = Sequential()

model.add(Conv1D(32, kernel_size=3, activation='elu', padding='same',
                 input_shape=(vector_size, 1)))
model.add(Conv1D(32, kernel_size=3, activation='elu', padding='same'))
model.add(Conv1D(32, kernel_size=3, activation='relu', padding='same'))
model.add(MaxPooling1D(pool_size=3))

model.add(Bidirectional(LSTM(512, dropout=0.2, recurrent_dropout=0.3)))

model.add(Dense(512, activation='sigmoid'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='sigmoid'))
model.add(Dropout(0.25))
model.add(Dense(512, activation='sigmoid'))
model.add(Dropout(0.25))

model.add(Dense(2, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.0001, decay=1e-6), metrics=['accuracy'])

tensorboard = TensorBoard(log_dir='logs/', histogram_freq=0, write_graph=True, write_images=True)

model.summary()
model.fit(np.array(x_train), np.array(y_train), batch_size=batch_size, epochs=no_epochs,
         validation_data=(np.array(x_test), np.array(y_test)),  callbacks=[tensorboard, EarlyStopping(min_delta=0.0001, patience=3)])
</code>```

Train on 90000 samples, validate on 10000 samples Epoch 1/10

  500/90000 [..............................] - ETA: 2:00:49
  /anaconda3/lib/python3.7/site-packages/keras/callbacks/callbacks.py:846:
  RuntimeWarning: Early stopping conditioned on metric val_loss which
  is not available. Available metrics are:    (self.monitor,
  ','.join(list(logs.keys()))), RuntimeWarning
  --------------------------------------------------------------------------- AlreadyExistsError                        Traceback (most recent call
  last)  in
        1 model.fit(np.array(x_train), np.array(y_train), batch_size=batch_size, epochs=no_epochs,
  ----> 2          validation_data=(np.array(x_test), np.array(y_test)),  callbacks=[tensorboard, EarlyStopping(min_delta=0.0001, patience=3)])
        3 print('You can continue')

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py
  in fit(self, x, y, batch_size, epochs, verbose, callbacks,
  validation_split, validation_data, shuffle, class_weight,
  sample_weight, initial_epoch, steps_per_epoch, validation_steps,
  validation_freq, max_queue_size, workers, use_multiprocessing,
  **kwargs)
      817         max_queue_size=max_queue_size,
      818         workers=workers,
  --> 819         use_multiprocessing=use_multiprocessing)
      820
      821   def evaluate(self,

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py
  in fit(self, model, x, y, batch_size, epochs, verbose, callbacks,
  validation_split, validation_data, shuffle, class_weight,
  sample_weight, initial_epoch, steps_per_epoch, validation_steps,
  validation_freq, max_queue_size, workers, use_multiprocessing,
  **kwargs)
      340                 mode=ModeKeys.TRAIN,
      341                 training_context=training_context,
  --> 342                 total_epochs=epochs)
      343             cbks.make_logs(model, epoch_logs, training_result, ModeKeys.TRAIN)
      344

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py
  in run_one_epoch(model, iterator, execution_function, dataset_size,
  batch_size, strategy, steps_per_epoch, num_samples, mode,
  training_context, total_epochs)
      126         step=step, mode=mode, size=current_batch_size) as batch_logs:
      127       try:
  --> 128         batch_outs = execution_function(iterator)
      129       except (StopIteration, errors.OutOfRangeError):
      130         # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py
  in execution_function(input_fn)
       96     # numpy translates Tensors to values in Eager mode.
       97     return nest.map_structure(_non_none_constant_value,
  ---> 98                               distributed_function(input_fn))
       99
      100   return execution_function

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py
  in call(self, *args, **kwds)
      566         xla_context.Exit()
      567     else:
  --> 568       result = self._call(*args, **kwds)
      569
      570     if tracing_count == self._get_tracing_count():

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py
  in _call(self, *args, **kwds)
      630         # Lifting succeeded, so variables are initialized and we can run the
      631         # stateless function.
  --> 632         return self._stateless_fn(*args, **kwds)
      633     else:
      634       canon_args, canon_kwds = \

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in call(self, *args, **kwargs)    2361     with self._lock:

  2362       graph_function, args, kwargs =
  self._maybe_define_function(args, kwargs)
  -> 2363     return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access    2364     2365   @property

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in _filtered_call(self, args, kwargs)    1609          if
  isinstance(t, (ops.Tensor,    1610

  resource_variable_ops.BaseResourceVariable))),
  -> 1611         self.captured_inputs)    1612     1613   def _call_flat(self, args, captured_inputs, cancellation_manager=None):

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in _call_flat(self, args, captured_inputs, cancellation_manager)

  1690       # No tape is watching; skip to running the function.

  1691       return
  self._build_call_outputs(self._inference_function.call(
  -> 1692           ctx, args, cancellation_manager=cancellation_manager))    1693

  forward_backward = self._select_forward_and_backward_functions(

  1694         args,

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in call(self, ctx, args, cancellation_manager)
      543               inputs=args,
      544               attrs=("executor_type", executor_type, "config_proto", config),
  --> 545               ctx=ctx)
      546         else:
      547           outputs = execute.execute_with_cancellation(

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/execute.py
  in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
       65     else:
       66       message = e.message
  ---> 67     six.raise_from(core._status_to_exception(e.code, message), None)
       68   except TypeError as e:
       69     keras_symbolic_tensors = [

/anaconda3/lib/python3.7/site-packages/six.py in raise_from(value,
  from_value)

AlreadyExistsError:  Resource
  __per_step_0/sequential/bidirectional/forward_lstm/while_grad/body/_429/gradients/AddN_13/tmp_var/N10tensorflow19TemporaryVariableOp6TmpVarE
     [[{{node
  sequential/bidirectional/forward_lstm/while_grad/body/_429/gradients/AddN_13/tmp_var}}]]
  [Op:__inference_distributed_function_12060]

Function call stack: distributed_function

答:
You must have a problem on same architectures from previous run being seen while training.

This should reset the keras session :

from tensorflow.keras import backend
backend.clear_session()
```

Title: Tensorflow.keras: AlreadyExistsError

Body:
I am building a model using tensorflow. I trained my model and it worked normally. Then, I modified my code and when I try to train my model, I am getting a AlreadyExistError. I restart my Jupyter Notebook but I’m still getting the same error. I need some help please.
here is my piece of code where I build the network and train it. The problem occurs in the last line.

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, Dropout, Dense, Flatten, LSTM, MaxPooling1D, Bidirectional
from tensorflow.keras.optimizers import Adam
from keras.callbacks import EarlyStopping, TensorBoard

model = Sequential()

model.add(Conv1D(32, kernel_size=3, activation='elu', padding='same',
                 input_shape=(vector_size, 1)))
model.add(Conv1D(32, kernel_size=3, activation='elu', padding='same'))
model.add(Conv1D(32, kernel_size=3, activation='relu', padding='same'))
model.add(MaxPooling1D(pool_size=3))

model.add(Bidirectional(LSTM(512, dropout=0.2, recurrent_dropout=0.3)))

model.add(Dense(512, activation='sigmoid'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='sigmoid'))
model.add(Dropout(0.25))
model.add(Dense(512, activation='sigmoid'))
model.add(Dropout(0.25))

model.add(Dense(2, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.0001, decay=1e-6), metrics=['accuracy'])

tensorboard = TensorBoard(log_dir='logs/', histogram_freq=0, write_graph=True, write_images=True)

model.summary()
model.fit(np.array(x_train), np.array(y_train), batch_size=batch_size, epochs=no_epochs,
         validation_data=(np.array(x_test), np.array(y_test)),  callbacks=[tensorboard, EarlyStopping(min_delta=0.0001, patience=3)])

Train on 90000 samples, validate on 10000 samples Epoch 1/10

  500/90000 [..............................] - ETA: 2:00:49
  /anaconda3/lib/python3.7/site-packages/keras/callbacks/callbacks.py:846:
  RuntimeWarning: Early stopping conditioned on metric val_loss which
  is not available. Available metrics are:    (self.monitor,
  ','.join(list(logs.keys()))), RuntimeWarning
  --------------------------------------------------------------------------- AlreadyExistsError                        Traceback (most recent call
  last)  in
        1 model.fit(np.array(x_train), np.array(y_train), batch_size=batch_size, epochs=no_epochs,
  ----> 2          validation_data=(np.array(x_test), np.array(y_test)),  callbacks=[tensorboard, EarlyStopping(min_delta=0.0001, patience=3)])
        3 print('You can continue')

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py
  in fit(self, x, y, batch_size, epochs, verbose, callbacks,
  validation_split, validation_data, shuffle, class_weight,
  sample_weight, initial_epoch, steps_per_epoch, validation_steps,
  validation_freq, max_queue_size, workers, use_multiprocessing,
  **kwargs)
      817         max_queue_size=max_queue_size,
      818         workers=workers,
  --> 819         use_multiprocessing=use_multiprocessing)
      820
      821   def evaluate(self,

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py
  in fit(self, model, x, y, batch_size, epochs, verbose, callbacks,
  validation_split, validation_data, shuffle, class_weight,
  sample_weight, initial_epoch, steps_per_epoch, validation_steps,
  validation_freq, max_queue_size, workers, use_multiprocessing,
  **kwargs)
      340                 mode=ModeKeys.TRAIN,
      341                 training_context=training_context,
  --> 342                 total_epochs=epochs)
      343             cbks.make_logs(model, epoch_logs, training_result, ModeKeys.TRAIN)
      344

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py
  in run_one_epoch(model, iterator, execution_function, dataset_size,
  batch_size, strategy, steps_per_epoch, num_samples, mode,
  training_context, total_epochs)
      126         step=step, mode=mode, size=current_batch_size) as batch_logs:
      127       try:
  --> 128         batch_outs = execution_function(iterator)
      129       except (StopIteration, errors.OutOfRangeError):
      130         # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py
  in execution_function(input_fn)
       96     # numpy translates Tensors to values in Eager mode.
       97     return nest.map_structure(_non_none_constant_value,
  ---> 98                               distributed_function(input_fn))
       99
      100   return execution_function

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py
  in call(self, *args, **kwds)
      566         xla_context.Exit()
      567     else:
  --> 568       result = self._call(*args, **kwds)
      569
      570     if tracing_count == self._get_tracing_count():

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py
  in _call(self, *args, **kwds)
      630         # Lifting succeeded, so variables are initialized and we can run the
      631         # stateless function.
  --> 632         return self._stateless_fn(*args, **kwds)
      633     else:
      634       canon_args, canon_kwds = \

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in call(self, *args, **kwargs)    2361     with self._lock:

  2362       graph_function, args, kwargs =
  self._maybe_define_function(args, kwargs)
  -> 2363     return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access    2364     2365   @property

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in _filtered_call(self, args, kwargs)    1609          if
  isinstance(t, (ops.Tensor,    1610

  resource_variable_ops.BaseResourceVariable))),
  -> 1611         self.captured_inputs)    1612     1613   def _call_flat(self, args, captured_inputs, cancellation_manager=None):

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in _call_flat(self, args, captured_inputs, cancellation_manager)

  1690       # No tape is watching; skip to running the function.

  1691       return
  self._build_call_outputs(self._inference_function.call(
  -> 1692           ctx, args, cancellation_manager=cancellation_manager))    1693

  forward_backward = self._select_forward_and_backward_functions(

  1694         args,

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py
  in call(self, ctx, args, cancellation_manager)
      543               inputs=args,
      544               attrs=("executor_type", executor_type, "config_proto", config),
  --> 545               ctx=ctx)
      546         else:
      547           outputs = execute.execute_with_cancellation(

/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/eager/execute.py
  in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
       65     else:
       66       message = e.message
  ---> 67     six.raise_from(core._status_to_exception(e.code, message), None)
       68   except TypeError as e:
       69     keras_symbolic_tensors = [

/anaconda3/lib/python3.7/site-packages/six.py in raise_from(value,
  from_value)

AlreadyExistsError:  Resource
  __per_step_0/sequential/bidirectional/forward_lstm/while_grad/body/_429/gradients/AddN_13/tmp_var/N10tensorflow19TemporaryVariableOp6TmpVarE
     [[{{node
  sequential/bidirectional/forward_lstm/while_grad/body/_429/gradients/AddN_13/tmp_var}}]]
  [Op:__inference_distributed_function_12060]

Function call stack: distributed_function


问:
Update react setState with mouse Event values
I can update state for a moment then it just freezes, can I not set state so often?

The aim is to simply show the cursor position to the user.

```<code>import React, { useState } from 'react';

const Inspector: React.FC = () => {

  const [state, setState] = useState({
    offsetX: 0,
    offsetY: 0,
  });

  const canvas = document.getElementById('canvas');
  if (canvas) {
    canvas.addEventListener(
      'mousemove',
      (event) => {
        setState((prev) => ({
          ...prev,
          offsetX: event.offsetX,
          offsetY: event.offsetY,
        }));
      },
      false
    );
  }

  return (
    <div className='inspector'>
      <div className='inspector--container'>
        <div className='inspector--description'>Cursor X</div>
        <input type='text' value={state.offsetX} />
      </div>

      <div className='inspector--container'>
        <div className='inspector--description'>Cursor Y</div>
        <input type='text' value={state.offsetY} />
      </div>
    </div>
  );
};

export { Inspector };
</code>```

答:
You are doing a state update in the Render part. So while rendering you update the state, which causes another Render, which causes another and goes on recursively leading to out of memory. React will catch the same and avoid this from happening, but no more state updates will be triggered after this.

use useEffect hook to do state update and you should be fine. Also, you should clear the event listener once component unmounts.

```<code>const Inspector: React.FC = () => {

const [state, setState] = useState({
   offsetX: 0,
   offsetY: 0,
});
useEffect(()=> {
  const canvas = document.getElementById('canvas');
  if (canvas) {
    canvas.addEventListener(
    'mousemove',
    (event) => {
       setState((prev) => ({
         ...prev,
         offsetX: event.offsetX,
         offsetY: event.offsetY,
        }));
      },
    false
   );
  }
 })

 return (
   <div className='inspector'>
     <div className='inspector--container'>
       <div className='inspector--description'>Cursor X</div>
       <input type='text' value={state.offsetX} />
  </div>

  <div className='inspector--container'>
    <div className='inspector--description'>Cursor Y</div>
    <input type='text' value={state.offsetY} />
  </div>
</div>
)};

export { Inspector };
</code>```

Body:
I can update state for a moment then it just freezes, can I not set state so often?

The aim is to simply show the cursor position to the user.

import React, { useState } from 'react';

const Inspector: React.FC = () => {

  const [state, setState] = useState({
    offsetX: 0,
    offsetY: 0,
  });

  const canvas = document.getElementById('canvas');
  if (canvas) {
    canvas.addEventListener(
      'mousemove',
      (event) => {
        setState((prev) => ({
          ...prev,
          offsetX: event.offsetX,
          offsetY: event.offsetY,
        }));
      },
      false
    );
  }

  return (

Cursor X

        <input type='text' value={state.offsetX} />

Cursor Y

        <input type='text' value={state.offsetY} />

  );
};

export { Inspector };

Body:
You are doing a state update in the Render part. So while rendering you update the state, which causes another Render, which causes another and goes on recursively leading to out of memory. React will catch the same and avoid this from happening, but no more state updates will be triggered after this.

use useEffect hook to do state update and you should be fine. Also, you should clear the event listener once component unmounts.

const Inspector: React.FC = () => {

const [state, setState] = useState({
   offsetX: 0,
   offsetY: 0,
});
useEffect(()=> {
  const canvas = document.getElementById('canvas');
  if (canvas) {
    canvas.addEventListener(
    'mousemove',
    (event) => {
       setState((prev) => ({
         ...prev,
         offsetX: event.offsetX,
         offsetY: event.offsetY,
        }));
      },
    false
   );
  }
 })

 return (
   <div className='inspector'>
     <div className='inspector--container'>
       <div className='inspector--description'>Cursor X</div>
       <input type='text' value={state.offsetX} />
  </div>

  <div className='inspector--container'>
    <div className='inspector--description'>Cursor Y</div>
    <input type='text' value={state.offsetY} />
  </div>
</div>
)};

export { Inspector };


问:
Execute ajax function if mouseover for one second and cancel if mouseout
I currently have user articles that I load in from my mySQL database, which includes the title of the article and the cover image the user submitted for the article. When the user hovers over the article for one second, I want a "preview" of the article to show, which includes some of the text of the article, the topic of the article, the word count, and the number of likes on the article. I'm having trouble coming up with a function that executes this ajax request only if the user has their mouse over the article for one second (shortened for simplicity):

```<code>    $(".articles").on("mouseenter", ".article-container-divs", function() {

        setTimeout(function() {

                $.ajax({
                    url: 'includes/articles/getArticlePreview.php',
                    type: 'POST',
                    data: {articleId: articleId, idUsers: idUsers},
                    dataType: 'json',
                    success: function(data) {
                        data.forEach(function(item) {

                            var wordCount = item.article.split(' ').length;
                            var topic = item.topic.slice(0,1).toUpperCase() + item.topic.slice(1).toLowerCase();

                            thisElement.find(".previewTopic").html("<span class='previewStyle'>Topic:</span> " + topic);
                            thisElement.find(".previewWordCount").html("<span class='previewStyle'>Word Count:</span> " + wordCount);
                            thisElement.find(".previewLikes").html("<span class='previewStyle'>Likes:</span> " + item.voteCount);
                            thisElement.find(".previewArticle p").html(item.article);

                        });
                    }
                });

        }, 1000);

    });

</code>```

I tried including a setTimeout() function, which executes the AJAX call after one second. The only problem is it executes it regardless of whether the user takes their mouse off the article or not. When the user takes their mouse off the article, I want it to cancel if the user hasn't hovered for at least one second. Any suggestions?

答:
Assign setTimeout function to a variable like this

```<code>myVar = setTimeout(function(){ alert("Hello"); }, 3000);
</code>```

on mouse off event use this

```<code>clearTimeout(myVar);
</code>```

Body:
I currently have user articles that I load in from my mySQL database, which includes the title of the article and the cover image the user submitted for the article. When the user hovers over the article for one second, I want a "preview" of the article to show, which includes some of the text of the article, the topic of the article, the word count, and the number of likes on the article. I'm having trouble coming up with a function that executes this ajax request only if the user has their mouse over the article for one second (shortened for simplicity):

    $(".articles").on("mouseenter", ".article-container-divs", function() {

        setTimeout(function() {

                $.ajax({
                    url: 'includes/articles/getArticlePreview.php',
                    type: 'POST',
                    data: {articleId: articleId, idUsers: idUsers},
                    dataType: 'json',
                    success: function(data) {
                        data.forEach(function(item) {

                            var wordCount = item.article.split(' ').length;
                            var topic = item.topic.slice(0,1).toUpperCase() + item.topic.slice(1).toLowerCase();

                            thisElement.find(".previewTopic").html("Topic: " + topic);
                            thisElement.find(".previewWordCount").html("Word Count: " + wordCount);
                            thisElement.find(".previewLikes").html("Likes: " + item.voteCount);
                            thisElement.find(".previewArticle p").html(item.article);

                        });
                    }
                });

        }, 1000);

    });

I tried including a setTimeout() function, which executes the AJAX call after one second. The only problem is it executes it regardless of whether the user takes their mouse off the article or not. When the user takes their mouse off the article, I want it to cancel if the user hasn't hovered for at least one second. Any suggestions?

Body:
Assign setTimeout function to a variable like this

myVar = setTimeout(function(){ alert("Hello"); }, 3000);

on mouse off event use this

clearTimeout(myVar);


问:
SQLite.SQLiteException: 'near "s": syntax error' when updating field in sqlite
I'm currently working on UWP project and I use sqlite database.In this project I want to update field in sqlite table(classroomteam).When I entered value with apostrophe(') It gives error saying "SQLite.SQLiteException: 'near "s": syntax error'"

This is the code that I used to save updated data to the table

```<code>public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
    {
        IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
        ClassroomTeam classroomTeam = new ClassroomTeam()
        {

            TeamName = classroomTeamItem.TeamName,
            Id = classroomTeamItem.Id,

        };
        String teamName = classroomTeamItem.TeamName;
        SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
        //Task<int> a = conn.UpdateAsync(configInfo);
        await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '"  + classroomTeamItem.TeamName + "' WHERE Id = '" + classroomTeam.Id + "'");
        await conn.CloseAsync();
        IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
    }
</code>```

I tried this to solve my issue and what I did is applying new String[] {classroomTeamItem.TeamName } in the query.Then I didn't get any error but the value is stored as System.String[] not the value I entered in sqlite table.The code I tried as follows.

```<code>public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
    {
        IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
        ClassroomTeam classroomTeam = new ClassroomTeam()
        {

            TeamName = classroomTeamItem.TeamName,
            Id = classroomTeamItem.Id,

        };
        String teamName = classroomTeamItem.TeamName;
        SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
        //Task<int> a = conn.UpdateAsync(configInfo);
        await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '"  + new String[] { classroomTeam.TeamName } + "' WHERE Id = '" + classroomTeam.Id + "'");
        await conn.CloseAsync();
        IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
    }
</code>```

I would appreciate if anyone can help me to resolve this issue.

答:
The sql string about how to update field is:

```<code>string SQL_UPDATE = "UPDATE " + TABLE_NAME + " SET Value = ? WHERE Key = ?";
</code>```

So you could try to change your update string to

```<code>await db.ExecuteAsync("UPDATE classroomteam SET TeamName = " + classroomTeamItem.TeamName + " WHERE Id = " + classroomTeam.Id);
</code>```

Or you can query for the specific data is most straightforwardly done using the Table method and then update your field. For example:

```<code>private async void update(ClassroomTeamItem classroomTeamItem)
{
    var query = db.Table<ClassroomTeam>().Where(s => s.Id==classroomTeam.Id);
    var result = await query.ToListAsync();
    foreach (var s in result)
    {
        s.TeamName = classroomTeamItem.TeamName;
        await db.UpdateAsync(s);
    }
}
</code>```

Body:
I'm currently working on UWP project and I use sqlite database.In this project I want to update field in sqlite table(classroomteam).When I entered value with apostrophe(') It gives error saying "SQLite.SQLiteException: 'near "s": syntax error'"

This is the code that I used to save updated data to the table

public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
    {
        IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
        ClassroomTeam classroomTeam = new ClassroomTeam()
        {

            TeamName = classroomTeamItem.TeamName,
            Id = classroomTeamItem.Id,

        };
        String teamName = classroomTeamItem.TeamName;
        SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
        //Task<int> a = conn.UpdateAsync(configInfo);
        await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '"  + classroomTeamItem.TeamName + "' WHERE Id = '" + classroomTeam.Id + "'");
        await conn.CloseAsync();
        IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
    }

I tried this to solve my issue and what I did is applying new String[] {classroomTeamItem.TeamName } in the query.Then I didn't get any error but the value is stored as System.String[] not the value I entered in sqlite table.The code I tried as follows.

public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
    {
        IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
        ClassroomTeam classroomTeam = new ClassroomTeam()
        {

            TeamName = classroomTeamItem.TeamName,
            Id = classroomTeamItem.Id,

        };
        String teamName = classroomTeamItem.TeamName;
        SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
        //Task<int> a = conn.UpdateAsync(configInfo);
        await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '"  + new String[] { classroomTeam.TeamName } + "' WHERE Id = '" + classroomTeam.Id + "'");
        await conn.CloseAsync();
        IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
    }

I would appreciate if anyone can help me to resolve this issue.

Body:
The sql string about how to update field is:

string SQL_UPDATE = "UPDATE " + TABLE_NAME + " SET Value = ? WHERE Key = ?";

So you could try to change your update string to

await db.ExecuteAsync("UPDATE classroomteam SET TeamName = " + classroomTeamItem.TeamName + " WHERE Id = " + classroomTeam.Id);

Or you can query for the specific data is most straightforwardly done using the Table method and then update your field. For example:

private async void update(ClassroomTeamItem classroomTeamItem)
{
    var query = db.Table<ClassroomTeam>().Where(s => s.Id==classroomTeam.Id);
    var result = await query.ToListAsync();
    foreach (var s in result)
    {
        s.TeamName = classroomTeamItem.TeamName;
        await db.UpdateAsync(s);
    }
}


问:
Saving data for widget
I created RSS widget that fetches data on onUpdate and saves it in an ArrayList of article objects. Each Object class look like so:

```<code>public class Story {
    private String title;
    private String link;
    private Date pubDate;
    private String imgUrl;
    private Bitmap img;
    private String content;
}
</code>```

It holds the data and as well the image in Bitmap format (very small images). The widget works like so, on pressing right and left buttons on widget it cycles between stories from an ArrayList. I can see that the data holds about 12-24 hours in the ArrayList, and then the widget is not working anymore.

What is the best way to store data for widget like this?

What is a life expectancy for global variables in widget?

答:
When you retrieve the data (which includes the Bitmap you need), encode your Bitmap to String, then put the String inside SharedPreferences.

You will want to change your image loading approach, where you get the String from the SharedPreferences first, decode it into  Bitmap (if it is not null or empty), then put it inside your ImageView.

This is a useful source to encode/decode Bitmap to String (and vice versa):

How many ways to convert bitmap to string and vice-versa?

Note: This is quite effective under the condition where the size of the Bitmap is really small. Otherwise, you need to use something like Glide or Picasso to help you with Bitmap caching.

Title: Saving data for widget

Body:
I created RSS widget that fetches data on onUpdate and saves it in an ArrayList of article objects. Each Object class look like so:

public class Story {
    private String title;
    private String link;
    private Date pubDate;
    private String imgUrl;
    private Bitmap img;
    private String content;
}

It holds the data and as well the image in Bitmap format (very small images). The widget works like so, on pressing right and left buttons on widget it cycles between stories from an ArrayList. I can see that the data holds about 12-24 hours in the ArrayList, and then the widget is not working anymore.

What is the best way to store data for widget like this?

What is a life expectancy for global variables in widget?


问:
How do I get the values from input text fields from my custom form through the request: Django 3.0?
So, I've been trying hard, getting values from input fields in my custom form.

I have a url that corresponds to the form and that form redirects it to the same form again.

The view of the form url checks whether the request method is Post. If it is, then I declare a variable equal to request.POST, I then assigned those values to my model- item_description(). Here is the code of the views.py:

```<code>def addItem(request):
    if request.method == "POST":
        data = request.POST
        print(data.__dict__)
        item_description(item_name=data.item_name, item_number=data.item_number, item_quantity=data.item_quantity)

    else:
        HttpResponse("Something went wrong!")

    return render(request, 'ims/addItemForm.html')
</code>```

HTML form:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>IMS| Add Item</title>
</head>
<body>
    <form action="{% url 'Item-addition' %}" method="post">
        {% csrf_token %}
        <input type="text" name="item_name" placeholder="Enter Item Name">
        <input type="text" name="item_number" placeholder="Enter Item Number">
        <input type="text" name="item_quantity" placeholder="Enter Item Quantity">
        <button type="submit" name="add" value="add">Add Item</button>
    </form>

    <a href="{% url 'Items-list' %}">See items</a>

</body>
</html>
</code>```

urls.py:

```<code>from django.urls import path

from . import views

urlpatterns = [
    path('add_item', views.addItem, name='Item-addition'),
    path('items', views.itemsList, name='Items-list'),
]
</code>```

models.py:

```<code>from django.db import models

class item_description(models.Model):
    item_name = models.CharField(max_length=200)
    item_number = models.CharField(max_length=200)
    item_quantity = models.CharField(max_length=200)

    def __str__(self):
        return self.item_name
</code>```

Also, I printed out the request which is a dictionary, but it was not having any of the values. Here is the printed request dictionary: {'_encoding': 'utf-8', '_mutable': False}.

Here is the error which I am getting:

File "/home/zaid/inventoryManagement/venv/src/ims/views.py", line 13, in addItem
      item_description(item_name=data.item_name, item_number=data.item_number, item_quantity=data.item_quantity)
  AttributeError: 'QueryDict' object has no attribute 'item_name'

Please help me getting values from the input fields.

答:
Your mistakes:

```<code>item_description(item_name=data.item_name, item_number=data.item_number, item_quantity=data.item_quantity)
</code>```

data is a QueryDict, so you must access the data in it using data['item_name'] or data.get('item_name') as you would for a regular dict.

item_description(...) doesn't actually do anything. It does not save anything to the database. To save to the database, you must use item_description.objects.create(...).

Other problems with your code:

you render the form fields on your own

you extract the POST data on your own

you attempt to save to the database on your own

you are missing input validation (what if some required values are missing? e.g. what if item_name is not submitted?)

you did not provide a suitable error message as feedback to the user if he/she enters inappropriate values (e.g. a string of length 201).

Django's ModelForm is able to handle all of these issues, so please use ModelForm instead.

If models.py is this:

```<code>from django.db import models

class ItemDescription(models.Model):
    item_name = models.CharField(max_length=200)
    item_number = models.CharField(max_length=200)
    item_quantity = models.CharField(max_length=200)

    def __str__(self):
        return self.item_name
</code>```

Then, create a ModelForm in forms.py:

```<code>from django import forms
from .models import ItemDescription

class ItemDescriptioneForm(forms.ModelForm):
    class Meta:
        model = ItemDescription
        fields = ['item_name', 'item_number', 'item_quantity']
</code>```

In your views.py, use the ModelForm you just created:

```<code>from django.shortcuts import render, redirect
from .forms import ItemDescriptionForm

def addItem(request):
    if request.method == 'POST':
        form = ItemDescriptionForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('Items-list')
    else:
        form = ItemDescriptionForm()

    return render(request, 'ims/addItemForm.html', {
        'form': form,
    })
</code>```

Show the form in your template:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Item</title>
</head>
<body>
    <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" />
    </form>
</body>
</html>
</code>```

Body:
So, I've been trying hard, getting values from input fields in my custom form.

I have a url that corresponds to the form and that form redirects it to the same form again.

The view of the form url checks whether the request method is Post. If it is, then I declare a variable equal to request.POST, I then assigned those values to my model- item_description(). Here is the code of the views.py:

def addItem(request):
    if request.method == "POST":
        data = request.POST
        print(data.__dict__)
        item_description(item_name=data.item_name, item_number=data.item_number, item_quantity=data.item_quantity)

    else:
        HttpResponse("Something went wrong!")

    return render(request, 'ims/addItemForm.html')

HTML form:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>IMS| Add Item</title>

    <form action="{% url 'Item-addition' %}" method="post">
        {% csrf_token %}
        <input type="text" name="item_name" placeholder="Enter Item Name">
        <input type="text" name="item_number" placeholder="Enter Item Number">
        <input type="text" name="item_quantity" placeholder="Enter Item Quantity">
        <button type="submit" name="add" value="add">Add Item</button>
    </form>

    See items

urls.py:

from django.urls import path

from . import views

urlpatterns = [
    path('add_item', views.addItem, name='Item-addition'),
    path('items', views.itemsList, name='Items-list'),
]

models.py:

from django.db import models

class item_description(models.Model):
    item_name = models.CharField(max_length=200)
    item_number = models.CharField(max_length=200)
    item_quantity = models.CharField(max_length=200)

    def __str__(self):
        return self.item_name

Also, I printed out the request which is a dictionary, but it was not having any of the values. Here is the printed request dictionary: {'_encoding': 'utf-8', '_mutable': False}.

Here is the error which I am getting:

File "/home/zaid/inventoryManagement/venv/src/ims/views.py", line 13, in addItem
      item_description(item_name=data.item_name, item_number=data.item_number, item_quantity=data.item_quantity)
  AttributeError: 'QueryDict' object has no attribute 'item_name'

Please help me getting values from the input fields.

Body:
Your mistakes:

item_description(item_name=data.item_name, item_number=data.item_number, item_quantity=data.item_quantity)

data is a QueryDict, so you must access the data in it using data['item_name'] or data.get('item_name') as you would for a regular dict.

item_description(...) doesn't actually do anything. It does not save anything to the database. To save to the database, you must use item_description.objects.create(...).

Other problems with your code:

you render the form fields on your own

you extract the POST data on your own

you attempt to save to the database on your own

you are missing input validation (what if some required values are missing? e.g. what if item_name is not submitted?)

you did not provide a suitable error message as feedback to the user if he/she enters inappropriate values (e.g. a string of length 201).

Django's ModelForm is able to handle all of these issues, so please use ModelForm instead.

If models.py is this:

from django.db import models

class ItemDescription(models.Model):
    item_name = models.CharField(max_length=200)
    item_number = models.CharField(max_length=200)
    item_quantity = models.CharField(max_length=200)

    def __str__(self):
        return self.item_name

Then, create a ModelForm in forms.py:

from django import forms
from .models import ItemDescription

class ItemDescriptioneForm(forms.ModelForm):
    class Meta:
        model = ItemDescription
        fields = ['item_name', 'item_number', 'item_quantity']

In your views.py, use the ModelForm you just created:

from django.shortcuts import render, redirect
from .forms import ItemDescriptionForm

def addItem(request):
    if request.method == 'POST':
        form = ItemDescriptionForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('Items-list')
    else:
        form = ItemDescriptionForm()

    return render(request, 'ims/addItemForm.html', {
        'form': form,
    })

Show the form in your template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Item</title>
</head>
<body>
    <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" />
    </form>
</body>
</html>


问:
htaccess make urls respond from /index.json as well as /
I have a Wordpress site that responds with JSON to every request, i.e. the following pages:

```<code>/
/about
/about/team
</code>```

All respond with json. The htaccess file looks like this:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

I'd like to keep what I have now, but also respond with the same data when index.json is added to the url:

```<code>/index.json
/about/index.json
/about/team/index.json
</code>```

How can I update my htaccess to also respond to these urls in the same way?

答:
Based on what @MrWhite said in comments (gonna quote here, because comments might get removed later),

However, the "problem" here is WordPress. WP routes URLs based on the REQUEST_URI, which does not change during a URL rewrite. So you really need to implement this within WordPress itself.

you could probably just “reset” the value of $_SERVER['REQUEST_URI'] in PHP, if it ends with /index.json. (Relatively easy string manipulation / regex job.)

The remaining problem would just be to figure out a “correct” way to do this – I guess trying to do this via any hooks from inside the theme’s functions.php or a plugin, might be too late. You can give that a try anyway, if you like - the order of hooks as described here is what I would go by, https://wordpress.stackexchange.com/a/162869

The init hook is pretty far down, even after the current user was determined, etc. – but maybe plugins_loaded or setup_theme might be suitable for stuff like this.

If that doesn’t work, still some possible alternatives:

If you can influence the PHP configuration, auto_prepend_file would allow you to specify a script that gets automatically run before anything else PHP does - so you could fix the value before the index.php code even executes.

You could write your own little “wrapper” file, say index2.php, that fixes the value, and then simply includes the original index.php afterwards. Only problem with that - you probably wouldn’t want to change the default WP rewriting between the BEGIN and END WORDPRESS comments in the .htaccess, because WP will overwrite that part, when you flush your permalink settings. But an additional internal rewrite of index.php to index2.php after, could probably solve that.

If mod_proxy is available, you could proxy the request internally. Probably not the best in terms of performance, but at least an alternative to an external rewrite, if you wanted to avoid that at all cost.

Body:
I have a Wordpress site that responds with JSON to every request, i.e. the following pages:

/
/about
/about/team

All respond with json. The htaccess file looks like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I'd like to keep what I have now, but also respond with the same data when index.json is added to the url:

/index.json
/about/index.json
/about/team/index.json

How can I update my htaccess to also respond to these urls in the same way?


Title: File into table awk

Body:
I am trying to make a table by reading the file.

Here is an example of the code I am trying to compile:

FHEAD|1|PRMPC|20200216020532|1037|S
TMBPE|2|MOD
    TPDTL|3|72810|1995019|11049-|11049-|Dcto 20|0|5226468|20200216000001|20200222235959|2||1||||
        TPGRP|4|5403307
        TGLIST|5|5031472|1|||
        TLITM|6|101055590
            TPDSC|7|0|||-20||2|1|
        TPGRP|8|5403308
        TGLIST|9|5031473|0|||
    TPDTL|13|10728|1995021|11049-|11049-|Dcto 30|0|5226469|20200216000001|20200222235959|2||1||||
        TPGRP|14|5403310
        TGLIST|15|5031475|1|||
            TLITM|16|210000041
            TLITM|17|101004522
                TPDSC|113|0|||-30||2|1|
        TPGRP|114|5403309
        TGLIST|115|5031474|0|||
            TLITM|116|101047933
            TLITM|117|101004681
            TLITM|118|101028161
                TPDSC|119|0|||-25||2|1|
TPISR|214|101004225|2350|EA|20200216000000|COP|
TTAIL|1135
FTAIL|1136|1134

I tried to develop the code but it returns all tags in one line

for filename in "$input"*.dat;
    do
    echo "$filename">>"$files"
    a=`awk -F'|' '$1=="FHEAD" && $5!=""{print $5}' "$filename"`
    b=`awk -F'|' '$1=="TPDTL" && $3!=""{print $3}' "$filename"`
    c=`awk -F'|' '$1=="TPDTL" && $4!=""{print $4}' "$filename"`
    d=`awk -F'|' '$1=="TPDTL" && $10!=""{print $10}' "$filename"`
    e=`awk -F'|' '$1=="TPDTL" && $11!=""{print $11}' "$filename"`
    f=`awk -F'|' '$1=="TPDSC" && $6!=""{print $6}' "$filename"`
    g=`awk -F'|' '$1=="TLITM" && $3!=""{print $3}' "$filename"`

For exemple:

echo -e ${d}

20200216000001 20200216000001

I wanted something like the picture.

Someone can help me?

Thanks in advance

Body:
Assuming:

The frequency of appearance of the keywords like FHEAD, TPDTL, etc
are not uniform. Use the latest one if needed.

The number of rows should be equal to the count of TLITM.

The table should be updated when TPDSC appears.

then would you please try the following:

awk 'BEGIN {FS = "|"; OFS = ","}
    $1 ~ /FHEAD/ {a = $5}
    $1 ~ /TPDTL/ {b = $3; c = $4; d = $10; e = $11}
    $1 ~ /TLITM/ {f[++tlitm_count] = $3}
    $1 ~ /TPDSC/ {g = $6;
        for (i=1; i<=tlitm_count; i++) {
            print a, b, c, d, e, f[i], g
        }
        tlitm_count = 0;
    }
' *.dat

Output:

1037,72810,1995019,20200216000001,20200222235959,101055590,-20
1037,10728,1995021,20200216000001,20200222235959,210000041,-30
1037,10728,1995021,20200216000001,20200222235959,101004522,-30
1037,10728,1995021,20200216000001,20200222235959,101047933,-25
1037,10728,1995021,20200216000001,20200222235959,101004681,-25
1037,10728,1995021,20200216000001,20200222235959,101028161,-25

If you want the output delimiter to be a whitespace, please modify the value of OFS.