问:
Javascript Uncaught TypeError: AccountID is not a function
I am trying to call the AccountID function from the test1 function and store the results in a variable however when i run this i get an uncaught type error that says AccoutID is not a function.

I can only get it to work if i nest the AccoutID function inside of Test1 which is not ideal.

could it be something related to scope?

```//This script is used to Generate A PDF for the HIN TO HIN email template generator tool

// This section decalres all variables to be parsed Back

var username = "";
var password = "";
var SessionID = "";
var IuserID = "";
var AccountID = "";
var AcctDetails = "";

// this function is used to generate a pop up and log you into the platform then capture the session id and user id

function PlatformLogin() {

    // captures the username and password from the popup form
    username = $('#username').val();
    password = $('#psw').val();
    // HTTP request to login to the platform using form data
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://autobots.avanteos.com.au/py/Login.py?Username=' + username + '&Password=' + password, false)
    xhr.send()
    // fetches the response from login as JSon then assigns user id and session id variable values
    var logindetails = JSON.parse(xhr.responseText);
    var SessionID = logindetails["@sSessionId"];
    var IuserID = logindetails["@iUserId"];
    //closes the pop up window
    document.getElementById("loginPopup").style.display = "none";

}

function AccountDetails(AcctID) {
    // This is a HTTP request to fetch the account details
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://autobots.avanteos.com.au/py/CGiscript.py?SessionId=' + SessionID + '&UserId=' + IuserID + '&AccountID=' + AcctID, false)
    //xhr.open('GET', 'http://autobots.avanteos.com.au/py/CGiscript.py?SessionId=48B18C24724B488B&UserId=1107385&AccountID=3672253', false)
    xhr.send()

    firsttry = xhr.response
    logincheck = firsttry.includes('user not logged in')

    if (logincheck = true) {

        return "Not logged in"

    } else {

        return JSON.parse(firsttry)

    }

}

function test1() {

    // First part of the request fetches the account id for the from account using the from account number

    var Acctidd = "8308184";

    var FromacctID = AccountID("8308184");

    if (FromAcctID = "Not logged in") {

        PlatformLogin();
        var FromAcctID = AccountID(Acctidd);
    }

    // This part fetches the account id for the TO account using the account number

    var ToAcctID = AccountID(Acctidd);

    if (ToAcctID = "Not logged in") {

        PlatformLogin();
        var ToAcctID = AccountID(Acctidd);
    }

    // This part fetches the Account details for the From Acccount

    var FromAcctDetails = AccountDetails(FromAcctID);

    if (FromAcctDetails = "Not logged in") {
        PlatformLogin();
        var FromAcctDetails = AccountDetails(FromAcctID);
    }

    //from data variables are set here
    var fromacctname = FromAcctDetails["@AccountName"]
    var fromacctnumber = FromAcctDetails["@AccountNumber"]
    var fromacctHIN = FromAcctDetails["@HINType"]
    console.log(fromacctname)
    console.log(fromacctnumber)

    // This part fetches the To Account details

    var ToAcctDetails = AccountDetails(ToAcctID);

    if (ToAcctDetails = "Not logged in") {
        PlatformLogin();
        var ToAcctDetails = AccountDetails(ToAcctID);
    }

    //To data variables are set here
    var Toacctname = ToAcctDetails["@AccountName"]
    var Toacctnumber = ToAcctDetails["@AccountNumber"]
    var ToacctHIN = ToAcctDetails["@HINType"]
    console.log(Toacctname)
    console.log(ToacctHIN)

}

function AccountID(AccountNumber) {

    // This HTTP request retrieves the account ID based on an account number
    var xhr = new XMLHttpRequest();
    //xhr.open('GET', 'http://autobots.avanteos.com.au/py/AccountID.py?SessionId=48B18C24724B488B&UserId=1107385&AccountNumber=8308184', false)
    xhr.open('GET', 'http://autobots.avanteos.com.au/py/CGiscript.py?SessionId=' + SessionID + '&UserId=' + IuserID + '&AccountNumber=' + AccountNumber, false)
    xhr.send
    //This code will check if you are logged in
    Acctidquery = xhr.response
    logincheck = Acctidquery.includes('user not logged in')

    if (logincheck = true) {

        return "Not logged in"

    } else {

        return Acctidquery

    }

}

// This function generates the PDF

function PDFGENfunc() {

    // First part of the request fetches the account id for the from account using the from account number

    var FromAcctID = AccountID("8308184");

    if (FromAcctID = "Not logged in") {

        PlatformLogin();
        var FromAcctID = AccountID("8308184");
    }

    // This part fetches the account id for the TO account using the account number

    var ToAcctID = AccountID("8308184");

    if (ToAcctID = "Not logged in") {

        PlatformLogin();
        var ToAcctID = AccountID("8308184");
    }

    // This part fetches the Account details for the From Acccount

    var FromAcctDetails = AccountDetails(FromAcctID);

    if (FromAcctDetails = "Not logged in") {
        PlatformLogin();
        var FromAcctDetails = AccountDetails(FromAcctID);
    }

    //from data variables are set here
    var fromacctname = FromAcctDetails["@AccountName"]
    var fromacctnumber = FromAcctDetails["@AccountNumber"]
    var fromacctHIN = FromAcctDetails["@HINType"]

    // This part fetches the To Account details

    var ToAcctDetails = AccountDetails(ToAcctID);

    if (ToAcctDetails = "Not logged in") {
        PlatformLogin();
        var ToAcctDetails = AccountDetails(ToAcctID);
    }

    //To data variables are set here
    var fromacctname = ToAcctDetails["@AccountName"]
    var fromacctnumber = ToAcctDetails["@AccountNumber"]
    var fromacctHIN = ToAcctDetails["@HINType"]

    // initialises jsPDF

    var doc = new jsPDF('p', 'mm', 'a4')

    // holds the text content

    var reportTitle = "Colonial First State Custom Solutions Level 1 105 Camberwell Road Hawthorn East VIC 3123 PO Box 1012 Camberwell VIC 3124 Telephone (03)9805111     Facsimile (03)98134182 "

    // this variable allows me to wrap report tittle to 90

    var splitTitle = doc.splitTextToSize(reportTitle, 90);

    // this is the image data for the cfs logo in URI data form

    var imgData = 'data:image/jpeg;base64,[encoded data, 14040 characters]'

    // set the font size here
    doc.setFontSize(9);
    doc.setFont('Calibri');

    // actually displays split title

    doc.text(150, 20, splitTitle)

    //displays the image
    doc.addImage(imgData, 'JPEG', 15, 20, 30, 12);

    // initial text

    var inittext = '
[Date]
\

\

Custom solutions Stock Transfer:
\

Dear Core,
\

Please Accept our authority for the transfer of the below listed securities to perform and internal transfer.
'

    doc.fromHTML(inittext, 15, 40)

    //displays the date

    doc.autoTable({
        startY: 80,
        head: [
            [{ content: 'From Account', colSpan: 1, rowSpan: 1, styles: { halign: 'center', fillColor: [107, 107, 107] } }],
        ],
    })

    doc.autoTable({
        startY: 90,
        head: [['Acct Name', 'Acct #', 'HIN', 'Sponsor A/C']],
        body: [

            ['John smith', '123456', '123456', '123456', '123456']

        ],
    })

    doc.autoTable({
        startY: 110,
        head: [
            [{ content: 'To Account', colSpan: 1, rowSpan: 1, styles: { halign: 'center', fillColor: [107, 107, 107] } }],
        ],
    })

    doc.autoTable({
        startY: 120,
        head: [['Acct Name', 'Acct #', 'HIN', 'Sponsor A/C']],
        body: [

            ['John smith', '123456', '123456', '123456', '123456']

        ],
    })

    doc.autoTable({
        startY: 140,
        head: [
            [{ content: 'To Account', colSpan: 1, rowSpan: 1, styles: { halign: 'center', fillColor: [107, 107, 107] } }],
        ],
    })

    doc.autoTable({
        startY: 150,
        styles: { theme: 'striped' },
        head: [['Stock', 'QTY']],
        body: [

            ['John smith', '123456']

        ],
    })

    // saves the document
    doc.save("Cows1.pdf");

}

```

答: Resolved - My issue was that at the beginning of my code i set the name of my function as a variable equals to blank , i should not have declared it as a variable.</p>

Body:
I am trying to call the AccountID function from the test1 function and store the results in a variable however when i run this i get an uncaught type error that says AccoutID is not a function.

I can only get it to work if i nest the AccoutID function inside of Test1 which is not ideal.

could it be something related to scope?

//This script is used to Generate A PDF for the HIN TO HIN email template generator tool

// This section decalres all variables to be parsed Back

var username = "";
var password = "";
var SessionID = "";
var IuserID = "";
var AccountID = "";
var AcctDetails = "";

// this function is used to generate a pop up and log you into the platform then capture the session id and user id

function PlatformLogin() {

    // captures the username and password from the popup form
    username = $('#username').val();
    password = $('#psw').val();
    // HTTP request to login to the platform using form data
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://autobots.avanteos.com.au/py/Login.py?Username=' + username + '&Password=' + password, false)
    xhr.send()
    // fetches the response from login as JSon then assigns user id and session id variable values
    var logindetails = JSON.parse(xhr.responseText);
    var SessionID = logindetails["@sSessionId"];
    var IuserID = logindetails["@iUserId"];
    //closes the pop up window
    document.getElementById("loginPopup").style.display = "none";

}

function AccountDetails(AcctID) {
    // This is a HTTP request to fetch the account details
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://autobots.avanteos.com.au/py/CGiscript.py?SessionId=' + SessionID + '&UserId=' + IuserID + '&AccountID=' + AcctID, false)
    //xhr.open('GET', 'http://autobots.avanteos.com.au/py/CGiscript.py?SessionId=48B18C24724B488B&UserId=1107385&AccountID=3672253', false)
    xhr.send()

    firsttry = xhr.response
    logincheck = firsttry.includes('user not logged in')

    if (logincheck = true) {

        return "Not logged in"

    } else {

        return JSON.parse(firsttry)

    }

}

function test1() {

    // First part of the request fetches the account id for the from account using the from account number

    var Acctidd = "8308184";

    var FromacctID = AccountID("8308184");

    if (FromAcctID = "Not logged in") {

        PlatformLogin();
        var FromAcctID = AccountID(Acctidd);
    }

    // This part fetches the account id for the TO account using the account number

    var ToAcctID = AccountID(Acctidd);

    if (ToAcctID = "Not logged in") {

        PlatformLogin();
        var ToAcctID = AccountID(Acctidd);
    }

    // This part fetches the Account details for the From Acccount

    var FromAcctDetails = AccountDetails(FromAcctID);

    if (FromAcctDetails = "Not logged in") {
        PlatformLogin();
        var FromAcctDetails = AccountDetails(FromAcctID);
    }

    //from data variables are set here
    var fromacctname = FromAcctDetails["@AccountName"]
    var fromacctnumber = FromAcctDetails["@AccountNumber"]
    var fromacctHIN = FromAcctDetails["@HINType"]
    console.log(fromacctname)
    console.log(fromacctnumber)

    // This part fetches the To Account details

    var ToAcctDetails = AccountDetails(ToAcctID);

    if (ToAcctDetails = "Not logged in") {
        PlatformLogin();
        var ToAcctDetails = AccountDetails(ToAcctID);
    }

    //To data variables are set here
    var Toacctname = ToAcctDetails["@AccountName"]
    var Toacctnumber = ToAcctDetails["@AccountNumber"]
    var ToacctHIN = ToAcctDetails["@HINType"]
    console.log(Toacctname)
    console.log(ToacctHIN)

}

function AccountID(AccountNumber) {

    // This HTTP request retrieves the account ID based on an account number
    var xhr = new XMLHttpRequest();
    //xhr.open('GET', 'http://autobots.avanteos.com.au/py/AccountID.py?SessionId=48B18C24724B488B&UserId=1107385&AccountNumber=8308184', false)
    xhr.open('GET', 'http://autobots.avanteos.com.au/py/CGiscript.py?SessionId=' + SessionID + '&UserId=' + IuserID + '&AccountNumber=' + AccountNumber, false)
    xhr.send
    //This code will check if you are logged in
    Acctidquery = xhr.response
    logincheck = Acctidquery.includes('user not logged in')

    if (logincheck = true) {

        return "Not logged in"

    } else {

        return Acctidquery

    }

}

// This function generates the PDF

function PDFGENfunc() {

    // First part of the request fetches the account id for the from account using the from account number

    var FromAcctID = AccountID("8308184");

    if (FromAcctID = "Not logged in") {

        PlatformLogin();
        var FromAcctID = AccountID("8308184");
    }

    // This part fetches the account id for the TO account using the account number

    var ToAcctID = AccountID("8308184");

    if (ToAcctID = "Not logged in") {

        PlatformLogin();
        var ToAcctID = AccountID("8308184");
    }

    // This part fetches the Account details for the From Acccount

    var FromAcctDetails = AccountDetails(FromAcctID);

    if (FromAcctDetails = "Not logged in") {
        PlatformLogin();
        var FromAcctDetails = AccountDetails(FromAcctID);
    }

    //from data variables are set here
    var fromacctname = FromAcctDetails["@AccountName"]
    var fromacctnumber = FromAcctDetails["@AccountNumber"]
    var fromacctHIN = FromAcctDetails["@HINType"]

    // This part fetches the To Account details

    var ToAcctDetails = AccountDetails(ToAcctID);

    if (ToAcctDetails = "Not logged in") {
        PlatformLogin();
        var ToAcctDetails = AccountDetails(ToAcctID);
    }

    //To data variables are set here
    var fromacctname = ToAcctDetails["@AccountName"]
    var fromacctnumber = ToAcctDetails["@AccountNumber"]
    var fromacctHIN = ToAcctDetails["@HINType"]

    // initialises jsPDF

    var doc = new jsPDF('p', 'mm', 'a4')

    // holds the text content

    var reportTitle = "Colonial First State Custom Solutions Level 1 105 Camberwell Road Hawthorn East VIC 3123 PO Box 1012 Camberwell VIC 3124 Telephone (03)9805111     Facsimile (03)98134182 "

    // this variable allows me to wrap report tittle to 90

    var splitTitle = doc.splitTextToSize(reportTitle, 90);

    // this is the image data for the cfs logo in URI data form

    var imgData = 'data:image/jpeg;base64,[encoded data, 14040 characters]'

    // set the font size here
    doc.setFontSize(9);
    doc.setFont('Calibri');

    // actually displays split title

    doc.text(150, 20, splitTitle)

    //displays the image
    doc.addImage(imgData, 'JPEG', 15, 20, 30, 12);

    // initial text

    var inittext = '
[Date]
\

\

Custom solutions Stock Transfer:
\

Dear Core,
\

Please Accept our authority for the transfer of the below listed securities to perform and internal transfer.
'

    doc.fromHTML(inittext, 15, 40)

    //displays the date

    doc.autoTable({
        startY: 80,
        head: [
            [{ content: 'From Account', colSpan: 1, rowSpan: 1, styles: { halign: 'center', fillColor: [107, 107, 107] } }],
        ],
    })

    doc.autoTable({
        startY: 90,
        head: [['Acct Name', 'Acct #', 'HIN', 'Sponsor A/C']],
        body: [

            ['John smith', '123456', '123456', '123456', '123456']

        ],
    })

    doc.autoTable({
        startY: 110,
        head: [
            [{ content: 'To Account', colSpan: 1, rowSpan: 1, styles: { halign: 'center', fillColor: [107, 107, 107] } }],
        ],
    })

    doc.autoTable({
        startY: 120,
        head: [['Acct Name', 'Acct #', 'HIN', 'Sponsor A/C']],
        body: [

            ['John smith', '123456', '123456', '123456', '123456']

        ],
    })

    doc.autoTable({
        startY: 140,
        head: [
            [{ content: 'To Account', colSpan: 1, rowSpan: 1, styles: { halign: 'center', fillColor: [107, 107, 107] } }],
        ],
    })

    doc.autoTable({
        startY: 150,
        styles: { theme: 'striped' },
        head: [['Stock', 'QTY']],
        body: [

            ['John smith', '123456']

        ],
    })

    // saves the document
    doc.save("Cows1.pdf");

}


来源: stackexchange

问:
How to get the duration of an audio file in iOS?
```<code>NSDictionary* fileAttributes =
    [[NSFileManager defaultManager] attributesOfItemAtPath:filename
                                                     error:nil]
</code>```

From the file attribute keys, you can get the date, size, etc. But how do you get the duration?

答:
I record a linear PCM file (.pcm) through AVAudioRecorder. I get the duration with the help of Farhad Malekpour. Maybe this can help you :
iPhone: get duration of an audio file

```<code>NSURL *fileUrl = [NSURL fileURLWithPath:yourFilePath];
AudioFileID fileID;
OSStatus result = AudioFileOpenURL((__bridge CFURLRef)fileUrl,kAudioFileReadPermission, 0, &fileID);
Float64 duration = 0; //seconds. the duration of the audio.
UInt32 ioDataSize = sizeof(Float64);

result = AudioFileGetProperty(fileID, kAudioFilePropertyEstimatedDuration,
&ioDataSize, &duration);
AudioFileClose(fileID);
if(0 == result) {
   //success
}
else {
  switch (result) {
    case kAudioFileUnspecifiedError:{
        //
    } break;
        // other cases...
    default:
        break;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
NSDictionary* fileAttributes =
    [[NSFileManager defaultManager] attributesOfItemAtPath:filename
                                                     error:nil]

From the file attribute keys, you can get the date, size, etc. But how do you get the duration?

Body:
I record a linear PCM file (.pcm) through AVAudioRecorder. I get the duration with the help of Farhad Malekpour. Maybe this can help you :
iPhone: get duration of an audio file

NSURL *fileUrl = [NSURL fileURLWithPath:yourFilePath];
AudioFileID fileID;
OSStatus result = AudioFileOpenURL((__bridge CFURLRef)fileUrl,kAudioFileReadPermission, 0, &fileID);
Float64 duration = 0; //seconds. the duration of the audio.
UInt32 ioDataSize = sizeof(Float64);

result = AudioFileGetProperty(fileID, kAudioFilePropertyEstimatedDuration,
&ioDataSize, &duration);
AudioFileClose(fileID);
if(0 == result) {
   //success
}
else {
  switch (result) {
    case kAudioFileUnspecifiedError:{
        //
    } break;
        // other cases...
    default:
        break;
  }
}

ContentLicense: CC BY-SA 4.0


问:
Using array for `ls --ignore`
I'm working on a bash script for my server backup.
Based on my web root(/home), I wanna filter my web directories excludes something generals.
I found --ignore option for it. Here's my code for returng what I want.

```<code>DIR_LIST=`ls -al $WWW_ROOT --ignore={.,..,ubuntu,test} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;
</code>```

But when I tried with array, it's not worked as well.

```<code>EXCLUDED=(. .. test ubuntu)
STR=$(IFS=,; echo "${EXCLUDED[*]}")
DIR_LIST=`ls -al $WWW_ROOT --ignore={$STR} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;
</code>```

echo $STR works well but echo $DIR_LIST is not.
I think brace is not worked properly.

How can I do this as I expected?

答:
Here is one way of doing it without using ls and to make matters worst you're using the -al flag.

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

shopt -s nullglob extglob

files=(/path/to/www/directory/!(ubuntu|test)/)

declare -p files
</code>```

That will show you the files in the array assignment.

If you want to loop through the files and remove the pathname from the file name without using any external commands from the shell.

```<code>for f in "${files[@]}"; do echo "${f##*/}"; done
</code>```

Which has the same result when using basename

```<code>for f in "${files[@]}"; do var=$(basename "$f"); echo "$var"; done
</code>```

Or just do it in the array

```<code>printf '%s\n' "${files[@]##*/}"
</code>```

The "${files##*/}" is a form of P.E. parameter expansion.

There is an online bash manual where you can look up P.E. see Parameter Expansion

Or the man page. see  PAGER='less +/^[[:space:]]*parameter\ expansion' man bash

Look up nullglob and extglob see shell globbing

The array named files now has the data/files that you're interested in.

By default the dotfiles is not listed so you don't have to worry about it, unless dotglob is enabled which is off by default.

Title: Using array for `ls --ignore`

Body:
I'm working on a bash script for my server backup.
Based on my web root(/home), I wanna filter my web directories excludes something generals.
I found --ignore option for it. Here's my code for returng what I want.

DIR_LIST=`ls -al $WWW_ROOT --ignore={.,..,ubuntu,test} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;

But when I tried with array, it's not worked as well.

EXCLUDED=(. .. test ubuntu)
STR=$(IFS=,; echo "${EXCLUDED[*]}")
DIR_LIST=`ls -al $WWW_ROOT --ignore={$STR} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;

echo $STR works well but echo $DIR_LIST is not.
I think brace is not worked properly.

How can I do this as I expected?

Body:
Here is one way of doing it without using ls and to make matters worst you're using the -al flag.

#!/usr/bin/env bash

shopt -s nullglob extglob

files=(/path/to/www/directory/!(ubuntu|test)/)

declare -p files

That will show you the files in the array assignment.

If you want to loop through the files and remove the pathname from the file name without using any external commands from the shell.

for f in "${files[@]}"; do echo "${f##*/}"; done

Which has the same result when using basename

for f in "${files[@]}"; do var=$(basename "$f"); echo "$var"; done

Or just do it in the array

printf '%s\n' "${files[@]##*/}"

The "${files##*/}" is a form of P.E. parameter expansion.

There is an online bash manual where you can look up P.E. see Parameter Expansion

Or the man page. see  PAGER='less +/^[[:space:]]*parameter\ expansion' man bash

Look up nullglob and extglob see shell globbing

The array named files now has the data/files that you're interested in.

By default the dotfiles is not listed so you don't have to worry about it, unless dotglob is enabled which is off by default.


问:
Changing search text with Javascript Buttons
I know this seems simple and obsolete, but I can't find a proper example of this anywhere.

My goal is to edit my search bar by adding text to the beginning of whatever the user inputs with javascript.

For example, a user inputs "Pie", there are three buttons underneath the search bar, the user can select "Apple" "Banana" or "Squash". When clicking on any of the buttons it should add the text to the beginning of pie, e.g. clicking on "Banana" Results in modifying the search bar with "Banana Pie".

I'm just trying to learn how to do this in JS and I can't find a proper example of this anywhere if someone can point me to the proper place to look i would greatly appreciate it.

答:
If you had an input element:

```<code><input type="text" id="userInput">
</code>```

Then you can get the value of it with:

```<code>let userInput = document.getElementById("userInput").value;
</code>```

In your event handler for the buttons, then you could just do string concatenation:

```<code>// In your button click event
let outputString = buttonValue + " " + userInput;
</code>```

Body:
If you had an input element:

<input type="text" id="userInput">

Then you can get the value of it with:

let userInput = document.getElementById("userInput").value;

In your event handler for the buttons, then you could just do string concatenation:

// In your button click event
let outputString = buttonValue + " " + userInput;


问:
Python WEBDRIVER - I can't select an element from a listbox and submit my answer
I would like to select an element from a listbox and then submit my answer so that my browser opens a new page with the elements i chose. I was able to select the argument but when I press the button "Search", it doesnt take into account my selections. Here are the html of the listbox :

```<code><select size="10" name="lbSources" id="lbSources" class="form" onkeypress="return OnKeyPressEnterSubmit('btnSearch', event);" style="width:250px;">
    <option value="UK_P">01 net</option>
    <option value="UKA_P">01 net - Hors-série</option>
    <option value="QAA_P">2 Rives, Les (Sorel-Tracy, QC)</option>
    <option value="WV_P">24 Heures (Suisse)</option>
    <option value="FJ_P">Abitibi Express Rouyn-Noranda/Abitibi-Ouest</option>
   (...)
</code>```

and the html of the search button :

```<code> <input type="image" name="btnSearch" id="btnSearch" src="/images/interface/buttons/SearchFR_on.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnSearch", "", true, "", "", false, false))">
</code>```

And here is how my Python code looks like:

```<code>selectBox = browser.find_element_by_name("lbSources")
selectBox.send_keys("UK_P")
browser.find_element_by_name("btnSearch").click()
</code>```

So it first selects a box but then... Nothing..

答:
You can use the direct xpath to select the list option and then trigger onkeypress event on the list box.

```<code>item = driver.find_element_by_xpath("//select[@id='lbSources']/option[@value='UK_P']")
# click on the list item
item.click()
# now trigger onKeyPress event
list_box = driver.find_element_by_xpath("//select[@id='lbSources']")
driver.execute_script("arguments[0].dispatchEvent(new Event('onkeypress', {'bubbles': true,'cancelable': true}));",list_box)
</code>```

Body:
I would like to select an element from a listbox and then submit my answer so that my browser opens a new page with the elements i chose. I was able to select the argument but when I press the button "Search", it doesnt take into account my selections. Here are the html of the listbox :

<select size="10" name="lbSources" id="lbSources" class="form" onkeypress="return OnKeyPressEnterSubmit('btnSearch', event);" style="width:250px;">
    <option value="UK_P">01 net</option>
    <option value="UKA_P">01 net - Hors-série</option>
    <option value="QAA_P">2 Rives, Les (Sorel-Tracy, QC)</option>
    <option value="WV_P">24 Heures (Suisse)</option>
    <option value="FJ_P">Abitibi Express Rouyn-Noranda/Abitibi-Ouest</option>
   (...)

and the html of the search button :

 <input type="image" name="btnSearch" id="btnSearch" src="/images/interface/buttons/SearchFR_on.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnSearch", "", true, "", "", false, false))">

And here is how my Python code looks like:

selectBox = browser.find_element_by_name("lbSources")
selectBox.send_keys("UK_P")
browser.find_element_by_name("btnSearch").click()

So it first selects a box but then... Nothing..

Body:
You can use the direct xpath to select the list option and then trigger onkeypress event on the list box.

item = driver.find_element_by_xpath("//select[@id='lbSources']/option[@value='UK_P']")
# click on the list item
item.click()
# now trigger onKeyPress event
list_box = driver.find_element_by_xpath("//select[@id='lbSources']")
driver.execute_script("arguments[0].dispatchEvent(new Event('onkeypress', {'bubbles': true,'cancelable': true}));",list_box)


问:
Get Prior Row of Dataframe in For Loop Python
This is what I believe to be a simple logic problem, but I have been working at this for a while and haven't figured it out, so hopefully someone can find the easy solution that I have been missing. I would like to be able to get the prior part of a dataframe using the following code, and have settle for the (row-1) solve in the fourth row, but that obviously did not work.

```<code>for row in players_at_start_of_period.iterrows():
    if(row[1]['PERIOD']):
        continue
    elif(row[1]['PERIOD'] - 2) > (row-1)[1]['PERIOD']:
        sub_map.update = {row[1]['TEAM_ID_1']: split_row(row[1]['TEAM_1_PLAYERS']), row[1]['TEAM_ID_2']: split_row(row[1]['TEAM_2_PLAYERS'])}
    else:
        continue
</code>```

What would I be able to do to access the value that exists one iteration prior to the current value of 'row'? Thanks!

答:
In my opinion, we can add a previous_row within the loop that copies the value of the current row just before the iteration exits. That will help in the next iteration to compare the then current row with previous_row.

Let me know if this logic works for you.

Body:
This is what I believe to be a simple logic problem, but I have been working at this for a while and haven't figured it out, so hopefully someone can find the easy solution that I have been missing. I would like to be able to get the prior part of a dataframe using the following code, and have settle for the (row-1) solve in the fourth row, but that obviously did not work.

for row in players_at_start_of_period.iterrows():
    if(row[1]['PERIOD']):
        continue
    elif(row[1]['PERIOD'] - 2) > (row-1)[1]['PERIOD']:
        sub_map.update = {row[1]['TEAM_ID_1']: split_row(row[1]['TEAM_1_PLAYERS']), row[1]['TEAM_ID_2']: split_row(row[1]['TEAM_2_PLAYERS'])}
    else:
        continue

What would I be able to do to access the value that exists one iteration prior to the current value of 'row'? Thanks!


问:
Cannot create proxy object in WCF
I am using WCF service from this link:

http://www.paymentsgateway.com/developerDocumentation/Integration/webservices/merchantservice.aspx#authentication

Now here if you scroll down this link they have given an eg of how to create a client:

```<code>    private void CreateClient(int mid)
{
    ClientRecord client = new ClientRecord();
    client.MerchantID = MerchantID;
    client.FirstName = "Bob";
    client.LastName = "Smith";
    //other code describing client omitted

    try
    {
        using (ClientServiceClient proxy = new ClientServiceClient())
        {
            int id = proxy.createClient(Authenticate.GetClientAuthTicket(txtID.Text.Trim(), txtKey.Text.Trim()), client);
            Response.Write("Created Client ID = " + id.ToString());
        }
    }
    catch (Exception e)
    {
      Response.Write(e.Message);
    }
}
</code>```

Now I dont understand what is this: ClientServiceClient??? I created the implementation like this:

```<code> public static PaymentsGatewayTest.Authentication GetClientAuthTicket (string APILogin, string key)
    {
        PaymentsGatewayTest.Authentication ticket = new PaymentsGatewayTest.Authentication();
        ticket.APILoginID = APILogin;
        ticket.UTCTime = DateTime.UtcNow.Ticks.ToString();
        ticket.TSHash = GenerateTSHash(ticket.APILoginID + "|" + ticket.UTCTime, key.Trim());
        return ticket;
    }

         private void CreateClient(int mid)
    {
        ClientRecord client = new ClientRecord();
        client.MerchantID = 11245;
        client.FirstName = "Bob";
        client.LastName = "Smith";
        //other code describing client omitted

        try
        {
            using (PaymentsAuthClient proxy = new PaymentsAuthClient())
            {

                int id = proxy.createClient(Authenticate.GetClientAuthTicket("", "", client));
                //Response.Write("Created Client ID = " + id.ToString());
            }
        }
        catch (Exception e)
        {
            //Response.Write(e.Message);
        }
    }
</code>```

I have create a Singleton class called PaymentsAuthClient, but this does not seems to work. What I am doing wrong here???

Thank you for your help in adv :)

答:
If you follow the links to the sample source:

http://www.paymentsgateway.com/community/codeSamples/singlepostpage/10-05-05/C_Web_Service_Code_Sample.aspx

You'll see that they have a Service Reference to the client web service, and the ClientServiceClient is autogenerated by Visual studio from the reference.

Their example is a service reference to :

https://sandbox.paymentsgateway.net/WS/Client.svc

If you look in the reference.cs file in the ServiceTestClient\Service References\ClientService folder, you'll see that that the client is called:

```<code>.....yournamespace.....ClientService.ClientServiceClient
</code>```

the service name is the namespace so I think you probably need:

```<code> .....yournamespace.....PaymentsAuthClient.ClientServiceClient
</code>```

Title: Cannot create proxy object in WCF

Body:
I am using WCF service from this link:

http://www.paymentsgateway.com/developerDocumentation/Integration/webservices/merchantservice.aspx#authentication

Now here if you scroll down this link they have given an eg of how to create a client:

    private void CreateClient(int mid)
{
    ClientRecord client = new ClientRecord();
    client.MerchantID = MerchantID;
    client.FirstName = "Bob";
    client.LastName = "Smith";
    //other code describing client omitted

    try
    {
        using (ClientServiceClient proxy = new ClientServiceClient())
        {
            int id = proxy.createClient(Authenticate.GetClientAuthTicket(txtID.Text.Trim(), txtKey.Text.Trim()), client);
            Response.Write("Created Client ID = " + id.ToString());
        }
    }
    catch (Exception e)
    {
      Response.Write(e.Message);
    }
}

Now I dont understand what is this: ClientServiceClient??? I created the implementation like this:

 public static PaymentsGatewayTest.Authentication GetClientAuthTicket (string APILogin, string key)
    {
        PaymentsGatewayTest.Authentication ticket = new PaymentsGatewayTest.Authentication();
        ticket.APILoginID = APILogin;
        ticket.UTCTime = DateTime.UtcNow.Ticks.ToString();
        ticket.TSHash = GenerateTSHash(ticket.APILoginID + "|" + ticket.UTCTime, key.Trim());
        return ticket;
    }

         private void CreateClient(int mid)
    {
        ClientRecord client = new ClientRecord();
        client.MerchantID = 11245;
        client.FirstName = "Bob";
        client.LastName = "Smith";
        //other code describing client omitted

        try
        {
            using (PaymentsAuthClient proxy = new PaymentsAuthClient())
            {

                int id = proxy.createClient(Authenticate.GetClientAuthTicket("", "", client));
                //Response.Write("Created Client ID = " + id.ToString());
            }
        }
        catch (Exception e)
        {
            //Response.Write(e.Message);
        }
    }

I have create a Singleton class called PaymentsAuthClient, but this does not seems to work. What I am doing wrong here???

Thank you for your help in adv :)

Body:
If you follow the links to the sample source:

http://www.paymentsgateway.com/community/codeSamples/singlepostpage/10-05-05/C_Web_Service_Code_Sample.aspx

You'll see that they have a Service Reference to the client web service, and the ClientServiceClient is autogenerated by Visual studio from the reference.

Their example is a service reference to :

https://sandbox.paymentsgateway.net/WS/Client.svc

If you look in the reference.cs file in the ServiceTestClient\Service References\ClientService folder, you'll see that that the client is called:

.....yournamespace.....ClientService.ClientServiceClient

the service name is the namespace so I think you probably need:

 .....yournamespace.....PaymentsAuthClient.ClientServiceClient


问:
Authentication on website using smart card in python
So I have a smart card provided by the company which looks like a credit card with a chip.
This card  logins on a website after the card is inserted into the card reader.

Now I have to write a program in python which can read the card and login on that website using Requests module.
I tried to find out how to retrieve this authentication data from the card using python script and then use this data but I am partially successful. I installed the pyscard:

```<code>from smartcard.System import readers
from smartcard.util import toHexString

r=readers()
print(r)

connection = r[0].createConnection()
connection.connect()
SELECT = [0xA0, 0x88, 0x00, 0x00] # CLA, INS, P1, P2
DF_TELECOM = [ 0x02, 0x7F, 0x10]  # Lc, Data, Le
data, sw1, sw2 = connection.transmit( SELECT + DF_TELECOM )
</code>```

So far I am able to transmit data and retrieve some data from card.
I sent the command 88 in INS (Source : ISO 7816) which is for some sort of internal authentication( I assume this authentication data is used to login on the website)  but I get below response :

```<code>data = []
sw1 = 110
sw2 = 00
</code>```

I couldn't find the meaning of  this response in ISO 7816. Can somebody tell me whether I have the right approach or hint to proceed further from here? In short, i want to know how to login on the website using python script and smart card?

答: Basically, the response you're getting is essentially "6E00" which means "Class not supported", just replace the "INS" value with 0x00 and you should be fine</p>

Body:
So I have a smart card provided by the company which looks like a credit card with a chip.
This card  logins on a website after the card is inserted into the card reader.

Now I have to write a program in python which can read the card and login on that website using Requests module.
I tried to find out how to retrieve this authentication data from the card using python script and then use this data but I am partially successful. I installed the pyscard:

from smartcard.System import readers
from smartcard.util import toHexString

r=readers()
print(r)

connection = r[0].createConnection()
connection.connect()
SELECT = [0xA0, 0x88, 0x00, 0x00] # CLA, INS, P1, P2
DF_TELECOM = [ 0x02, 0x7F, 0x10]  # Lc, Data, Le
data, sw1, sw2 = connection.transmit( SELECT + DF_TELECOM )

So far I am able to transmit data and retrieve some data from card.
I sent the command 88 in INS (Source : ISO 7816) which is for some sort of internal authentication( I assume this authentication data is used to login on the website)  but I get below response :

data = []
sw1 = 110
sw2 = 00

I couldn't find the meaning of  this response in ISO 7816. Can somebody tell me whether I have the right approach or hint to proceed further from here? In short, i want to know how to login on the website using python script and smart card?


答:
Check this.

function SetValue(ts) {
  var txt = document.getElementById("searchabar");
  var n = txt.value.indexOf(":");
  var text = txt.value;
  if (n > 0) {
    var text = txt.value.substring(n + 1);
  }
  txt.value = ts + ":" + text;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head></head>

<body>
  <input type="" name="" placeholder="Search bar" id="searchabar">
  <input type="button" name="" value='Apple' onclick="SetValue('Apple')">
  <input type="button" name="" value='Squash' onclick="SetValue('Squash')">
  <input type="button" name="" value='Banana' onclick="SetValue('Banana')">
  <script type="text/javascript">
  </script>
</body>

</html></code>```

Title: Changing search text with Javascript Buttons

Body:
I know this seems simple and obsolete, but I can't find a proper example of this anywhere.

My goal is to edit my search bar by adding text to the beginning of whatever the user inputs with javascript.

For example, a user inputs "Pie", there are three buttons underneath the search bar, the user can select "Apple" "Banana" or "Squash". When clicking on any of the buttons it should add the text to the beginning of pie, e.g. clicking on "Banana" Results in modifying the search bar with "Banana Pie".

I'm just trying to learn how to do this in JS and I can't find a proper example of this anywhere if someone can point me to the proper place to look i would greatly appreciate it.

Body:
Check this.

function SetValue(ts) {
  var txt = document.getElementById("searchabar");
  var n = txt.value.indexOf(":");
  var text = txt.value;
  if (n > 0) {
    var text = txt.value.substring(n + 1);
  }
  txt.value = ts + ":" + text;
}

<!DOCTYPE html>
<html lang="en">

<head></head>

<body>
  <input type="" name="" placeholder="Search bar" id="searchabar">
  <input type="button" name="" value='Apple' onclick="SetValue('Apple')">
  <input type="button" name="" value='Squash' onclick="SetValue('Squash')">
  <input type="button" name="" value='Banana' onclick="SetValue('Banana')">
  <script type="text/javascript">
  </script>
</body>

</html>


答:
You can do that in following steps:

Create the buttons in the html and give them same class.

Access them in javascript and add onclick listener to them.

Change the value of input in that function.

const input = document.getElementById('test');

document.querySelectorAll('.fruit').forEach(fruit => {
  fruit.onclick= function(){
    input.value = `${fruit.innerText} ${input.value}`
  }

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="test" type="text" />
<button class="fruit">Apple</button>
<button class="fruit">Banana</button></code>```

Body:
You can do that in following steps:

Create the buttons in the html and give them same class.

Access them in javascript and add onclick listener to them.

Change the value of input in that function.

const input = document.getElementById('test');

document.querySelectorAll('.fruit').forEach(fruit => {
  fruit.onclick= function(){
    input.value = `${fruit.innerText} ${input.value}`
  }

})

<input id="test" type="text" />
<button class="fruit">Apple</button>
<button class="fruit">Banana</button>


问:
How to replace sentence above nested table without using selection object
Consider this situation:
there is a sentence of words above a nested table to be replaced with new text.

I have tried the following :

ActiveDocument.Tables(1).Cell(1, 1).Range.Paragraphs(1).Range.Text = "New Text"

However, the end result is shown in (2)

I want to obtain result (3) ideally without using selection object (including selection.find)

If selection object is used,
I have already figured a solution as follows:

```<code>ActiveDocument.Tables(1).Cell(1, 1).Range.Paragraphs(1).range.select
selection.typetext "New Text"
</code>```

Would appreciate your help :)

答:
This may not be an elegant solution but it works
(would appreciate any constructive feedback)</p>

```<code>ActiveDocument.Tables(1).Range.InsertBefore "New Text" & vbCr
vstart = ActiveDocument.Tables(1).Range.Paragraphs(1).Range.End
vend = ActiveDocument.Tables(1).Range.Paragraphs(2).Range.End
ActiveDocument.Range(vstart - 1, vend).delete
</code>```

Body:
Consider this situation:
there is a sentence of words above a nested table to be replaced with new text.

I have tried the following :

ActiveDocument.Tables(1).Cell(1, 1).Range.Paragraphs(1).Range.Text = "New Text"

However, the end result is shown in (2)

I want to obtain result (3) ideally without using selection object (including selection.find)

If selection object is used,
I have already figured a solution as follows:

ActiveDocument.Tables(1).Cell(1, 1).Range.Paragraphs(1).range.select
selection.typetext "New Text"

Would appreciate your help :)

Body:
This may not be an elegant solution but it works
(would appreciate any constructive feedback)

ActiveDocument.Tables(1).Range.InsertBefore "New Text" & vbCr
vstart = ActiveDocument.Tables(1).Range.Paragraphs(1).Range.End
vend = ActiveDocument.Tables(1).Range.Paragraphs(2).Range.End
ActiveDocument.Range(vstart - 1, vend).delete


问:
How can I handle the warning of file_get_contents() function in PHP?
I wrote a PHP code like this

```<code>$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
</code>```

But when I remove "http://" from $site I get the following warning:

Warning:
  file_get_contents(www.google.com)
  [function.file-get-contents]: failed
  to open stream:

I tried try and catch but it didn't work.

答:
```<code>if (!file_get_contents($data)) {
  exit('<h1>ERROR MESSAGE</h1>');
} else {
      return file_get_contents($data);
}
</code>```

OwnerDisplayName: Waseem

Body:
I wrote a PHP code like this

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;

But when I remove "http://" from $site I get the following warning:

Warning:
  file_get_contents(www.google.com)
  [function.file-get-contents]: failed
  to open stream:

I tried try and catch but it didn't work.

LastEditorDisplayName: Waseem


问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答:
You could use String.Join.  Try something like this:

```<code>String query = "select * from table where RecordId in ({0});";
String formatted = String.Format(query, String.Join(",", list.ToArray()));
</code>```

As a side note this will not protect you against SQL injection - hopefully this example will point you in the right direction.

OwnerDisplayName: JoelHess

ContentLicense: CC BY-SA 2.5

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare

Body:
You could use String.Join.  Try something like this:

String query = "select * from table where RecordId in ({0});";
String formatted = String.Format(query, String.Join(",", list.ToArray()));

As a side note this will not protect you against SQL injection - hopefully this example will point you in the right direction.

OwnerDisplayName: Andrew Hare


问:
Django Models and Admin interface question
I am preparing a Examination website for my students. Simple website, with use of Django's admin interface to create the Question paper.

I have following models:

```<code>class Paper(models.Model):
    name = models.CharField(max_length=2000, unique=False)
    short_desc = models.TextField(unique=False)

class Question(models.Model):
    text = models.TextField(unique=False)
    order = models.IntegerField(unique=True)
    paper = models.ForeignKey(Paper, unique=False)
</code>```

While adding questions to the paper, I want that I should be able to add the question from the Paper's admin interface itself, by clicking a "+" sign or some kind of "add more questions" etc.

In my current setup, I have to first create the paper and then go into Question interface and add them one by one (and heaven's forbid) if I lose their order number.

Remember, each Question belongs to a Paper and it is not a ManyToMany thing here.

Do I have to modify the admin in any way or am I doing it wrong?

Thanks.

答:
The admin interface has the ability to
  edit models on the same page as a
  parent model. These are called
  inlines. See InlineModelAdmin

Create a QuestionInline:

```<code>class QuestionInline(admin.TabularInline):
    model = Question
</code>```

and in PaperAdmin add:

```<code>class PaperAdmin(admin.ModelAdmin):
    ...
    inlines = [
        QuestionInline,
    ]
</code>```

Body:
I am preparing a Examination website for my students. Simple website, with use of Django's admin interface to create the Question paper.

I have following models:

class Paper(models.Model):
    name = models.CharField(max_length=2000, unique=False)
    short_desc = models.TextField(unique=False)

class Question(models.Model):
    text = models.TextField(unique=False)
    order = models.IntegerField(unique=True)
    paper = models.ForeignKey(Paper, unique=False)

While adding questions to the paper, I want that I should be able to add the question from the Paper's admin interface itself, by clicking a "+" sign or some kind of "add more questions" etc.

In my current setup, I have to first create the paper and then go into Question interface and add them one by one (and heaven's forbid) if I lose their order number.

Remember, each Question belongs to a Paper and it is not a ManyToMany thing here.

Do I have to modify the admin in any way or am I doing it wrong?

Thanks.

Body:
The admin interface has the ability to
  edit models on the same page as a
  parent model. These are called
  inlines. See InlineModelAdmin

Create a QuestionInline:

class QuestionInline(admin.TabularInline):
    model = Question

and in PaperAdmin add:

class PaperAdmin(admin.ModelAdmin):
    ...
    inlines = [
        QuestionInline,
    ]


问:
Scroll only a part of a page
I have a fixed Toolbar in the top. The scrollbar of the page is for the whole page. The toolbar wont move from the top and is always visible and i have no problem with that. But i want only the content of the page to be scrollable instead of the whole page

Example i have a div called  content inside the body and i want only that to be scrollable instead of the whole body

Code

```<code><body>
  <div>
     <div class="Top">
        <?php $var = 1; include('PHP/ToolBar.php') ?>
     </div>

     <div class="content">
        <h5>Page Content</h5>
     </div>
  </div>
</body>
</code>```

The whole page scrolls but i want only the content to be scrollable.

Using webkit for customised scrollbar

```<code>::-webkit-scrollbar {
  width: 10px;
}
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
  background: #555555;
}
</code>```

答:
If your page is just divided into .Top and .content sections
You can behave as follows

.Top{
      position: fixed;
      top: 0;
      right: 0;
      left: 0;
      width: 100%;
      background-color: crimson;
      height:40px;
  }
  .content{
      height: calc(100% - 40px);
      position: fixed;
      bottom: 0;
      right: 0;
      left: 0;
      width: 100%;
      overflow-y: scroll;
      background-color: cyan;
  }

  .content::-webkit-scrollbar {
      width: 8px;
  }

  .content::-webkit-scrollbar-track {
    background-color: #ededed;
  }

  .content::-webkit-scrollbar-thumb {
     background-color: #999999;
     outline: 1px solid #999999;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

    <div>
        <div class="Top">

        </div>

        <div class="content">
           <h5>Page Content</h5>
           <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque doloremque, quisquam possimus qui facilis eveniet quas veniam eos, repellendus officiis explicabo quia quidem aut a, voluptas nesciunt. Soluta ducimus ad eos mollitia est, non consectetur quaerat nostrum natus voluptas odio esse quis sequi quidem sapiente. Tempore sunt molestiae, maiores velit itaque harum error possimus temporibus! Voluptatibus, rerum. Reiciendis laudantium porro maiores consequatur adipisci animi sunt aperiam ratione saepe. Fugit, dignissimos rem, dolores quam velit quos dicta facere asperiores est ut ipsa reprehenderit culpa illum! Id reiciendis est animi voluptas fugiat quisquam nihil alias quia impedit voluptatibus reprehenderit voluptatum, optio sequi ipsa eaque eos facilis vitae recusandae rerum dolor numquam iste doloribus nulla magni? Quaerat ipsam accusamus ex laborum sint repudiandae maiores, animi explicabo, similique dolorum hic quos assumenda veritatis perspiciatis eos harum deleniti distinctio! Placeat officia magni voluptate dolores facilis, quaerat provident facere reiciendis sequi quisquam eos mollitia laborum cumque vel similique tempore itaque explicabo consectetur, aliquid alias labore quos officiis ab sapiente. Odio numquam repellendus ex rem, quae, natus consequuntur temporibus iusto atque necessitatibus earum odit libero quia reiciendis tenetur distinctio dolorem officiis impedit accusantium fuga placeat. Nobis voluptas maiores doloremque? Fuga nostrum nisi sapiente eos aut quam quasi deleniti, reiciendis quis aliquam placeat unde excepturi optio soluta magnam vero architecto. Ad sunt, nemo laboriosam hic aut natus. Consequatur optio officiis nam. Ab ratione accusantium dicta rerum aliquam earum quae temporibus, quibusdam impedit? Saepe laborum eligendi, similique doloribus dolorum dolorem cum laudantium commodi? Id dolorum atque pariatur consectetur dolorem dolore minima amet esse voluptas veniam ad a accusamus non doloribus totam eos nisi eius nobis, quo maxime vitae! Culpa minus accusamus, sed, pariatur facilis consequuntur sit nam debitis perspiciatis deleniti a minima sint unde quam voluptas quidem porro aut repellendus obcaecati. Magni voluptatem odio quia, natus sit quos, laudantium, dolores quam recusandae deserunt esse? Ad facilis sunt a eum aliquam assumenda hic aliquid! Fugit optio quo, reiciendis unde a laborum alias quos incidunt voluptate non cupiditate aspernatur. Sint excepturi, rerum quod exercitationem accusamus non minus, at rem maiores earum, neque accusantium molestiae repellat? Nam, porro optio tenetur harum magnam dolorem alias at tempore dolores maiores sunt ipsam vel culpa placeat eligendi ullam iusto quam qui aliquam et sequi officiis. Corrupti incidunt sit consequatur asperiores facilis laboriosam quasi architecto tenetur soluta ea, cupiditate dolor! Cumque recusandae voluptates aperiam ab, officia dolores esse assumenda quae praesentium nihil quasi qui voluptas quisquam eveniet fugit at excepturi ex, quidem accusamus in necessitatibus molestias eaque veniam deserunt. Repellat nihil voluptate ipsum repellendus! Ullam, harum! Eius reprehenderit corporis facere, culpa maxime temporibus atque laboriosam quos unde. Quos illo impedit voluptatum aliquid maiores, dolorem autem dignissimos? Voluptatibus labore quia accusantium ea accusamus aliquam est rerum tenetur, quidem deserunt. Amet placeat quo aspernatur voluptatem iure at ea eum temporibus. Molestiae eos ducimus ipsa molestias? Tenetur laborum quae adipisci at vitae accusamus tempore aliquid dolorem praesentium doloribus quas autem officiis consectetur, nulla fuga et exercitationem. Sequi fugit ut eveniet exercitationem? Ex quo similique vel, molestias voluptatibus sit sunt quidem nemo at nostrum quas debitis eligendi, doloribus consequuntur officiis ducimus tenetur eaque amet perferendis blanditiis, nulla nam! Cumque, sequi distinctio? Assumenda, facere tempore error blanditiis, maiores, magnam quis quaerat molestias voluptas iusto voluptates fuga explicabo beatae ex impedit minus reprehenderit maxime cumque consectetur. Aperiam, eos modi ut quisquam ab pariatur eum cum velit nostrum impedit amet, quod temporibus itaque tenetur recusandae magni nisi tempore deserunt assumenda provident. Unde aut delectus voluptatibus iusto possimus nulla quam odio totam, ullam reiciendis quae eos magnam, exercitationem ea asperiores? Rem repellat sint debitis facilis placeat officiis, eveniet nihil quos. Sit fugiat quis nesciunt illum necessitatibus earum, accusantium praesentium, sapiente numquam quaerat ab ea eius iusto, deserunt accusamus inventore unde doloribus suscipit maxime hic? Similique iusto harum odit dicta ea amet, ullam unde. Deserunt aut earum iusto impedit adipisci similique, aliquid amet numquam facilis voluptatum consectetur, error accusantium laboriosam porro delectus, voluptates consequatur accusamus maiores unde modi? Ullam quidem iure, molestias odit non ex quasi, exercitationem perferendis dolore modi nostrum provident cumque atque nihil quae iusto necessitatibus fugit deserunt doloribus? Possimus accusamus aliquid cumque unde iusto ea ad nihil eaque dolore, vel eveniet! Debitis facere maxime expedita amet corrupti nihil rem vitae qui eveniet.</p>

        </div>
     </div>

</body></code>```

Title: Scroll only a part of a page

Body:
I have a fixed Toolbar in the top. The scrollbar of the page is for the whole page. The toolbar wont move from the top and is always visible and i have no problem with that. But i want only the content of the page to be scrollable instead of the whole page

Example i have a div called  content inside the body and i want only that to be scrollable instead of the whole body

Code

        <?php $var = 1; include('PHP/ToolBar.php') ?>

Page Content

The whole page scrolls but i want only the content to be scrollable.

Using webkit for customised scrollbar

::-webkit-scrollbar {
  width: 10px;
}
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
  background: #555555;
}

Body:
If your page is just divided into .Top and .content sections
You can behave as follows

.Top{
      position: fixed;
      top: 0;
      right: 0;
      left: 0;
      width: 100%;
      background-color: crimson;
      height:40px;
  }
  .content{
      height: calc(100% - 40px);
      position: fixed;
      bottom: 0;
      right: 0;
      left: 0;
      width: 100%;
      overflow-y: scroll;
      background-color: cyan;
  }

  .content::-webkit-scrollbar {
      width: 8px;
  }

  .content::-webkit-scrollbar-track {
    background-color: #ededed;
  }

  .content::-webkit-scrollbar-thumb {
     background-color: #999999;
     outline: 1px solid #999999;
  }

<body>

    <div>
        <div class="Top">

        </div>

        <div class="content">
           <h5>Page Content</h5>
           <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque doloremque, quisquam possimus qui facilis eveniet quas veniam eos, repellendus officiis explicabo quia quidem aut a, voluptas nesciunt. Soluta ducimus ad eos mollitia est, non consectetur quaerat nostrum natus voluptas odio esse quis sequi quidem sapiente. Tempore sunt molestiae, maiores velit itaque harum error possimus temporibus! Voluptatibus, rerum. Reiciendis laudantium porro maiores consequatur adipisci animi sunt aperiam ratione saepe. Fugit, dignissimos rem, dolores quam velit quos dicta facere asperiores est ut ipsa reprehenderit culpa illum! Id reiciendis est animi voluptas fugiat quisquam nihil alias quia impedit voluptatibus reprehenderit voluptatum, optio sequi ipsa eaque eos facilis vitae recusandae rerum dolor numquam iste doloribus nulla magni? Quaerat ipsam accusamus ex laborum sint repudiandae maiores, animi explicabo, similique dolorum hic quos assumenda veritatis perspiciatis eos harum deleniti distinctio! Placeat officia magni voluptate dolores facilis, quaerat provident facere reiciendis sequi quisquam eos mollitia laborum cumque vel similique tempore itaque explicabo consectetur, aliquid alias labore quos officiis ab sapiente. Odio numquam repellendus ex rem, quae, natus consequuntur temporibus iusto atque necessitatibus earum odit libero quia reiciendis tenetur distinctio dolorem officiis impedit accusantium fuga placeat. Nobis voluptas maiores doloremque? Fuga nostrum nisi sapiente eos aut quam quasi deleniti, reiciendis quis aliquam placeat unde excepturi optio soluta magnam vero architecto. Ad sunt, nemo laboriosam hic aut natus. Consequatur optio officiis nam. Ab ratione accusantium dicta rerum aliquam earum quae temporibus, quibusdam impedit? Saepe laborum eligendi, similique doloribus dolorum dolorem cum laudantium commodi? Id dolorum atque pariatur consectetur dolorem dolore minima amet esse voluptas veniam ad a accusamus non doloribus totam eos nisi eius nobis, quo maxime vitae! Culpa minus accusamus, sed, pariatur facilis consequuntur sit nam debitis perspiciatis deleniti a minima sint unde quam voluptas quidem porro aut repellendus obcaecati. Magni voluptatem odio quia, natus sit quos, laudantium, dolores quam recusandae deserunt esse? Ad facilis sunt a eum aliquam assumenda hic aliquid! Fugit optio quo, reiciendis unde a laborum alias quos incidunt voluptate non cupiditate aspernatur. Sint excepturi, rerum quod exercitationem accusamus non minus, at rem maiores earum, neque accusantium molestiae repellat? Nam, porro optio tenetur harum magnam dolorem alias at tempore dolores maiores sunt ipsam vel culpa placeat eligendi ullam iusto quam qui aliquam et sequi officiis. Corrupti incidunt sit consequatur asperiores facilis laboriosam quasi architecto tenetur soluta ea, cupiditate dolor! Cumque recusandae voluptates aperiam ab, officia dolores esse assumenda quae praesentium nihil quasi qui voluptas quisquam eveniet fugit at excepturi ex, quidem accusamus in necessitatibus molestias eaque veniam deserunt. Repellat nihil voluptate ipsum repellendus! Ullam, harum! Eius reprehenderit corporis facere, culpa maxime temporibus atque laboriosam quos unde. Quos illo impedit voluptatum aliquid maiores, dolorem autem dignissimos? Voluptatibus labore quia accusantium ea accusamus aliquam est rerum tenetur, quidem deserunt. Amet placeat quo aspernatur voluptatem iure at ea eum temporibus. Molestiae eos ducimus ipsa molestias? Tenetur laborum quae adipisci at vitae accusamus tempore aliquid dolorem praesentium doloribus quas autem officiis consectetur, nulla fuga et exercitationem. Sequi fugit ut eveniet exercitationem? Ex quo similique vel, molestias voluptatibus sit sunt quidem nemo at nostrum quas debitis eligendi, doloribus consequuntur officiis ducimus tenetur eaque amet perferendis blanditiis, nulla nam! Cumque, sequi distinctio? Assumenda, facere tempore error blanditiis, maiores, magnam quis quaerat molestias voluptas iusto voluptates fuga explicabo beatae ex impedit minus reprehenderit maxime cumque consectetur. Aperiam, eos modi ut quisquam ab pariatur eum cum velit nostrum impedit amet, quod temporibus itaque tenetur recusandae magni nisi tempore deserunt assumenda provident. Unde aut delectus voluptatibus iusto possimus nulla quam odio totam, ullam reiciendis quae eos magnam, exercitationem ea asperiores? Rem repellat sint debitis facilis placeat officiis, eveniet nihil quos. Sit fugiat quis nesciunt illum necessitatibus earum, accusantium praesentium, sapiente numquam quaerat ab ea eius iusto, deserunt accusamus inventore unde doloribus suscipit maxime hic? Similique iusto harum odit dicta ea amet, ullam unde. Deserunt aut earum iusto impedit adipisci similique, aliquid amet numquam facilis voluptatum consectetur, error accusantium laboriosam porro delectus, voluptates consequatur accusamus maiores unde modi? Ullam quidem iure, molestias odit non ex quasi, exercitationem perferendis dolore modi nostrum provident cumque atque nihil quae iusto necessitatibus fugit deserunt doloribus? Possimus accusamus aliquid cumque unde iusto ea ad nihil eaque dolore, vel eveniet! Debitis facere maxime expedita amet corrupti nihil rem vitae qui eveniet.</p>

        </div>
     </div>

</body>


问:
Event handling in Azure Data Factory
Is there any method available in azure data factory to track the events of a pipeline? I have an event log table and I need to log all the events associated with the pipelines into the same table. Any best practice templates /methods available to achieve the same?

Regards,
Sandeep

答:
1.You could use Azure Monitor in ADF and enable diagnostic log and store the logs into Azure Blob Storage.Then analysis logs and transfer them into tables as you want.

2.Another choice,you could use ADF monitor SDK or REST API to retrieve the activities run details by Pipeline Run Id:

```<code>List<ActivityRun> activityRuns = client.ActivityRuns.ListByPipelineRun(
resourceGroup, dataFactoryName, runResponse.RunId, DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow.AddMinutes(10)).ToList();
if (pipelineRun.Status == "Succeeded")
    Console.WriteLine(activityRuns.First().Output);
else
    Console.WriteLine(activityRuns.First().Error);
</code>```

Then you could get all the activities details into tables as you want.

Title: Event handling in Azure Data Factory

Body:
1.You could use Azure Monitor in ADF and enable diagnostic log and store the logs into Azure Blob Storage.Then analysis logs and transfer them into tables as you want.

2.Another choice,you could use ADF monitor SDK or REST API to retrieve the activities run details by Pipeline Run Id:

List<ActivityRun> activityRuns = client.ActivityRuns.ListByPipelineRun(
resourceGroup, dataFactoryName, runResponse.RunId, DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow.AddMinutes(10)).ToList();
if (pipelineRun.Status == "Succeeded")
    Console.WriteLine(activityRuns.First().Output);
else
    Console.WriteLine(activityRuns.First().Error);

Then you could get all the activities details into tables as you want.


答: if "ubuntu" and "test" is file, it should work. if they are directories, you need add dot "." , like ".test" or ".ubuntu" in EXCLUDED</p>

Title: Using array for `ls --ignore`

Body:
I'm working on a bash script for my server backup.
Based on my web root(/home), I wanna filter my web directories excludes something generals.
I found --ignore option for it. Here's my code for returng what I want.

DIR_LIST=`ls -al $WWW_ROOT --ignore={.,..,ubuntu,test} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;

But when I tried with array, it's not worked as well.

EXCLUDED=(. .. test ubuntu)
STR=$(IFS=,; echo "${EXCLUDED[*]}")
DIR_LIST=`ls -al $WWW_ROOT --ignore={$STR} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;

echo $STR works well but echo $DIR_LIST is not.
I think brace is not worked properly.

How can I do this as I expected?


问:
repeat awk and if statement for all columns
I have a file of more than 50 columns and I would like to output only fields with last character equals to 1 in all columns. How do loop the if statement shown below for all columns?

```<code>awk '{if(substr($0,length($0),1) == 1) print $0}' file_with_one_column.tsv
</code>```

extra info:
(1) delimiter: tab
(2) output format: same number of columns as input (excluding fields with last character != 1). i.e not one line ouput
(3) same number of lines in all columns
(4) issue: some fields contain only '.' charachter.

I'm getting this issue when I tried to use for loop
awk: 1: unexpected character '.'

Example input:

```<code>ENSG00000267601.1    ENSG00000256861.1    ENSG00000259953.2
DGCR8_H_2_2          .                    SAFB2_K_1_2
IGF2BP3_H_1_1        DDX6_K_1_2           LIN28B_H_1_2
NKRF_H_2_2           PPIL4_K_2_2          LIN28B_K_1_1
IGF2BP1_H_2_2        CDC40_H_1_2          LIN28B_K_2_1
POLR2G_H_2_2         IGF2BP3_H_1_2        .
</code>```

Desired output:

```<code>ENSG00000267601.1    ENSG00000256861.1    ENSG00000259953.2
IGF2BP3_H_1_1                             LIN28B_K_1_1
                                          LIN28B_K_2_1
</code>```

答:
Like this:

```<code>awk '{for(i=1;i<=NF;i++){if(substr($i,length($i),1)=="1") print $i}}' file.tsv
</code>```

This prints every field on a separate line.

If you want to filter the lines and only print those columns which end with 1 you may use:

```<code>#!/bin/bash
awk '{
    found = 0
    for(i=1;i<=NF;i++){
        if(substr($i,length($i),1) == "1") {
            printf "%s%s", (found?OFS:""), $i
            found = 1
        }
    }
    if(found) {
        printf "%s", ORS
    }
}' file.tsv
</code>```

Btw, unless your input file is really large, I would call the check substr($i,length($i),1) == "1" micro-optimization and replace it by the more readable regular expression $i ~ /1$/

Body:
I have a file of more than 50 columns and I would like to output only fields with last character equals to 1 in all columns. How do loop the if statement shown below for all columns?

awk '{if(substr($0,length($0),1) == 1) print $0}' file_with_one_column.tsv

extra info:
(1) delimiter: tab
(2) output format: same number of columns as input (excluding fields with last character != 1). i.e not one line ouput
(3) same number of lines in all columns
(4) issue: some fields contain only '.' charachter.

I'm getting this issue when I tried to use for loop
awk: 1: unexpected character '.'

Example input:

ENSG00000267601.1    ENSG00000256861.1    ENSG00000259953.2
DGCR8_H_2_2          .                    SAFB2_K_1_2
IGF2BP3_H_1_1        DDX6_K_1_2           LIN28B_H_1_2
NKRF_H_2_2           PPIL4_K_2_2          LIN28B_K_1_1
IGF2BP1_H_2_2        CDC40_H_1_2          LIN28B_K_2_1
POLR2G_H_2_2         IGF2BP3_H_1_2        .

Desired output:

ENSG00000267601.1    ENSG00000256861.1    ENSG00000259953.2
IGF2BP3_H_1_1                             LIN28B_K_1_1
                                          LIN28B_K_2_1

Body:
Like this:

awk '{for(i=1;i<=NF;i++){if(substr($i,length($i),1)=="1") print $i}}' file.tsv

This prints every field on a separate line.

If you want to filter the lines and only print those columns which end with 1 you may use:

#!/bin/bash
awk '{
    found = 0
    for(i=1;i<=NF;i++){
        if(substr($i,length($i),1) == "1") {
            printf "%s%s", (found?OFS:""), $i
            found = 1
        }
    }
    if(found) {
        printf "%s", ORS
    }
}' file.tsv

Btw, unless your input file is really large, I would call the check substr($i,length($i),1) == "1" micro-optimization and replace it by the more readable regular expression $i ~ /1$/


问:
Populating more than 1 property in a subdocument using Mongoose
For argument's sake, say I have a the following mongoose models

```<code>REGION: {
_id
name
teams (TEAM)
}

TEAM {
_id
name
region (REGION)
coach (COACH)
players (PLAYER)
}

COACH {
_id
name
team (TEAM)
}

PLAYER{
_id
name
team (TEAM)
}
</code>```

And I wanted to populate a region object with all their teams and finally the teams with their coach and players, how would I go about that

答: I would flip it : think in terms of Player docs. each has a coach, team, region.  So load the Player docs with those fields....   then you'll be able to set up index on those fields and efficiently query them....</p>

Body:
For argument's sake, say I have a the following mongoose models

REGION: {
_id
name
teams (TEAM)
}

TEAM {
_id
name
region (REGION)
coach (COACH)
players (PLAYER)
}

COACH {
_id
name
team (TEAM)
}

PLAYER{
_id
name
team (TEAM)
}

And I wanted to populate a region object with all their teams and finally the teams with their coach and players, how would I go about that


问:
What's the correct way to share memory between my AssemblyScript module and my JS?
I'm following this code here, trying to share memory between my AssemblyScript code and my JS:

```<code>  let aryPtr = instance.exports.allocateF32Array(3);
  let ary = new Float32Array(instance.exports.memory.buffer, aryPtr, 3);

  ary[0] = 1.0;
  ary[1] = 2.0;
  instance.exports.addArray(aryPtr);
</code>```

And my index.ts:

```<code>export function allocateF32Array(length: i32): Float32Array {
  return new Float32Array(length);
}

export function addArray(data: Float32Array): i32 {
  data[2] = data[0] + data[1];
  return data.length;
}
</code>```

But this results in RuntimeError: memory access out of bounds in addArray. Have I misunderstood how this is supposed to work?

答:
I recommend to use the official loader for such purposes.

On the JavaScript side: (node.js for example)

const fs = require("fs");
const loader = require("@assemblyscript/loader");
const module = loader.instantiateSync(
  fs.readFileSync("optimized.wasm"),
  {}
);
var ptrArr = module.__retain(module.__allocArray(module.FLOAT32ARRAY, [1, 2, 0]));
console.log('length:', module.addArray(ptrArr));

const arr = module.__getFloat32Array(ptrArr);
console.log('result:', arr[2]);

// free array
module.__release(ptrArr);
```
<p>On the AssemblyScript side:</p>
<pre class="lang-js prettyprint-override"><code>export const FLOAT32ARRAY = idof<Float32Array>();

export function addArray(data: Float32Array): i32 {
  data[2] = data[0] + data[1];
  return data.length;
}
</code>```

Body:
I'm following this code here, trying to share memory between my AssemblyScript code and my JS:

  let aryPtr = instance.exports.allocateF32Array(3);
  let ary = new Float32Array(instance.exports.memory.buffer, aryPtr, 3);

  ary[0] = 1.0;
  ary[1] = 2.0;
  instance.exports.addArray(aryPtr);

And my index.ts:

export function allocateF32Array(length: i32): Float32Array {
  return new Float32Array(length);
}

export function addArray(data: Float32Array): i32 {
  data[2] = data[0] + data[1];
  return data.length;
}

But this results in RuntimeError: memory access out of bounds in addArray. Have I misunderstood how this is supposed to work?

Body:
I recommend to use the official loader for such purposes.

On the JavaScript side: (node.js for example)

const fs = require("fs");
const loader = require("@assemblyscript/loader");
const module = loader.instantiateSync(
  fs.readFileSync("optimized.wasm"),
  {}
);
var ptrArr = module.__retain(module.__allocArray(module.FLOAT32ARRAY, [1, 2, 0]));
console.log('length:', module.addArray(ptrArr));

const arr = module.__getFloat32Array(ptrArr);
console.log('result:', arr[2]);

// free array
module.__release(ptrArr);

On the AssemblyScript side:

export const FLOAT32ARRAY = idof<Float32Array>();

export function addArray(data: Float32Array): i32 {
  data[2] = data[0] + data[1];
  return data.length;
}


问:
How can I convert spectrogram data to a tensor (or multidimensional numpy array)?
I am using keras and have:

```<code>        corrupted_samples, corrupted_sample_rate = sf.read(
            self.corrupted_audio_file_paths[index])

        frequencies, times, spectrogram = scipy.signal.spectrogram(
            corrupted_samples, corrupted_sample_rate)
</code>```

As per the docs, this gives:

```<code>f (ndarray) - Array of sample frequencies.
t (ndarray) - Array of segment times.
Sxx (ndarray) - Spectrogram of x. By default, the last axis of Sxx corresponds to the segment times.
</code>```

I assume all of the times will line up, so I don't care about the value of the time (I don't think). The same is true of frequencies. So what I actually need is the values at each time for each frequency, which is given by Sxx (or spectrogram) in my code. I'm unsure how to actually do that. It seems simple though.

答:
Based on https://towardsdatascience.com/speech-recognition-analysis-f03ff9ce78e9, the author stated that the spectrogram is a spectro-temporal representation of the sound and show some of the steps of converting wav file to spectogram.

One of the example could be as below:

```<code>## Check the sampling rate of the WAV file.
audio_file = './siren_mfcc_demo.wav'

import wave
with wave.open(audio_file, "rb") as wave_file:
    sr = wave_file.getframerate()
print(sr)

audio_binary = tf.read_file(audio_file)

# tf.contrib.ffmpeg not supported on Windows, refer to issue
# https://github.com/tensorflow/tensorflow/issues/8271
waveform = tf.contrib.ffmpeg.decode_audio(audio_binary, file_format='wav', samples_per_second=sr, channel_count=1)
print(waveform.numpy().shape)

signals = tf.reshape(waveform, [1, -1])
signals.get_shape()

# Compute a [batch_size, ?, 128] tensor of fixed length, overlapping windows
# where each window overlaps the previous by 75% (frame_length - frame_step
# samples of overlap).
frames = tf.contrib.signal.frame(signals, frame_length=128, frame_step=32)
print(frames.numpy().shape)

# `magnitude_spectrograms` is a [batch_size, ?, 129] tensor of spectrograms. We
# would like to produce overlapping fixed-size spectrogram patches; for example,
# for use in a situation where a fixed size input is needed.
magnitude_spectrograms = tf.abs(tf.contrib.signal.stft(
    signals, frame_length=256, frame_step=64, fft_length=256))

print(magnitude_spectrograms.numpy().shape)
</code>```

The method above is referring to https://colab.research.google.com/drive/1Adcy25HYC4c9uSBDK9q5_glR246m-TSx#scrollTo=QTa1BVSOw1Oe

Hope it can help you.

Body:
I am using keras and have:

        corrupted_samples, corrupted_sample_rate = sf.read(
            self.corrupted_audio_file_paths[index])

        frequencies, times, spectrogram = scipy.signal.spectrogram(
            corrupted_samples, corrupted_sample_rate)

As per the docs, this gives:

f (ndarray) - Array of sample frequencies.
t (ndarray) - Array of segment times.
Sxx (ndarray) - Spectrogram of x. By default, the last axis of Sxx corresponds to the segment times.

I assume all of the times will line up, so I don't care about the value of the time (I don't think). The same is true of frequencies. So what I actually need is the values at each time for each frequency, which is given by Sxx (or spectrogram) in my code. I'm unsure how to actually do that. It seems simple though.

Body:
Based on https://towardsdatascience.com/speech-recognition-analysis-f03ff9ce78e9, the author stated that the spectrogram is a spectro-temporal representation of the sound and show some of the steps of converting wav file to spectogram.

One of the example could be as below:

## Check the sampling rate of the WAV file.
audio_file = './siren_mfcc_demo.wav'

import wave
with wave.open(audio_file, "rb") as wave_file:
    sr = wave_file.getframerate()
print(sr)

audio_binary = tf.read_file(audio_file)

# tf.contrib.ffmpeg not supported on Windows, refer to issue
# https://github.com/tensorflow/tensorflow/issues/8271
waveform = tf.contrib.ffmpeg.decode_audio(audio_binary, file_format='wav', samples_per_second=sr, channel_count=1)
print(waveform.numpy().shape)

signals = tf.reshape(waveform, [1, -1])
signals.get_shape()

# Compute a [batch_size, ?, 128] tensor of fixed length, overlapping windows
# where each window overlaps the previous by 75% (frame_length - frame_step
# samples of overlap).
frames = tf.contrib.signal.frame(signals, frame_length=128, frame_step=32)
print(frames.numpy().shape)

# `magnitude_spectrograms` is a [batch_size, ?, 129] tensor of spectrograms. We
# would like to produce overlapping fixed-size spectrogram patches; for example,
# for use in a situation where a fixed size input is needed.
magnitude_spectrograms = tf.abs(tf.contrib.signal.stft(
    signals, frame_length=256, frame_step=64, fft_length=256))

print(magnitude_spectrograms.numpy().shape)

The method above is referring to https://colab.research.google.com/drive/1Adcy25HYC4c9uSBDK9q5_glR246m-TSx#scrollTo=QTa1BVSOw1Oe

Hope it can help you.


问:
I cant seem to get my flask app to display my Form- flask_wtf
```<code>@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if request.method == 'POST':
        return render_template('contact.html',form=form)
                if form.validate_on_submit():
                      msg=Message(request.form['subject'], sender = request.form['name'],request.form['email'],
                      recepients=[request.form['email']])
                      msg.body='This is the body'
                      mail.send(msg)
                     flash('Message sent successfully')
                return redirect(url_for('/'))

</code>```

Ive been trying to run a simple Flask form in my flask app however it wonbt display the form. Ive been searching around online and I cant seem to find where Im getting the error.
Here is my html code and form.py as well:

```<code>{% extends "base.html" %}
{% block main %}
{% block content %}
<h1>Contact Form</h1>
<p> Fill in this form to contact the site owners</p>
<br>
<form action= "{{url_for('/contact')}", method= "post">

    <div class="form-group">
            <label for="name"> Name</label>
            <input type="text" class="form-control" name="name" id="name"/>
    </div>
    {{form.name.label}}  {{form.name}} <br>
    <br>
   <div class="form-group">
            <label for="email">E-mail</label>
            <input type="email" class="form-control" name="email" id="email" placeholder="jdoe@example.com" />
    </div>
  {{form.email.label}}{{form.email}}<br>
    <div class="form-group">
             <label for="subject">Subject</label>
             <input type="text" class="form-control" name="subject" id="subject"/>
   </div>
  {{form.subject.label}}{{form.subject}}<br>
     <div class="form-group">
       <label for="message">Message</label>
       <input type="text" class="form-control" name="message" id="message"/>
   </div>

  {{form.message.label}}<br>
  {{form.message}}
  {{form.csrf_token}}

<button type ="submit">Send</button>

</form>
{% endblock %}

</code>```

答:
You're rendering the template too early. Try instead:</p>

```<code>@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        msg = Message(request.form['subject'],
                      sender=request.form['name'],
                      request.form['email'],
                      recipients=[request.form['email']])
        msg.body='This is the body'
        mail.send(msg)
        flash('Message sent successfully')
        return redirect(url_for('/'))
    return render_template('contact.html',form=form)
</code>```

Body:
@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if request.method == 'POST':
        return render_template('contact.html',form=form)
                if form.validate_on_submit():
                      msg=Message(request.form['subject'], sender = request.form['name'],request.form['email'],
                      recepients=[request.form['email']])
                      msg.body='This is the body'
                      mail.send(msg)
                     flash('Message sent successfully')
                return redirect(url_for('/'))

Ive been trying to run a simple Flask form in my flask app however it wonbt display the form. Ive been searching around online and I cant seem to find where Im getting the error.
Here is my html code and form.py as well:

{% extends "base.html" %}
{% block main %}
{% block content %}

Contact Form

 Fill in this form to contact the site owners

<form action= "{{url_for('/contact')}", method= "post">

             Name
            <input type="text" class="form-control" name="name" id="name"/>

    {{form.name.label}}  {{form.name}}

            E-mail
            <input type="email" class="form-control" name="email" id="email" placeholder="jdoe@example.com" />

  {{form.email.label}}{{form.email}}

             Subject
             <input type="text" class="form-control" name="subject" id="subject"/>

  {{form.subject.label}}{{form.subject}}

       Message
       <input type="text" class="form-control" name="message" id="message"/>

  {{form.message.label}}

  {{form.message}}
  {{form.csrf_token}}

<button type ="submit">Send</button>

</form>
{% endblock %}

Body:
You're rendering the template too early. Try instead:

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        msg = Message(request.form['subject'],
                      sender=request.form['name'],
                      request.form['email'],
                      recipients=[request.form['email']])
        msg.body='This is the body'
        mail.send(msg)
        flash('Message sent successfully')
        return redirect(url_for('/'))
    return render_template('contact.html',form=form)


问:
Scalable spring scheduler for mongodb fetch
I have mongodb collection named A. In that collection there is date and time field named field1. In my scenario I have to collect records which has  expired date and time based on field1.

I thought of writting spring scheduler Job which runs on every min to fetch date and time expired records from mongodb but when I start writing I could not make spring scheduler as scalable.

In scheduler, convert the record to String and do a message push to Kafka topic. In my case spring scheduler runs on 4 instances and push duplicate messages to Kafka topic.

Question is, In spring scheduler, how can I stop duplicate messages to Kafka topic or how to achieve scalable scheduler with out any duplicate messages?

Any event based framework to support my scenario? Means when the record expired it should immediately notify the java system, ie. Similar to TailableCursorlisteners in spring listens to cappedcollection.

答:
You can use a shedlock library which will ensure that only one job through all instances is running
Here is tutorial for more information:

https://www.baeldung.com/shedlock-spring


问:
MSYS2 Qt-creator examples not showing
I have installed qt-creator on windows 10 using msys2.

I installed packages according to https://wiki.qt.io/MSYS2

base-devel git mercurial cvs wget p7zip

perl ruby python2 mingw-w64-i686-toolchain mingw-w64-x86_64-toolchain

mingw-w64-i686-qt-creator mingw-w64-x86_64-qt-creator

I had previously installed qt from the official site but the mingw version is too old and I'd rather not have two mingw versions installed.

I have existing C:\msys64\mingw64\share\qt5\examples folder but it seems there are some folders missing from C:\msys64\mingw64\share\qt5\doc compared to the official install. Maybe that has something to do with it.

So the question: Is there a specific package I need to install so that the examples show up in the qt-creator examples page or something else?

答:
The qt-creator in msys2 distribution do not have examples installed. The msys2 also do not have separate package for it.

But as what @user3930978 found. You can use example package from archlinux site for workaround.

But unfortunately, msys2 qt5 configured with "-nomake examples" parameter. You need  to modify generated file. The easiest way is still to install qt5 and creator with official full pack.

Title: MSYS2 Qt-creator examples not showing


问:
Which IP address goes in proxy_pass when configuring NGINX
Which IP address goes in the location proxy_pass in the NGINX configuration file nginx.conf?  Is it public IP address of the server?

```<code>http {
  ...
  location /api/ {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://<which ip address goes in here?>:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}
</code>```

答: It doesn't have to be public but your nginx has to be able to resolve it. It can be a private network IP address or 127.0.0.1 if your back-end runs on the same machine.

Body:
Which IP address goes in the location proxy_pass in the NGINX configuration file nginx.conf?  Is it public IP address of the server?

http {
  ...
  location /api/ {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://<which ip address goes in here?>:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}


问:
Rendering video in game engine with dynamic FPS
I'm trying to render a pre-exported video in my game engine and have stumbled upon problems when trying to schedule frames. Namely, while the video is exported at fixed FPS, the engine has a dynamic frame rate (which may be higher or lower than the video's). When trying to choose which video frame to render in the current engine frame, my algorithms keep running into edge cases which ruins either the speed of the video or the distribution of the video frames.

I'm aware at this point that there is probably no algorithm which will run perfectly in all situations, but there are three situations which are likely to happen during the runtime and should be covered by the algorithm:

Arbitrary stable frame rate in the engine, with a ~5% margin of error. (For example, if average frame time is 33.333ms, all of the frame durations would fall within the 31.6666ms - 35ms range.)

Arbitrary semi-stable frame rate, with <5% of the frames having a duration outside the margin of error.

Stable frame rate which can change to a different stable frame rate during the video playback.

During these 3 situations, the following should hold true:

When observing over arbitrary period of time, speed at which the video renders is the same as the speed at which video would render at its original FPS.

When observing over arbitrary period of time, during which engine had a stable frame rate, frame distribution should be balanced.

Having all this in mind, I've tried 2 solutions which didn't yield good results even with a couple of heuristics.

A really naive solution in which delta time of the current frame is multiplied by the frame rate, the result is rounded and video playback is advanced by that many frames. While this solution works perfectly at some frame rates, the speed difference is too high at others. For example, if the video is at 60FPS and engine renders at 30FPS, every engine frame will advance the video playback by 2 frames, which is perfect. However, even at ~39 FPS, due to the rounding effect, the playback will still only be advanced by 2 frames in each engine frame, resulting in the decreased speed of the video.

A timeline-based solution where we keep track of the accumulated duration of all previous engine frames. Summing that and the duration of the current engine frame, then rounding it to the nearest multiple of the video frame duration, we get the approximate video frame which should be rendered in the engine. This solution balances the video speed perfectly, but there's many edge cases where the frame distribution becomes very unbalanced, leading to stuttering in the video. Using the same example as earlier, with video at 60FPS and engine at 30FPS, there's an edge case where one frame with duration of ~41.66666ms will lead to the situation where the video frames are advanced as (1, 3, 1, 3, 1, 3....) instead of (2, 2, 2, 2, 2, 2...).

I guess my questions are: Is there a problem with known algorithms and heuristics which could be reduced to this one? If not, is there a nice heuristic which would yield better results in the 3 situations I've described above?

答:
You could take your second approach and apply some simple smoothing, e.g. advance your frame by the average of the last two values, always rounding down and propagating error forward, i.e. when the sum is an odd number and you round down to get an integer you add 1 to the next sum to balance it out.

So 1, 3, 1, 3, 1, 3... would produce 2, 2, 2, 2, 2... and 2, 3, 2, 3, 2, 3 would produce 2, 3, 2, 3, 2... etc

pseudo-code:

```<code>int prevValue = 0
int error = 0;
bool firstValue = true;
int getNextValue(int value)
{
    if(firstValue)
    {
        prevValue = value;
        firstValue = false;
    }
    int sum = value + prevValue + error;
    error = sum % 2;
    prevValue = value;
    return sum / 2; // integer division
}
</code>```

Body:
You could take your second approach and apply some simple smoothing, e.g. advance your frame by the average of the last two values, always rounding down and propagating error forward, i.e. when the sum is an odd number and you round down to get an integer you add 1 to the next sum to balance it out.

So 1, 3, 1, 3, 1, 3... would produce 2, 2, 2, 2, 2... and 2, 3, 2, 3, 2, 3 would produce 2, 3, 2, 3, 2... etc

pseudo-code:

int prevValue = 0
int error = 0;
bool firstValue = true;
int getNextValue(int value)
{
    if(firstValue)
    {
        prevValue = value;
        firstValue = false;
    }
    int sum = value + prevValue + error;
    error = sum % 2;
    prevValue = value;
    return sum / 2; // integer division
}


问:
Spring MVC - Thymeleaf th:action th:object
I am using Spring MVC and Thymeleaf.
My template looks like this at the form tag:

```<code><form method="post" class="from-group">
</form>
</code>```

It's works, but without th:action th:object.
I liked this so much (very simple), but I did not find any explanation about this.

How does it work without th:action and th:object?

答: when you click submit button it will redirect to the current page you are on if you don't include th:action. eg: if th:action="home", it will redirect you to ../home  when you submit the form. th:object is sort of what kind of object you want to response. eg: an object called 'person', which it has Name, Sex, DOB, ect. You do not need to use it.

Body:
I am using Spring MVC and Thymeleaf.
My template looks like this at the form tag:

<form method="post" class="from-group">
</form>

It's works, but without th:action th:object.
I liked this so much (very simple), but I did not find any explanation about this.

How does it work without th:action and th:object?


问:
Recursion for my code doesn't seem to work even though I am returning everything
I am making code to check if a number is a prime or not, but I want the argument to be both list and integer. For that I'm using recursion but the recursion doesn't seem to work.</p>

```<code> def prime_checker(suspected_prime):
    if type(suspected_prime) == type(list()):
        result_list = list()
        for x in range(len(suspected_prime)):
            result_list.append(prime_checker(suspected_prime[x]))
        return(result_list)
    else:
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1
</code>```

答:
Currently you have :

```<code>def prime-checker (input could be scalar or a list)
</code>```

Strategy 1 : (Remove the looping inside prime-checker, always deal with a scalar, i.e. non-list). so you have :

```<code>def prime_checker (scalar, ie. non-list input arg) :
</code>```

To handle this, change your implementation to always handle a scalar.  Do your looping externally, outside the prime-checker function. With this your prime-checker will only have the math calculation part, so it will be simpler and easier to understand.

Strategy 2:
Alternately, if you insist on keeping the list looping inside prime-checker.

Case 1 : if your input is just a number , say 45. Then send the input arg as [45]
So , the external invocation of prime-checker (from the external caller) would become

```<code>results = prime_checker( [45])
</code>```

Case 2: If your input is a list, say list1, then your invocation is

```<code>results = prime_checker (list1).
</code>```

So, now your implementation always expects and deals with a list.

```<code># we always get input as a list (hence I changed the arg name)
 def prime_checker(suspected_list):
    # this branch *looks* recursive, but actually only handles a list
    if (len(suspected_list) > 1) :
        result_list = []
        for prime_candidate in suspected_list:
            result_list.append(prime_checker([prime_candidate]) # recur, as a list
        return(result_list)
    else: (when suspected list has only 1 entry)
        # this branch does the actual prime calculation for a single input
        suspected_prime = suspected_list[0]
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1
</code>```

Body:
I am making code to check if a number is a prime or not, but I want the argument to be both list and integer. For that I'm using recursion but the recursion doesn't seem to work.

 def prime_checker(suspected_prime):
    if type(suspected_prime) == type(list()):
        result_list = list()
        for x in range(len(suspected_prime)):
            result_list.append(prime_checker(suspected_prime[x]))
        return(result_list)
    else:
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1

Body:
Currently you have :

def prime-checker (input could be scalar or a list)

Strategy 1 : (Remove the looping inside prime-checker, always deal with a scalar, i.e. non-list). so you have :

def prime_checker (scalar, ie. non-list input arg) :

To handle this, change your implementation to always handle a scalar.  Do your looping externally, outside the prime-checker function. With this your prime-checker will only have the math calculation part, so it will be simpler and easier to understand.

Strategy 2:
Alternately, if you insist on keeping the list looping inside prime-checker.

Case 1 : if your input is just a number , say 45. Then send the input arg as [45]
So , the external invocation of prime-checker (from the external caller) would become

results = prime_checker( [45])

Case 2: If your input is a list, say list1, then your invocation is

results = prime_checker (list1).

So, now your implementation always expects and deals with a list.

# we always get input as a list (hence I changed the arg name)
 def prime_checker(suspected_list):
    # this branch *looks* recursive, but actually only handles a list
    if (len(suspected_list) > 1) :
        result_list = []
        for prime_candidate in suspected_list:
            result_list.append(prime_checker([prime_candidate]) # recur, as a list
        return(result_list)
    else: (when suspected list has only 1 entry)
        # this branch does the actual prime calculation for a single input
        suspected_prime = suspected_list[0]
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1


问:
Bash redirect not appearing unless using append?
Why does the following work when using >> but not with >?

GNU bash, version 4.4.12

答: The reason you're seeing this happen is because the shell will start by setting up the redirection, and when you use >, it will clear the file that you're redirecting to. So in this case, the first thing that happens is the test file gets cleared. Then, it runs the commands. So now that test is an empty file, cat test will be empty as well and so tr will receive an empty input from the pipe, and thus nothing will be redirected to the file.