问:
Brew install docker does not include docker engine?
Trying to setup docker from brew, however the engine does not seem to be included in any of the any of the official formulas.

```<code>brew install docker-machine docker-compose
</code>```

So these only installs the clients?
Is there no keg with the engine/daemon?

答:
To install Docker for Mac with homebrew:

```<code>brew install homebrew/cask/docker
</code>```

To install the command line completion:

```<code>brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion
</code>```

Body:
Trying to setup docker from brew, however the engine does not seem to be included in any of the any of the official formulas.

brew install docker-machine docker-compose

So these only installs the clients?
Is there no keg with the engine/daemon?

Body:
To install Docker for Mac with homebrew:

brew install homebrew/cask/docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion


来源: stackexchange

问:
Reference .net core 2.0 into a .net 45/46 project
How can I add a reference of a .Net Core 2.0 project into my .Net 46 project?

My project is structured as follow:

Solution
- Data Project (.Net Core 2.0)
- Test Project (.Net 46)

I'm trying to reference the Data Project into my Test Project as I need to insert some data using it. The only reason I created a .Net Core 2.0 is that I'm trying to use Entity Framework on Visual Studio for Mac and it didn't work using the "normal" Entity Framework nuget package, so I opted for the EntityFrameworkCore.

I was able to manually reference the Data Project dll, but then when I run a test I get the message

```<code>"Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=2.0.0.0. Culture=neutral' or one of its dependencies"
</code>```

Is there any solution for this? If not, what's the best way to work with Visual Studio on Mac and Sql Server when you need to retrieve and insert data? Would Dapper work?

Thanks

答:
What you asked is impossible.

.NET Framework projects can only consume .NET Standard Class Library projects, but not .NET Core projects.

See the reference for more information,

https://blog.lextudio.com/which-class-library-project-to-go-in-visual-studio-2015-2017-a48710cf3dff

ContentLicense: CC BY-SA 3.0

Body:
How can I add a reference of a .Net Core 2.0 project into my .Net 46 project?

My project is structured as follow:

Solution
- Data Project (.Net Core 2.0)
- Test Project (.Net 46)

I'm trying to reference the Data Project into my Test Project as I need to insert some data using it. The only reason I created a .Net Core 2.0 is that I'm trying to use Entity Framework on Visual Studio for Mac and it didn't work using the "normal" Entity Framework nuget package, so I opted for the EntityFrameworkCore.

I was able to manually reference the Data Project dll, but then when I run a test I get the message

"Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=2.0.0.0. Culture=neutral' or one of its dependencies"

Is there any solution for this? If not, what's the best way to work with Visual Studio on Mac and Sql Server when you need to retrieve and insert data? Would Dapper work?

Thanks


问:
Slow CSV row parsing and splitting
I'm trying to parse a csv of over 100,000 lines and the performance problems don't even let me get to the end of the file before hitting "Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded"

Is there something wrong, or any way I can improve?

```<code>public static List<String[]> readCSV(String filePath) throws IOException{
    List<String[]> csvLine= new ArrayList<String[]>();
    CSVReader reader = new CSVReader(new FileReader(filePath), '\n');
    String[] row;

    while((row = reader.readNext()) != null){
        csvLine.add(removeWhiteSpace(row[0].toString().split(",")));
    }

    reader.close();
    return csvLine;
}

private static String[] removeWhiteSpace(String[] split) {
    for(int index =0; index < split.length;index++){
        split[index] = split[index].trim();
    }
    return split;
}
</code>```

答:
Is a design error try to put such a large file in memory.
Depending of what you want to do, you should either write a new file processed, or put the lines into a dba.
This implements the first:</p>

```<code>FileInputStream inputStream = null;
Scanner sc = null;
try {
    inputStream = new FileInputStream(path);
    sc = new Scanner(inputStream, "UTF-8");
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        // System.out.println(line);
    }
    // note that Scanner suppresses exceptions
    if (sc.ioException() != null) {
        throw sc.ioException();
    }
} finally {
    if (inputStream != null) {
        inputStream.close();
    }
    if (sc != null) {
        sc.close();
    }
}
</code>```

Title: Slow CSV row parsing and splitting

Body:
I'm trying to parse a csv of over 100,000 lines and the performance problems don't even let me get to the end of the file before hitting "Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded"

Is there something wrong, or any way I can improve?

public static List<String[]> readCSV(String filePath) throws IOException{
    List<String[]> csvLine= new ArrayList<String[]>();
    CSVReader reader = new CSVReader(new FileReader(filePath), '\n');
    String[] row;

    while((row = reader.readNext()) != null){
        csvLine.add(removeWhiteSpace(row[0].toString().split(",")));
    }

    reader.close();
    return csvLine;
}

private static String[] removeWhiteSpace(String[] split) {
    for(int index =0; index < split.length;index++){
        split[index] = split[index].trim();
    }
    return split;
}

Body:
Is a design error try to put such a large file in memory.
Depending of what you want to do, you should either write a new file processed, or put the lines into a dba.
This implements the first:

FileInputStream inputStream = null;
Scanner sc = null;
try {
    inputStream = new FileInputStream(path);
    sc = new Scanner(inputStream, "UTF-8");
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        // System.out.println(line);
    }
    // note that Scanner suppresses exceptions
    if (sc.ioException() != null) {
        throw sc.ioException();
    }
} finally {
    if (inputStream != null) {
        inputStream.close();
    }
    if (sc != null) {
        sc.close();
    }
}


问:
recursive Add python matrix sparse
I am new to Python - I came from matlab. I am trying to compile this code:

```<code>import numpy as np
from scipy import sparse

n=3
dim=2^n

sx = np.array([[0,1],[1,0]])
sy = np.array([[0,-1j],[1j,0]])
sz = np.array([[1,0],[0,-1]])
ssx= sparse.csr_matrix(sx)
ssy= sparse.csr_matrix(sy)
ssz= sparse.csr_matrix(sz)

expon1=np.zeros((n,n))
for i in range(n-1):
    expon1[i,i]=1
    expon1[i+1,i]=1
expon1[0,n-1]=1
expon1[n-1,n-1]=1
expon2=np.identity(n)

Sigs1=sparse.csr_matrix(0,(dim, dim))
for j in range(n-1):
    Sig1=sparse.csr_matrix(1)
    for i in range(n-1):
        Sig1=sparse.kron(Sig1,ssx.power(expon1[i,j]))
    Sigs1= Sigs1+Sig1
</code>```

After running python3 sparse.py [name of file], the terminal prints the following text:

```<code>Traceback (most recent call last):
  File "sparse.py", line 31, in <module>
    Sigs1= Sigs1+Sig1
  File "/usr/lib/python3/dist-packages/scipy/sparse/compressed.py", line 341, in __add__
    raise ValueError("inconsistent shapes")
ValueError: inconsistent shapes
</code>```

答:
I didnt go through your whole code, but looking at it I can say your problem is probably here.

```<code>n=3
dim=2^n
</code>```

This ^ operator in python is for bitwise XOR while this ** is for power.

Title: recursive Add python matrix sparse

Body:
I am new to Python - I came from matlab. I am trying to compile this code:

import numpy as np
from scipy import sparse

n=3
dim=2^n

sx = np.array([[0,1],[1,0]])
sy = np.array([[0,-1j],[1j,0]])
sz = np.array([[1,0],[0,-1]])
ssx= sparse.csr_matrix(sx)
ssy= sparse.csr_matrix(sy)
ssz= sparse.csr_matrix(sz)

expon1=np.zeros((n,n))
for i in range(n-1):
    expon1[i,i]=1
    expon1[i+1,i]=1
expon1[0,n-1]=1
expon1[n-1,n-1]=1
expon2=np.identity(n)

Sigs1=sparse.csr_matrix(0,(dim, dim))
for j in range(n-1):
    Sig1=sparse.csr_matrix(1)
    for i in range(n-1):
        Sig1=sparse.kron(Sig1,ssx.power(expon1[i,j]))
    Sigs1= Sigs1+Sig1

After running python3 sparse.py [name of file], the terminal prints the following text:

Traceback (most recent call last):
  File "sparse.py", line 31, in <module>
    Sigs1= Sigs1+Sig1
  File "/usr/lib/python3/dist-packages/scipy/sparse/compressed.py", line 341, in __add__
    raise ValueError("inconsistent shapes")
ValueError: inconsistent shapes

Body:
I didnt go through your whole code, but looking at it I can say your problem is probably here.

n=3
dim=2^n

This ^ operator in python is for bitwise XOR while this ** is for power.


问:
join multiple times in SQL
These are the 2 tables.
Tech_data:

```<code>Id Tech Agent1_id Agent2_ID
1  JAVA   1           2
2  SQL    3           4
</code>```

Agent_table

```<code>Id Name
1  Mike
2  John
3  Jim
4  Baron
</code>```

I need to write a query to bring the below output

```<code>TECH_ID   Tech  Agent1_Name Agent2_Name
1         Java    Mike       John
2         SQL     Jim        Baron
</code>```

I wrote LEFT OUTER JOIN ON tech_id=agent1_id, but i do not know how to join 2 ids in ON condition.

答:
You can add a second left outer join just like the one you have used, on the same table by giving them different aliases as follows.

```<code>select t.Id tech_id, t.tech, a1.name, a2.name
from tech_data t
left outer join agent_table a1 on a1.Id = t.agent1_id
left outer join agent_table a2 on a2.Id = t.agent2_Id;
</code>```

Check the fiddle below:
http://sqlfiddle.com/#!4/73f02b/1

Title: join multiple times in SQL

Body:
These are the 2 tables.
Tech_data:

Id Tech Agent1_id Agent2_ID
1  JAVA   1           2
2  SQL    3           4

Agent_table

Id Name
1  Mike
2  John
3  Jim
4  Baron

I need to write a query to bring the below output

TECH_ID   Tech  Agent1_Name Agent2_Name
1         Java    Mike       John
2         SQL     Jim        Baron

I wrote LEFT OUTER JOIN ON tech_id=agent1_id, but i do not know how to join 2 ids in ON condition.

Body:
You can add a second left outer join just like the one you have used, on the same table by giving them different aliases as follows.

select t.Id tech_id, t.tech, a1.name, a2.name
from tech_data t
left outer join agent_table a1 on a1.Id = t.agent1_id
left outer join agent_table a2 on a2.Id = t.agent2_Id;

Check the fiddle below:
http://sqlfiddle.com/#!4/73f02b/1


问:
c# linq GroupBy and Sum up only the lowerest in each group
This is the problem:
I have a long list of objects with properties

```<code>1) int Book (B)
2) int Chapter (C)
3) int Paragraph (P)
4) int TimesRead (nx)
</code>```

each book is the sum of all it's chapters and each chapter is the sum of all it's paragraphs. Obviously only if you have read all the chapters of a book it counts for having read the whole book. The same is true for a chapter; all paragraphs have to be read to count the chapter as read.

The list of references that looks like this

```<code>B1 - C1 - P1 - 3x
B1 - C1 - P2 - 3x
B1 - C1 - P3 - 4x
B1 - C2 - P1 - 5x
B1 - C2 - P2 - 2x
B1 - C2 - P3 - 2x
B1 - C2 - P4 - 9x
B2 - C1 - P1 - 3x
...tens of thousands of them
</code>```

B1C1 counts only as 3x read. B1C2 counts as 2x read because each of the paragraphs have been read 3x and 2x respectively. What I want to count is only the minimum.
I want the sum of all the chapters how often they have been read through completely. But how do I go about summing up only the lowerest TimesRead for each chapter;

```<code>B1C1 + B1C2 + B2C1
 3   +   2  +   3
</code>```

using linq or a loop (I'd prefer linq).

This is as far as I get but it's not correct. How do I get only the groups with the lowest TimesRead for each pair x.Book-x.Chapter?

```<code>SumTotalChaptersRead = listBookChapterParagraph
    .Where(x => x.TimesRead >= 1)
    .GroupBy(x => new Tuple<string, int>($"{x.Book}-{x.Chapter}", x.TimesRead))
    .ToList()
    .Where(x => x.TimesRead[.Min])
    .Sum(s => s.Key.Item2);
</code>```

Somehow there must be a TimesRead.Min somewhere in this.

答:
This is working for me (in LINQPad):

```<code>void Main()
{
    var data = new List<Info>
    {
        new Info(){ Book=1, Chapter=1, Paragraph=1, TimesRead=3},
        new Info(){ Book=1, Chapter=1, Paragraph=2, TimesRead=3},
        new Info(){ Book=1, Chapter=1, Paragraph=3, TimesRead=4},
        new Info(){ Book=1, Chapter=2, Paragraph=1, TimesRead=5},
        new Info(){ Book=1, Chapter=2, Paragraph=2, TimesRead=2},
        new Info(){ Book=1, Chapter=2, Paragraph=3, TimesRead=2},
        new Info(){ Book=1, Chapter=2, Paragraph=4, TimesRead=9},
        new Info(){ Book=2, Chapter=1, Paragraph=1, TimesRead=3},
    };

    var query = data.GroupBy(d => new {d.Book, d.Chapter})
    .Select(g => new
    {
        Book = g.Key.Book,
        Chapter = g.Key.Chapter,
        MinTimesRead = g.Min(d => d.TimesRead)
    });

    query.Dump();
}

public class Info
{
    public int Book { get; set; }
    public int Chapter { get; set; }
    public int Paragraph { get; set; }
    public int TimesRead { get; set; }
}
</code>```

It produces the following output:

It does this by grouping on Book and Chapter, and returning an anonymous object containing the Book, Chapter, and the minimum TimesRead for that group.

The Sum of TimesRead is just a simple matter of .Sum(q => q.MinTimesRead) on that result.

LINQPad file is available here.

If you want access to the items within the groupings, change the Select to:

```<code>.Select(g => new
{
    Book = g.Key.Book,
    Chapter = g.Key.Chapter,
    MinTimesRead = g.Min(d => d.TimesRead),
    Items = g.Select(i => i)
});
</code>```

Which will give you:

(image may be slightly out of sync with code, as I tweaked the code to be more memory efficient with larger data sets after I took the screenshot)

Body:
This is the problem:
I have a long list of objects with properties

1) int Book (B)
2) int Chapter (C)
3) int Paragraph (P)
4) int TimesRead (nx)

each book is the sum of all it's chapters and each chapter is the sum of all it's paragraphs. Obviously only if you have read all the chapters of a book it counts for having read the whole book. The same is true for a chapter; all paragraphs have to be read to count the chapter as read.

The list of references that looks like this

B1 - C1 - P1 - 3x
B1 - C1 - P2 - 3x
B1 - C1 - P3 - 4x
B1 - C2 - P1 - 5x
B1 - C2 - P2 - 2x
B1 - C2 - P3 - 2x
B1 - C2 - P4 - 9x
B2 - C1 - P1 - 3x
...tens of thousands of them

B1C1 counts only as 3x read. B1C2 counts as 2x read because each of the paragraphs have been read 3x and 2x respectively. What I want to count is only the minimum.
I want the sum of all the chapters how often they have been read through completely. But how do I go about summing up only the lowerest TimesRead for each chapter;

B1C1 + B1C2 + B2C1
 3   +   2  +   3

using linq or a loop (I'd prefer linq).

This is as far as I get but it's not correct. How do I get only the groups with the lowest TimesRead for each pair x.Book-x.Chapter?

SumTotalChaptersRead = listBookChapterParagraph
    .Where(x => x.TimesRead >= 1)
    .GroupBy(x => new Tuple<string, int>($"{x.Book}-{x.Chapter}", x.TimesRead))
    .ToList()
    .Where(x => x.TimesRead[.Min])
    .Sum(s => s.Key.Item2);

Somehow there must be a TimesRead.Min somewhere in this.

Body:
This is working for me (in LINQPad):

void Main()
{
    var data = new List<Info>
    {
        new Info(){ Book=1, Chapter=1, Paragraph=1, TimesRead=3},
        new Info(){ Book=1, Chapter=1, Paragraph=2, TimesRead=3},
        new Info(){ Book=1, Chapter=1, Paragraph=3, TimesRead=4},
        new Info(){ Book=1, Chapter=2, Paragraph=1, TimesRead=5},
        new Info(){ Book=1, Chapter=2, Paragraph=2, TimesRead=2},
        new Info(){ Book=1, Chapter=2, Paragraph=3, TimesRead=2},
        new Info(){ Book=1, Chapter=2, Paragraph=4, TimesRead=9},
        new Info(){ Book=2, Chapter=1, Paragraph=1, TimesRead=3},
    };

    var query = data.GroupBy(d => new {d.Book, d.Chapter})
    .Select(g => new
    {
        Book = g.Key.Book,
        Chapter = g.Key.Chapter,
        MinTimesRead = g.Min(d => d.TimesRead)
    });

    query.Dump();
}

public class Info
{
    public int Book { get; set; }
    public int Chapter { get; set; }
    public int Paragraph { get; set; }
    public int TimesRead { get; set; }
}

It produces the following output:

It does this by grouping on Book and Chapter, and returning an anonymous object containing the Book, Chapter, and the minimum TimesRead for that group.

The Sum of TimesRead is just a simple matter of .Sum(q => q.MinTimesRead) on that result.

LINQPad file is available here.

If you want access to the items within the groupings, change the Select to:

.Select(g => new
{
    Book = g.Key.Book,
    Chapter = g.Key.Chapter,
    MinTimesRead = g.Min(d => d.TimesRead),
    Items = g.Select(i => i)
});

Which will give you:

(image may be slightly out of sync with code, as I tweaked the code to be more memory efficient with larger data sets after I took the screenshot)


问:
Selecting an appropriate .gitignore so it doesn't upload itself.
I have received feedback on my first ever programming assignment in Python. In general, it was pretty good but I don't fully understand one point. To mark the assignment my teacher cloned my repo via github. The feedback advised using "an appropriate .gitignore that doesn't upload .gitignore itself".

Can anyone expand on this point for me? Still trying to get familiar with git and don't fully understand gitignore.

答:
Each line in the .gitignore file establishes a pattern. When deciding if a file should be ignored, Git looks to see if it matches one of the patterns in the .gitignore file.

If you added the text .gitignore into the .gitignore file, the .gitignore file itself would not be controlled within the Git version control system, and would not get uploaded to a remote repository.

Controlling the .gitignore file within Git is no bad thing, however, in my humble opinion. It means all users of the repository have access to the same configuration.


问:
How to shorten path in import Angular?
Sometimes I have to specify the full path to another service/component based on current component location like:

```<code>import {LocalService} from '../../../_services/LocaleService';
</code>```

To agree that it is not convenient.

How to shorten this path to more beauty and elegant?

答:
This may be a matter of style. Consider restructuring your application to follow the LIFT principle such that you can Locate code quickly, Identify the code at a glance, keep the Flattest structure you can, and Try to be DRY.

To keep the folder structure as flat as possible, take advantage of splitting your application into modules and utilize folders by feature.

Take a  look here for a good example of folder structure.

Title: How to shorten path in import Angular?

Body:
Sometimes I have to specify the full path to another service/component based on current component location like:

import {LocalService} from '../../../_services/LocaleService';

To agree that it is not convenient.

How to shorten this path to more beauty and elegant?


问:
Set database name dynamically in LINQ to SQL
I am using LINQ to SQL to connect to database from my application. When I am changing environment from production to staging, I can update my connection string in web.config.
But there is one more value I need to update when environment changes. That is database name. In LINQ to SQL designer file, database name is mentioned as attribute like-

```<code>[System.Data.Linq.Mapping.DatabaseAttribute(Name="somedbname")]
</code>```

How can I pick up value of Name dynamically from some config file?

Any help is really appreciated.

答:
I fixed this problem by editing the .dbml file outside of Visual Studio (the designer doesn't seem to allow access to the DatabaseAttribute) and getting rid of the name property here:

```<code><Database Name="BadName" Class="OutputDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
</code>```

(note that the accepted answer is no longer correct: this attribute was overriding my connection string)

ContentLicense: CC BY-SA 2.5

Body:
I am using LINQ to SQL to connect to database from my application. When I am changing environment from production to staging, I can update my connection string in web.config.
But there is one more value I need to update when environment changes. That is database name. In LINQ to SQL designer file, database name is mentioned as attribute like-

[System.Data.Linq.Mapping.DatabaseAttribute(Name="somedbname")]

How can I pick up value of Name dynamically from some config file?

Any help is really appreciated.

Body:
I fixed this problem by editing the .dbml file outside of Visual Studio (the designer doesn't seem to allow access to the DatabaseAttribute) and getting rid of the name property here:

<Database Name="BadName" Class="OutputDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">

(note that the accepted answer is no longer correct: this attribute was overriding my connection string)


问:
Oracle date comparison in where clause issue
I am seeing different results for a query whenever I rearrange the conditions of the where clause; I am trying to figure out why this is. I was given to try and figure out what is going on, so I could use some help to ascertain what may be causing an issue. To be clear, we are not receiving errors when running the select statement, but receiving unintended data results. This is an Oracle database (10-g I believe). We have two conditions for the same field. The first is to make sure the results are greater than 30 years ago (this database was not set my by myself, but the team that owns the application decided to change the created_date to 30 in the past was a good idea).....the second is to have a more specific date range of September 1st to October 1st.

```<code>SELECT created_date
FROM tableName
WHERE
created_date > sysdate - 11000 -- 30 years in the past
AND short_name like 'FOO%'
AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
AND TO_DATE('10-01-2017', 'MM-DD-YYYY')
</code>```

When running the query above, we receive results with a created_date outside of the condition at the end of the where clause.

However, when I place the comparison between the created_date and the sysdate AFTER the comparison between the two dates, we receive the correct results.

```<code>SELECT created_date
FROM tableName
WHERE
short_name like 'FOO%'
AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
AND TO_DATE('10-01-2017', 'MM-DD-YYYY')
AND created_date > sysdate - 11000 -- 30 years in the past
</code>```

Also, I removed the trunc portion of "AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')  " to "AND created_date BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')  " and received the intended results with the sysdate comparison before or afterward.

```<code>SELECT created_date
    FROM tableName
    WHERE
    created_date > sysdate - 11000 -- 30 years in the past
    AND short_name like 'FOO%'
    AND created_date BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
    AND TO_DATE('10-01-2017', 'MM-DD-YYYY')
</code>```

EDIT:

There are numerous records in the database. There is only 1 result with a created_date of 22-Sep-17.

```<code>SELECT created_date
FROM tableName
WHERE
created_date > sysdate - 11000 -- 30 years in the past
AND short_name like 'FOO%'
AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
AND TO_DATE('10-01-2017', 'MM-DD-YYYY')
</code>```

Produces 25 entries with a created_date of 17-Feb-04 and 1 with 22-Sep-17.

I understand sysdate - 11,000 is a little more than 30 years. The current requirement is to do a check for 11000 days and not 30 years. I was off in the year estimate. The sysdate is used because records that are considered old or updated will be placed with a created_date further than sysdate - 11000. I understand this makes no sense when there is already another date range condition in this query, but the solution has already been built and sent off. In order to make changes, I need to figure out WHY I am getting what I am getting, which is why I am posting here.

The second date range, in this case, 09-01-2017 and 10-01-2017, are parameters passed in by so they could be any range from any day in the past up until today. I understand it is a bad design, but I did not build it.

These will give two subtly different results for the values between
  2017-10-01 00:00:01 and 2017-10-01 23:59:59. The query using TRUNC
  will include that range where without TRUNC that range will be
  excluded.

The intended result is to have on record returned back within the date range 22-Sep-17; however, we are receiving 25 records all with dates of 17-Feb-04....If I remove the created_date > sysdate - 11000 I receive the only one record as well.

答:
The first is to make sure the results are greater than 30 years ago

You aren't subtracting 30 years, you are subtracting 11,000 days which is approximately (depending on leap years) 30 years and 42 days.

If you want to subtract 30 years then use:

```<code>ADD_MONTHS( date_value, -30 * 12 )
</code>```

the second is to have a more specific date range of September 1st to October 1st.

This makes the first condition irrelevant - if it is between 2017-09-01 and 2017-10-01 then it will be within the last 30 years and you do not need that first condition.

I removed the trunc portion of "AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')" to "AND created_date BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')" and received the intended results with the sysdate comparison before or afterward.

These will give two subtly different results for the values between 2017-10-01 00:00:01 and 2017-10-01 23:59:59. The query using TRUNC will include that range where without TRUNC that range will be excluded.

Also, using TRUNC means that Oracle will not us an index on the created_date column (and would require a function-based index on TRUNC( created_date )). If you want to use an index then just use the column and test to see if it is greater or equal than the start of the range and less than the end of the range plus one day (to include up to 23:59:59 of that day).

The simplified equivalent of your TRUNC query is:

```<code>SELECT created_date
FROM   tableName
WHERE  short_name like 'FOO%'
AND    created_date >= DATE '2017-09-01'                    -- range start
AND    created_date <  DATE '2017-10-01' + INTERVAL '1' DAY -- range end + 1 day
</code>```

Body:
I am seeing different results for a query whenever I rearrange the conditions of the where clause; I am trying to figure out why this is. I was given to try and figure out what is going on, so I could use some help to ascertain what may be causing an issue. To be clear, we are not receiving errors when running the select statement, but receiving unintended data results. This is an Oracle database (10-g I believe). We have two conditions for the same field. The first is to make sure the results are greater than 30 years ago (this database was not set my by myself, but the team that owns the application decided to change the created_date to 30 in the past was a good idea).....the second is to have a more specific date range of September 1st to October 1st.

SELECT created_date
FROM tableName
WHERE
created_date > sysdate - 11000 -- 30 years in the past
AND short_name like 'FOO%'
AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
AND TO_DATE('10-01-2017', 'MM-DD-YYYY')

When running the query above, we receive results with a created_date outside of the condition at the end of the where clause.

However, when I place the comparison between the created_date and the sysdate AFTER the comparison between the two dates, we receive the correct results.

SELECT created_date
FROM tableName
WHERE
short_name like 'FOO%'
AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
AND TO_DATE('10-01-2017', 'MM-DD-YYYY')
AND created_date > sysdate - 11000 -- 30 years in the past

Also, I removed the trunc portion of "AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')  " to "AND created_date BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')  " and received the intended results with the sysdate comparison before or afterward.

SELECT created_date
    FROM tableName
    WHERE
    created_date > sysdate - 11000 -- 30 years in the past
    AND short_name like 'FOO%'
    AND created_date BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
    AND TO_DATE('10-01-2017', 'MM-DD-YYYY')

EDIT:

There are numerous records in the database. There is only 1 result with a created_date of 22-Sep-17.

SELECT created_date
FROM tableName
WHERE
created_date > sysdate - 11000 -- 30 years in the past
AND short_name like 'FOO%'
AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')
AND TO_DATE('10-01-2017', 'MM-DD-YYYY')

Produces 25 entries with a created_date of 17-Feb-04 and 1 with 22-Sep-17.

I understand sysdate - 11,000 is a little more than 30 years. The current requirement is to do a check for 11000 days and not 30 years. I was off in the year estimate. The sysdate is used because records that are considered old or updated will be placed with a created_date further than sysdate - 11000. I understand this makes no sense when there is already another date range condition in this query, but the solution has already been built and sent off. In order to make changes, I need to figure out WHY I am getting what I am getting, which is why I am posting here.

The second date range, in this case, 09-01-2017 and 10-01-2017, are parameters passed in by so they could be any range from any day in the past up until today. I understand it is a bad design, but I did not build it.

These will give two subtly different results for the values between
  2017-10-01 00:00:01 and 2017-10-01 23:59:59. The query using TRUNC
  will include that range where without TRUNC that range will be
  excluded.

The intended result is to have on record returned back within the date range 22-Sep-17; however, we are receiving 25 records all with dates of 17-Feb-04....If I remove the created_date > sysdate - 11000 I receive the only one record as well.

Body:
The first is to make sure the results are greater than 30 years ago

You aren't subtracting 30 years, you are subtracting 11,000 days which is approximately (depending on leap years) 30 years and 42 days.

If you want to subtract 30 years then use:

ADD_MONTHS( date_value, -30 * 12 )

the second is to have a more specific date range of September 1st to October 1st.

This makes the first condition irrelevant - if it is between 2017-09-01 and 2017-10-01 then it will be within the last 30 years and you do not need that first condition.

I removed the trunc portion of "AND trunc(created_date) BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')" to "AND created_date BETWEEN TO_DATE('09-01-2017', 'MM-DD-YYYY')" and received the intended results with the sysdate comparison before or afterward.

These will give two subtly different results for the values between 2017-10-01 00:00:01 and 2017-10-01 23:59:59. The query using TRUNC will include that range where without TRUNC that range will be excluded.

Also, using TRUNC means that Oracle will not us an index on the created_date column (and would require a function-based index on TRUNC( created_date )). If you want to use an index then just use the column and test to see if it is greater or equal than the start of the range and less than the end of the range plus one day (to include up to 23:59:59 of that day).

The simplified equivalent of your TRUNC query is:

SELECT created_date
FROM   tableName
WHERE  short_name like 'FOO%'
AND    created_date >= DATE '2017-09-01'                    -- range start
AND    created_date <  DATE '2017-10-01' + INTERVAL '1' DAY -- range end + 1 day


问:
Problem when specifying build configuration in TFS2010 build definition
Allow me to start by saying that this is a new and first time TFS deployment with 0 experience in Visual Studio as an added bonus. I've managed to get everything installed and am excited to say that I can even deploy as part of the build process to our different staging environments, but this is where things have gone south.

I'm trying to set up separate build definitions for each stage of development so that I can take advantage of config transforms and use granular permissions for who gets to promote where. In the configuration manager I have it set up so each solution configuration has a 1-1 mapping to a project context and always building 'Any CPU'. The problem is that when I use the /p:Configuration=QA switch in the MSBuild Arguments or just specify it in the 'Items to Build; section of the Build process parameters the build fails with a warning and it doesn't seem to get as far as MSDeploy.

Using the following arguments to MSBuild I am deploying with a default configuration, but again, no love on specifying a configuration.

/p:DeployOnBuild=True /p:DeployTarget=MSDeployPublish /p:MSDeployPublishMethod=WMSVC /p:MsDeployServiceUrl=10.31.60.109 /p:username=tfsdeploy /p:password=lulz /p:DeployIISAppPath=Bob /p:AllowUntrustedCertificate=True

Here is the warning I get in the TFS Build Explorer when specifying the configuration to use.

C:\Builds\2\Bob\Bob - Final Test\Sources\Bob\Bob.sln.metaproj: The specified solution configuration "QA|Any CPU" is invalid. Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform="Any CPU") or leave those properties blank to use the default solution configuration.

The solution originally was created in VS2008 and a local copy from VSS was pulled down with VS2008 and then pushed into TFS2010 using VS2010 pretty much letting MS work its magic to convert/update.

Any help is greatly appreciated.

答:
The issue I ran into here was that the names of the build configurations were different in the .sln and .csproj files and these can't be mapped to each other as I thought I was doing from within the VS2010 ide.

This is actually a pretty simple error. If you get it, check your spelling in the build definition then verify against the .sln and .csproj files using a text editor like vim/notepad.


问:
jQuery checkbox filter, working but want to reset when unchecked
I'm building a filter for a selection of condos. I've figured out how to filter using a slider and now also need to filter by number of bedrooms using two checkboxes.

```<code><form name="filter" method="post" action="">
  <p>Bedrooms
    <input id="1bdrm" type="checkbox" value="1bdrm" />1 Bedroom
    <input id="2bdrm" type="checkbox" value="2bdrm" />2 Bedroom
  </p>
</form>
</code>```

So far I have the filter limiting the selection to show only 1 bedroom units, but can't figure out how to reset and show all units when unchecking the checkbox.

```<code>// Set values for units
$('#cohen').data({
  id: 4,
  sqft: 976,
  bdrms: 2
});
$('#curnoe').data({
  id: 5,
  sqft: 572,
  bdrms: 2
});
$('#richler').data({
  id: 6,
  sqft: 624,
  bdrms: 2
});
$('#carr').data({
  id: 7,
  sqft: 544,
  bdrms: 1
});
$('#lawrence').data({
  id: 10,
  sqft: 467,
  bdrms: 1
});

//filter by number of bedrooms
$(document).ready(function() {
  var theValue;

  $("#1bdrm").click(function() {
    filterItems();
  });
});

function filterItems() {
  $.each($('.condo-box'), function() {
    $this = $(this);
    itemData = $this.data();
    if (itemData.bdrms == 1) {
      $this.show();
      itemData.matching = true;
    } else {
      $this.hide();
      itemData.matching = false;
    }
  });
}
</code>```

Here's a fiddle link.. https://jsfiddle.net/3y9vz1q1/ I'm using the .data method to store unique attributes on each unit so that i can filter for each attribute (example: I have another script written for a slider that limits condos by sqft.

Hoping the community can point me in the right direction! Thanks in advance.

Marc.

答:
You are marking elements that have the data tag bdrms set to 1 as invisible. This does not change. So once they are invisible, they will remain that way.

There are several ways to solve this, one being a seperate function that's being called when the checkbox isn't checked:

```<code>if($(this).is(':checked')){
    filterItems();
} else {
    resetAll();
}
</code>```

After that it's a simple matter of writing a function that resets the invisble elements back to visible:

```<code>function resetAll()
{
    $.each($('.condo-box'), function() {
        $this = $(this);
        if($this.is(":hidden")){
            $this.show();
        }
    });
}
</code>```

So updating your fiddle would be: https://jsfiddle.net/3y9vz1q1/1/ Which works fine.

UPDATE:

A far better solution would be to make both checkboxes work and use a single function:

```<code>$(document).ready(function() {
    $("#1bdrm, #2bdrm").click(function() {
    var bdrm1 = false;
    var bdrm2 = false;
    if($("#1bdrm").is(':checked')){
        bdrm1 = true;
    }
    if($("#2bdrm").is(':checked')){
        bdrm2 = true;
    }

    filterItems(bdrm1, bdrm2);
  });
});

function filterItems(bdrm1, bdrm2){
    $.each($('.condo-box'), function() {
    $this = $(this);
    itemData = $this.data();
    if(bdrm1 && !bdrm2){
      if(itemData.bdrms == 1){
        $this.show();
        itemData.matching = true;
      } else {
        $this.hide();
        itemData.matching = false;
      }
    }
    else if(bdrm2 && !bdrm1){
      if(itemData.bdrms == 2){
        $this.show();
        itemData.matching = true;
      } else {
        $this.hide();
        itemData.matching = false;
      }
    } else {
        $this.show();
        itemData.matching = true;
    }
  });
}
</code>```

Fiddle update: https://jsfiddle.net/3y9vz1q1/2/

Body:
I'm building a filter for a selection of condos. I've figured out how to filter using a slider and now also need to filter by number of bedrooms using two checkboxes.

<form name="filter" method="post" action="">

Bedrooms
    <input id="1bdrm" type="checkbox" value="1bdrm" />1 Bedroom
    <input id="2bdrm" type="checkbox" value="2bdrm" />2 Bedroom

</form>

So far I have the filter limiting the selection to show only 1 bedroom units, but can't figure out how to reset and show all units when unchecking the checkbox.

// Set values for units
$('#cohen').data({
  id: 4,
  sqft: 976,
  bdrms: 2
});
$('#curnoe').data({
  id: 5,
  sqft: 572,
  bdrms: 2
});
$('#richler').data({
  id: 6,
  sqft: 624,
  bdrms: 2
});
$('#carr').data({
  id: 7,
  sqft: 544,
  bdrms: 1
});
$('#lawrence').data({
  id: 10,
  sqft: 467,
  bdrms: 1
});

//filter by number of bedrooms
$(document).ready(function() {
  var theValue;

  $("#1bdrm").click(function() {
    filterItems();
  });
});

function filterItems() {
  $.each($('.condo-box'), function() {
    $this = $(this);
    itemData = $this.data();
    if (itemData.bdrms == 1) {
      $this.show();
      itemData.matching = true;
    } else {
      $this.hide();
      itemData.matching = false;
    }
  });
}

Here's a fiddle link.. https://jsfiddle.net/3y9vz1q1/ I'm using the .data method to store unique attributes on each unit so that i can filter for each attribute (example: I have another script written for a slider that limits condos by sqft.

Hoping the community can point me in the right direction! Thanks in advance.

Marc.

Body:
You are marking elements that have the data tag bdrms set to 1 as invisible. This does not change. So once they are invisible, they will remain that way.

There are several ways to solve this, one being a seperate function that's being called when the checkbox isn't checked:

if($(this).is(':checked')){
    filterItems();
} else {
    resetAll();
}

After that it's a simple matter of writing a function that resets the invisble elements back to visible:

function resetAll()
{
    $.each($('.condo-box'), function() {
        $this = $(this);
        if($this.is(":hidden")){
            $this.show();
        }
    });
}

So updating your fiddle would be: https://jsfiddle.net/3y9vz1q1/1/ Which works fine.

UPDATE:

A far better solution would be to make both checkboxes work and use a single function:

$(document).ready(function() {
    $("#1bdrm, #2bdrm").click(function() {
    var bdrm1 = false;
    var bdrm2 = false;
    if($("#1bdrm").is(':checked')){
        bdrm1 = true;
    }
    if($("#2bdrm").is(':checked')){
        bdrm2 = true;
    }

    filterItems(bdrm1, bdrm2);
  });
});

function filterItems(bdrm1, bdrm2){
    $.each($('.condo-box'), function() {
    $this = $(this);
    itemData = $this.data();
    if(bdrm1 && !bdrm2){
      if(itemData.bdrms == 1){
        $this.show();
        itemData.matching = true;
      } else {
        $this.hide();
        itemData.matching = false;
      }
    }
    else if(bdrm2 && !bdrm1){
      if(itemData.bdrms == 2){
        $this.show();
        itemData.matching = true;
      } else {
        $this.hide();
        itemData.matching = false;
      }
    } else {
        $this.show();
        itemData.matching = true;
    }
  });
}

Fiddle update: https://jsfiddle.net/3y9vz1q1/2/


问:
Vue.js use slot from children's children
So I have the following example:

Here is my child component. Every other ones of the following components is based upon this.

```<code><template>
  <div class="content-box">
    <div class="boxtitlecontainer titleColor">
      <slot name="title">Title</slot>
    </div>
    <div class="insidebox boxColor">
      <slot></slot>
    </div>
  </div>
</template>
</code>```

This is one of the children.

```<code><template>
  <div class="example">
    <box>
      <div slot="title"><slot name="title">Title</slot></div>
      <slot></slot>
    </box>
  </div>
</template>
</code>```

This component is directly used in my App.vue. To use <slot>s, the only way i found is this one above.

My question is: Is there a more elegant way of doing this and to not stack up div-Boxes unnecessary? I mean, I can do it with no named slots. I guess that the <slot> can be showed recursivly like content -> slot(1st children) -> slot(2nd children) but i have no idea about how to do it with named slots.

Thanks in advance for any help.

答:
instead of depending on slot for passing your content, why not use props instead?</p>

```<code><template>
  <div class="example">
    <box>
      <div v-text="title">Title</div>
      <slot></slot>
    </box>
  </div>
</template>

<script>
export default {
  props: ['title']
}
</script>
</code>```

Body:
So I have the following example:

Here is my child component. Every other ones of the following components is based upon this.

<template>

      <slot name="title">Title</slot>

      <slot></slot>

</template>

This is one of the children.

<template>

    <box>

<slot name="title">Title</slot>

      <slot></slot>
    </box>

</template>

This component is directly used in my App.vue. To use <slot>s, the only way i found is this one above.

My question is: Is there a more elegant way of doing this and to not stack up div-Boxes unnecessary? I mean, I can do it with no named slots. I guess that the <slot> can be showed recursivly like content -> slot(1st children) -> slot(2nd children) but i have no idea about how to do it with named slots.

Thanks in advance for any help.

Body:
instead of depending on slot for passing your content, why not use props instead?

<template>
  <div class="example">
    <box>
      <div v-text="title">Title</div>
      <slot></slot>
    </box>
  </div>
</template>

<script>
export default {
  props: ['title']
}
</script>


问:
Typescript cannot find module Protractor
I am integrating e2e testing in my project. The project uses Typescript (2.6.1).

I have just installed Protractor (5.2.0) but no matter what I do Typescript cannot import anything from the Protractor module.

My tsconfig looks like this:

```<code>{
    "compilerOptions": {
        "target": "es5",
        "module": "amd"
    },
    "exclude": [
        "./spec",
        "./node_modules",
        "./bower_components"
    ]
}
</code>```

My very simple try out test looks like this:

```<code>import { browser } from "protractor";

describe("test should run", () => {
    it("should navigate to the page", () => {

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

I get the following error: TypeScript error: usermanagement/ts/controllers/RolesController.e2e.ts(1,25): error TS2307: Cannot find module 'protractor'.

Looking at the Protractor installation in my node_modules folder I do find a reference to a typings file and the actual typings themselves. However Typescript simply does not 'see' them. Interestingly Typescript has no problem finding typings in the node_modules/@types folder.

Anyone know what I am doing wrong?

答:
In your tsconfig add:

```<code>"module": "commonjs"
</code>```

More

This is the recommended config I mention here as well https://basarat.gitbooks.io/typescript/content/docs/quick/nodejs.html

Body:
I am integrating e2e testing in my project. The project uses Typescript (2.6.1).

I have just installed Protractor (5.2.0) but no matter what I do Typescript cannot import anything from the Protractor module.

My tsconfig looks like this:

{
    "compilerOptions": {
        "target": "es5",
        "module": "amd"
    },
    "exclude": [
        "./spec",
        "./node_modules",
        "./bower_components"
    ]
}

My very simple try out test looks like this:

import { browser } from "protractor";

describe("test should run", () => {
    it("should navigate to the page", () => {

    });
});

I get the following error: TypeScript error: usermanagement/ts/controllers/RolesController.e2e.ts(1,25): error TS2307: Cannot find module 'protractor'.

Looking at the Protractor installation in my node_modules folder I do find a reference to a typings file and the actual typings themselves. However Typescript simply does not 'see' them. Interestingly Typescript has no problem finding typings in the node_modules/@types folder.

Anyone know what I am doing wrong?

Body:
In your tsconfig add:

"module": "commonjs"

More

This is the recommended config I mention here as well https://basarat.gitbooks.io/typescript/content/docs/quick/nodejs.html


问:
generic call of class in c#
```<code>SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
</code>```

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

```<code>if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...
</code>```

i want to make something like

```<code>(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...
</code>```

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.

答:
It sounds like you're trying to work around creating a factory pattern, which would, IMO, be the correct way to solve this problem.

http://aspalliance.com/809

Title: generic call of class in c#

Body:
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...

i want to make something like

(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.


问:
knockout validation after input
I have a class:

```<code>Model.Feedback.Data = function () {
    var self = this;

    self.Name = ko.observable('').extend({
        pattern: {
            params: /^[A-Za-z]+[A-Za-z\s]*$/,
            message: 'Invalid name'
        }
    });

    self.Email = ko.observable('').extend({
        pattern: {
            params: /^[a-zA-Z0-9!#$%&'*+/=?^`{|}~]+(?:[\._-][a-zA-Z0-9!#$%&'*+/=?^`{|}~]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/,
            message: 'Invalid e-mail'
        },
        maxLength: {
            params: 256,
            message: 'Long email'
        }
    });

    return this;
};
</code>```

I have an HTML code:

```<code><form class="form-additem-checkin" data-bind="submit: send">
    <!--ko with: Data-->
    <div class="form-additem-group-row">
        <div class="form-additem-group-row__col form-additem-group-row__col_label"><div class="form-additem-group__label">E-mail</div></div>
        <div class="form-additem-group-row__col form-additem-group-row__col_field">
            <input type="text" class="field field_type2 input--full" placeholder="You e-mail" data-bind="textInput: Email" />
            <div class="form-additem-group-row__error" data-bind="validationMessage: Email"></div>
        </div>
    </div>
    <div class="form-additem-group-row">
        <div class="form-additem-group-row__col form-additem-group-row__col_label"><div class="form-additem-group__label">Name</div></div>
        <div class="form-additem-group-row__col form-additem-group-row__col_field">
            <input type="text" class="field field_type2 input--full" placeholder="You name" data-bind="textInput: Name" />
            <div class="form-additem-group-row__error" data-bind="validationMessage: Name"></div>
        </div>
    </div>
    <!--/ko-->
    <div class="form-additem-auth__button">
        <button type="submit" class="btn btn--green form-additem-button">Send</button>
    </div>
</form>
</code>```

Now, if you enter test@ a in the email field, you will immediately get an error message.

What can I do to check the field after losing the focus of the field?

答:
Usage of value binding instead textInput seems to resolve it. (Credits: Jason Spake)

Alternatively you can use hasFocus binding and show the error message once there is no focus. (Not so elegant + message disappears once the input is focussed again.)

Title: knockout validation after input

Body:
I have a class:

Model.Feedback.Data = function () {
    var self = this;

    self.Name = ko.observable('').extend({
        pattern: {
            params: /^[A-Za-z]+[A-Za-z\s]*$/,
            message: 'Invalid name'
        }
    });

    self.Email = ko.observable('').extend({
        pattern: {
            params: /^[a-zA-Z0-9!#$%&'*+/=?^`{|}~]+(?:[\._-][a-zA-Z0-9!#$%&'*+/=?^`{|}~]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/,
            message: 'Invalid e-mail'
        },
        maxLength: {
            params: 256,
            message: 'Long email'
        }
    });

    return this;
};

I have an HTML code:

<form class="form-additem-checkin" data-bind="submit: send">

E-mail

            <input type="text" class="field field_type2 input--full" placeholder="You e-mail" data-bind="textInput: Email" />

Name

            <input type="text" class="field field_type2 input--full" placeholder="You name" data-bind="textInput: Name" />

        <button type="submit" class="btn btn--green form-additem-button">Send</button>

</form>

Now, if you enter test@ a in the email field, you will immediately get an error message.

What can I do to check the field after losing the focus of the field?


问:
get the whole word string after finding the word in a text
i have a problem developing this function, i have this text..

```<code>Testing Function
ok
US.Cool
rwgehtrhjyw54 US_Cool
fhknehq is ryhetjuy6u24
gflekhtrhissfhejyw54i
</code>```

my function :

```<code>function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
begin
 Result := 0;
 for i:= 1 to Length(sTheString) do
   begin
    x := Copy(sTheString,i,Length(sWordToFind));
    if X = sWordToFind then
      begin
        if X.Length > sWordToFind.Length then
         begin
          Result := 100;
          break;
         end else

         begin
          Result := i;
          break;
         end;
       end;
   end;
end;
</code>```

now, i want X to be US.Cool, but here its always = US,  because i want to check the length of sWordToFind and X.

答:
I spend a few times on your idea, so i wrote below codes, but it is not a good way for develop a Start With search. with some research you can find builtin functions, that provide better performance. you can try StrUtils.SearchBuf Function it will provide a full function string search.

anyway this code are working with SPACE separator, I hope it will be useful for you:

```<code>function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
flag : Boolean;
begin
 Result := 0;
 i := 1;
 flag := False;
 while True do
   begin
   if i > Length(sTheString) then  Break;

   if not flag then
       x := Copy(sTheString,i,Length(sWordToFind))
   else
   begin

       if sTheString[i] = ' ' then Break;
       x := x + sTheString[i];
   end;

    if (X = sWordToFind)  then
      begin
        flag := True;
        if (X.Length >= sWordToFind.Length) and
           (sTheString[i + Length(sWordToFind)]  = ' ') then
          break
        else
          i := i +  Length(sWordToFind) -1;

       end;

     i := i + 1;
   end;
   Result :=  Length(x);
end;
</code>```

Body:
i have a problem developing this function, i have this text..

Testing Function
ok
US.Cool
rwgehtrhjyw54 US_Cool
fhknehq is ryhetjuy6u24
gflekhtrhissfhejyw54i

my function :

function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
begin
 Result := 0;
 for i:= 1 to Length(sTheString) do
   begin
    x := Copy(sTheString,i,Length(sWordToFind));
    if X = sWordToFind then
      begin
        if X.Length > sWordToFind.Length then
         begin
          Result := 100;
          break;
         end else

         begin
          Result := i;
          break;
         end;
       end;
   end;
end;

now, i want X to be US.Cool, but here its always = US,  because i want to check the length of sWordToFind and X.

Body:
I spend a few times on your idea, so i wrote below codes, but it is not a good way for develop a Start With search. with some research you can find builtin functions, that provide better performance. you can try StrUtils.SearchBuf Function it will provide a full function string search.

anyway this code are working with SPACE separator, I hope it will be useful for you:

function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
flag : Boolean;
begin
 Result := 0;
 i := 1;
 flag := False;
 while True do
   begin
   if i > Length(sTheString) then  Break;

   if not flag then
       x := Copy(sTheString,i,Length(sWordToFind))
   else
   begin

       if sTheString[i] = ' ' then Break;
       x := x + sTheString[i];
   end;

    if (X = sWordToFind)  then
      begin
        flag := True;
        if (X.Length >= sWordToFind.Length) and
           (sTheString[i + Length(sWordToFind)]  = ' ') then
          break
        else
          i := i +  Length(sWordToFind) -1;

       end;

     i := i + 1;
   end;
   Result :=  Length(x);
end;


问:
File handles in Perl
Instead of the typical file handle I am used to:

```<code>open INPUT, $input;
while ($line = <INPUT>) {
    ....
}
close INPUT;
</code>```

How do I retrieve a pointer to the line in a file so that I can advance these pointers at wiil? I'm trying to create two pointers to their corresponding sorted files so that I can advance pointers based on whether the line in one file is "less" or "greater" than the line in the other.

Note: Assume input files are BIG.

答:
Why not store in an array?

```<code>my @lines1 = <INPUT1>;
my @lines2 = <INPUT2>;
</code>```

Here's an example on ysth's seek/tell suggestion, which is probably more what you want if the files are too big:
http://www.nntp.perl.org/group/perl.beginners/2007/12/msg97522.html

Title: File handles in Perl

Body:
Instead of the typical file handle I am used to:

open INPUT, $input;
while ($line = <INPUT>) {
    ....
}
close INPUT;

How do I retrieve a pointer to the line in a file so that I can advance these pointers at wiil? I'm trying to create two pointers to their corresponding sorted files so that I can advance pointers based on whether the line in one file is "less" or "greater" than the line in the other.

Note: Assume input files are BIG.

Body:
Why not store in an array?

my @lines1 = <INPUT1>;
my @lines2 = <INPUT2>;

Here's an example on ysth's seek/tell suggestion, which is probably more what you want if the files are too big:
http://www.nntp.perl.org/group/perl.beginners/2007/12/msg97522.html


问:
Import error with unit tests: "No module named ..." from local libary
I'm new to Python (JS developer) and am trying to run a testing suite. My project folder structure is as such:

```<code>project/
  __init__.py
  libs/
    __init__.py
    s3panda.py
  tests
    __init__.py
    tests_s3panda.py
</code>```

In terminal, I'm running python tests_s3panda.py.

I don't understand how it's unable to find a local module:

Traceback (most recent call last):   File "tests_s3panda.py", line 7,
  in
      from libs.s3panda import S3Panda ImportError: No module named libs.s3panda

tests_s3panda.py snippet:

```<code>from __future__ import absolute_import

import unittest

import pandas as pd

from libs.s3panda import S3Panda

class TestS3Panda(unittest.TestCase):
    ...
</code>```

Doing from ..libs.s3panda import S3Panda for relative path, I get:

ValueError: Attempted relative import in non-package

答:
I believe the fact that there is no init.py in the top-level folder means that Python is not aware that libs and tests are both part of the same module called project.

Try adding an __init__.py to your project folder, then write the import statement as from project.libs.s3panda import S3Panda. In general, you want to specify absolute imports rather than relative imports (When to use absolute imports).

Body:
I'm new to Python (JS developer) and am trying to run a testing suite. My project folder structure is as such:

project/
  __init__.py
  libs/
    __init__.py
    s3panda.py
  tests
    __init__.py
    tests_s3panda.py

In terminal, I'm running python tests_s3panda.py.

I don't understand how it's unable to find a local module:

Traceback (most recent call last):   File "tests_s3panda.py", line 7,
  in
      from libs.s3panda import S3Panda ImportError: No module named libs.s3panda

tests_s3panda.py snippet:

from __future__ import absolute_import

import unittest

import pandas as pd

from libs.s3panda import S3Panda

class TestS3Panda(unittest.TestCase):
    ...

Doing from ..libs.s3panda import S3Panda for relative path, I get:

ValueError: Attempted relative import in non-package


问:
What Does the Batch Command rp Do?
I have a makefile that is ran by GNU Make in Windows. There are two lines within a target's recipe that I did not write, these are them:

```<code>@echo Executing Command
@rp prebuild
</code>```

I know what the @ symbol does, it prevents the command from being echoed to the batch shell. Therefore the first line will not say:

```<code>echo Executing Command
Executing Command
</code>```

Instead it will just say:

```<code>Executing Command
</code>```

However what does the second line do? I can't seem to find any information for the rp command under the batch syntax.

答: Turns out it was an external batch script named rp.bat that it was calling.</p>

Title: What Does the Batch Command rp Do?

Body:
I have a makefile that is ran by GNU Make in Windows. There are two lines within a target's recipe that I did not write, these are them:

@echo Executing Command
@rp prebuild

I know what the @ symbol does, it prevents the command from being echoed to the batch shell. Therefore the first line will not say:

echo Executing Command
Executing Command

Instead it will just say:

Executing Command

However what does the second line do? I can't seem to find any information for the rp command under the batch syntax.


问:
How do you detect if a user creates a worksheet using ctrl-click in excel?
Is there any way in Excel VBA to detect when a user creates a worksheet by holding ctrl and clicking on a tab then dragging it?

The newsheet event doesn't appear to be triggered when this occurs so was wondering if there is any other way to detect this...

答:
The only way that I know how to get around the problem is to keep track of the sheet count.

You can do this by adding a public variable to a module, e.g.

```<code>Public SheetCount As Integer
</code>```

And then add the following event handlers into ThisWorkbook

```<code>Option Explicit

Private Sub Workbook_Open()
    SheetCount = ThisWorkbook.Sheets.Count
End Sub

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

    Dim newCount As Integer
    newCount = ThisWorkbook.Sheets.Count

    If newCount > SheetCount Then
        SheetCount = newCount
        MsgBox "sheet added"
    End If

End Sub

Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
    SheetCount = SheetCount - 1
End Sub
</code>```

The MsgBox is just for testing purposes, naturally.

Body:
The only way that I know how to get around the problem is to keep track of the sheet count.

You can do this by adding a public variable to a module, e.g.

Public SheetCount As Integer

And then add the following event handlers into ThisWorkbook

Option Explicit

Private Sub Workbook_Open()
    SheetCount = ThisWorkbook.Sheets.Count
End Sub

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

    Dim newCount As Integer
    newCount = ThisWorkbook.Sheets.Count

    If newCount > SheetCount Then
        SheetCount = newCount
        MsgBox "sheet added"
    End If

End Sub

Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
    SheetCount = SheetCount - 1
End Sub

The MsgBox is just for testing purposes, naturally.


问:
tensorflow "adding an op" debugging?
I try to extend the tensorflow library: https://www.tensorflow.org/extend/adding_an_op

```<code>REGISTER_OP("Test")
.Input("input: string")
.Attr("test: float")
.Output("output: string")
.Doc(R"doc("some douc")doc");

class Test : public OpKernel {
 public:
  explicit Test(OpKernelConstruction* context) : OpKernel(context)
  {
    std::cout << "Why is this not printing" << std::endl;
    std::string input;
    OP_REQUIRES_OK(context, context->GetAttr("test", &input));
    std::cout << input << std::endl;
  }

  void Compute(OpKernelContext* context) override
  {
    std::cout << "Why is that not printing? " << std::endl;
    Tensor input_tensor = context->input(0);
    Tensor* output_tensor = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output("output",
    input_tensor.shape(), &output_tensor));
    auto output = output_tensor->flat<string>();
  }
};

REGISTER_KERNEL_BUILDER(Name("Test") \
                        .Device(DEVICE_CPU), \
                        Test);
</code>```

Why is this function not printing? But I get an return value when I start the function. I think that it is not possible to print something, is not it?

Edit: How I call it in main.py?

```<code>import tensorflow as tf
import tensorflow.contrib.icg as tficg

if __name__ == '__main__':
    print('start')
    print(tficg.stereo_matching('hello', 1))
</code>```

Output:

```<code>start
Tensor("StereoMatching:0", dtype=string)
</code>```

答: This should print. Are you looking at stdout and stderr?</p>

Title: tensorflow "adding an op" debugging?

Body:
I try to extend the tensorflow library: https://www.tensorflow.org/extend/adding_an_op

REGISTER_OP("Test")
.Input("input: string")
.Attr("test: float")
.Output("output: string")
.Doc(R"doc("some douc")doc");

class Test : public OpKernel {
 public:
  explicit Test(OpKernelConstruction* context) : OpKernel(context)
  {
    std::cout << "Why is this not printing" << std::endl;
    std::string input;
    OP_REQUIRES_OK(context, context->GetAttr("test", &input));
    std::cout << input << std::endl;
  }

  void Compute(OpKernelContext* context) override
  {
    std::cout << "Why is that not printing? " << std::endl;
    Tensor input_tensor = context->input(0);
    Tensor* output_tensor = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output("output",
    input_tensor.shape(), &output_tensor));
    auto output = output_tensor->flat<string>();
  }
};

REGISTER_KERNEL_BUILDER(Name("Test") \
                        .Device(DEVICE_CPU), \
                        Test);

Why is this function not printing? But I get an return value when I start the function. I think that it is not possible to print something, is not it?

Edit: How I call it in main.py?

import tensorflow as tf
import tensorflow.contrib.icg as tficg

if __name__ == '__main__':
    print('start')
    print(tficg.stereo_matching('hello', 1))

Output:

start
Tensor("StereoMatching:0", dtype=string)


问:
Request Access Token in Postman for Azure AD B2C
How can I request an Access Token in Postman against an Azure AD B2C tenant?

I tried taking the url from Run Now in the Azure portal and putting that in the Auth Url but that produces the following error:

Update

Following Chris's answer, I'm now past the above error.  I'm able to sign-in but still can't get an access token:

AADB2C90085: The service has encountered an internal error. Please reauthenticate and try again.
   Correlation ID: 45c56d47-4739-465f-8e02-49ba5b3a1b86
   Timestamp: 2017-11-16 15:27:52Z

答:
For the Auth URL field, you only have to enter the authorization endpoint URL without the query string parameters:

```<code>https://login.microsoftonline.com/te/{tenant}/{policy}/oauth2/v2.0/authorize
</code>```

For the Access Token URL field:

```<code>https://login.microsoftonline.com/te/{tenant}/{policy}/oauth2/v2.0/token
</code>```

For the Callback URL field, you must enter a reply URL that is registered with the Azure AD B2C application, such as:

```<code>https://www.getpostman.com/oauth2/callback
</code>```

For the Scope field, enter "openid" as well as any API access scopes.

For the Client Authentication field, select "Send client credentials in body".

Body:
For the Auth URL field, you only have to enter the authorization endpoint URL without the query string parameters:

https://login.microsoftonline.com/te/{tenant}/{policy}/oauth2/v2.0/authorize

For the Access Token URL field:

https://login.microsoftonline.com/te/{tenant}/{policy}/oauth2/v2.0/token

For the Callback URL field, you must enter a reply URL that is registered with the Azure AD B2C application, such as:

https://www.getpostman.com/oauth2/callback

For the Scope field, enter "openid" as well as any API access scopes.

For the Client Authentication field, select "Send client credentials in body".


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答:
The nature of design is changing, I'd say the new way is to think before coding, but just about what will be implemented in the next iteration. See "Is design dead".

Design for today, code for tomorrow.

OwnerDisplayName: Phil H

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H

OwnerDisplayName: philippe


问:
Implement restful url in .net where service is implemented using IHTTPHandler
I want to implement a restful service in ASP.NET. I want it to be compatible with .Net 2.0 and IIS 5+. I am constrained to not use ASP.NET MVC or REST starter kit. By reading on internet I have learned that it can be implemented using HTTPHandlers. The problem is, the request will come in as a POST request. And I want to URL to be like:

http://abc.com/MyService/MyMethod1/
and
http://abc.com/MyService/MyMethod2/

Any workarounds for this?

Thanks,
Vamyip

答:
If you can allow the restriction of only IIS 7.0 and above you could use URL Rewrite http://www.iis.net/download/URLRewrite to do that pretty easily.

Can I ask why is it that you need to support IIS 5+? That is an 11 year old technology that hopefully people will move out of those platforms in favor of more recent versions. Also keep in mind support for some of those platforms is ending pretty soon.

If the concern is developers running Windows XP I would point out that IIS Express includes version 7.5+ functionality and is available for all platforms Windows XP and above.


问:
PHP - trying to write function outputs via fwrite into file
It is late (in Europe anyhow) and my mind is blocked with why I can't find the answer to the above question.

My goal ist to have sth. like a keygen program that first writes into an external .csv or .txt. The rest afterwards can be ignored for now.

Anyhow I can't see how I could write the combined effort of my functions into a file and humbly ask for help.

```<code><?php
if (isset($_POST["codeCount"]))
    $codeCount = $_POST["codeCount"];
if (isset($_POST["digitsCount"]))
    $digitsCount = $_POST["digitsCount"];
if (isset($_POST["blockCount"]))
    $blockCount = $_POST["blockCount"];

#Generieren eines Blocks mit x Digits
function keygen($digitsCount){
    $charpool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    for ($i=0; $i < $digitsCount; $i++) {
        $five = substr($charpool, random_int(0, strlen($charpool)-1), 1);
        echo $five;
    }
}

#Wie viele Blöcke soll es geben?
function keygenLong($blockCount, $digitsCount){
    for ($i=0; $i < $blockCount; $i++) {
        echo keygen($digitsCount);
        if ($i != $blockCount-1) {
            echo "-";
        }
    }
}

#Wie viele Codes benötigen wir ingesamt?
function codeOutput($codeCount, $blockCount, $digitsCount){
    for ($i=0; $i < $codeCount; $i++) {
        keygenLong($blockCount, $digitsCount);
        echo "<br>";
    }
}

codeOutput($codeCount, $blockCount, $digitsCount);

// $code = "codeOutput";
// $string = $code($codeCount, $blockCount, $digitsCount);

if (isset($_POST["submit"])) {

    $file = fopen("keys.txt","w");

    fwrite($file, codeOutput($codeCount, $blockCount, $digitsCount);
);

    fclose($file);
}
</code>```

答:
Have your functions return values instead of echo-ing them out. Then you can assign the values to a variable and write it to your file.

For example

```<code>function keygen($digitsCount){
    $charpool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    for ($i=0; $i < $digitsCount; $i++) {
        $five[] = substr($charpool, random_int(0, strlen($charpool)-1), 1);
    }
    return implode('', $five);
}

function keygenLong($blockCount, $digitsCount){
    for ($i=0; $i < $blockCount; $i++) {
        $out[] = keygen($digitsCount);
    }
    return implode('-', $out);
}

function codeOutput($codeCount, $blockCount, $digitsCount){
    for ($i=0; $i < $codeCount; $i++) {
        $out[] = keygenLong($blockCount, $digitsCount);
    }
    return $out; // this one is still an array
}

$data = codeOutput($codeCount, $blockCount, $digitsCount);
</code>```

Then to write the data to a file...

```<code>file_put_contents('keys.txt', implode(PHP_EOL, $data));
</code>```

Or output for HTML

```<code>echo implode('<br>', $data);
</code>```

Body:
It is late (in Europe anyhow) and my mind is blocked with why I can't find the answer to the above question.

My goal ist to have sth. like a keygen program that first writes into an external .csv or .txt. The rest afterwards can be ignored for now.

Anyhow I can't see how I could write the combined effort of my functions into a file and humbly ask for help.

<?php
if (isset($_POST["codeCount"]))
    $codeCount = $_POST["codeCount"];
if (isset($_POST["digitsCount"]))
    $digitsCount = $_POST["digitsCount"];
if (isset($_POST["blockCount"]))
    $blockCount = $_POST["blockCount"];

#Generieren eines Blocks mit x Digits
function keygen($digitsCount){
    $charpool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    for ($i=0; $i < $digitsCount; $i++) {
        $five = substr($charpool, random_int(0, strlen($charpool)-1), 1);
        echo $five;
    }
}

#Wie viele Blöcke soll es geben?
function keygenLong($blockCount, $digitsCount){
    for ($i=0; $i < $blockCount; $i++) {
        echo keygen($digitsCount);
        if ($i != $blockCount-1) {
            echo "-";
        }
    }
}

#Wie viele Codes benötigen wir ingesamt?
function codeOutput($codeCount, $blockCount, $digitsCount){
    for ($i=0; $i < $codeCount; $i++) {
        keygenLong($blockCount, $digitsCount);
        echo "
";
    }
}

codeOutput($codeCount, $blockCount, $digitsCount);

// $code = "codeOutput";
// $string = $code($codeCount, $blockCount, $digitsCount);

if (isset($_POST["submit"])) {

    $file = fopen("keys.txt","w");

    fwrite($file, codeOutput($codeCount, $blockCount, $digitsCount);
);

    fclose($file);
}

Body:
Have your functions return values instead of echo-ing them out. Then you can assign the values to a variable and write it to your file.

For example

function keygen($digitsCount){
    $charpool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    for ($i=0; $i < $digitsCount; $i++) {
        $five[] = substr($charpool, random_int(0, strlen($charpool)-1), 1);
    }
    return implode('', $five);
}

function keygenLong($blockCount, $digitsCount){
    for ($i=0; $i < $blockCount; $i++) {
        $out[] = keygen($digitsCount);
    }
    return implode('-', $out);
}

function codeOutput($codeCount, $blockCount, $digitsCount){
    for ($i=0; $i < $codeCount; $i++) {
        $out[] = keygenLong($blockCount, $digitsCount);
    }
    return $out; // this one is still an array
}

$data = codeOutput($codeCount, $blockCount, $digitsCount);

Then to write the data to a file...

file_put_contents('keys.txt', implode(PHP_EOL, $data));

Or output for HTML

echo implode('<br>', $data);


问:
Run gradle task and save its return value to shell script variable
Is there a way to run a gradle task and save it output to shell variable ?

For example lets consider a gradle task that prints module version :

```<code>task getVersion << {
    println '2.2.0'
}
</code>```

I run this task in the shell like this :

```<code>$./gradlew getVersion
</code>```

Is it possible to save output of gradle task getVersion into shell variable. For example:

```<code>VERSION=`./gradlew getVersion`
echo "Module Version is $VERSION"
</code>```

答:
In bash, you can do it like this:

```<code>VERSION=$(./gradlew -q getVersion | tail -n 1)
</code>```

-q : set gradle output to quit

| tail -n 1 : only use the last line of the output in your variable. Might not need this part, but sometime gradle outputs warnings/errors before printing the actual output. I personally experienced this while upgrading to gradle4.1. After the upgrade it also showed Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.

Body:
Is there a way to run a gradle task and save it output to shell variable ?

For example lets consider a gradle task that prints module version :

task getVersion << {
    println '2.2.0'
}

I run this task in the shell like this :

$./gradlew getVersion

Is it possible to save output of gradle task getVersion into shell variable. For example:

VERSION=`./gradlew getVersion`
echo "Module Version is $VERSION"

Body:
In bash, you can do it like this:

VERSION=$(./gradlew -q getVersion | tail -n 1)

-q : set gradle output to quit

| tail -n 1 : only use the last line of the output in your variable. Might not need this part, but sometime gradle outputs warnings/errors before printing the actual output. I personally experienced this while upgrading to gradle4.1. After the upgrade it also showed Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.


问:
In asp.net with sqlite set pragma Synchronous=Off
Try optimize Sqlite in an asp.net app by setting Synchronous=Off in the connection string, but keyword isn't supported https://github.com/ericsink/SQLitePCL.raw/issues/147
https://github.com/aspnet/Microsoft.Data.Sqlite/issues/354

Bottom of issue #354 suggests a solution with a pragma command towards the connection

```<code>using (var command = connection.CreateCommand())
{
    command.CommandText = "PRAGMA foreign_keys = true;";
    command.ExecuteNonQuery();
}
</code>```

Try to use this for Synchronous
https://sqlite.org/pragma.html#pragma_synchronous but uncertain where/how to obtain the correct connection corresponding to my DbContext type.

答:
Drop down to the ADO.NET connection in EF Core using code like this:

db.Database.OpenConnection();
try
{
    var connection = db.Database.GetDbConnection();

    // TODO: Use connection
}
finally
{
    db.Database.CloseConnection();
}
```

Body:
Try optimize Sqlite in an asp.net app by setting Synchronous=Off in the connection string, but keyword isn't supported https://github.com/ericsink/SQLitePCL.raw/issues/147
https://github.com/aspnet/Microsoft.Data.Sqlite/issues/354

Bottom of issue #354 suggests a solution with a pragma command towards the connection

using (var command = connection.CreateCommand())
{
    command.CommandText = "PRAGMA foreign_keys = true;";
    command.ExecuteNonQuery();
}

Try to use this for Synchronous
https://sqlite.org/pragma.html#pragma_synchronous but uncertain where/how to obtain the correct connection corresponding to my DbContext type.


问:
How to access plugin output in serverless.yml of Serverless Framework?
Context: to achieve full "infrastructure as code", I want to codify the process of requesting a SSL certificate using certbot, validating a domain using DNS TXT records, uploading the certificate to Amazon Certificate Manager (ACM), and finally attaching the certificate ACM ARN to my Cloudfront distribution. This should all be done through the Serverless framework.

I saw 2 potential options to make this work.

Option 1: use of asynchronous javascript file variables

I.e. in serverless.yml I would define entries like:

```<code>custom:

  domains:
    prod: tommedema.tk

  ssl:
    prod:
      dnsTxtRoot: ${{file(scripts/request-cert.js):cert.dnsTxtRoot}}
      dnsTxtWww: ${{file(scripts/request-cert.js):cert.dnsTxtWww}}
      certArn: ${{file(scripts/request-cert.js):cert.certArn}}
</code>```

Where resources would then use these variables like so:

```<code>- Type: TXT
  Name: _acme-challenge.www.${{self:custom.domains.${{self:provider.stage}}, ''}}
  TTL: '86400'
  ResourceRecords:
    - ${{self:custom.ssl.${{self:provider.stage}}.dnsTxtWww}}
</code>```

Where scripts/request-cert.js would look like:

```<code>module.exports.cert = () => {
  console.log('running async logic')

  // TODO: run certbot, get DNS records, upload to ACM

  return Promise.resolve({
    dnsTxtRoot: '"LnaKMkgqlIkXXXXXXXX-7PkKvqb_wqwVnC4q0"',
    dnsTxtWww: '"c43VS-XXXXXXXXXWVBRPCXXcA"',
    certArn: 'arn:aws:acm:us-east-1:XXXX95:certificate/XXXXXX'
  })
}
</code>```

The problem here is that it appears to be impossible to send parameters to request-cert.js, or for this script to be aware of the serverless or options plugin parameters (as it is not a plugin, but a simple script without context). This means that the script cannot be aware of the stage and domain etc. that the deployment is for, and therefore it is missing necessary variables in order to request the certificate.

So, option 1 seems out of the question.

Option 2: create a plugin

Of course I can create a plugin, which will have all required variables because it can access the serverless and options objects. The problem now is that I would have to access the output of the plugin inside serverless.yml, and so far I have not seen how this can be done. I.e. I would like to be able to do something like this:

```<code>custom:

  domains:
    prod: tommedema.tk

  ssl:
    prod:
      dnsTxtRoot: ${{myPlugin:cert.dnsTxtRoot}}
      dnsTxtWww: ${{myPlugin:cert.dnsTxtWww}}
      certArn: ${{myPlugin:cert.certArn}}
</code>```

But this does not seem possible. Is that right?

If this is also not possible, how can I achieve my purpose to programatically (i.e. following infrastructure as code principles) deploy my services with custom SSL certificates, without any manual steps? I.e.

request certificate from certbot

receive DNS txt records for validation from certbot

attach DNS txt records to route53 recordsets

deploy the DNS records and validate the certificate

download the certificate from certbot and upload it to ACM

receive the certificate ARN from ACM

reference to the certificate ARN from within the cloudfront distribution inside the cloudformation template

redeploy with the certificate ARN attached

答:
You could do it at deploy time, but certificates expire so it's best to make this a recurring thing.

When I was faced with this problem, I created a Lambda to upsert the SSL certificate and install it. (it needs a long timeout, but that's fine - it doesn't need to run often). The key it needs can be given as secure environment variables.

Then I use serverless-warmup-plugin to set up a daily trigger to check whether the certificate is due to be refreshed. The plugin is configurable to warm up relevant lambdas on deployment too, which allows me to check for expired or missing SSL certs on each deploy.

Maybe you could do something similar.

Body:
Context: to achieve full "infrastructure as code", I want to codify the process of requesting a SSL certificate using certbot, validating a domain using DNS TXT records, uploading the certificate to Amazon Certificate Manager (ACM), and finally attaching the certificate ACM ARN to my Cloudfront distribution. This should all be done through the Serverless framework.

I saw 2 potential options to make this work.

Option 1: use of asynchronous javascript file variables

I.e. in serverless.yml I would define entries like:

custom:

  domains:
    prod: tommedema.tk

  ssl:
    prod:
      dnsTxtRoot: ${{file(scripts/request-cert.js):cert.dnsTxtRoot}}
      dnsTxtWww: ${{file(scripts/request-cert.js):cert.dnsTxtWww}}
      certArn: ${{file(scripts/request-cert.js):cert.certArn}}

Where resources would then use these variables like so:

- Type: TXT
  Name: _acme-challenge.www.${{self:custom.domains.${{self:provider.stage}}, ''}}
  TTL: '86400'
  ResourceRecords:
    - ${{self:custom.ssl.${{self:provider.stage}}.dnsTxtWww}}

Where scripts/request-cert.js would look like:

module.exports.cert = () => {
  console.log('running async logic')

  // TODO: run certbot, get DNS records, upload to ACM

  return Promise.resolve({
    dnsTxtRoot: '"LnaKMkgqlIkXXXXXXXX-7PkKvqb_wqwVnC4q0"',
    dnsTxtWww: '"c43VS-XXXXXXXXXWVBRPCXXcA"',
    certArn: 'arn:aws:acm:us-east-1:XXXX95:certificate/XXXXXX'
  })
}

The problem here is that it appears to be impossible to send parameters to request-cert.js, or for this script to be aware of the serverless or options plugin parameters (as it is not a plugin, but a simple script without context). This means that the script cannot be aware of the stage and domain etc. that the deployment is for, and therefore it is missing necessary variables in order to request the certificate.

So, option 1 seems out of the question.

Option 2: create a plugin

Of course I can create a plugin, which will have all required variables because it can access the serverless and options objects. The problem now is that I would have to access the output of the plugin inside serverless.yml, and so far I have not seen how this can be done. I.e. I would like to be able to do something like this:

custom:

  domains:
    prod: tommedema.tk

  ssl:
    prod:
      dnsTxtRoot: ${{myPlugin:cert.dnsTxtRoot}}
      dnsTxtWww: ${{myPlugin:cert.dnsTxtWww}}
      certArn: ${{myPlugin:cert.certArn}}

But this does not seem possible. Is that right?

If this is also not possible, how can I achieve my purpose to programatically (i.e. following infrastructure as code principles) deploy my services with custom SSL certificates, without any manual steps? I.e.

request certificate from certbot

receive DNS txt records for validation from certbot

attach DNS txt records to route53 recordsets

deploy the DNS records and validate the certificate

download the certificate from certbot and upload it to ACM

receive the certificate ARN from ACM

reference to the certificate ARN from within the cloudfront distribution inside the cloudformation template

redeploy with the certificate ARN attached


问:
How to get last record based on a date with some other aggregate column in a SQL query
I know this question is already asked like 100 time and I reviewed all of them but I'm Kinda Stuck and had to asked for help

I have table like this:

```<code>hivenumber Visitdate   CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-10    10       2        4
    2      2017-11-10    11       1        3
    3      2017-11-10    12       3        3
    1      2017-11-12    13       1        1
    3      2017-11-11    14       5        2
</code>```

At first I want to aggregate it by HiveNumber

```<code>Select HiveNumber
From tHivesDetails
Group BY HiveNumber
</code>```

Then I want the last record of CombNo for each HiveNumber

```<code>Select Top(1) CombNo
From `tHivesDetails`
Order By VisitDate Desc
</code>```

Then I need sum of Wax for each HiveNumber

```<code>Select Sum(Wax)
From `tHivesDetails`
Group BY HiveNumber
</code>```

and at the end I want average of BeeBehave

```<code>Select Avg(BeeBehave)
From tHivesDetails
Group By HiveNumber
</code>```

I don't know how to combine these queries to 1 and have one table with all I need in this case. I read most of same question but unfortunately couldn't figure it how do that.

I want a result like this:

```<code>hivenumber  Visitdate  CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-12    13      Sum      avg
    2      2017-11-10    11      sum      avg
    3      2017-11-11    14      sum      avg
</code>```

答:
Try this:</p>

```<code>SELECT tA.HiveNumber, tA.WaxNoSum, tA.BeeBehaveSum, tB.CombsNoLatest
FROM (SELECT HiveNumber, SUM(WaxNo) AS WaxNoSum, AVG(BeeBehave) AS BeeBehaveSum
      FROM tHivesDetails
      GROUP BY HiveNumber) AS tA LEFT JOIN (SELECT HiveNumber, MAX(CombsNO) AS CombsNoLatest
                                            FROM tHivesDetails
                                            GROUP BY HiveNumber) AS tB ON tA.HiveNumber = tB.HiveNumber
</code>```

Body:
I know this question is already asked like 100 time and I reviewed all of them but I'm Kinda Stuck and had to asked for help

I have table like this:

hivenumber Visitdate   CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-10    10       2        4
    2      2017-11-10    11       1        3
    3      2017-11-10    12       3        3
    1      2017-11-12    13       1        1
    3      2017-11-11    14       5        2

At first I want to aggregate it by HiveNumber

Select HiveNumber
From tHivesDetails
Group BY HiveNumber

Then I want the last record of CombNo for each HiveNumber

Select Top(1) CombNo
From `tHivesDetails`
Order By VisitDate Desc

Then I need sum of Wax for each HiveNumber

Select Sum(Wax)
From `tHivesDetails`
Group BY HiveNumber

and at the end I want average of BeeBehave

Select Avg(BeeBehave)
From tHivesDetails
Group By HiveNumber

I don't know how to combine these queries to 1 and have one table with all I need in this case. I read most of same question but unfortunately couldn't figure it how do that.

I want a result like this:

hivenumber  Visitdate  CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-12    13      Sum      avg
    2      2017-11-10    11      sum      avg
    3      2017-11-11    14      sum      avg

Body:
Try this:

SELECT tA.HiveNumber, tA.WaxNoSum, tA.BeeBehaveSum, tB.CombsNoLatest
FROM (SELECT HiveNumber, SUM(WaxNo) AS WaxNoSum, AVG(BeeBehave) AS BeeBehaveSum
      FROM tHivesDetails
      GROUP BY HiveNumber) AS tA LEFT JOIN (SELECT HiveNumber, MAX(CombsNO) AS CombsNoLatest
                                            FROM tHivesDetails
                                            GROUP BY HiveNumber) AS tB ON tA.HiveNumber = tB.HiveNumber


问:
AboutToQuit signal/event in Android
I'm new to Java and Android and I'm coming from a Qt/C++ background. In Qt there is this QCoreApplication object that represents the whole application and when this object is destroyed, the application dies. In Qt there is this signal on QCoreApplication which is QCoreApplication::aboutToQuit which gets emitted when the application is in an imminent process of being closed. This is very handy when you want, e.g. save settings data to disk just before the application is closed.

My question: Is there a similar aboutToQuit-like mechanism with which you could get notified when an Android application is imminently closing?

EDIT:

I would like to make some additions to my question after nPn answer. We cannot rely on the Android Activity Life Cycle as we need this information in a library/SDK we are developing. So we want to get notified when an application that is using our library/SDK is closing.

We are developing an SDK for some clients to use in Android apps. Like this would not be enough, this SDK also uses a native C++ SDK in the background with which is linked with through a JNI interface.

The end goal is to get notified in C++ that the application is being destroyed in Android. Having an event/signal in Android would be enough as we could forward the information to C++.

So as a resume the layers are: Android App -> Custom Android SDK -> Native C++ SDK

If there is something unclear, I will edit the question further

答:
I was just reading up on some of the latest developments (I have not been doing too much Android programing lately and wanted to learn more about the new recommended Architecture).

When I read the following, I thought about this question from a few days ago.

Lifecycle-aware components perform actions in response to a change in
  the lifecycle status of another component, such as activities and
  fragments. These components help you produce better-organized, and
  often lighter-weight code, that is easier to maintain.

A common pattern is to implement the actions of the dependent
  components in the lifecycle methods of activities and fragments.
  However, this pattern leads to a poor organization of the code and to
  the proliferation of errors. By using lifecycle-aware components, you
  can move the code of dependent components out of the lifecycle methods
  and into the components themselves.

I think if some component in your library can implement the LifeCycleObserver interface,  you would not need to rely on the callbacks in the Activities, Fragments, etc, rather you could observe the changes in your own objects and react accordingly.

For example if you create a class that implements the LifecycleObserver ,   such as this.

```<code>class LifeCycleMonitor(private val lifeCycleOwner: LifecycleOwner) : LifecycleObserver {

    init {
        lifeCycleOwner.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroyEvent() {
        println("activity was destroyed")
    }
}
</code>```

and then instantiate the class in an object that is a LifecycleOwner (such as an Activity) the method annotated with the corresponding event will be called.

```<code>class MainActivity : AppCompatActivity() {

    private val lifeCycleMonitor = LifeCycleMonitor(this)

}
</code>```

Note there is also a ProcessLifecycleOwner which might be even closer to what you are looking for, as it covers the entire App, not just a given Activity or Fragment.

Title: AboutToQuit signal/event in Android

Body:
I was just reading up on some of the latest developments (I have not been doing too much Android programing lately and wanted to learn more about the new recommended Architecture).

When I read the following, I thought about this question from a few days ago.

Lifecycle-aware components perform actions in response to a change in
  the lifecycle status of another component, such as activities and
  fragments. These components help you produce better-organized, and
  often lighter-weight code, that is easier to maintain.

A common pattern is to implement the actions of the dependent
  components in the lifecycle methods of activities and fragments.
  However, this pattern leads to a poor organization of the code and to
  the proliferation of errors. By using lifecycle-aware components, you
  can move the code of dependent components out of the lifecycle methods
  and into the components themselves.

I think if some component in your library can implement the LifeCycleObserver interface,  you would not need to rely on the callbacks in the Activities, Fragments, etc, rather you could observe the changes in your own objects and react accordingly.

For example if you create a class that implements the LifecycleObserver ,   such as this.

class LifeCycleMonitor(private val lifeCycleOwner: LifecycleOwner) : LifecycleObserver {

    init {
        lifeCycleOwner.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroyEvent() {
        println("activity was destroyed")
    }
}

and then instantiate the class in an object that is a LifecycleOwner (such as an Activity) the method annotated with the corresponding event will be called.

class MainActivity : AppCompatActivity() {

    private val lifeCycleMonitor = LifeCycleMonitor(this)

}

Note there is also a ProcessLifecycleOwner which might be even closer to what you are looking for, as it covers the entire App, not just a given Activity or Fragment.


问:
How to populate values into a VBA array using the evaluate method and return them back to an Excel sheet?
I am trying to populate an array with the values from the VBA EVALUATE method.  Once the array is populated, then I want to populate a range of cells in an Excel worksheet with the values from the array.

I wrote a SUB to do what I want, however when I run this function, I get the following error:

Run-time error 9: Subscript out of range

So my question is: How do I correct my script to get max_min_date2 to run correctly? A screenshot of my data is upload here

```<code>Sub max_min_date2():

  'Define an array
  Dim values As Variant

  'Define the size of the array
  values = Range("L2:L1000").Value

    'Set up for loop'
    For i = 2 To 1000

     'Populate values in the array.
     values(i - 1) = Evaluate("=MAX(IF(A:A=" & Cells(i, 11).Address & ",B:B))")

     Next i

  'Populate Excel sheet with values in the array.
  Range("L2:L1000").Value = values

End Sub
</code>```

答:
```<code>Sub max_min_date2()

'Define an array
Dim values As Variant
Dim LastRow As Long
Dim LastRow2 As Long
'set the worksheet
With Worksheets("Sheet1") 'Change to your sheet
    'get last row to avoid unnecessary loops
    LastRow = .Cells(.Rows.Count, 11).End(xlUp).Row
    'get last row of ref data to avoid unnecessary calculations
    LastRow2 = .Cells(.Rows.Count, 1).End(xlUp).Row
    'Define the size of the array make it a two dimensional for ease of assigning back to array.
    ReDim values(1 To LastRow - 1, 1 To 1) As Variant

    'Set up for loop'
    For i = 2 To LastRow

        'Populate values in the array.
        values(i - 1, 1) = .Evaluate("=MAX(IF(A2:A" & LastRow2 & "=" & .Cells(i, 11).Address & ",B2:B" & LastRow2 & "))")

    Next i

    'Populate Excel sheet with values in the array.
    .Range("L2").Resize(LastRow - 1).Value = values

End With

End Sub
</code>```

Body:
I am trying to populate an array with the values from the VBA EVALUATE method.  Once the array is populated, then I want to populate a range of cells in an Excel worksheet with the values from the array.

I wrote a SUB to do what I want, however when I run this function, I get the following error:

Run-time error 9: Subscript out of range

So my question is: How do I correct my script to get max_min_date2 to run correctly? A screenshot of my data is upload here

Sub max_min_date2():

  'Define an array
  Dim values As Variant

  'Define the size of the array
  values = Range("L2:L1000").Value

    'Set up for loop'
    For i = 2 To 1000

     'Populate values in the array.
     values(i - 1) = Evaluate("=MAX(IF(A:A=" & Cells(i, 11).Address & ",B:B))")

     Next i

  'Populate Excel sheet with values in the array.
  Range("L2:L1000").Value = values

End Sub