问:
Python, Scrapy, Selenium - Fill out a form
I have a page where I click on the text "Neu hier? Jetzt registrieren". Then a text box and a button will appear. How can I eliminate the error?

He does not find either the text box or the button.

HTML-Part:

```<code><form method="post" action="./index.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="aspnetForm">
<input type="text" class="email w_200" name="Email" value="" autocomplete="on" tabindex="1" />
<input type="button" class="submit bu" style="width: 197px" tabindex="4" value="Registrieren"/>
</form>
</code>```

Result from the code below:

```<code>start!ready!you are here!
</code>```

The source:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import scrapy
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from scrapy.http import Request
#https://github.com/mozilla/geckodriver/releases
class northshoreSpider(scrapy.Spider):
    name = 'xxx'
    allowed_domains = ['mypage.de']
    start_urls = ['http://mypage.de']

    def __init__(self, category='', **kwargs):
        print('start!')
        options = Options()
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        super().__init__(**kwargs)

        self.driver = webdriver.Chrome(executable_path='/home/chef/Desktop/chromedriver', chrome_options=options)

    def parse(self,response):
        self.driver.get('http://mypage.de')
        try:
            next = self.driver.find_elements_by_xpath("//*[contains(text(), 'Neu hier? Jetzt registrieren')]")[0]
            url = 'http://mypage.de'
            yield Request(url,callback=self.parse2)
            next.click()
        except Exception as e:
            print('error2!' +  str(e))
        self.driver.close()
        print('ready!')

    def parse2(self,response):
        name="Email"
        print('you are here!')
        formdata = {'name': 'mailfrom@gmx.de'}
        yield FormRequest.from_response(response,
                                formnumber=0,
                                formdata=formdata,
                                clickdata={'value': 'Registrieren'},
                                callback=self.parse3)

    def parse3(self,response):
        print("doneTestRegistration")
</code>```

答: I was looking at the documentation here https://docs.scrapy.org/en/latest/topics/request-response.html#formrequest-objects and notice that you're passing a formnumber inside your parse2 function. If this is the first form on the page, then it should be formnumber=0 or you can leave it out as the default is zero.

Body:
I have a page where I click on the text "Neu hier? Jetzt registrieren". Then a text box and a button will appear. How can I eliminate the error?

He does not find either the text box or the button.

HTML-Part:

<form method="post" action="./index.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="aspnetForm">
<input type="text" class="email w_200" name="Email" value="" autocomplete="on" tabindex="1" />
<input type="button" class="submit bu" style="width: 197px" tabindex="4" value="Registrieren"/>
</form>

Result from the code below:

start!ready!you are here!

The source:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import scrapy
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from scrapy.http import Request
#https://github.com/mozilla/geckodriver/releases
class northshoreSpider(scrapy.Spider):
    name = 'xxx'
    allowed_domains = ['mypage.de']
    start_urls = ['http://mypage.de']

    def __init__(self, category='', **kwargs):
        print('start!')
        options = Options()
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        super().__init__(**kwargs)

        self.driver = webdriver.Chrome(executable_path='/home/chef/Desktop/chromedriver', chrome_options=options)

    def parse(self,response):
        self.driver.get('http://mypage.de')
        try:
            next = self.driver.find_elements_by_xpath("//*[contains(text(), 'Neu hier? Jetzt registrieren')]")[0]
            url = 'http://mypage.de'
            yield Request(url,callback=self.parse2)
            next.click()
        except Exception as e:
            print('error2!' +  str(e))
        self.driver.close()
        print('ready!')

    def parse2(self,response):
        name="Email"
        print('you are here!')
        formdata = {'name': 'mailfrom@gmx.de'}
        yield FormRequest.from_response(response,
                                formnumber=0,
                                formdata=formdata,
                                clickdata={'value': 'Registrieren'},
                                callback=self.parse3)

    def parse3(self,response):
        print("doneTestRegistration")


来源: stackexchange

问:
Found a cell with a particular value, how to reference that cell to search the entire column for another value
I am trying to write a program in excel where the user inputs a value, it searches the other worksheets for that value, finds the columns with that value, searches the rows of that column for dates that are later than today's date, and returns a the contents of column 1 of the rows with values later than today's date.

So far I've been able to find the cells with the input value, but I'm stuck with how to reference the column of the found cells to have the entire column searched for the date.

Below is what I have so far, and I think I should enter after "If Worksheets(i).Cells(2, j).Value = Method Then" another If statement: "If Worksheets(i).Cells(?, ?).Value >=Today() Then", but I'm not sure how to reference the cells I would like to search since those are contingent on where they are found in the previous statement.

```<code>Private Sub CommandButton1_Click()

totalsheets = Worksheets.Count
Method = Worksheets("Search a Method").Cells(3, 6).Value

For i = 1 To totalsheets
    If Worksheets(i).Name <> "Search a Method" Then

    lastcolumn = Worksheets(i).Cells(2, Columns.Count).End(xlToLeft).Column

    For j = 2 To lastcolumn
        If Worksheets(i).Cells(2, j).Value = Method Then

        Worksheets("Search a Method").Activate

        lastrow = Worksheets("Search a Method").Cells(Rows.Count, 1).End(xlUp).Row
        Worksheets("Search a Method").Cells(lastrow + 1, 1).Value = Worksheets(i).Name

        End If
    Next
    End If
Next

End Sub
</code>```

答:
Will build on my suggestion about using .Find(), the below example should give some guidance:

```<code>Dim findrng As Range, col As Long, method As String
method = "dog"
With Sheets(1)
    Set findrng = .Rows(2).Find(what:=method, LookIn:=xlValues, LookAt:=xlPart, searchorder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
End With
col = findrng.Column
Debug.Print col
</code>```

I put "cat" in cells(2,2) and "dog" in cells(2,3), so with the above code, the immediate window reads "3", indicative of the column method was found.

Image of the above:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a program in excel where the user inputs a value, it searches the other worksheets for that value, finds the columns with that value, searches the rows of that column for dates that are later than today's date, and returns a the contents of column 1 of the rows with values later than today's date.

So far I've been able to find the cells with the input value, but I'm stuck with how to reference the column of the found cells to have the entire column searched for the date.

Below is what I have so far, and I think I should enter after "If Worksheets(i).Cells(2, j).Value = Method Then" another If statement: "If Worksheets(i).Cells(?, ?).Value >=Today() Then", but I'm not sure how to reference the cells I would like to search since those are contingent on where they are found in the previous statement.

Private Sub CommandButton1_Click()

totalsheets = Worksheets.Count
Method = Worksheets("Search a Method").Cells(3, 6).Value

For i = 1 To totalsheets
    If Worksheets(i).Name <> "Search a Method" Then

    lastcolumn = Worksheets(i).Cells(2, Columns.Count).End(xlToLeft).Column

    For j = 2 To lastcolumn
        If Worksheets(i).Cells(2, j).Value = Method Then

        Worksheets("Search a Method").Activate

        lastrow = Worksheets("Search a Method").Cells(Rows.Count, 1).End(xlUp).Row
        Worksheets("Search a Method").Cells(lastrow + 1, 1).Value = Worksheets(i).Name

        End If
    Next
    End If
Next

End Sub

Body:
Will build on my suggestion about using .Find(), the below example should give some guidance:

Dim findrng As Range, col As Long, method As String
method = "dog"
With Sheets(1)
    Set findrng = .Rows(2).Find(what:=method, LookIn:=xlValues, LookAt:=xlPart, searchorder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
End With
col = findrng.Column
Debug.Print col

I put "cat" in cells(2,2) and "dog" in cells(2,3), so with the above code, the immediate window reads "3", indicative of the column method was found.

Image of the above:


问:
how to enable php pdo driver for Postgres on Ubuntu 18.04
I installed php 7.2 and php 7.3 on Ubuntu 18.04, and created a php file to log on to and insert data into the Postgres database.  My script responded  "could not find driver."

Research turned up that I have to edit the php.ini files and enable the extensions for Postgres and PDO.  Below are all the extension= lines in the php.ini files.  The closest I could find are the pdo lines shown below.

```<code>extension=pdo_pgsql
extension=pgsql
</code>```

So I edited the php.ini files and removed the semi-colons from each of those lines to enable them.  Then I restarted Apache2:

```<code>sudo systemctl restart apache2
</code>```

But I still get "could not find driver."

This is the entire listing of extensions from the php.ini files.  Which other extensions do I need to enable to allow PDO access to Postgres?

php.ini 7.3

```<code>;extension=bz2
;extension=curl
;extension=fileinfo
;extension=gd2
;extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
;extension=ldap
;extension=mbstring
;extension=exif      ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
;extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
extension=pdo_pgsql
;extension=pdo_sqlite
extension=pgsql
;extension=shmop
</code>```

php.ini 7.2

```<code>;extension=bz2
;extension=curl
;extension=fileinfo
;extension=gd2
;extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
;extension=ldap
;extension=mbstring
;extension=exif      ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
;extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
extension=pdo_pgsql
;extension=pdo_sqlite
extension=pgsql
;extension=shmop
</code>```

This is the php logon script (the logon credentials are replaced with dummy values here because I can't reveal them):

```<code><?php

$params = [
    'host' => '[IP Address]',
    'user' => '[username]',
    'pwd' => '[password]',
    'db' => '[dbname]'
];

$dsn = sprintf('pgsql:host=%s;dbname=%s;user=%s;password=%s',
    $params['host'],
    $params['db'],
    $params['user'],
    $params['pwd']);

try {
    $dsn = sprintf('pgsql:host=%s;dbname=%s;unix_socket=%s',
        $params['host'], $params['db'], $params['sock']);
    $opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
    $pdo = new PDO($dsn, $params['user'], $params['pwd'], $opts);
} catch (PDOException $e) {
    echo $e->getMessage();
} catch (Throwable $e) {
    echo $e->getMessage();
}

?>
</code>```

Then I edited the two .ini files and added ".so" at the end of each of the two lines and restarted Apache2, but I still get the same error message.

Thanks for any ideas.

答:
I think you're missing the php-pgsql library, run the following commands and it should start working (keep the changes for the php.ini files):

```<code>sudo apt install php-pgsql
sudo service apache2 reload
</code>```

I do not have Ubuntu which means the library names could be different.

Hope it helps

Body:
I installed php 7.2 and php 7.3 on Ubuntu 18.04, and created a php file to log on to and insert data into the Postgres database.  My script responded  "could not find driver."

Research turned up that I have to edit the php.ini files and enable the extensions for Postgres and PDO.  Below are all the extension= lines in the php.ini files.  The closest I could find are the pdo lines shown below.

extension=pdo_pgsql
extension=pgsql

So I edited the php.ini files and removed the semi-colons from each of those lines to enable them.  Then I restarted Apache2:

sudo systemctl restart apache2

But I still get "could not find driver."

This is the entire listing of extensions from the php.ini files.  Which other extensions do I need to enable to allow PDO access to Postgres?

php.ini 7.3

;extension=bz2
;extension=curl
;extension=fileinfo
;extension=gd2
;extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
;extension=ldap
;extension=mbstring
;extension=exif      ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
;extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
extension=pdo_pgsql
;extension=pdo_sqlite
extension=pgsql
;extension=shmop

php.ini 7.2

;extension=bz2
;extension=curl
;extension=fileinfo
;extension=gd2
;extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
;extension=ldap
;extension=mbstring
;extension=exif      ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
;extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
extension=pdo_pgsql
;extension=pdo_sqlite
extension=pgsql
;extension=shmop

This is the php logon script (the logon credentials are replaced with dummy values here because I can't reveal them):

<?php

$params = [
    'host' => '[IP Address]',
    'user' => '[username]',
    'pwd' => '[password]',
    'db' => '[dbname]'
];

$dsn = sprintf('pgsql:host=%s;dbname=%s;user=%s;password=%s',
    $params['host'],
    $params['db'],
    $params['user'],
    $params['pwd']);

try {
    $dsn = sprintf('pgsql:host=%s;dbname=%s;unix_socket=%s',
        $params['host'], $params['db'], $params['sock']);
    $opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
    $pdo = new PDO($dsn, $params['user'], $params['pwd'], $opts);
} catch (PDOException $e) {
    echo $e->getMessage();
} catch (Throwable $e) {
    echo $e->getMessage();
}

?>

Then I edited the two .ini files and added ".so" at the end of each of the two lines and restarted Apache2, but I still get the same error message.

Thanks for any ideas.

Body:
I think you're missing the php-pgsql library, run the following commands and it should start working (keep the changes for the php.ini files):

sudo apt install php-pgsql
sudo service apache2 reload

I do not have Ubuntu which means the library names could be different.

Hope it helps


问:
Event toggle listener
I'm trying to change some styles with the ui.activeFilter() method but it says:

Cannot read property toggle of undefined.

And I set the variable filterLinks to global scope. I can't figure why it's not working.

```<code>"use strict";

// UI elements
const filterLinks = document.querySelectorAll('a');
const itemsLeft = document.querySelectorAll('span');

// Event listeners
filterLinks.forEach(function(link) {
  link.addEventListener('click', check);
});

// Laptops
class Laptop {
    constructor(availability, price, brand) {
      this.availability = availability;
      this.price = price;
      this.brand = brand;
    }
}

// Filter methods
class UiMethod {
    activeFilter(dddd) {
        dddd.classList.toggle('checked');

        if(dddd.className === 'checked') {
            console.log("test");
        } else {
            console.log('Try again you can do it, you are close to the succes');
        }
    }
}

const ui = new UiMethod;

// Function helpers
function check(e) {

    ui.activeFilter(filterLinks);
    e.preventDefault();
}
</code>```

答:
Simple solution, your check(e) function needs a slight update. Instead of passing the entire object, you just need to pass the e.target of the click function to only affect that object.

change:
ui.activeFilter(filterLinks);

to:
 ui.activeFilter(e.target);

"use strict";

// UI elements
const filterLinks = document.querySelectorAll('a');

// Event listeners
filterLinks.forEach(function(link) {
  link.addEventListener('click', check);
});

// Laptops
class Laptop {
    constructor(availability, price, brand) {
      this.availability = availability;
      this.price = price;
      this.brand = brand;
    }
}

// Filter methods
class UiMethod {
    activeFilter(dddd) {
        dddd.classList.toggle('checked');

        if(dddd.className === 'checked') {
            console.log("test");
        } else {
            console.log('Try again you can do it, you are close to the succes');
        }
    }
}

const ui = new UiMethod;

// Function helpers
function check(e) {
    ui.activeFilter(e.target);
    e.preventDefault();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.checked{
color:red;
}</code>```

test

test2

test3```

Title: Event toggle listener

Body:
I'm trying to change some styles with the ui.activeFilter() method but it says:

Cannot read property toggle of undefined.

And I set the variable filterLinks to global scope. I can't figure why it's not working.

"use strict";

// UI elements
const filterLinks = document.querySelectorAll('a');
const itemsLeft = document.querySelectorAll('span');

// Event listeners
filterLinks.forEach(function(link) {
  link.addEventListener('click', check);
});

// Laptops
class Laptop {
    constructor(availability, price, brand) {
      this.availability = availability;
      this.price = price;
      this.brand = brand;
    }
}

// Filter methods
class UiMethod {
    activeFilter(dddd) {
        dddd.classList.toggle('checked');

        if(dddd.className === 'checked') {
            console.log("test");
        } else {
            console.log('Try again you can do it, you are close to the succes');
        }
    }
}

const ui = new UiMethod;

// Function helpers
function check(e) {

    ui.activeFilter(filterLinks);
    e.preventDefault();
}

Body:
Simple solution, your check(e) function needs a slight update. Instead of passing the entire object, you just need to pass the e.target of the click function to only affect that object.

change:
ui.activeFilter(filterLinks);

to:
 ui.activeFilter(e.target);

"use strict";

// UI elements
const filterLinks = document.querySelectorAll('a');

// Event listeners
filterLinks.forEach(function(link) {
  link.addEventListener('click', check);
});

// Laptops
class Laptop {
    constructor(availability, price, brand) {
      this.availability = availability;
      this.price = price;
      this.brand = brand;
    }
}

// Filter methods
class UiMethod {
    activeFilter(dddd) {
        dddd.classList.toggle('checked');

        if(dddd.className === 'checked') {
            console.log("test");
        } else {
            console.log('Try again you can do it, you are close to the succes');
        }
    }
}

const ui = new UiMethod;

// Function helpers
function check(e) {
    ui.activeFilter(e.target);
    e.preventDefault();
}

.checked{
color:red;
}

<a href="#">test</a><BR>
<a href="#">test2</a><BR>
<a href="#">test3</a>


问:
How to make inherited abstract method from parent abstract for own children?
I want to pass abstraction of a method down from the first parent to the children of the children of that parent.
The body of this method is empty but I want to force both the children of this class and the children of the children class to implement exactly this method.

I've tried finding similar questions but have failed. This might be due to me not understanding the use of "abstract" correctly. In this case, I apologise.

Here is an example in code:

```<code>    public abstract class A
    {
        public abstract void ImportantMethod();
    }

    public abstract class B : A
    {
        public override void ImportantMethod()
        {
            // now this method will still not be used but MUST be implemented in child classes of this class
        }
    }

    public class C : B
    {
        // I can override this method, but it is not enforced - and that is what I am after.
        public override void ImportantMethod()
        {

        }
    }
</code>```

It is obviously possible that I am using abstraction the wrong way and that there is a specific way to do this, but I would like to know what that is and why as I am a new programmer.

答:
The word abstract means that at least one of the inheriting classes must implement this method.

If B does implement it, you have no way to force C to do so.

If B does not implement it, B must be declared abstract and the implementation will be left to B inheritors.

Body:
I want to pass abstraction of a method down from the first parent to the children of the children of that parent.
The body of this method is empty but I want to force both the children of this class and the children of the children class to implement exactly this method.

I've tried finding similar questions but have failed. This might be due to me not understanding the use of "abstract" correctly. In this case, I apologise.

Here is an example in code:

    public abstract class A
    {
        public abstract void ImportantMethod();
    }

    public abstract class B : A
    {
        public override void ImportantMethod()
        {
            // now this method will still not be used but MUST be implemented in child classes of this class
        }
    }

    public class C : B
    {
        // I can override this method, but it is not enforced - and that is what I am after.
        public override void ImportantMethod()
        {

        }
    }

It is obviously possible that I am using abstraction the wrong way and that there is a specific way to do this, but I would like to know what that is and why as I am a new programmer.


问:
Use a String as a conditional in java (Convert String to boolean)
I am new here!

I am doing a school project where I take a .csv file as input and read every line of values and store them into a String[], and then create an ArrayList.

The CSV file has some temperature measurements and I'm required to make filters for the different temperature measurements. What I want to know if there is a way to make the condition of an if statement the value of a string.

Since there are different ways to filter the information (>,<,>=,<=, from int x to int y) I want to create a method that concatenates a string that creates the condition the user is looking for;

Prompts user to choose what data from the array he wants to filter by.

(For instance option 3, which means its the data stored in String[2])

Then asks the user to choose how he wants to filter: >,<,>=,<=, from int x to int y.

Finally asks the remaining value to finish the comparison.

From these prompts we could build:

String a = String[2] + (comparison operator) + comparison value.

For example a = String[2] + " > 20"

Then I want to use the 'a' like this:  if(a){}

Where the console should read this as: - - - - - - -  if(Double.valueOf(String[2]) > 20){}

My IDE is BlueJ which tells me incompatible types: java.lang.String cannot be converted to boolean.
You may wonder why I use a String[] if I'm comparing double values,

Thanks in advance and my apologies if my idea is preposterous or not clear.

答:
If you want to evaluate conditions from Strings you could use something like this:</p>

```<code>public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {
            Boolean eval = (Boolean) engine.eval("40 > 10");
            assert(eval);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
If you want to evaluate conditions from Strings you could use something like this:

public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {
            Boolean eval = (Boolean) engine.eval("40 > 10");
            assert(eval);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }


问:
Ruby On Rails, SQL and SQL parameters
I have complex SQL query. I need safely to pass parameters to SQL query. How can I avoid sql injections without using activerecord? Where should I keep SQL models/controllers? Does anyone know good practice to work with SQL server without activerecord?</p>

答:
When you bypass ActiveRecord you pretty much have to do everything manually.  I assume you have good reasons for doing so.

ActiveRecord::Base has the following methods: sanitize_sql_for_assignments (for set) and sanitize_sql_for_conditions (for select).  There are a few other sanitize_sql_* that are probably worth looking at too.  Both accept a hash (uses the keys as column names) or a string.

I could be mistaken, but to fetch records and skip ActiveRecord, I think you use ActiveRecord::Base.connection.execute(sql) which should return objects from your database connector.  Checks the docs for the connector to see what is returned and how to work with it.

As for best practices, sorry, I can't help you there :-)

ContentLicense: CC BY-SA 3.0

Title: Ruby On Rails, SQL and SQL parameters


问:
assign variables to argparse not through command line
I am trying to write tests (using pytest) for a script, but I don't know how to create/pass arguments to main(), especially when it doesn't recieve arguments. and even if I change it to def main(args = None): then it'll initiate it on the first line.

tests.py

```<code>def test_main(capfd):
    main()
    out, err = capfd.readouterr()
    assert out == "my expected output"
</code>```

script.py

```<code>def init_parser():
    parser = argparse.ArgumentParser(description="The script searches one or \
                                     more named input files for lines \
                                     containing a match to a regular \
                                     expression pattern.")
    parser.add_argument('regex', help='the regular expression.')
    parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default=[sys.stdin],
                        help='the name of the file(s) to search.')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-u', '--underscore', action='store_true', help='prints \
                       "^" under the matching text.')
    group.add_argument('-c', '--color', action='store_true', help='highlights \
                       matching text.')
    group.add_argument('-m', '--machine', action='store_true', help='generates \
                       machine readable output.')

    return parser

def main():
    args = init_parser().parse_args()
    for file in args.infile:
        for i, line in enumerate(iter(file.readline, '')):
            for substring in re.finditer(args.regex, line):
                    if args.underscore:
                        underscore_output(file.name, i + 1, line[:-1],
                                          substring.start(), substring.end())
                    elif args.color:
                        color_output(file.name, i + 1, line[:-1],
                                     substring.group())
                    elif args.machine:
                        machine_output(file.name, i + 1, substring.start(),
                                       substring.group())
                    else:
                        print_line(file.name, i + 1, line[:-1])```
```

答:
In the test code, you would patch out sys.argv before calling main:

```<code>def test_main(monkeypatch):
    monkeypatch.setattr("sys.argv", ["script.py", "test_regex", "test_infile"])
    main()
    # put your assertions here
</code>```

Body:
I am trying to write tests (using pytest) for a script, but I don't know how to create/pass arguments to main(), especially when it doesn't recieve arguments. and even if I change it to def main(args = None): then it'll initiate it on the first line.

tests.py

def test_main(capfd):
    main()
    out, err = capfd.readouterr()
    assert out == "my expected output"

script.py

def init_parser():
    parser = argparse.ArgumentParser(description="The script searches one or \
                                     more named input files for lines \
                                     containing a match to a regular \
                                     expression pattern.")
    parser.add_argument('regex', help='the regular expression.')
    parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default=[sys.stdin],
                        help='the name of the file(s) to search.')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-u', '--underscore', action='store_true', help='prints \
                       "^" under the matching text.')
    group.add_argument('-c', '--color', action='store_true', help='highlights \
                       matching text.')
    group.add_argument('-m', '--machine', action='store_true', help='generates \
                       machine readable output.')

    return parser

def main():
    args = init_parser().parse_args()
    for file in args.infile:
        for i, line in enumerate(iter(file.readline, '')):
            for substring in re.finditer(args.regex, line):
                    if args.underscore:
                        underscore_output(file.name, i + 1, line[:-1],
                                          substring.start(), substring.end())
                    elif args.color:
                        color_output(file.name, i + 1, line[:-1],
                                     substring.group())
                    elif args.machine:
                        machine_output(file.name, i + 1, substring.start(),
                                       substring.group())
                    else:
                        print_line(file.name, i + 1, line[:-1])```

Body:
In the test code, you would patch out sys.argv before calling main:

def test_main(monkeypatch):
    monkeypatch.setattr("sys.argv", ["script.py", "test_regex", "test_infile"])
    main()
    # put your assertions here


问:
Libre Office Base Query
I'm running a Libre Office Base database to manage my co-op's membership directory.  I'm trying to write a query to get a count of current membership, but I keep running into a SQL Status 37000, error code -16, Wrong data type: java.lang.IllegalArgumentException in statement [SELECT COUNT(*) FROM "Families" WHERE "Families"."Renewal Date" > '06/30/18'].

My query

```<code>SELECT COUNT(*) FROM "Families" WHERE "Families"."Renewal Date" > '06/30/18'
</code>```

From everything I've seen and read, that query is formatted appropriately and I've checked the table name and column name, repeatedly.

答:
You can use this construction for Date values

{D '2012-01-01'}

```<code>SELECT COUNT(*) FROM "Families" WHERE "Families"."Renewal Date" > {D '2018-06-30'}
</code>```

the format '06/30/18' is ok only for Open Office

Title: Libre Office Base Query

Body:
I'm running a Libre Office Base database to manage my co-op's membership directory.  I'm trying to write a query to get a count of current membership, but I keep running into a SQL Status 37000, error code -16, Wrong data type: java.lang.IllegalArgumentException in statement [SELECT COUNT(*) FROM "Families" WHERE "Families"."Renewal Date" > '06/30/18'].

My query

SELECT COUNT(*) FROM "Families" WHERE "Families"."Renewal Date" > '06/30/18'

From everything I've seen and read, that query is formatted appropriately and I've checked the table name and column name, repeatedly.

Body:
You can use this construction for Date values

{D '2012-01-01'}

SELECT COUNT(*) FROM "Families" WHERE "Families"."Renewal Date" > {D '2018-06-30'}

the format '06/30/18' is ok only for Open Office


答:
Add the following expression to the select list:

, max(INVOICE_SEQ_NUMBER) over (partition by INVOICE_NUMBER) as MAX_INV_SEQ_NUMBER.

Title: How to get max sequence number?

Body:
This is a continuation of my previous post : here

I have this query:

SELECT INVOICE_NUMBER, INVOICE_SEQ_NUMBER, FILE_NUMBER
FROM (SELECT A.INVOICE_NUMBER, A.INVOICE_SEQ_NUMBER, B.FILE_NUMBER,
             DENSE_RANK() OVER (ORDER BY A.INVOICE_NUMBER) as seqnum
      FROM TABLE1 A JOIN
           TABLE2 B
           ON A.INVOICE_NUMBER = B.INVOICE_NUMBER AND
              A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
     ) t
WHERE seqnum <= 3;

And this result:

-----------------------------------------------------
| INVOICE_NUMBER | INVOICE_SEQ_NUMBER | FILE_NUMBER |
------------------------------------------------------
|1111111111-1    |          1         | P4324324525 |
-----------------------------------------------------
|1111111111-1    |          2         | P4565674574 |
-----------------------------------------------------
|1111111111-1    |          3         | V4324552557 |
-----------------------------------------------------
|1111111111-1    |          4         | V4324552525 |
-----------------------------------------------------
|2222222222-2    |          1         | S4563636574 |
-----------------------------------------------------
|3333333333-3    |          1         | Q4324325675 |
-----------------------------------------------------
|3333333333-3    |          2         | Q4565674574 |
-----------------------------------------------------

So the new requirement is how do I get the maximum invoice sequence number for the same invoice number? The result should be like this:

------------------------------------------------------------------------
| INVOICE_NUMBER | INVOICE_SEQ_NUMBER | FILE_NUMBER |MAX_INV_SEQ_NUMBER|
------------------------------------------------------------------------
|1111111111-1    |          1         | P4324324525 |        4         |
------------------------------------------------------------------------
|1111111111-1    |          2         | P4565674574 |        4         |
------------------------------------------------------------------------
|1111111111-1    |          3         | V4324552557 |        4         |
------------------------------------------------------------------------
|1111111111-1    |          4         | V4324552525 |        4         |
------------------------------------------------------------------------
|2222222222-2    |          1         | S4563636574 |        1         |
------------------------------------------------------------------------
|3333333333-3    |          1         | Q4324325675 |        2         |
------------------------------------------------------------------------
|3333333333-3    |          2         | Q4565674574 |        2         |
------------------------------------------------------------------------


问:
Find name, department name and marks of top performer in software engineering
Write a query to display name, department name and marks of the top performer in software engineering.The solution has to be implemented in subqueries.
The expected result shows a single row.

I tried the below code

```<code>   select student_name, department_name,
    mark
   from student s, department d,
   (select max(value)
    from mark
    where subject_id=
                     ( select subject_id
                       from subject sb
                       where lower(subject_name)='software engineering')
    group by student_id
    )m1
    where s.department_id=d.department_id and
          s.student_id=m1.student_id
    order by department_name;
</code>```

But this code gives an error at 12th line of invalid identifier in m1.student_id.

Please Help.

答:
You need to add student_id in subquery:</p>

```<code>select
    student_name, department_name,
    mark
from
    student s, department d,
    (select student_id,max(value)
     from mark
     where subject_id = (select subject_id
                         from subject sb
                         where lower(subject_name)='software engineering')
     group by student_id) m1
where
    s.department_id = d.department_id
    and s.student_id = m1.student_id
order by
    department_name;
</code>```

Body:
Write a query to display name, department name and marks of the top performer in software engineering.The solution has to be implemented in subqueries.
The expected result shows a single row.

I tried the below code

   select student_name, department_name,
    mark
   from student s, department d,
   (select max(value)
    from mark
    where subject_id=
                     ( select subject_id
                       from subject sb
                       where lower(subject_name)='software engineering')
    group by student_id
    )m1
    where s.department_id=d.department_id and
          s.student_id=m1.student_id
    order by department_name;

But this code gives an error at 12th line of invalid identifier in m1.student_id.

Please Help.

Body:
You need to add student_id in subquery:

select
    student_name, department_name,
    mark
from
    student s, department d,
    (select student_id,max(value)
     from mark
     where subject_id = (select subject_id
                         from subject sb
                         where lower(subject_name)='software engineering')
     group by student_id) m1
where
    s.department_id = d.department_id
    and s.student_id = m1.student_id
order by
    department_name;


问:
Display Excel sheet in the Browser?
I need to display the newly generated excel (from tables using Apache POI) in a web browser (whatever it is, Firefox, Opera or IE). I've created the JSP file with

contentType="application/vnd.ms-excel"

But I'm not getting it.

Here's my code snippet :

```<code><%@page session="true" contentType="application/vnd.ms-excel" pageEncoding="UTF-8"%>
<%@page import="org.apache.poi.ss.usermodel.CellStyle"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="org.apache.poi.ss.usermodel.CreationHelper"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>

<html>
    <head>
        <%!
            int r=0;

            HSSFWorkbook book;
            HSSFSheet sheet;
            HSSFRow row;

            CreationHelper createHelper = book.getCreationHelper();

            Connection conn;
            Statement stmt;
            ResultSet rs;
        %>
        <title>Report</title>
        <%
            book = new HSSFWorkbook();
            sheet = book.createSheet("Report");
        %>
    </head>
    <body>
        <%
            try     {

                    // Header of the Excel File
                row = sheet.createRow(r);

                row.createCell(0).setCellValue("Visit ID");
                row.createCell(1).setCellValue("Carrier Name");
                row.createCell(2).setCellValue("Phone Number");
                row.createCell(3).setCellValue("Patient Name");
                row.createCell(4).setCellValue("Subscriber ID");
                row.createCell(5).setCellValue("Subscriber Name");
                row.createCell(6).setCellValue("Chart Number");
                row.createCell(7).setCellValue("Date Of Birth");
                row.createCell(8).setCellValue("Subscriber Employer");
                row.createCell(9).setCellValue("Service Date");
                row.createCell(10).setCellValue("Provider Name");
                row.createCell(11).setCellValue("CPT Code");
                row.createCell(12).setCellValue("Aging Date");
                row.createCell(13).setCellValue("Total");
                row.createCell(14).setCellValue("Follow Up Notes");
                row.createCell(15).setCellValue("Internal Status Code");

                CellStyle cellStyle = book.createCellStyle();
                cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("MM/dd/yyyy"));

                Statement stNotes;
                ResultSet rsNotes;

                Class.forName("com.mysql.jdbc.Driver");

                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/maintain", "root", "root");
                stmt = conn.createStatement();

                stNotes = conn.createStatement();

                rs = stmt.executeQuery("SELECT b.VisitID, b.CarrierName, b.PhoneNum, b.PatientName, "
                        + "b.SubscriberID, b.SubscriberName, b.ChartNum, b.DoB, b.SubscriberEmp, "
                        + "b.ServiceDate, b.ProviderName, b.CPTCode, b.BillingDate, b.BalanceAmt "
                        + "FROM billing b INNER JOIN followup f ON b.VisitID = f.VisitID GROUP BY VisitID");

                while(rs.next())    {
                    r++;

                    row = sheet.createRow(r);

                    row.createCell(0).setCellValue(rs.getString("VisitID"));
                    row.createCell(1).setCellValue(rs.getString("CarrierName"));
                    row.createCell(2).setCellValue(rs.getString("PhoneNum"));
                    row.createCell(3).setCellValue(rs.getString("PatientName"));
                    row.createCell(4).setCellValue(rs.getString("SubscriberID"));
                    row.createCell(5).setCellValue(rs.getString("SubscriberName"));
                    row.createCell(6).setCellValue(rs.getString("ChartNum"));
                    row.createCell(7).setCellValue(rs.getString("DoB"));
                    row.createCell(8).setCellValue(rs.getString("SubscriberEmp"));

                    row.createCell(9).setCellValue(rs.getString("ServiceDate"));
                    row.createCell(9).setCellStyle(cellStyle);

                    row.createCell(10).setCellValue(rs.getString("ProviderName"));
                    row.createCell(11).setCellValue(rs.getString("CPTCode"));

                    row.createCell(12).setCellValue(rs.getString("BillingDate"));
                    row.createCell(12).setCellStyle(cellStyle);

                    row.createCell(13).setCellValue(rs.getString("BalanceAmt"));

                    rsNotes = stNotes.executeQuery("SELECT Date, InternalStatusCode, FollowUpNote "
                            + "FROM followup WHERE VisitID='" + rs.getString("VisitID") + "' ORDER BY Date");

                    while(rsNotes.next())   {
                        row.createCell(14).setCellValue(rsNotes.getString("Date") + " - " + rsNotes.getString("FollowUpNote"));
                        row.createCell(15).setCellValue(rs.getString("VisitID"));
                    }
                }

            }
            catch(ClassNotFoundException cnf) {
                out.print("<br> Error : MySQL Driver not found. <br>");
            }
            catch(Exception ex)  {
                out.print("Error :  <br>" + ex);
            }
        %>
    </body>
</html>
</code>```

I'm getting this exception with Tomcat 6.0.26 :

```<code>exception

org.apache.jasper.JasperException: java.lang.NullPointerException
    org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:156)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

root cause

java.lang.NullPointerException
    org.apache.jsp.GetReport_jsp.<init>(GetReport_jsp.java:29)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    java.lang.Class.newInstance0(Class.java:355)
    java.lang.Class.newInstance(Class.java:308)
    org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:145)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
</code>```

Did I miss something or anything wrong?
Can anybody help me to get rid of this problem?

Thanx in advance.

答: Take a look at WorkbookTag project from SourceForge which does exactly what you need: HTML worksheet rendering using Apache POI... WorkbookTag</p>

ContentLicense: CC BY-SA 2.5

Title: Display Excel sheet in the Browser?

Body:
I need to display the newly generated excel (from tables using Apache POI) in a web browser (whatever it is, Firefox, Opera or IE). I've created the JSP file with

contentType="application/vnd.ms-excel"

But I'm not getting it.

Here's my code snippet :

<%@page session="true" contentType="application/vnd.ms-excel" pageEncoding="UTF-8"%>
<%@page import="org.apache.poi.ss.usermodel.CellStyle"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="org.apache.poi.ss.usermodel.CreationHelper"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>

        <%!
            int r=0;

            HSSFWorkbook book;
            HSSFSheet sheet;
            HSSFRow row;

            CreationHelper createHelper = book.getCreationHelper();

            Connection conn;
            Statement stmt;
            ResultSet rs;
        %>
        <title>Report</title>
        <%
            book = new HSSFWorkbook();
            sheet = book.createSheet("Report");
        %>

        <%
            try     {

                    // Header of the Excel File
                row = sheet.createRow(r);

                row.createCell(0).setCellValue("Visit ID");
                row.createCell(1).setCellValue("Carrier Name");
                row.createCell(2).setCellValue("Phone Number");
                row.createCell(3).setCellValue("Patient Name");
                row.createCell(4).setCellValue("Subscriber ID");
                row.createCell(5).setCellValue("Subscriber Name");
                row.createCell(6).setCellValue("Chart Number");
                row.createCell(7).setCellValue("Date Of Birth");
                row.createCell(8).setCellValue("Subscriber Employer");
                row.createCell(9).setCellValue("Service Date");
                row.createCell(10).setCellValue("Provider Name");
                row.createCell(11).setCellValue("CPT Code");
                row.createCell(12).setCellValue("Aging Date");
                row.createCell(13).setCellValue("Total");
                row.createCell(14).setCellValue("Follow Up Notes");
                row.createCell(15).setCellValue("Internal Status Code");

                CellStyle cellStyle = book.createCellStyle();
                cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("MM/dd/yyyy"));

                Statement stNotes;
                ResultSet rsNotes;

                Class.forName("com.mysql.jdbc.Driver");

                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/maintain", "root", "root");
                stmt = conn.createStatement();

                stNotes = conn.createStatement();

                rs = stmt.executeQuery("SELECT b.VisitID, b.CarrierName, b.PhoneNum, b.PatientName, "
                        + "b.SubscriberID, b.SubscriberName, b.ChartNum, b.DoB, b.SubscriberEmp, "
                        + "b.ServiceDate, b.ProviderName, b.CPTCode, b.BillingDate, b.BalanceAmt "
                        + "FROM billing b INNER JOIN followup f ON b.VisitID = f.VisitID GROUP BY VisitID");

                while(rs.next())    {
                    r++;

                    row = sheet.createRow(r);

                    row.createCell(0).setCellValue(rs.getString("VisitID"));
                    row.createCell(1).setCellValue(rs.getString("CarrierName"));
                    row.createCell(2).setCellValue(rs.getString("PhoneNum"));
                    row.createCell(3).setCellValue(rs.getString("PatientName"));
                    row.createCell(4).setCellValue(rs.getString("SubscriberID"));
                    row.createCell(5).setCellValue(rs.getString("SubscriberName"));
                    row.createCell(6).setCellValue(rs.getString("ChartNum"));
                    row.createCell(7).setCellValue(rs.getString("DoB"));
                    row.createCell(8).setCellValue(rs.getString("SubscriberEmp"));

                    row.createCell(9).setCellValue(rs.getString("ServiceDate"));
                    row.createCell(9).setCellStyle(cellStyle);

                    row.createCell(10).setCellValue(rs.getString("ProviderName"));
                    row.createCell(11).setCellValue(rs.getString("CPTCode"));

                    row.createCell(12).setCellValue(rs.getString("BillingDate"));
                    row.createCell(12).setCellStyle(cellStyle);

                    row.createCell(13).setCellValue(rs.getString("BalanceAmt"));

                    rsNotes = stNotes.executeQuery("SELECT Date, InternalStatusCode, FollowUpNote "
                            + "FROM followup WHERE VisitID='" + rs.getString("VisitID") + "' ORDER BY Date");

                    while(rsNotes.next())   {
                        row.createCell(14).setCellValue(rsNotes.getString("Date") + " - " + rsNotes.getString("FollowUpNote"));
                        row.createCell(15).setCellValue(rs.getString("VisitID"));
                    }
                }

            }
            catch(ClassNotFoundException cnf) {
                out.print("
 Error : MySQL Driver not found.
");
            }
            catch(Exception ex)  {
                out.print("Error :
" + ex);
            }
        %>

I'm getting this exception with Tomcat 6.0.26 :

exception

org.apache.jasper.JasperException: java.lang.NullPointerException
    org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:156)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

root cause

java.lang.NullPointerException
    org.apache.jsp.GetReport_jsp.<init>(GetReport_jsp.java:29)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    java.lang.Class.newInstance0(Class.java:355)
    java.lang.Class.newInstance(Class.java:308)
    org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:145)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

Did I miss something or anything wrong?
Can anybody help me to get rid of this problem?

Thanx in advance.


问:
Content Security Policy nonce does not apply to event handler attributes
I am in the process of adding CSP headers to a site that has a long way to go before it can adopt a strict policy.  There are quite a few inline scripts, so I am using nonce- to allow specific inline scripts.  I have found that it doesn't work on the onload attribute of a script tag with src.  Here's an example:

```<code>// header:
Content-Security-Policy: script-src self https: 'nonce-d3adbe3fed'

<script async defer src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" nonce="d3adbe3fed" onload="console.log('onload', _.VERSION)"></script>
</code>```

Full working demo at https://brave-pasteur-0d438b.netlify.com/

Chrome gives the following error:

```<code>Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src self https: 'nonce-d3adbe3fed'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
</code>```

The message suggests that it should be possible to enable inline event handlers with a nonce, but as far I as I can tell, nonce is only intended to work on inline scripts.

This is just a demo, but the use case is an async/deferred tracking script which loads the tracking library, then in the onload handler makes a tracking call to the loaded library.

Is it possible to use a nonce on an onload or other event handler attribute, or will I need to change my implementation?  Using script-src 'unsafe-inline' or script-src-attr 'unsafe-inline' is not an option, as those are the vulnerabilities I am specifically trying to address. And putting the contents of the onload handler into a separate script following the script tag is also not an option because the script is async deferred, and needs to stay that way.

答:
If there is a way to use nonce on an inline handler, I will accept an answer that demonstrates it.  Unfortunately, at the time of writing, I don't think there is.

As a workaround, the following script exhibits the same behavior and timing as an script with async/defer and an onload handler, while satisfying the specified CSP policy:

```<code><script nonce="d3adbe3fed">
    let s = document.createElement('script');
    s.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js';
    s.onload = () => console.log(_.VERSION);
    document.documentElement.appendChild(s);
</script>
</code>```

Of course, the long term solution is to eliminate inline scripts completely, but in the short term that isn't always feasible, and it is better to implement a more lax policy quickly, than to put it off and have no CSP at all.

Body:
I am in the process of adding CSP headers to a site that has a long way to go before it can adopt a strict policy.  There are quite a few inline scripts, so I am using nonce- to allow specific inline scripts.  I have found that it doesn't work on the onload attribute of a script tag with src.  Here's an example:

// header:
Content-Security-Policy: script-src self https: 'nonce-d3adbe3fed'

Full working demo at https://brave-pasteur-0d438b.netlify.com/

Chrome gives the following error:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src self https: 'nonce-d3adbe3fed'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

The message suggests that it should be possible to enable inline event handlers with a nonce, but as far I as I can tell, nonce is only intended to work on inline scripts.

This is just a demo, but the use case is an async/deferred tracking script which loads the tracking library, then in the onload handler makes a tracking call to the loaded library.

Is it possible to use a nonce on an onload or other event handler attribute, or will I need to change my implementation?  Using script-src 'unsafe-inline' or script-src-attr 'unsafe-inline' is not an option, as those are the vulnerabilities I am specifically trying to address. And putting the contents of the onload handler into a separate script following the script tag is also not an option because the script is async deferred, and needs to stay that way.

Body:
If there is a way to use nonce on an inline handler, I will accept an answer that demonstrates it.  Unfortunately, at the time of writing, I don't think there is.

As a workaround, the following script exhibits the same behavior and timing as an script with async/defer and an onload handler, while satisfying the specified CSP policy:

<script nonce="d3adbe3fed">
    let s = document.createElement('script');
    s.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js';
    s.onload = () => console.log(_.VERSION);
    document.documentElement.appendChild(s);
</script>

Of course, the long term solution is to eliminate inline scripts completely, but in the short term that isn't always feasible, and it is better to implement a more lax policy quickly, than to put it off and have no CSP at all.


问:
building an FCP XML file with python
I'm trying to translate metadata I have on video and audio files into an FCP XML file, that would be readable by most NLEs (though my main target is Premiere Pro). The PP SDK is terribly documented and confusing as hell, and I don't really need to create a panel, but rather to run a python script that would create an XML file that details the necessary bins, the relevant files in each (video and audio) and create some sequences from those files with specific start time (I know the sync point of the seperate audio and video). It's simply XML but I can't find a decent specification of how that XML should look like.

I know this might be kind of a big question for SO, but I really don't know where to start. There's a lot of things about this subject as far as extracting and reading FCP XML files with scripts, but building one is a different animal altogether. The official FCP XML docs don't mention anything about bins and general project hierarchy.

I tried creating my required result in Premiere Pro and then exporting an FCP XML, hoping to reverse engineer it, but it's filled to the brim with confusing information. You can see the whole thing here: https://codebeautify.org/xmlviewer/cb9a1a1f

I can't tell what's needed here, what I can get rid off, and how to rebuild this with a simple python script in a way that Premiere would understand.

What am I to do? I just need a hint of the right direction. I've been banging my head at the wall for so long now. I need some help. Please.

答:
For the python modules I would go with:
"xml.etree.ElementTree" and "re"

check this link for more detailes:
How to convert .txt file into xml file using python?

I would start small. Create a very simple timeline in PP with only 1 track and 2 video clips (no audio).
Export this data to xml and find out how PP builds the timeline as an xml.

In the file you added you can see under the "clipitem" tag there's some metadata which you can change. try changing the duration for example. play around with this until you will get a better understanding of the xml structure.

Then you can start using python's ElementTree to parse the xml elements and replace the data with re.

Its a tedious job and there is no short way about it. In fact if your goal is to build complex timelines using xml edits I really think its an endless task, that's why GUI's are for. but to extract data and maybe building some simple edits, it is worth a try.

I have just finished a small project with BMD Resolve where I had to insert titles with an xml and got good results using this method.

Title: building an FCP XML file with python


问:
How to send notifications by email automatically on a date?
I have a little problem, I don't know how to program a function in .NET MVC to send emails on a date.

For example: Every 25th of each Month send an email to my team partners to remember them update the stock. And the 27th of each Month send and email to his boss to check the stock.

I tried to do this, but i code a function that every time that someone's enter to the WebApp checks the date and if is the 25th sends the email.

The problems:

It sends like thousands of emails, because it is executed every time
when a person is inside the app.

If no ones enter to the app the function can be executed :(

答: Create a Console application put in a windows server and use the window task scheduler to schedule it.</p>


问:
How to Open KML file (from assets folder)
I have a KML file in assets folder. i want to open it into google earth or google map. but none of these worked.
This is what I tried:

For Google Map

```<code>private GoogleMap map;
KmlLayer layer;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_locations);

    try {
        layer = new KmlLayer(map,getAssets().open("locations.kml"),context);
        layer.addLayerToMap();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

for Google earth

```<code>    File KML = null;
    try {
        KML = new File(String.valueOf(getAssets().open("locations.kml")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Intent i =
getPackageManager().getLaunchIntentForPackage("com.google.earth");
    i.setDataAndType(Uri.fromFile(KML), "xml");
    startActivity(i);
</code>```

答:
Create a new project with  Google Map Activity.

Now in the onMapReady() method use retrieveFileFromResource()

```<code>private void retrieveFileFromResource() {
        try {
            KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.kml, getApplicationContext());
            kmlLayer.addLayerToMap();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }
</code>```

3.Full code

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    retrieveFileFromResource();
}

private void retrieveFileFromResource() {
    try {
        KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.kml, getApplicationContext());
        kmlLayer.addLayerToMap();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }
}
}
</code>```

Body:
I have a KML file in assets folder. i want to open it into google earth or google map. but none of these worked.
This is what I tried:

For Google Map

private GoogleMap map;
KmlLayer layer;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_locations);

    try {
        layer = new KmlLayer(map,getAssets().open("locations.kml"),context);
        layer.addLayerToMap();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

for Google earth

    File KML = null;
    try {
        KML = new File(String.valueOf(getAssets().open("locations.kml")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Intent i =
getPackageManager().getLaunchIntentForPackage("com.google.earth");
    i.setDataAndType(Uri.fromFile(KML), "xml");
    startActivity(i);

Body:
Create a new project with  Google Map Activity.

Now in the onMapReady() method use retrieveFileFromResource()

private void retrieveFileFromResource() {
        try {
            KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.kml, getApplicationContext());
            kmlLayer.addLayerToMap();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }

3.Full code

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    retrieveFileFromResource();
}

private void retrieveFileFromResource() {
    try {
        KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.kml, getApplicationContext());
        kmlLayer.addLayerToMap();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }
}
}


问:
Multiple left join using lambda syntax in Entity Framework
I have the following 3 tables

Courses

```<code>Id, SortOrder, CourseName, CourseArea, CourseFor
</code>```

Students

```<code>Id, FullName
</code>```

CourseStudents

```<code>CourseId, StudentId, CollegeId
</code>```

Requirement:

Get all course students from the 'Medical' area for 'foreign' students available in College '125'. Include courses even if there are no students enrolled in it.

Working SQL query:

```<code>SELECT cr.Id, cr.CourseName, st.FullName
FROM dbo.Courses cr
LEFT JOIN dbo.CourseStudents cst ON cr.Id = cst.CourseId
                                 AND cst.CollegeId = 125
LEFT JOIN dbo.Students st ON cst.StudentId = st.Id
WHERE
    cr.CourseArea = 'Medical'
    AND cr.CourseFor = 'Foreigner'
ORDER BY
    cr.SortOrder, st.FullName
</code>```

Can anyone help me with the lambda syntax (I tried GroupJoin)? While what I am looking for is the lambda syntax, the query syntax is also good to know.

UPDATE: I am very close, but still not complete

```<code>    context.Courses
        .GroupJoin(context.CourseStudents,
            x => new { x.Id, CollegeId NOT IN COURSES TABLE :( },
            y => new { Id = y.CourseId, y.CollegeId=125 },
            (x, y) => new { Courses = x, CourseStudents = y })
        .SelectMany(x => x.CourseStudents.DefaultIfEmpty(),
            (x, y) => new { x.Courses, CourseStudents = y })
        .GroupJoin(context.Students,
            x => x.CourseStudents.StudentId,
            y => y.Id,
            (x, y) => new { CoursesCourseStudents = x, Students = y }
        )
        .SelectMany(x => x.Students.DefaultIfEmpty(),
        (x, y) => new { x = x.CoursesCourseStudents, Students = y })
        .Select(x => new
        {
            x.x.Courses.Id,
            x.x.Courses.CourseName,
            x.Students.FullName,
            x.x.CourseStudents.CollegeId,
            x.x.Courses.CourseFor,
            x.x.Courses.CourseArea,
            x.x.Courses.SortOrder
        })
        .Where(x => x.CourseFor == "Foreigner" && x.CourseArea == "Medical")
        .OrderBy(x => x.SortOrder)
        .ToList();
</code>```

答:
SOLUTION: I got it working by doing the following. See line 3 and 4.

```<code>context.Courses
    .GroupJoin(context.CourseStudents,
        x => new { x.Id, CollegeId=125 },
        y => new { Id = y.CourseId, y.CollegeId },
        (x, y) => new { Courses = x, CourseStudents = y })
    .SelectMany(x => x.CourseStudents.DefaultIfEmpty(),
        (x, y) => new { x.Courses, CourseStudents = y })
    .GroupJoin(context.Students,
        x => x.CourseStudents.StudentId,
        y => y.Id,
        (x, y) => new { CoursesCourseStudents = x, Students = y }
    )
    .SelectMany(x => x.Students.DefaultIfEmpty(),
    (x, y) => new { x = x.CoursesCourseStudents, Students = y })
    .Select(x => new
    {
        x.x.Courses.Id,
        x.x.Courses.CourseName,
        x.Students.FullName,
        x.x.CourseStudents.CollegeId,
        x.x.Courses.CourseFor,
        x.x.Courses.CourseArea,
        x.x.Courses.SortOrder
    })
    .Where(x => x.CourseFor == "Foreigner" && x.CourseArea == "Medical")
    .OrderBy(x => x.SortOrder)
    .ToList();
</code>```

Body:
I have the following 3 tables

Courses

Id, SortOrder, CourseName, CourseArea, CourseFor

Students

Id, FullName

CourseStudents

CourseId, StudentId, CollegeId

Requirement:

Get all course students from the 'Medical' area for 'foreign' students available in College '125'. Include courses even if there are no students enrolled in it.

Working SQL query:

SELECT cr.Id, cr.CourseName, st.FullName
FROM dbo.Courses cr
LEFT JOIN dbo.CourseStudents cst ON cr.Id = cst.CourseId
                                 AND cst.CollegeId = 125
LEFT JOIN dbo.Students st ON cst.StudentId = st.Id
WHERE
    cr.CourseArea = 'Medical'
    AND cr.CourseFor = 'Foreigner'
ORDER BY
    cr.SortOrder, st.FullName

Can anyone help me with the lambda syntax (I tried GroupJoin)? While what I am looking for is the lambda syntax, the query syntax is also good to know.

UPDATE: I am very close, but still not complete

    context.Courses
        .GroupJoin(context.CourseStudents,
            x => new { x.Id, CollegeId NOT IN COURSES TABLE :( },
            y => new { Id = y.CourseId, y.CollegeId=125 },
            (x, y) => new { Courses = x, CourseStudents = y })
        .SelectMany(x => x.CourseStudents.DefaultIfEmpty(),
            (x, y) => new { x.Courses, CourseStudents = y })
        .GroupJoin(context.Students,
            x => x.CourseStudents.StudentId,
            y => y.Id,
            (x, y) => new { CoursesCourseStudents = x, Students = y }
        )
        .SelectMany(x => x.Students.DefaultIfEmpty(),
        (x, y) => new { x = x.CoursesCourseStudents, Students = y })
        .Select(x => new
        {
            x.x.Courses.Id,
            x.x.Courses.CourseName,
            x.Students.FullName,
            x.x.CourseStudents.CollegeId,
            x.x.Courses.CourseFor,
            x.x.Courses.CourseArea,
            x.x.Courses.SortOrder
        })
        .Where(x => x.CourseFor == "Foreigner" && x.CourseArea == "Medical")
        .OrderBy(x => x.SortOrder)
        .ToList();

Body:
SOLUTION: I got it working by doing the following. See line 3 and 4.

context.Courses
    .GroupJoin(context.CourseStudents,
        x => new { x.Id, CollegeId=125 },
        y => new { Id = y.CourseId, y.CollegeId },
        (x, y) => new { Courses = x, CourseStudents = y })
    .SelectMany(x => x.CourseStudents.DefaultIfEmpty(),
        (x, y) => new { x.Courses, CourseStudents = y })
    .GroupJoin(context.Students,
        x => x.CourseStudents.StudentId,
        y => y.Id,
        (x, y) => new { CoursesCourseStudents = x, Students = y }
    )
    .SelectMany(x => x.Students.DefaultIfEmpty(),
    (x, y) => new { x = x.CoursesCourseStudents, Students = y })
    .Select(x => new
    {
        x.x.Courses.Id,
        x.x.Courses.CourseName,
        x.Students.FullName,
        x.x.CourseStudents.CollegeId,
        x.x.Courses.CourseFor,
        x.x.Courses.CourseArea,
        x.x.Courses.SortOrder
    })
    .Where(x => x.CourseFor == "Foreigner" && x.CourseArea == "Medical")
    .OrderBy(x => x.SortOrder)
    .ToList();


问:
Shortcut for "Keep Open"
In visual studio I often open files using CTRL + , and hitting enter on the file I desire.

To keep this file open even when navigating to another file, you can click on the "Keep Open" button on the file tab. This is slightly cumbersome... Is there anyway to do this with a shortcut instead?

答:
Ctrl + Alt + Home

When I right click on the file tab, I can see this shortcut listed to the right of "Keep Tab Open"

Title: Shortcut for "Keep Open"


问:
Is there a way to initialize a variable in a controller, and use it in FXML?
So, I was making a menu in FXML and I was using a Group so I had to set a prefWidth otherwise it'd look weird. To do that, I wanted to initialize a variable with the screen width in the controller, and then use the width variable while setting up the menu in FXML. But I just couldn't find a way to do that.

Generalizing this problem, I want to initialize a variable in a controller and then use it in FXML like this:

[Controller]

package sample;

import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
    @Override
    public void initialize (URL url, ResourceBundle resourceBundle) {
        String text = "test";
    }
}
```

<p>[FXML]</p>

```<?import javafx.scene.control.Label?>
<?import javafx.scene.BorderPane?>

<BorderPane>

</BorderPane>
```

I know, there are other ways to do it (like id-ing it and setting the text in the controller) but I just wanna see if it is possible to do it this way.

答:
FXMLLoader can bind a property in FXML to another in the controller. So you can define a property in the controller and access it FXML using its name.

Controller:

public class Controller implements Initializable {
    private StringProperty title = new SimpleStringProperty(this, "title", "");
    public final StringProperty titleProperty() {
        return title;
    }

    public final void setTitle(String value) {
        titleProperty().setValue(value);
    }

    public final String getTitle() {
        return title.getValue();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setTitle("test");
    }
}
```

<p>FXML:</p>

```<BorderPane>

</BorderPane>
```

Note that in order for FXMLLoader to create the binding, a property should have mutators and accessor like in the example.

Body:
So, I was making a menu in FXML and I was using a Group so I had to set a prefWidth otherwise it'd look weird. To do that, I wanted to initialize a variable with the screen width in the controller, and then use the width variable while setting up the menu in FXML. But I just couldn't find a way to do that.

Generalizing this problem, I want to initialize a variable in a controller and then use it in FXML like this:

[Controller]

package sample;

import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
    @Override
    public void initialize (URL url, ResourceBundle resourceBundle) {
        String text = "test";
    }
}

[FXML]

<?import javafx.scene.control.Label?>
<?import javafx.scene.BorderPane?>

<BorderPane>

</BorderPane>

I know, there are other ways to do it (like id-ing it and setting the text in the controller) but I just wanna see if it is possible to do it this way.

Body:
FXMLLoader can bind a property in FXML to another in the controller. So you can define a property in the controller and access it FXML using its name.

Controller:

public class Controller implements Initializable {
    private StringProperty title = new SimpleStringProperty(this, "title", "");
    public final StringProperty titleProperty() {
        return title;
    }

    public final void setTitle(String value) {
        titleProperty().setValue(value);
    }

    public final String getTitle() {
        return title.getValue();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setTitle("test");
    }
}

FXML:

<BorderPane>
    <center>
        <label text="${controller.title}"/>
    </center>
</BorderPane>

Note that in order for FXMLLoader to create the binding, a property should have mutators and accessor like in the example.


问:
Application using Auth0 going to login page on refresh
My simple application written in Javascript is using a service (which is written as a wrapper on Auth0) for authentication. On successful login, if I refresh the home page, application again goes to login page (even if I have stored the access token in cookies)

I also tried to store the access token in browser session storage.

As my index.html is launched, i am checking if my application url contains access token. If there is no access token, I redirect it to login page.

```<code>if (((window.location.hash).indexOf('access_token') < 0)) {
            location.replace(redirectUrl);
}
</code>```

On successful login, as url has access token in it, app works fine further.
But next time when I refresh the home page, it don't have access token in URL.

As per my understanding, as I have access token in cookies, it should not ask me for login again as long as token is valid.

It is still asking for login. What should be the strategy should I use to persist the token ?

On logout, I am setting the cookie to expire. Is there any ideal way to do log out other than this?

答:
This can often be troubleshooted with a HAR file capture to follow the trail being left in the authentication flow. However since we don't have that option at this juncture here are a couple things to look at.

Are you using Dev keys in your auth scenario?

Expiry time

Where is the access token being stored?

https://auth0.com/docs/tokens/overview-access-tokens

Body:
My simple application written in Javascript is using a service (which is written as a wrapper on Auth0) for authentication. On successful login, if I refresh the home page, application again goes to login page (even if I have stored the access token in cookies)

I also tried to store the access token in browser session storage.

As my index.html is launched, i am checking if my application url contains access token. If there is no access token, I redirect it to login page.

if (((window.location.hash).indexOf('access_token') < 0)) {
            location.replace(redirectUrl);
}

On successful login, as url has access token in it, app works fine further.
But next time when I refresh the home page, it don't have access token in URL.

As per my understanding, as I have access token in cookies, it should not ask me for login again as long as token is valid.

It is still asking for login. What should be the strategy should I use to persist the token ?

On logout, I am setting the cookie to expire. Is there any ideal way to do log out other than this?


问:
How can I nest dynamic page routed components in React Routers?
I'm working on a dynamic webpage using React.  I'm using a Switch component from React Routers to change from the home page to various other pages, as needed by the user.  I want the following routing to create a new account:

Home page >> login page >> Create account (1) > (2) > (3) >> back to login or home page
In words: The user should be able to navigate from the home page to a login page, from the login page to a create account page with three steps (each a unique component), and from the third step back to the home page.

My trouble lies in getting from the third create-account page back to the home or login page.  I can create links that bring me from Page 1 > 2, 2 > 1, 2 > 3, or 3 > 2.  But I can't make page three render a link that will bring me back to Home.

I initially had a switch statement in my Create Account page rendering three separate components.  If I set the route home inside of this switch statement, the div would render Home inside of it, as expected.  If I simply omitted the route, the page would fail to render when I clicked on the link, but clearly had the right path because it would load properly upon refresh.
I've also tried:
Moving the Router to circumscribe the entire component, rather than just the Switch component.
Moving the Route to home before anything else in the document - as expected this just rendered the home page above the create account page upon activating the route.
Using a Redirect inside and outside of the Switch statement.
A really nasty method of rendering inside the div the value of a "component" key from inside an object, and manually updating the values in that object when the links are clicked, rather than using anything even vaguely associated with React Routers.  This worked better than it should have, but not perfectly.

**As kind of a side note I've been told (though I have no personal experience) that Vue has a 'stepper' that could be used to navigate through pages 1, 2, and 3, to avoid using a nested router at all.  Is there such a thing in React or React-Routers?

The App:

```<code>function App() {
  return (

    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/Login" component={Login} />
        <Route path="/CreateAccount" component={CreateAccount} />
        <Route path="/Account_Recovery" component={Recovery} />
        <Route path="/RR_One" component={RR_One} />
      </Switch>
    </Router>

  );
}
</code>```

The Create Account Page as it exists now:

```<code>class CreateAccount extends React.Component {
  render() {
    return (

    <Router>
      <PageHeader pageTitle="Create a Free Account"/>

      <div className="pageBody">
        <div className="centerHalf">

            <Route path="/CreateAccount/1" component={PageOne} />
            <Route path="/CreateAccount/2" component={PageTwo} />
            <Route path="/CreateAccount/3" component={PageThree} />

        </div>
        <p>Paragraph outside of the changing div.</p>
      </div>

    </Router>
)}};
</code>```

An example component PageThree (the others are similar for now, just linking between each other):

```<code>class PageThree extends React.Component {
  render() {
    return (
      <div>
        <p>Page Three</p>
        <Link to={{pathname: "/CreateAccount/2"}}>Go to page 2</Link> <br />
        <Link to={{pathname: "/Login"}}>Complete</Link>
      </div>
)}};
</code>```

答:
The solution was actually very simple:  I had misunderstood the purpose of the Router component, and the nesting of these (not of the switch statement or the routes) was the real problem.  By removing the inner Router component (in my case, the one in the CreateAccount component) the navigation was able to flow smoothly from page three back to an external page.</p>

```<code>class CreateAccount extends React.Component {
  render() {
    return (

    <div>

      <PageHeader pageTitle="Create a Free Account"/>

      <div className="pageBody">
        <div className="centerHalf">

            <Route path="/CreateAccount/1" component={PageOne} />
            <Route path="/CreateAccount/2" component={PageTwo} />
            <Route path="/CreateAccount/3" component={PageThree} />

        </div>
        <p>Paragraph outside of the changing div.</p>
      </div>

    </div>
)}};
</code>```

Body:
I'm working on a dynamic webpage using React.  I'm using a Switch component from React Routers to change from the home page to various other pages, as needed by the user.  I want the following routing to create a new account:

Home page >> login page >> Create account (1) > (2) > (3) >> back to login or home page
In words: The user should be able to navigate from the home page to a login page, from the login page to a create account page with three steps (each a unique component), and from the third step back to the home page.

My trouble lies in getting from the third create-account page back to the home or login page.  I can create links that bring me from Page 1 > 2, 2 > 1, 2 > 3, or 3 > 2.  But I can't make page three render a link that will bring me back to Home.

I initially had a switch statement in my Create Account page rendering three separate components.  If I set the route home inside of this switch statement, the div would render Home inside of it, as expected.  If I simply omitted the route, the page would fail to render when I clicked on the link, but clearly had the right path because it would load properly upon refresh.
I've also tried:
Moving the Router to circumscribe the entire component, rather than just the Switch component.
Moving the Route to home before anything else in the document - as expected this just rendered the home page above the create account page upon activating the route.
Using a Redirect inside and outside of the Switch statement.
A really nasty method of rendering inside the div the value of a "component" key from inside an object, and manually updating the values in that object when the links are clicked, rather than using anything even vaguely associated with React Routers.  This worked better than it should have, but not perfectly.

**As kind of a side note I've been told (though I have no personal experience) that Vue has a 'stepper' that could be used to navigate through pages 1, 2, and 3, to avoid using a nested router at all.  Is there such a thing in React or React-Routers?

The App:

function App() {
  return (

    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/Login" component={Login} />
        <Route path="/CreateAccount" component={CreateAccount} />
        <Route path="/Account_Recovery" component={Recovery} />
        <Route path="/RR_One" component={RR_One} />
      </Switch>
    </Router>

  );
}

The Create Account Page as it exists now:

class CreateAccount extends React.Component {
  render() {
    return (

    <Router>
      <PageHeader pageTitle="Create a Free Account"/>

            <Route path="/CreateAccount/1" component={PageOne} />
            <Route path="/CreateAccount/2" component={PageTwo} />
            <Route path="/CreateAccount/3" component={PageThree} />

Paragraph outside of the changing div.

    </Router>
)}};

An example component PageThree (the others are similar for now, just linking between each other):

class PageThree extends React.Component {
  render() {
    return (

Page Three

        <Link to={{pathname: "/CreateAccount/2"}}>Go to page 2</Link>

        <Link to={{pathname: "/Login"}}>Complete</Link>

)}};

Body:
The solution was actually very simple:  I had misunderstood the purpose of the Router component, and the nesting of these (not of the switch statement or the routes) was the real problem.  By removing the inner Router component (in my case, the one in the CreateAccount component) the navigation was able to flow smoothly from page three back to an external page.

class CreateAccount extends React.Component {
  render() {
    return (

    <div>

      <PageHeader pageTitle="Create a Free Account"/>

      <div className="pageBody">
        <div className="centerHalf">

            <Route path="/CreateAccount/1" component={PageOne} />
            <Route path="/CreateAccount/2" component={PageTwo} />
            <Route path="/CreateAccount/3" component={PageThree} />

        </div>
        <p>Paragraph outside of the changing div.</p>
      </div>

    </div>
)}};


问:
Scala Array map function documentation (PSSQ #1)
PSSQ stand for Possibly Stupid Scala Question :)

Getting to know Scala a little bit, and in the obligatory Hello World example (code below) the arguments to the main function is an array of strings.

```<code>object HelloWorld
{
    def main(args: Array[String]): Unit =
    {
        args.map((arg:String) => arg.toUpperCase());
        printf("%s %s!", "Hello", "World");
    }
}
</code>```

In the example, I'm using the map() function on the array. However, when I check the Scala API documentation, map() isn't listed as one of the functions available for Array. Is there some kind of magic going on, or am I missing something obvious in the API documentation?

答:
This is because of one key feature of Scala called implicit conversions. There is plenty of documents about them on the net, for instance see this one: http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-6

The upcoming Scala 2.9 REPL can help you find out which might be involved here:

```<code>scala> :implicits -v
</code>```

... looking for Array we find several ones that go to mutable.ArrayOps. The scaladoc for that one: http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/scala/collection/mutable/ArrayOps.html

This means that since the implicit conversion method refArrayOps is in scope (in the default Predef), whenever you try to call a method on an Array that is not defined for Array but for ArrayOps, scala will insert (implicitly) the conversion, hence you actually have

```<code>Predef.refArrayOps(args).map(...)
</code>```

Body:
PSSQ stand for Possibly Stupid Scala Question :)

Getting to know Scala a little bit, and in the obligatory Hello World example (code below) the arguments to the main function is an array of strings.

object HelloWorld
{
    def main(args: Array[String]): Unit =
    {
        args.map((arg:String) => arg.toUpperCase());
        printf("%s %s!", "Hello", "World");
    }
}

In the example, I'm using the map() function on the array. However, when I check the Scala API documentation, map() isn't listed as one of the functions available for Array. Is there some kind of magic going on, or am I missing something obvious in the API documentation?

Body:
This is because of one key feature of Scala called implicit conversions. There is plenty of documents about them on the net, for instance see this one: http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-6

The upcoming Scala 2.9 REPL can help you find out which might be involved here:

scala> :implicits -v

... looking for Array we find several ones that go to mutable.ArrayOps. The scaladoc for that one: http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/scala/collection/mutable/ArrayOps.html

This means that since the implicit conversion method refArrayOps is in scope (in the default Predef), whenever you try to call a method on an Array that is not defined for Array but for ArrayOps, scala will insert (implicitly) the conversion, hence you actually have

Predef.refArrayOps(args).map(...)


问:
Angular validation not working when Function name mentioned in HTML
Angular Validation does not work when I use the valiadation function name in HTML.

If i Remove it, It works.

```<code>    export class RegisterComponent implements OnInit {
    ngOnInit() {
    }
    constructor (private formBuilder: FormBuilder,
        private titleService: Title,
        private _router: Router) {
        this.setTitle('BS - Register New');
    }

    // tslint:disable-next-line: member-ordering
    registerForm: FormGroup = new FormGroup ({
        orgName: new FormControl(null,
        [Validators.required,
        Validators.minLength(5),
        this.checkOrgName
        ] )
    });

    checkOrgName (controls: AbstractControl): ValidationErrors | null{
        if (controls.value === 'ABCDEF') {
            console.log("Error")
            return {incorrectOrg: 'Company Name can not be ABCDEF'}
        } else {
            return null;
        }
    }
</code>```

HTML Code

```<code>div class="form-group">
        <label for="orgName">Organization Name</label>
        <!-- Name , and formControlName should be same as in ts file  -->
        <input
          name="orgName"
          formControlName="orgName"
          type="text"
          id="orgName"
          placeholder="Organization Name"
          class="form-control"
          autofocus
          [class.is-invalid]="registerForm.get('orgName').invalid &&
                              registerForm.get('orgName').touched">

        <div *ngIf="registerForm.get('orgName').invalid &&
                    registerForm.get('orgName').touched">

          <!-- <small *ngIf="registerForm.get('orgName').errors?.required" -->
          <small *ngIf="registerForm.get('orgName').errors?.required"
                  class="text-danger">
               Organization Name is Required
          </small>

          <small *ngIf="registerForm.get('orgName').errors?.minlength"
                  class="text-danger">
              Organization Name should be more than 5 Characters long
          </small>

          <small

*ngIf="registerForm.controls.orgName.errors?.checkOrgName"
                    class="text-danger">
            {{registerForm.get('orgName').errors['incorrectOrg']}}
          </small>
        </div>
      </div>
</code>```

In the Above code, validation works but  the error is not displayed,

**But if i replace "*ngIf="registerForm.controls.orgName.errors?.checkOrgName"  by "*ngIf="registerForm.controls.orgName.errors"  in HTML **

The error message is displayed successfully.

Please help me by letting me know what is the mistake in the code if Function name is mentioned in HTML?

Regards,
Ashish

答:
You have to use the key of the object you returned from the validator.

So it should be *ngIf="registerForm.controls.orgName.errors?.incorrectOrg" in the template.

Body:
Angular Validation does not work when I use the valiadation function name in HTML.

If i Remove it, It works.

    export class RegisterComponent implements OnInit {
    ngOnInit() {
    }
    constructor (private formBuilder: FormBuilder,
        private titleService: Title,
        private _router: Router) {
        this.setTitle('BS - Register New');
    }

    // tslint:disable-next-line: member-ordering
    registerForm: FormGroup = new FormGroup ({
        orgName: new FormControl(null,
        [Validators.required,
        Validators.minLength(5),
        this.checkOrgName
        ] )
    });

    checkOrgName (controls: AbstractControl): ValidationErrors | null{
        if (controls.value === 'ABCDEF') {
            console.log("Error")
            return {incorrectOrg: 'Company Name can not be ABCDEF'}
        } else {
            return null;
        }
    }

HTML Code

div class="form-group">
        Organization Name

        <input
          name="orgName"
          formControlName="orgName"
          type="text"
          id="orgName"
          placeholder="Organization Name"
          class="form-control"
          autofocus
          [class.is-invalid]="registerForm.get('orgName').invalid &&
                              registerForm.get('orgName').touched">

               Organization Name is Required

              Organization Name should be more than 5 Characters long

            {{registerForm.get('orgName').errors['incorrectOrg']}}

In the Above code, validation works but  the error is not displayed,

**But if i replace "*ngIf="registerForm.controls.orgName.errors?.checkOrgName"  by "*ngIf="registerForm.controls.orgName.errors"  in HTML **

The error message is displayed successfully.

Please help me by letting me know what is the mistake in the code if Function name is mentioned in HTML?

Regards,
Ashish


答: you could also look at the quartz.net library use that to schedule on a timer</p>

Title: How to send notifications by email automatically on a date?

Body:
I have a little problem, I don't know how to program a function in .NET MVC to send emails on a date.

For example: Every 25th of each Month send an email to my team partners to remember them update the stock. And the 27th of each Month send and email to his boss to check the stock.

I tried to do this, but i code a function that every time that someone's enter to the WebApp checks the date and if is the 25th sends the email.

The problems:

It sends like thousands of emails, because it is executed every time
when a person is inside the app.

If no ones enter to the app the function can be executed :(