问:
Microsoft Access condense multiple lines in a table
I have a question in MS Access 2007 and I hope someone has the answer. I have a long but simple table containing customer names and the days of the week that deliveries are made. I would like to summarize this table by listing the name and all the days into one new field "ALLDays" while still preserving all the data.

The source table looks something like this:

```<code>Name         Day
CustomerA    Monday
CustomerA    Thursday
CustomerB    Tuesday
CustomerB    Friday
CustomerC    Wednesday
CustomerC    Saturday
</code>```

I would like to have a query which returns results like this:

```<code>Name         ALLDays
CustomerA    Monday, Thursday
CustomerB    Tuesday, Friday
CustomerC    Wednesday, Saturday
</code>```

Thanks.

答:
Since this is just a small range of options, another approach with no VBA would be to set up a series of IIF statements and concatenate the results.

```<code>SELECT name,
   IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday, ") &
   IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday, ") &
   IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday, ") &
   IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday, ") &
   IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday, ") &
   IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday, ") &
   IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday, ") AS AllDays
FROM Table1
GROUP BY name
</code>```

If you a perfectionist, you could even get rid of the last comma like this

```<code>SELECT name,
LEFT(
   IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday, ") &
   IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday, ") &
   IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday, ") &
   IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday, ") &
   IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday, ") &
   IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday, ") &
   IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday, "),
LEN(
   IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday, ") &
   IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday, ") &
   IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday, ") &
   IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday, ") &
   IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday, ") &
   IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday, ") &
   IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday, ")
) - 2
)
AS AllDays
FROM Table1
GROUP BY name
</code>```

You may also consider keeping them in separate columns, as this may prove more useful if accessing this query from another. For instance, finding only instances with a Tuesday would be easier this way. Something like:

```<code>SELECT name,
IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday") AS Monday,
IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday") AS Tuesday,
IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday") AS Wednesday,
IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday") AS Thursday,
IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday") AS Friday,
IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday") AS Saturday,
IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday") AS Sunday
FROM Table1
GROUP BY name
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a question in MS Access 2007 and I hope someone has the answer. I have a long but simple table containing customer names and the days of the week that deliveries are made. I would like to summarize this table by listing the name and all the days into one new field "ALLDays" while still preserving all the data.

The source table looks something like this:

Name         Day
CustomerA    Monday
CustomerA    Thursday
CustomerB    Tuesday
CustomerB    Friday
CustomerC    Wednesday
CustomerC    Saturday

I would like to have a query which returns results like this:

Name         ALLDays
CustomerA    Monday, Thursday
CustomerB    Tuesday, Friday
CustomerC    Wednesday, Saturday

Thanks.

Body:
Since this is just a small range of options, another approach with no VBA would be to set up a series of IIF statements and concatenate the results.

SELECT name,
   IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday, ") &
   IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday, ") &
   IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday, ") &
   IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday, ") &
   IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday, ") &
   IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday, ") &
   IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday, ") AS AllDays
FROM Table1
GROUP BY name

If you a perfectionist, you could even get rid of the last comma like this

SELECT name,
LEFT(
   IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday, ") &
   IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday, ") &
   IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday, ") &
   IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday, ") &
   IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday, ") &
   IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday, ") &
   IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday, "),
LEN(
   IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday, ") &
   IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday, ") &
   IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday, ") &
   IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday, ") &
   IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday, ") &
   IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday, ") &
   IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday, ")
) - 2
)
AS AllDays
FROM Table1
GROUP BY name

You may also consider keeping them in separate columns, as this may prove more useful if accessing this query from another. For instance, finding only instances with a Tuesday would be easier this way. Something like:

SELECT name,
IIF(SUM(IIF(day = "Monday",1,0)) >0, "Monday") AS Monday,
IIF(SUM(IIF(day = "Tuesday",1,0)) >0, "Tuesday") AS Tuesday,
IIF(SUM(IIF(day = "Wednesday",1,0)) >0, "Wednesday") AS Wednesday,
IIF(SUM(IIF(day = "Thursday",1,0)) >0, "Thursday") AS Thursday,
IIF(SUM(IIF(day = "Friday",1,0)) >0, "Friday") AS Friday,
IIF(SUM(IIF(day = "Saturday",1,0)) >0, "Saturday") AS Saturday,
IIF(SUM(IIF(day = "Sunday",1,0)) >0, "Sunday") AS Sunday
FROM Table1
GROUP BY name


来源: stackexchange

问:
Selecting by subset of multiindex level
Toy example

Suppose I have the dataframe df shown below

```<code>           C
L0 L1 L2
0  w  P   11
      Q    9
      R   21
      S    4
   x  P    3
      Q    0
      R   23
      S   20
   y  P   19
      Q    0
      R    7
      S   13
   z  P   17
      Q    0
      R    5
      S    1
1  w  P    8
      Q    2
      R   12
      S    0
   x  P   22
      Q   14
      R    2
      S   18
   y  P    6
      Q    0
      R   16
      S   15
   z  P   10
      Q    0
      R    8
      S    0
</code>```

Note that the rows of df are indexed by 3-level multi-index.

I can find the minimum of the C column for each value of the L2 level, as follows:

```<code>In [58]: df.groupby(level='L2').min()
Out[58]:
    C
L2
P   3
Q   0
R   2
S   0
</code>```

Similarly, the following expression shows the values of L2 for which this minimum is greater than 0:

```<code>In [59]: df.groupby(level='L2').min() > 0
Out[59]:
        C
L2
P    True
Q   False
R    True
S   False
</code>```

Question: How can I select the rows of the original dataframe df corresponding to the values of L2 for which the minimum of C is greater than 0?

In this simple example the problem boils down to selecting the rows of df whose L2 value is either 'P' or 'R'.  Therefore, it would not be difficult to brute-force the problem by concatenating the rows for L2='P' with those for L2='R'.

In the application I have in mind, however, such a solution becomes unwieldy, since here the L2 level has ~2000 values, and for about half of them, the minimum is greater than 0.

Therefore, I'm looking for a more scalable way to solve this selection problem.

DATA

```<code>L0  L1  L2  C
0   w   P   11
0   w   Q   9
0   w   R   21
0   w   S   4
0   x   P   3
0   x   Q   0
0   x   R   23
0   x   S   20
0   y   P   19
0   y   Q   0
0   y   R   7
0   y   S   13
0   z   P   17
0   z   Q   0
0   z   R   5
0   z   S   1
1   w   P   8
1   w   Q   2
1   w   R   12
1   w   S   0
1   x   P   22
1   x   Q   14
1   x   R   2
1   x   S   18
1   y   P   6
1   y   Q   0
1   y   R   16
1   y   S   15
1   z   P   10
1   z   Q   0
1   z   R   8
1   z   S   0
</code>```

答:
Here's one way

Store the L2 values needed

```<code>In [413]: m = df.groupby(level='L2').min() > 0

In [414]: m
Out[414]:
        C
L2
P    True
Q   False
R    True
S   False
</code>```

Using, get_level_values(index_level_name).isin(to_be_filtered) filter only needed values.

```<code>In [415]: df[df.index.get_level_values('L2').isin(m.loc[m.C, :].index)]
Out[415]:
           C
L0 L1 L2
0  w  P   11
      R   21
   x  P    3
      R   23
   y  P   19
      R    7
   z  P   17
      R    5
1  w  P    8
      R   12
   x  P   22
      R    2
   y  P    6
      R   16
   z  P   10
      R    8
</code>```

Here's another way. Using, transform and subset selection

```<code>In [430]: df[(df.groupby(level='L2').transform('min') > 0).C]
Out[430]:
           C
L0 L1 L2
0  w  P   11
      R   21
   x  P    3
      R   23
   y  P   19
      R    7
   z  P   17
      R    5
1  w  P    8
      R   12
   x  P   22
      R    2
   y  P    6
      R   16
   z  P   10
      R    8
</code>```

Details

```<code>In [416]: m.loc[m.C, :].index
Out[416]: Index([u'P', u'R'], dtype='object', name=u'L2')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Selecting by subset of multiindex level

Body:
Toy example

Suppose I have the dataframe df shown below

           C
L0 L1 L2
0  w  P   11
      Q    9
      R   21
      S    4
   x  P    3
      Q    0
      R   23
      S   20
   y  P   19
      Q    0
      R    7
      S   13
   z  P   17
      Q    0
      R    5
      S    1
1  w  P    8
      Q    2
      R   12
      S    0
   x  P   22
      Q   14
      R    2
      S   18
   y  P    6
      Q    0
      R   16
      S   15
   z  P   10
      Q    0
      R    8
      S    0

Note that the rows of df are indexed by 3-level multi-index.

I can find the minimum of the C column for each value of the L2 level, as follows:

In [58]: df.groupby(level='L2').min()
Out[58]:
    C
L2
P   3
Q   0
R   2
S   0

Similarly, the following expression shows the values of L2 for which this minimum is greater than 0:

In [59]: df.groupby(level='L2').min() > 0
Out[59]:
        C
L2
P    True
Q   False
R    True
S   False

Question: How can I select the rows of the original dataframe df corresponding to the values of L2 for which the minimum of C is greater than 0?

In this simple example the problem boils down to selecting the rows of df whose L2 value is either 'P' or 'R'.  Therefore, it would not be difficult to brute-force the problem by concatenating the rows for L2='P' with those for L2='R'.

In the application I have in mind, however, such a solution becomes unwieldy, since here the L2 level has ~2000 values, and for about half of them, the minimum is greater than 0.

Therefore, I'm looking for a more scalable way to solve this selection problem.

DATA

L0  L1  L2  C
0   w   P   11
0   w   Q   9
0   w   R   21
0   w   S   4
0   x   P   3
0   x   Q   0
0   x   R   23
0   x   S   20
0   y   P   19
0   y   Q   0
0   y   R   7
0   y   S   13
0   z   P   17
0   z   Q   0
0   z   R   5
0   z   S   1
1   w   P   8
1   w   Q   2
1   w   R   12
1   w   S   0
1   x   P   22
1   x   Q   14
1   x   R   2
1   x   S   18
1   y   P   6
1   y   Q   0
1   y   R   16
1   y   S   15
1   z   P   10
1   z   Q   0
1   z   R   8
1   z   S   0

Body:
Here's one way

Store the L2 values needed

In [413]: m = df.groupby(level='L2').min() > 0

In [414]: m
Out[414]:
        C
L2
P    True
Q   False
R    True
S   False

Using, get_level_values(index_level_name).isin(to_be_filtered) filter only needed values.

In [415]: df[df.index.get_level_values('L2').isin(m.loc[m.C, :].index)]
Out[415]:
           C
L0 L1 L2
0  w  P   11
      R   21
   x  P    3
      R   23
   y  P   19
      R    7
   z  P   17
      R    5
1  w  P    8
      R   12
   x  P   22
      R    2
   y  P    6
      R   16
   z  P   10
      R    8

Here's another way. Using, transform and subset selection

In [430]: df[(df.groupby(level='L2').transform('min') > 0).C]
Out[430]:
           C
L0 L1 L2
0  w  P   11
      R   21
   x  P    3
      R   23
   y  P   19
      R    7
   z  P   17
      R    5
1  w  P    8
      R   12
   x  P   22
      R    2
   y  P    6
      R   16
   z  P   10
      R    8

Details

In [416]: m.loc[m.C, :].index
Out[416]: Index([u'P', u'R'], dtype='object', name=u'L2')


问:
How to change the voice in pyttsx3?
This code is working but I'm only able to switch between the voices which came preInstalled in Microsoft Windows. These voices are "Microsoft David Mobile" and "Microsoft Zira Mobile".

Later I installed "Microsoft Kalpana Mobile" and set it as the default Windows voice. But still I'm not able to switch to "Microsoft Kalpana Mobile". The code is-

```<code>import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #changing index changes voices but ony 0 and 1 are working here
engine.say('Hello World')
engine.runAndWait()
</code>```

Only 0 and 1 are working as indices inside voices[].

I want the "Microsoft Kalpana Mobile" to speak. I'm working on this project for past 2 months. If this doesn't work, all my efforts will go in vein. Please Help:(

Thanks in advance.

答:
You can try this code:

```<code>import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
for voice in voices:
    print(voice, voice.id)
    engine.setProperty('voice', voice.id)
    engine.say("Hello World!")
    engine.runAndWait()
    engine.stop()
</code>```

Then instead of the for loop, just pick up your preferred voice.id

Title: How to change the voice in pyttsx3?

Body:
This code is working but I'm only able to switch between the voices which came preInstalled in Microsoft Windows. These voices are "Microsoft David Mobile" and "Microsoft Zira Mobile".

Later I installed "Microsoft Kalpana Mobile" and set it as the default Windows voice. But still I'm not able to switch to "Microsoft Kalpana Mobile". The code is-

import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #changing index changes voices but ony 0 and 1 are working here
engine.say('Hello World')
engine.runAndWait()

Only 0 and 1 are working as indices inside voices[].

I want the "Microsoft Kalpana Mobile" to speak. I'm working on this project for past 2 months. If this doesn't work, all my efforts will go in vein. Please Help:(

Thanks in advance.

Body:
You can try this code:

import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
for voice in voices:
    print(voice, voice.id)
    engine.setProperty('voice', voice.id)
    engine.say("Hello World!")
    engine.runAndWait()
    engine.stop()

Then instead of the for loop, just pick up your preferred voice.id


问:
How to transform list of indexed dataFrames to one DataFrame?
From the following dictionnary made of dataframes :

```<code>{0:     count  hashtag_id
17    540         397
8     432         329
44    385         996
15    360         392,
1:     count  hashtag_id
19   1100         996
13    869         592
20    600         996}
</code>```

I want to learn how to create a DataFrame that looks like :

```<code>count   hashtag_id  user_id
540     397         0
432     329         0
385     996         0
360     360         0
1100    996         1
869     592         1
600     996         1
</code>```

Can you help me achieve it ?

答:
Let's say your dictionary is called d

First, append the user ids:

Iterate over the dictionary: For each DataFrame, create a new column called 'user_id' and assign the DataFrame's key as the value to the newly created column 'user_id'

```<code>for key,value in d.iteritems():
    value['user_id'] = key
</code>```

Now concat all the DataFrames to create one Dataframe

```<code>import pandas as pd
df = pd.concat(d.values())
</code>```

You might want to reset the index after doing the concat:

```<code>df = df.reset_index(drop = True)
</code>```

Body:
From the following dictionnary made of dataframes :

{0:     count  hashtag_id
17    540         397
8     432         329
44    385         996
15    360         392,
1:     count  hashtag_id
19   1100         996
13    869         592
20    600         996}

I want to learn how to create a DataFrame that looks like :

count   hashtag_id  user_id
540     397         0
432     329         0
385     996         0
360     360         0
1100    996         1
869     592         1
600     996         1

Can you help me achieve it ?

Body:
Let's say your dictionary is called d

First, append the user ids:

Iterate over the dictionary: For each DataFrame, create a new column called 'user_id' and assign the DataFrame's key as the value to the newly created column 'user_id'

for key,value in d.iteritems():
    value['user_id'] = key

Now concat all the DataFrames to create one Dataframe

import pandas as pd
df = pd.concat(d.values())

You might want to reset the index after doing the concat:

df = df.reset_index(drop = True)


问:
Entity framework custom inheritance with caliburn.micro
I am writing a WPF app using caliburn.micro to work with a database. I am using entity framework with the database-first approach (since I already have a db) to generate classes. Is it possible to make the entity framework gererate classes that would inherit the PropertyChangedBase class of caliburn Or to make them implement the IHandle interface. I need these classes to have it for the views to know when the data has been changed.</p>

答:
The 'pure' MVVM way of doing it (it's not set in stone and many people do implement notification in their models) would be to mirror the properties in your View Model.

Taking the Person example, your model is a simple POCO:

```<code>public class Person
{
    public String FirstName { get; set; }
    public String Surname { get; set; }
}
</code>```

Your View Model translates this into something to view, a very simple version can use the 'model' as it's backing fields:

```<code>public class PersonViewModel : PropertyChangedBase
{
    private Person person;
    public Person Person
    {
        get { return person; }
        set { person = value;
              NotifyOfPropertyChange(() => FirstName);
              NotifyOfPropertyChange(() => Surname)};
    }

    public String FirstName
    {
        get { return Person.FirstName; }
        set
        {
            if (Person.FirstName != value)
            {
                Person.FirstName = value;
                NotifyOfPropertyChange(() => FirstName);
            }
        }
    }

    public String Surname
    {
        get { return Person.Surname; }
        set
        {
            if (Person.Surname != value)
            {
                Person.Surname = value;
                NotifyOfPropertyChange(() => Surname);
            }
        }
    }
}
</code>```

If you're model is linked to a database through EF it is also useful when saving/loading changes etc. You can implement a save/undo or IsDirty tracking:

```<code>public class PersonViewModel : PropertyChangedBase
{
    private Person person;
    public Person Person
    {
        get { return person; }
        set { person = value; }
    }

    private String firstName;
    public String FirstName
    {
        get { return firstName; }
        set
        {
            if (firstName != value)
            {
                firstName = value;
                NotifyOfPropertyChange(() => FirstName);
            }
        }
    }

    private String surname;
    public String Surname
    {
        get { return surname; }
        set
        {
            if (surname != value)
            {
                surname = value;
                NotifyOfPropertyChange(() => Surname);
            }
        }
    }

    public void SaveToModel()
    {
        Person.FirstName = FirstName;
        Person.Surname = Surname;
        // trigger EF save?
    }

    public void LoadFromModel()
    {
        FirstName = Person.FirstName;
        Surname = Person.Surname;
    }
}
</code>```

See these questions for plenty of discussion of the pros and cons of implementing PropertyChange on the Model:

MVVM duplicating Model properties in ViewModel

In MVVM model should the model implement INotifyPropertyChanged interface?

In MVVM should the ViewModel or Model implement INotifyPropertyChanged?

Having done both, I'd recommend you keep notifications out of the Model and try strive to keep it as simple as possible.

Body:
The 'pure' MVVM way of doing it (it's not set in stone and many people do implement notification in their models) would be to mirror the properties in your View Model.

Taking the Person example, your model is a simple POCO:

public class Person
{
    public String FirstName { get; set; }
    public String Surname { get; set; }
}

Your View Model translates this into something to view, a very simple version can use the 'model' as it's backing fields:

public class PersonViewModel : PropertyChangedBase
{
    private Person person;
    public Person Person
    {
        get { return person; }
        set { person = value;
              NotifyOfPropertyChange(() => FirstName);
              NotifyOfPropertyChange(() => Surname)};
    }

    public String FirstName
    {
        get { return Person.FirstName; }
        set
        {
            if (Person.FirstName != value)
            {
                Person.FirstName = value;
                NotifyOfPropertyChange(() => FirstName);
            }
        }
    }

    public String Surname
    {
        get { return Person.Surname; }
        set
        {
            if (Person.Surname != value)
            {
                Person.Surname = value;
                NotifyOfPropertyChange(() => Surname);
            }
        }
    }
}

If you're model is linked to a database through EF it is also useful when saving/loading changes etc. You can implement a save/undo or IsDirty tracking:

public class PersonViewModel : PropertyChangedBase
{
    private Person person;
    public Person Person
    {
        get { return person; }
        set { person = value; }
    }

    private String firstName;
    public String FirstName
    {
        get { return firstName; }
        set
        {
            if (firstName != value)
            {
                firstName = value;
                NotifyOfPropertyChange(() => FirstName);
            }
        }
    }

    private String surname;
    public String Surname
    {
        get { return surname; }
        set
        {
            if (surname != value)
            {
                surname = value;
                NotifyOfPropertyChange(() => Surname);
            }
        }
    }

    public void SaveToModel()
    {
        Person.FirstName = FirstName;
        Person.Surname = Surname;
        // trigger EF save?
    }

    public void LoadFromModel()
    {
        FirstName = Person.FirstName;
        Surname = Person.Surname;
    }
}

See these questions for plenty of discussion of the pros and cons of implementing PropertyChange on the Model:

MVVM duplicating Model properties in ViewModel

In MVVM model should the model implement INotifyPropertyChanged interface?

In MVVM should the ViewModel or Model implement INotifyPropertyChanged?

Having done both, I'd recommend you keep notifications out of the Model and try strive to keep it as simple as possible.


问:
How to temporarily replace a NuGet reference with a local build
I'm working on a C# project using Visual Studio 2015, with NuGet for package management. For one reference, I'd like to temporarily use a local build while I'm iterating on a fix, rather than the released version. What's the best way to accomplish this?

If I were using an SVN external, I'd drop the new locally built copies into the external reference's folder, and be set. Other package management software (like CocoaPods) would allow me to point to a local directory to resolve the reference. With NuGet, it doesn't look like there's any mechanism for this.

When I try dropping my new DLL over the package reference inside the packages folder, I get inconsistent behavior in Visual Studio. My build will fail with hundreds of errors, most of which go away from the Error List quickly. I'm ultimately left with a warning telling me it could not resolve the reference to the assembly I'm trying to replace (though the properties of the reference do indicate it's finding my new version).

答:
We've had great success using this tool. It's easy to use and works.

VS 2019
https://marketplace.visualstudio.com/items?itemName=RicoSuter.NuGetReferenceSwitcherforVisualStudio2019

VS 2017
https://marketplace.visualstudio.com/items?itemName=RicoSuter.NuGetReferenceSwitcherforVisualStudio2017

VS 2015
https://marketplace.visualstudio.com/items?itemName=RicoSuter.NuGetReferenceSwitcherforVisualStudio2015

ContentLicense: CC BY-SA 4.0


问:
Template for documenting Architecture alternatives and decisions
We are putting a process in place where all architecture changes must be documented.

Are there any standard templates for documenting alternatives and decisions?

答:
We collect information regarding architectural decision records at https://adr.github.io/.

MADR - The Markdown Architecture Decision Records

MADR establishes an easy markdown format for  architectural decisions.

The template reads as follows:

# {short title of solved problem and solution}

## Context and Problem Statement

{Describe the context and problem statement, e.g., in free form using two to three sentences or in the form of an illustrative story.
 You may want to articulate the problem in form of a question and add links to collaboration boards or issue management systems.}

## Decision Drivers

* {decision driver 1, e.g., a force, facing concern, …}
* {decision driver 2, e.g., a force, facing concern, …}
* …

## Considered Options

* {title of option 1}
* {title of option 2}
* {title of option 3}
* …

## Decision Outcome

Chosen option: "{title of option 1}", because
{justification. e.g., only option, which meets k.o. criterion decision driver | which resolves force {force} | … | comes out best (see below)}.

### Positive Consequences

* {e.g., improvement of one or more desired qualities, …}
* …

### Negative Consequences

* {e.g., compromising one or more desired qualities, …}
* …

## Validation

{describe how the implementation of/compliance with the ADR is validated. E.g., by a review or an ArchUnit test}

## Pros and Cons of the Options

### {title of option 1}

{example | description | pointer to more information | …}

* Good, because {argument a}
* Good, because {argument b}

* Neutral, because {argument c}
* Bad, because {argument d}
* …

### {title of other option}

{example | description | pointer to more information | …}

* Good, because {argument a}
* Good, because {argument b}
* Neutral, because {argument c}
* Bad, because {argument d}
* …

## More Information

{You might want to provide additional evidence/confidence for the decision outcome here and/or
 document the team agreement on the decision and/or
 define when this decision when and how the decision should be realized and if/when it should be re-visited and/or
 how the decision is validated.
 Links to other decisions and resources might here appear as well.}
```

The template is available at https://github.com/adr/madr/blob/main/template/adr-template.md.

Sustainable Architectural Decision

The blog post Sustainable Architectural Design Decisions proposes following text:

In the context of <use case/user story u>, facing <concern c> we decided for <option o> to achieve <quality q>, accepting <downside d>.

In some projects, we use the following extension:

In the context of <use case/user story u>,
facing <concern c>
we decided for <option o>
and neglected <other options>,
to achieve <system qualities/desired consequences>,
accepting <downside d/undesired consequences>,
because <additional rationale>.

Other Solutions

Other solutions, including markdown templates, are listed at https://adr.github.io/.

Body:
We collect information regarding architectural decision records at https://adr.github.io/.

MADR - The Markdown Architecture Decision Records

MADR establishes an easy markdown format for  architectural decisions.

The template reads as follows:

# {short title of solved problem and solution}

## Context and Problem Statement

{Describe the context and problem statement, e.g., in free form using two to three sentences or in the form of an illustrative story.
 You may want to articulate the problem in form of a question and add links to collaboration boards or issue management systems.}

<!-- This is an optional element. Feel free to remove. -->
## Decision Drivers

* {decision driver 1, e.g., a force, facing concern, …}
* {decision driver 2, e.g., a force, facing concern, …}
* … <!-- numbers of drivers can vary -->

## Considered Options

* {title of option 1}
* {title of option 2}
* {title of option 3}
* … <!-- numbers of options can vary -->

## Decision Outcome

Chosen option: "{title of option 1}", because
{justification. e.g., only option, which meets k.o. criterion decision driver | which resolves force {force} | … | comes out best (see below)}.

<!-- This is an optional element. Feel free to remove. -->
### Positive Consequences

* {e.g., improvement of one or more desired qualities, …}
* …

<!-- This is an optional element. Feel free to remove. -->
### Negative Consequences

* {e.g., compromising one or more desired qualities, …}
* …

<!-- This is an optional element. Feel free to remove. -->
## Validation

{describe how the implementation of/compliance with the ADR is validated. E.g., by a review or an ArchUnit test}

<!-- This is an optional element. Feel free to remove. -->
## Pros and Cons of the Options

### {title of option 1}

<!-- This is an optional element. Feel free to remove. -->
{example | description | pointer to more information | …}

* Good, because {argument a}
* Good, because {argument b}
<!-- use "neutral" if the given argument weights neither for good nor bad -->
* Neutral, because {argument c}
* Bad, because {argument d}
* … <!-- numbers of pros and cons can vary -->

### {title of other option}

{example | description | pointer to more information | …}

* Good, because {argument a}
* Good, because {argument b}
* Neutral, because {argument c}
* Bad, because {argument d}
* …

<!-- This is an optional element. Feel free to remove. -->
## More Information

{You might want to provide additional evidence/confidence for the decision outcome here and/or
 document the team agreement on the decision and/or
 define when this decision when and how the decision should be realized and if/when it should be re-visited and/or
 how the decision is validated.
 Links to other decisions and resources might here appear as well.}

The template is available at https://github.com/adr/madr/blob/main/template/adr-template.md.

Sustainable Architectural Decision

The blog post Sustainable Architectural Design Decisions proposes following text:

In the context of <use case/user story u>, facing <concern c> we decided for <option o> to achieve <quality q>, accepting <downside d>.

In some projects, we use the following extension:

In the context of <use case/user story u>,
facing <concern c>
we decided for <option o>
and neglected <other options>,
to achieve <system qualities/desired consequences>,
accepting <downside d/undesired consequences>,
because <additional rationale>.

Other Solutions

Other solutions, including markdown templates, are listed at https://adr.github.io/.


问:
I am unable to get value from div tag
```<code><!DOCTYPE html>
<html>
<body>

<p>Write something in the text field to trigger a function.</p>

<div id="myInput" oninput="myFunction()" contenteditable>100</div>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myInput").value;
    document.getElementById("demo").innerHTML = "You wrote: " + x;
}
</script>

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

Please give me some solution on this. In output i get value for x is "undefined".

答:
Its not a input text field. So, you cannot use value property.</p>

```<code>function myFunction() {
    var x = document.getElementById("myInput");
    document.getElementById("demo").innerHTML = "You wrote: " + x.innerText;
}
</code>```

Title: I am unable to get value from div tag

Body:
<!DOCTYPE html>

Write something in the text field to trigger a function.

100

Please give me some solution on this. In output i get value for x is "undefined".

Body:
Its not a input text field. So, you cannot use value property.

function myFunction() {
    var x = document.getElementById("myInput");
    document.getElementById("demo").innerHTML = "You wrote: " + x.innerText;
}


问:
Trying to check if a value is undefined to control setting of ng-checked
I have a problem setting ng-checked to true for checkboxes based on whether a value is undefined or not. For example in the following code..

```<code><input class="custom-checkbox form-control" id="{{ point.pointId }}-{{ value }}"
  type="checkbox"
  ng-true-value="'{{ value }}'"
  ng-model="item.sections[inspectionSection.sectionShortName[point.pointId].value">
</code>```

I am trying to set ng-checked by checking if value, which can be set to one of several values, is defined.

For example something like:

```<code>ng-checked={{ if(value !== undefined) }}
</code>```

I can't seem to get it working. Anything I try in ng-checked either checks all the checkboxes or none. Any help much appreciated!

答:
I would recommend using a function in this case.</p>

```<code>ng-checked="isNotUndefined(value)"

// in the controller
isUndefined (value) {
   return value !== undefined
}
</code>```

Body:
I have a problem setting ng-checked to true for checkboxes based on whether a value is undefined or not. For example in the following code..

<input class="custom-checkbox form-control" id="{{ point.pointId }}-{{ value }}"
  type="checkbox"
  ng-true-value="'{{ value }}'"
  ng-model="item.sections[inspectionSection.sectionShortName[point.pointId].value">

I am trying to set ng-checked by checking if value, which can be set to one of several values, is defined.

For example something like:

ng-checked={{ if(value !== undefined) }}

I can't seem to get it working. Anything I try in ng-checked either checks all the checkboxes or none. Any help much appreciated!

Body:
I would recommend using a function in this case.

ng-checked="isNotUndefined(value)"

// in the controller
isUndefined (value) {
   return value !== undefined
}


问:
How to label each bar on X axis using histogram in R in PowerBi
I'm using R and PowerBI. I use hist() function for histogram and it does the job.
I'm not able to put labels for each bar on x axis. The closes parameter I found is called  labels = TRUE

I want each bar to have a value that is increment of 10,000 in this case.

答:
assign the histogram to a variable and then obtain the values to plot and co-ordinates to plot at from that variable. Set xaxt = "n" to supress x-axis at first and then use axis to add the desired x-axis. Read more at ?par

```<code>set.seed(42)
x = rnorm(250)
h = hist(x, xaxt = "n")
text(x = h$mids, y = h$counts, labels = h$counts, pos = 3)
axis(side = 1, at = h$mids, seq_along(h$mids)*10000, las = 2)
</code>```

Body:
assign the histogram to a variable and then obtain the values to plot and co-ordinates to plot at from that variable. Set xaxt = "n" to supress x-axis at first and then use axis to add the desired x-axis. Read more at ?par

set.seed(42)
x = rnorm(250)
h = hist(x, xaxt = "n")
text(x = h$mids, y = h$counts, labels = h$counts, pos = 3)
axis(side = 1, at = h$mids, seq_along(h$mids)*10000, las = 2)


问:
Using parallel stream to find a single object in collection
Rather new to streams in Java, still getting the hang of it. I've seen a few examples but none of them seem to fit my use case.

I have a list of objects that can grow exponentially and I would like to parallelize the loop I'm using to find a single item in this list.

Here is what I currently have:

```<code>for (Node node : itemList)
{
    if (node.itemData().dataId() == searchData.itemData().dataId())
        return node;
}

return null;
</code>```

Here is my attempt at a concurrent version of this loop

```<code>List<Node> nodeItem = itemList.parallelStream()
                              .filter(item -> item.itemData().dataId() == searchData.itemData().dataId())
                              .collect(Collectors.toList());

return (!nodeItem.isEmpty() ? nodeItem.get(0) : null);
</code>```

There are two problems I am seeing here. The first one being that I am putting this single entry into a List. I understand that this is a result of collect() but I don't see any other way of collecting an individual item.

The other issue I see here is that the paralleled threads will continue working through their part of the list until they're finished iterating. I would prefer if each worker was signaled to end prematurely when the item is found.

答:
As JB stated, you can use Stream#findAny, a terminal operation that will return an Optional of the element you're looking for.

```<code>return itemList.parallelStream()
               .filter(item -> item.itemData().dataId() == searchData.itemData().dataId())
               .findAny()
               .orElse(null);
</code>```

Body:
Rather new to streams in Java, still getting the hang of it. I've seen a few examples but none of them seem to fit my use case.

I have a list of objects that can grow exponentially and I would like to parallelize the loop I'm using to find a single item in this list.

Here is what I currently have:

for (Node node : itemList)
{
    if (node.itemData().dataId() == searchData.itemData().dataId())
        return node;
}

return null;

Here is my attempt at a concurrent version of this loop

List<Node> nodeItem = itemList.parallelStream()
                              .filter(item -> item.itemData().dataId() == searchData.itemData().dataId())
                              .collect(Collectors.toList());

return (!nodeItem.isEmpty() ? nodeItem.get(0) : null);

There are two problems I am seeing here. The first one being that I am putting this single entry into a List. I understand that this is a result of collect() but I don't see any other way of collecting an individual item.

The other issue I see here is that the paralleled threads will continue working through their part of the list until they're finished iterating. I would prefer if each worker was signaled to end prematurely when the item is found.

Body:
As JB stated, you can use Stream#findAny, a terminal operation that will return an Optional of the element you're looking for.

return itemList.parallelStream()
               .filter(item -> item.itemData().dataId() == searchData.itemData().dataId())
               .findAny()
               .orElse(null);


问:
Put for if in one line python
Say i have one list:

```<code>v=['one','','two','three','',]
</code>```

Now i want to filter out all the empty values:

```<code>for i in v:
  if i==''
    pass
  else:
    print(i)
</code>```

I want to do this in one line :

```<code>vr=[i if i!='' else pass for i in v]
</code>```

getting bellow error.

```<code> File "<console>", line 1
 vr=[i if i!='' else pass for i in vt1]
                     ^
 SyntaxError: invalid syntax
</code>```

Kindly suggest .

答:
If your interested on different approach

Python 3.x:

```<code>vr = list(filter(('').__ne__, v))
</code>```

Python 2.x:

```<code>vr = filter(lambda a: a != '', v)
</code>```

Title: Put for if in one line python

Body:
Say i have one list:

v=['one','','two','three','',]

Now i want to filter out all the empty values:

for i in v:
  if i==''
    pass
  else:
    print(i)

I want to do this in one line :

vr=[i if i!='' else pass for i in v]

getting bellow error.

 File "<console>", line 1
 vr=[i if i!='' else pass for i in vt1]
                     ^
 SyntaxError: invalid syntax

Kindly suggest .

Body:
If your interested on different approach

Python 3.x:

vr = list(filter(('').__ne__, v))

Python 2.x:

vr = filter(lambda a: a != '', v)


问:
Get campaign subject line with mailchimp API v3.0
I ve used this function to get a specific campaign's details using Mailchimp API v3.0.

```<code>function mc_insert_campaign($email, $apikey, $server) {

    $apiKey = 'xxxxxxxxxxxxmyAPI';
    $camp_id = '1753ef2cce';

    $auth = base64_encode( 'user:'. $apikey );
    $data = array(
        'apikey'        => $apikey,
        'id' => $camp_id
        );
    $json_data = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/campaigns/'. $camp_id);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
        'Authorization: Basic '. $auth));
    curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    $result = curl_exec($ch);
//    if ($debug) {
//        var_dump($result);
//    }
    $json = json_decode($result);

    $camp_type = $json->{'type'};

    echo $camp_type;

}
</code>```

So far it works ok for me since that I 'm taking the Campaign Type.
But I need to extract the subject line too.

As I read in MC API documentation the json answer it looks like :

```<code>{
  "id": "42694e9e57",
  "type": "regular",
  "create_time": "2015-09-15T14:40:36+00:00",
  "archive_url": ".....",
  "status": "save",
  "emails_sent": 0,
  "send_time": "",
  "content_type": "template",
  "recipients": {
    "list_id": "57afe96172",
    "segment_text": ""
  },
  "settings": {
    "subject_line": "I have a rice crispy treat watermelon farm.",
    "title": "Freddie's Jokes Vol. 1",
    "from_name": "Freddie",
    "reply_to": "freddie@freddiesjokes.com",
    "use_conversation": false,
    "to_name": "",
    "folder_id": 0,
    "authenticate": true,
    "auto_footer": false,
    "inline_css": false,
    "auto_tweet": false,
    "fb_comments": false,
    "timewarp": false,
    "template_id": 100,
    "drag_and_drop": true
  }, .........
</code>```

I have tried something like

```<code>$camp_type = $json->{'settings'}{'type'};
</code>```

but it didn't worked. What am I doing wrong?
Thank you in advance..

答:
Finally I found the solution... I suppose it is very basic but I m posting it anyway just in case someone interested!

The solution is: $camp_subject_line = $json->settings->{'subject_line'}.

Thanx anyway!

Body:
I ve used this function to get a specific campaign's details using Mailchimp API v3.0.

function mc_insert_campaign($email, $apikey, $server) {

    $apiKey = 'xxxxxxxxxxxxmyAPI';
    $camp_id = '1753ef2cce';

    $auth = base64_encode( 'user:'. $apikey );
    $data = array(
        'apikey'        => $apikey,
        'id' => $camp_id
        );
    $json_data = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/campaigns/'. $camp_id);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
        'Authorization: Basic '. $auth));
    curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    $result = curl_exec($ch);
//    if ($debug) {
//        var_dump($result);
//    }
    $json = json_decode($result);

    $camp_type = $json->{'type'};

    echo $camp_type;

}

So far it works ok for me since that I 'm taking the Campaign Type.
But I need to extract the subject line too.

As I read in MC API documentation the json answer it looks like :

{
  "id": "42694e9e57",
  "type": "regular",
  "create_time": "2015-09-15T14:40:36+00:00",
  "archive_url": ".....",
  "status": "save",
  "emails_sent": 0,
  "send_time": "",
  "content_type": "template",
  "recipients": {
    "list_id": "57afe96172",
    "segment_text": ""
  },
  "settings": {
    "subject_line": "I have a rice crispy treat watermelon farm.",
    "title": "Freddie's Jokes Vol. 1",
    "from_name": "Freddie",
    "reply_to": "freddie@freddiesjokes.com",
    "use_conversation": false,
    "to_name": "",
    "folder_id": 0,
    "authenticate": true,
    "auto_footer": false,
    "inline_css": false,
    "auto_tweet": false,
    "fb_comments": false,
    "timewarp": false,
    "template_id": 100,
    "drag_and_drop": true
  }, .........

I have tried something like

$camp_type = $json->{'settings'}{'type'};

but it didn't worked. What am I doing wrong?
Thank you in advance..


问:
Allow Gridstack draggable only to a specific area of the item
I am using Gridstack js to create draggable/resizable widgets for a dashboard. The picture shows an example widget. I have kept the default draggable values as is and I can drag it by double clicking anywhere inside the widget. What I want to do is make the widget draggable only by clicking on the gray area. Should the default draggable values be overridden for this? If so how? I am fairly new to jquery/js, and couldn't find anything similar on the internet.

答:
Assuming you're using gridstack's default of jQueryUI's draggable, you can re-set the draggable constructor with the cancel option on any elements you want to not be draggable. In the code below, adding the not-draggable class any divs inside of the grid stack item will have its dragging suppressed.

```<code>$('.grid-stack-item').draggable({cancel: "div.not-draggable" });
</code>```

Body:
Assuming you're using gridstack's default of jQueryUI's draggable, you can re-set the draggable constructor with the cancel option on any elements you want to not be draggable. In the code below, adding the not-draggable class any divs inside of the grid stack item will have its dragging suppressed.

$('.grid-stack-item').draggable({cancel: "div.not-draggable" });


问:
How can I to filter a List of objects by the first occurrences of a List of properties?
Let's say I have the following code:

```<code>private class AccountRecord : IEquatable<AccountRecord>, IComparable<AccountRecord>
    {
        public Guid accountid { get; set; }
        public string accountnumber { get; set; }
        public string name { get; set; }
        public Guid ownerid { get; set; }
        public string owneridtype { get; set; }
        public int number { get; set; }
        public string companyname { get; set; }
        public AccountRecord(Guid accountid, string accountnumber, string name, Guid ownerid, string owneridtype, int number, string companyname)
        {
            this.accountid = accountid;
            this.accountnumber = accountnumber;
            this.name = name;
            this.ownerid = ownerid;
            this.owneridtype = owneridtype;
            this.number = number;
            this.companyname = companyname;
        }
        public bool Equals(AccountRecord other)
        {
            if(this.name.Equals(other.name) && this.number == other.number){
                return true;
            }
            else
            {
                return false;
            }
        }
        public int CompareTo(AccountRecord other)
        {
            if (this.number > other.number)
            {
                return 1;
            }
            else if (this.number < other.number)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
</code>```

Somewhere else I have a List of these objects:

```<code>private List<AccountRecord> accountRecords = new List<AccountRecord>();
</code>```

And I add several objects to the list:

```<code>accountRecords.Add(new AccountRecord(
                Row.accountid,
                Row.accountnumber,
                name,
                Row.ownerid,
                Row.owneridtype,
                number,
                companyname));
</code>```

I then get a list of distinct values for the 'companyname' property.

```<code>List<string> distinctCompanynames = accountRecords.Distinct(x => x.companyname).ToList<string>();
</code>```

I'd like to get a List of AccountRecord objects with the highest 'number' property for each distinct 'companyname' property. Thanks to the work that I have done, I can do this with a nested for loop but my entire approach doesn't seem like the best approach considering all the tools C# has at it's disposal. This list will eventually get very large and this code will be executed frequently so I must do this as efficiently as possible. How can I do this faster/better than my current method?

My current method is:

Make List of AccountRecords

Sort

(Reverse) Rewriting the CompareTo method of AccountRecord can remove this step.

Make List of distinct 'companyname' values in List of AccountRecords

Hard-code a nested for loop to perform some action on the first existence of an AccountRecord with each distinct 'companyname'.

What I'd like the method to be:

Make List of AccountRecords

Get a new list (or filter this list into becoming) a List of AccountRecord objects with the highest 'number' property for each distinct 'companyname' property.

If you have any questions, then please let me know.

答:
I haven't tested this, but this should work:

```<code>from ac in accountRecords
group ac by ac.companyname into company
select new
{
    Company = company.Key,
    Number = company.OrderByDescending(g => g.number).FirstOrDefault()
}
</code>```

UPDATE:  Read the question a bit more closely.  It can be simplifed:

```<code>List<AccountRecord> highestRecords =
   (from ac in accountRecords
    group ac by ac.companyname into company
    select company.OrderByDescending(g => g.number).FirstOrDefault())
   .ToList();
</code>```

Body:
Let's say I have the following code:

private class AccountRecord : IEquatable<AccountRecord>, IComparable<AccountRecord>
    {
        public Guid accountid { get; set; }
        public string accountnumber { get; set; }
        public string name { get; set; }
        public Guid ownerid { get; set; }
        public string owneridtype { get; set; }
        public int number { get; set; }
        public string companyname { get; set; }
        public AccountRecord(Guid accountid, string accountnumber, string name, Guid ownerid, string owneridtype, int number, string companyname)
        {
            this.accountid = accountid;
            this.accountnumber = accountnumber;
            this.name = name;
            this.ownerid = ownerid;
            this.owneridtype = owneridtype;
            this.number = number;
            this.companyname = companyname;
        }
        public bool Equals(AccountRecord other)
        {
            if(this.name.Equals(other.name) && this.number == other.number){
                return true;
            }
            else
            {
                return false;
            }
        }
        public int CompareTo(AccountRecord other)
        {
            if (this.number > other.number)
            {
                return 1;
            }
            else if (this.number < other.number)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }

Somewhere else I have a List of these objects:

private List<AccountRecord> accountRecords = new List<AccountRecord>();

And I add several objects to the list:

accountRecords.Add(new AccountRecord(
                Row.accountid,
                Row.accountnumber,
                name,
                Row.ownerid,
                Row.owneridtype,
                number,
                companyname));

I then get a list of distinct values for the 'companyname' property.

List<string> distinctCompanynames = accountRecords.Distinct(x => x.companyname).ToList<string>();

I'd like to get a List of AccountRecord objects with the highest 'number' property for each distinct 'companyname' property. Thanks to the work that I have done, I can do this with a nested for loop but my entire approach doesn't seem like the best approach considering all the tools C# has at it's disposal. This list will eventually get very large and this code will be executed frequently so I must do this as efficiently as possible. How can I do this faster/better than my current method?

My current method is:

Make List of AccountRecords

Sort

(Reverse) Rewriting the CompareTo method of AccountRecord can remove this step.

Make List of distinct 'companyname' values in List of AccountRecords

Hard-code a nested for loop to perform some action on the first existence of an AccountRecord with each distinct 'companyname'.

What I'd like the method to be:

Make List of AccountRecords

Get a new list (or filter this list into becoming) a List of AccountRecord objects with the highest 'number' property for each distinct 'companyname' property.

If you have any questions, then please let me know.

Body:
I haven't tested this, but this should work:

from ac in accountRecords
group ac by ac.companyname into company
select new
{
    Company = company.Key,
    Number = company.OrderByDescending(g => g.number).FirstOrDefault()
}

UPDATE:  Read the question a bit more closely.  It can be simplifed:

List<AccountRecord> highestRecords =
   (from ac in accountRecords
    group ac by ac.companyname into company
    select company.OrderByDescending(g => g.number).FirstOrDefault())
   .ToList();


问:
Form action relative URL
I have html file like this:

```<code> <!DOCTYPE html>
 <html>
  <head>
    <title>HTML Form</title>
  </head>
  <body>
  </body>

</html>
 <FORM action="/wsd/html_form_check" method="post">
    <P>
    //INPUTS AND LABES AND THINGS
    <INPUT type="submit" value="Send">
    </P>
 </FORM>
</code>```

Now I get an error saying

```<code>AssertionError: Invalid form action.
</code>```

I suppose it has something to do with the

```<code><FORM action="/wsd/html_form_check" method="post">
</code>```

I was told that the HTTP request should look like this:

```<code>POST /wsd/html_form_check HTTP/1.1
Host: 127.0.0.1
</code>```

So what am I doing wrong? Any help is appreciated!
Thanks!

答:
A bit late, but I had to deal with the same issue.

Consider the following piece of HTML code:

```<code><form id="file_uploader" action="/Home/Upload" class="dropzone">
 <div class="fallback">
  <input name="file" type="file" multiple />
 </div>
</form>
</code>```

In the development environment it runs fine. However, deploying it to IIS anywhere else but the root website will cause the action URL to become invalid. For instance, if it were deployed to https://example.com/deployed_app, then the actual action URL that the form will call is https://example.com/Home/Upload, which is invalid.

The solution is to change the action URL to this:

```<code><form id="file_uploader" action="~/Home/Upload" class="dropzone">
</code>```

Title: Form action relative URL

Body:
I have html file like this:

 <!DOCTYPE html>

    <title>HTML Form</title>

 <FORM action="/wsd/html_form_check" method="post">

    //INPUTS AND LABES AND THINGS
    <INPUT type="submit" value="Send">

 </FORM>

Now I get an error saying

AssertionError: Invalid form action.

I suppose it has something to do with the

<FORM action="/wsd/html_form_check" method="post">

I was told that the HTTP request should look like this:

POST /wsd/html_form_check HTTP/1.1
Host: 127.0.0.1

So what am I doing wrong? Any help is appreciated!
Thanks!

Body:
A bit late, but I had to deal with the same issue.

Consider the following piece of HTML code:

<form id="file_uploader" action="/Home/Upload" class="dropzone">
 <div class="fallback">
  <input name="file" type="file" multiple />
 </div>
</form>

In the development environment it runs fine. However, deploying it to IIS anywhere else but the root website will cause the action URL to become invalid. For instance, if it were deployed to https://example.com/deployed_app, then the actual action URL that the form will call is https://example.com/Home/Upload, which is invalid.

The solution is to change the action URL to this:

<form id="file_uploader" action="~/Home/Upload" class="dropzone">


问:
Java RMI server to client communication not working
I'm developing a game which use server communication with socket and RMI. I'm quite new to RMI and i'm encountering some problems while trying to communicate between a server and a client which are not on the same PC.
In localhost it work flawlessy, otherwise communication don't work as expected.
Here some code snippets:

```<code>public RMIServer (ServerInterface mainServer){
    this.mainServer = mainServer;
}

public void startServer() throws IOException {
    Registry registry  = createOrLoadRegistry(Server.RMIPORT);
    try {
        System.out.println("Insert server ip address: ");
        Scanner in = new Scanner(System.in);
        String address = in.nextLine();
        in.close();
        System.setProperty("java.rmi.server.hostname", address);
        registry.bind("RMIServerInterface", this);
        UnicastRemoteObject.exportObject(this, Server.RMIPORT+1);
    } catch (RemoteException | AlreadyBoundException e) {
        System.err.println(e.getMessage());
    }
}

private Registry createOrLoadRegistry(int port) throws IOException{
    try {
        System.out.println("creating register.. ");
        return LocateRegistry.createRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    try {
        return LocateRegistry.getRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    return null;
}
</code>```

Socket works very good instead.

EDIT:
To let RMI work in first place I was forced to use:

```<code>System.setProperty("java.rmi.server.hostname")

enter code here
</code>```

because server IP was randomly set to 127.0.1.1 (loopback).
I printed the stack track on server side and this was the result:

```<code>    creating register..
Insert server ip address:
192.168.1.73
Socket server is ready
Recieved RMI client connection
create first room..
cchvo has been added to room
Number of players: 1
java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is:
  java.net.ConnectException: Connessione rifiutata (Connection refused)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
  at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
  at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
  at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:130)
  at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
  at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
  at com.sun.proxy.$Proxy1.notifyNewPlayer(Unknown Source)
  at server.RMIPlayer.notifyNewPlayer(RMIPlayer.java:28)
  at server.Room.notifyNewPlayer(Room.java:147)
  at server.Room.addPlayer(Room.java:106)
  at server.Server.createRoom(Server.java:98)
  at server.Server.addPlayerFirstAvailableRoom(Server.java:119)
  at server.RMIServer.addRoom(RMIServer.java:82)
  at server.RMIServer.loginPlayer(RMIServer.java:75)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
  at sun.rmi.transport.Transport$1.run(Transport.java:200)
  at sun.rmi.transport.Transport$1.run(Transport.java:197)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
  at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connessione rifiutata (Connection refused)
  at java.net.PlainSocketImpl.socketConnect(Native Method)
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
  at java.net.Socket.connect(Socket.java:589)
  at java.net.Socket.connect(Socket.java:538)
  at java.net.Socket.<init>(Socket.java:434)
  at java.net.Socket.<init>(Socket.java:211)
  at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
  at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
  ... 30 more
</code>```

答:
I've finally managed to fix this by simply adding

```<code>System.setProperty ("java.rmi.server.hostname", clientIp)
</code>```

in client too. Hope to help someone with the same problems.

PS: only one PC (with Debian) over 3 had this problem with hostname, the others running Ubuntu and Windows had not.
Thanks for the answers.

Body:
I'm developing a game which use server communication with socket and RMI. I'm quite new to RMI and i'm encountering some problems while trying to communicate between a server and a client which are not on the same PC.
In localhost it work flawlessy, otherwise communication don't work as expected.
Here some code snippets:

public RMIServer (ServerInterface mainServer){
    this.mainServer = mainServer;
}

public void startServer() throws IOException {
    Registry registry  = createOrLoadRegistry(Server.RMIPORT);
    try {
        System.out.println("Insert server ip address: ");
        Scanner in = new Scanner(System.in);
        String address = in.nextLine();
        in.close();
        System.setProperty("java.rmi.server.hostname", address);
        registry.bind("RMIServerInterface", this);
        UnicastRemoteObject.exportObject(this, Server.RMIPORT+1);
    } catch (RemoteException | AlreadyBoundException e) {
        System.err.println(e.getMessage());
    }
}

private Registry createOrLoadRegistry(int port) throws IOException{
    try {
        System.out.println("creating register.. ");
        return LocateRegistry.createRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    try {
        return LocateRegistry.getRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    return null;
}

Socket works very good instead.

EDIT:
To let RMI work in first place I was forced to use:

System.setProperty("java.rmi.server.hostname")

enter code here

because server IP was randomly set to 127.0.1.1 (loopback).
I printed the stack track on server side and this was the result:

    creating register..
Insert server ip address:
192.168.1.73
Socket server is ready
Recieved RMI client connection
create first room..
cchvo has been added to room
Number of players: 1
java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is:
  java.net.ConnectException: Connessione rifiutata (Connection refused)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
  at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
  at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
  at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:130)
  at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
  at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
  at com.sun.proxy.$Proxy1.notifyNewPlayer(Unknown Source)
  at server.RMIPlayer.notifyNewPlayer(RMIPlayer.java:28)
  at server.Room.notifyNewPlayer(Room.java:147)
  at server.Room.addPlayer(Room.java:106)
  at server.Server.createRoom(Server.java:98)
  at server.Server.addPlayerFirstAvailableRoom(Server.java:119)
  at server.RMIServer.addRoom(RMIServer.java:82)
  at server.RMIServer.loginPlayer(RMIServer.java:75)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
  at sun.rmi.transport.Transport$1.run(Transport.java:200)
  at sun.rmi.transport.Transport$1.run(Transport.java:197)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
  at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connessione rifiutata (Connection refused)
  at java.net.PlainSocketImpl.socketConnect(Native Method)
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
  at java.net.Socket.connect(Socket.java:589)
  at java.net.Socket.connect(Socket.java:538)
  at java.net.Socket.<init>(Socket.java:434)
  at java.net.Socket.<init>(Socket.java:211)
  at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
  at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
  ... 30 more

Body:
I've finally managed to fix this by simply adding

System.setProperty ("java.rmi.server.hostname", clientIp)

in client too. Hope to help someone with the same problems.

PS: only one PC (with Debian) over 3 had this problem with hostname, the others running Ubuntu and Windows had not.
Thanks for the answers.


问:
Generated recursive object based on array
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

```<code>{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}
</code>```

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?

答:
var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => {
  return nested? {path, nested}: {path};
}, null);

console.log(tree);```
</div>
</div>
</p>

<p>or even better/simpler, just:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => ({path, nested}), null);

console.log(tree);</code>```

It simplifies things for the JS engine if all objects have the same hidden class (simplified: same property names).

Body:
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?

Body:
var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => {
  return nested? {path, nested}: {path};
}, null);

console.log(tree);

or even better/simpler, just:

var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => ({path, nested}), null);

console.log(tree);

It simplifies things for the JS engine if all objects have the same hidden class (simplified: same property names).


问:
Is there any way to cache build dependencies using AWS CodeBuild?
Between 1 and 2 minutes of my AWS CodeBuilds are spent downloading dependencies from Maven Central.

Short of building a pre-provisioned Docker container, is there any way to cache these between builds?

答: CodeBuild now provides a cache feature you can use to pre-load your dependencies.</p>


问:
Round off the area points in Highcharts Polar
Is there is a way to round off the area points and make them less pointed when used in the polar chart?

I have tried the 'areaspline', but with polar chart it's not quite right, as you can see here:

http://jsfiddle.net/qwbu6r3t/2/

```<code>Highcharts.chart('container', {

    chart: {
        polar: true
    },

    title: {
        text: 'Highcharts Polar Chart'
    },

    pane: {
        startAngle: 0,
        endAngle: 360
    },

    xAxis: {
        tickInterval: 45,
        min: 0,
        max: 360,
        labels: {
            formatter: function () {
                return this.value + '°';
            }
        }
    },

    yAxis: {
        min: 0
    },

    plotOptions: {
        series: {
            pointStart: 0,
            pointInterval: 45
        }
    },

    series: [{
        type: 'areaspline',
        name: 'Area spline',
        data: [1, 2, 3, 4, 5, 6, 7, 8]
    }, {
        type: 'area',
        name: 'Area',
        data: [1, 8, 2, 7, 3, 6, 4, 5]
    }]
});
</code>```

EDIT

What I need

答:
You can override highcharts Highcharts.seriesTypes.areaSpline.prototype.getPointSpline with same method but with changed smoothing parameter. (Default 1.5)

```<code>...
var smoothing = 3, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
...
</code>```

Live example:
http://jsfiddle.net/q3h6xwog/

Body:
Is there is a way to round off the area points and make them less pointed when used in the polar chart?

I have tried the 'areaspline', but with polar chart it's not quite right, as you can see here:

http://jsfiddle.net/qwbu6r3t/2/

Highcharts.chart('container', {

    chart: {
        polar: true
    },

    title: {
        text: 'Highcharts Polar Chart'
    },

    pane: {
        startAngle: 0,
        endAngle: 360
    },

    xAxis: {
        tickInterval: 45,
        min: 0,
        max: 360,
        labels: {
            formatter: function () {
                return this.value + '°';
            }
        }
    },

    yAxis: {
        min: 0
    },

    plotOptions: {
        series: {
            pointStart: 0,
            pointInterval: 45
        }
    },

    series: [{
        type: 'areaspline',
        name: 'Area spline',
        data: [1, 2, 3, 4, 5, 6, 7, 8]
    }, {
        type: 'area',
        name: 'Area',
        data: [1, 8, 2, 7, 3, 6, 4, 5]
    }]
});

EDIT

What I need

Body:
You can override highcharts Highcharts.seriesTypes.areaSpline.prototype.getPointSpline with same method but with changed smoothing parameter. (Default 1.5)

...
var smoothing = 3, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
...

Live example:
http://jsfiddle.net/q3h6xwog/


问:
Learn how to develop open source applications with many developers
I'm a solo developer and always have been, but I've been learning lately about the possibilities of source control and project collaboration. I would really like to learn how to work with large groups of developers (say on github). I think it would be an amazing learning experience, but up till now I have always been the only developer on a given project. Are there any recourses for learning how to work on small portions of a project to get bits done? Books? Examples? I know I have to start somewhere, but I'm not sure how. Thanks.</p>

答:
Join an open source project.

Find something on GitHub or another large open source project repository using a language you like and/or a project that fires your imagination.

Read the wiki/mailing lists and find out how to contribute.

In this case, the best way to learn is to do.


问:
Firebase HTTP Trigger Cloud Function to change users' values in realtime database
So I have written code which should change a certain value in the database. I would use cron-jobs to trigger it in every 24h, but there is something wrong with my code.</p>

```<code>const functions = require('firebase-functions');

exports.resetPicksStatus = functions.https.onRequest((req, res) => {
  .ref('/users/{userId}')
  .onWrite(event => {
    const status = event.data.val()
    if (status.resetted) {
        return true
    }
    console.log("Resetting status for " + event.paramas.userId)
    status.resetted = true
    status.picksDone = resetToNil(status.picksDone)
    return event.data.ref.set(status)
  })
})

  function resetToNil(s) {
    var resetValue = s
    resetValue = resetValue.replace(/\b1\b/ig, "0")
    return resetValue
  }
</code>```

答:
It looks like you're trying to put a Realtime Database trigger inside your HTTP trigger, which won't have the outcome you're looking for. Instead of using a database trigger, use the Firebase Admin SDK to access the database from within the HTTP trigger.

In your code, add

```<code>const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const ref = admin.database().ref();
</code>```

And use ref to access the database.

Check out the Admin SDK documentation here.

Here are some samples of Cloud Functions, some of which show the Admin SDK.

Here's a video showing how to use the Admin SDK

Here's a video on timing Cloud Functions

Body:
So I have written code which should change a certain value in the database. I would use cron-jobs to trigger it in every 24h, but there is something wrong with my code.

const functions = require('firebase-functions');

exports.resetPicksStatus = functions.https.onRequest((req, res) => {
  .ref('/users/{userId}')
  .onWrite(event => {
    const status = event.data.val()
    if (status.resetted) {
        return true
    }
    console.log("Resetting status for " + event.paramas.userId)
    status.resetted = true
    status.picksDone = resetToNil(status.picksDone)
    return event.data.ref.set(status)
  })
})

  function resetToNil(s) {
    var resetValue = s
    resetValue = resetValue.replace(/\b1\b/ig, "0")
    return resetValue
  }

Body:
It looks like you're trying to put a Realtime Database trigger inside your HTTP trigger, which won't have the outcome you're looking for. Instead of using a database trigger, use the Firebase Admin SDK to access the database from within the HTTP trigger.

In your code, add

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const ref = admin.database().ref();

And use ref to access the database.

Check out the Admin SDK documentation here.

Here are some samples of Cloud Functions, some of which show the Admin SDK.

Here's a video showing how to use the Admin SDK

Here's a video on timing Cloud Functions


问:
How to correctly store connection strings in environment variables for retrieval by production ASP.Net Core MVC applications
I am working on an ASP.NET Core MVC application and I am having an issue with my connection strings.

I have an ASPNETCORE_ENVIRONMENT variable set to Production on my production server and my production server is a Windows Server 2012R2 running IIS. I also have the DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed on the production server.

During development, I am using UserSecrets to hold my connection string. This is working properly.

For production, I want my connection strings in environment variables on my production server and this is where I am having an issue. I suspect that it may be in the way I am structuring the environment variable.

When I try to access the database in production I get an error indicating basically that it can't cannot parse the connection string.

```<code>An exception occurred in the database while iterating the results of a query.

System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2
parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
</code>```

If I put the connection string in appSettings.json, the production server works just fine.

So, here is an example of my appSettings.json file showing the connection string that works in production;

```<code>{
  "ConnectionStrings": {
     "TestDb": "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
  },

    ...
    ...
    ...
  }
}
</code>```

If I deploy this appSettings.json file to production, it works OK.

In my ASP.Net Core application, in the Startup.cs file, I have the following;

```<code>public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

}
</code>```

My understanding is that the last builder.add... listed has priority, so in my case, if a connection string exists in the environment, it should take priority over anything in appsettings.

So in production, if I use the following appSettings.config file;

```<code>{
  "ConnectionStrings": {
     "TestDb": "Placeholder for connection string. Overridden by User Secrets in Development and Environment Variables in Production. "
  },

    ...
    ...
    ...
  }
}
</code>```

It should not matter what I have as a value for ConnectionStrings:TestDb in that appsettings.json file if I have an environment variable for the connection string.

Listed below is the environment variable I am using;

```<code>Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
</code>```

However, when I use this setup, I get an error when I try to access the database indicating that it can't parse the connection string.

I have to assume that the problem is the way I have the connection string specified in the environment variable, but after quite a while searching online, I have not been able to find an example of exactly what the environment variable value should look like. For example, do I need to put leading and trailing single quotes around the entire string? Does individual sections of the connection string need single or double quotes?

Any help, such as an example of a proper connection string defined in an environment variable, would be greatly appreciated.

答:
In your configuration you have this line:

```<code>.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
</code>```

This is telling your configuration system that there might be a JSON file that exists with environment specific settings in it. So you only need a file that exists on the production box called appSettings.Production.config containing something like this:

```<code>{
  "ConnectionStrings": {
     "TestDb": "Server=...;Catalog=...;Etc=..."
  }
}
</code>```

The values in here will override anything specified in the base JSON settings file.

Body:
I am working on an ASP.NET Core MVC application and I am having an issue with my connection strings.

I have an ASPNETCORE_ENVIRONMENT variable set to Production on my production server and my production server is a Windows Server 2012R2 running IIS. I also have the DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed on the production server.

During development, I am using UserSecrets to hold my connection string. This is working properly.

For production, I want my connection strings in environment variables on my production server and this is where I am having an issue. I suspect that it may be in the way I am structuring the environment variable.

When I try to access the database in production I get an error indicating basically that it can't cannot parse the connection string.

An exception occurred in the database while iterating the results of a query.

System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2
parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)

If I put the connection string in appSettings.json, the production server works just fine.

So, here is an example of my appSettings.json file showing the connection string that works in production;

{
  "ConnectionStrings": {
     "TestDb": "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
  },

    ...
    ...
    ...
  }
}

If I deploy this appSettings.json file to production, it works OK.

In my ASP.Net Core application, in the Startup.cs file, I have the following;

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

}

My understanding is that the last builder.add... listed has priority, so in my case, if a connection string exists in the environment, it should take priority over anything in appsettings.

So in production, if I use the following appSettings.config file;

{
  "ConnectionStrings": {
     "TestDb": "Placeholder for connection string. Overridden by User Secrets in Development and Environment Variables in Production. "
  },

    ...
    ...
    ...
  }
}

It should not matter what I have as a value for ConnectionStrings:TestDb in that appsettings.json file if I have an environment variable for the connection string.

Listed below is the environment variable I am using;

Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"

However, when I use this setup, I get an error when I try to access the database indicating that it can't parse the connection string.

I have to assume that the problem is the way I have the connection string specified in the environment variable, but after quite a while searching online, I have not been able to find an example of exactly what the environment variable value should look like. For example, do I need to put leading and trailing single quotes around the entire string? Does individual sections of the connection string need single or double quotes?

Any help, such as an example of a proper connection string defined in an environment variable, would be greatly appreciated.

Body:
In your configuration you have this line:

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

This is telling your configuration system that there might be a JSON file that exists with environment specific settings in it. So you only need a file that exists on the production box called appSettings.Production.config containing something like this:

{
  "ConnectionStrings": {
     "TestDb": "Server=...;Catalog=...;Etc=..."
  }
}

The values in here will override anything specified in the base JSON settings file.


问:
Can I run a Go web server with HTML/JavaScript UI as a cross platform application (Linux, Android, iOS, macOS, Windows)
I'm experimenting with Go and as I web developer I want to explore the possibilities of building the same Go web service with the same HTML/JavaScript/CSS UI cross platform for Linux, Android, iOS, macOS, Windows and so on.

I am aware of frameworks such as Electron, Cordova, gomobile but none of them seem to work both with Go and a web UI to generate several of Linux binary, Android APK, Windows exe, macOS dmg, iOS binary (don't know that format yet) without having to code different UIs for different platforms.

Any suggestions on how to solve this?

答:
All of these platforms have browsers to render web content. Frameworks like Cordova wrap a native app around a browser component (web view).

The missing part is deploying a local go server, that would be the backend of your app. AFAIK, there is no cross platform solution for this yet.

Also, using a server locally violates it's main purposes (serving many clients concurrently, security of remotely stored information).


问:
I am unable to get value from div tag
```<code><!DOCTYPE html>
<html>
<body>

<p>Write something in the text field to trigger a function.</p>

<div id="myInput" oninput="myFunction()" contenteditable>100</div>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myInput").value;
    document.getElementById("demo").innerHTML = "You wrote: " + x;
}
</script>

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

Please give me some solution on this. In output i get value for x is "undefined".

答:
As an alternative to the other answers you can change your myInput element to an

<textarea.. or <input type="text"..

```<code><textarea id="myInput" oninput="myFunction()">100</textarea>
</code>```

Title: I am unable to get value from div tag

Body:
<!DOCTYPE html>

Write something in the text field to trigger a function.

100

Please give me some solution on this. In output i get value for x is "undefined".

Body:
As an alternative to the other answers you can change your myInput element to an

<textarea.. or <input type="text"..

<textarea id="myInput" oninput="myFunction()">100</textarea>


问:
Regular Expressions to Display Messages from a Text Log File
I'm trying to figure out how to use regular expressions to condense and sort the information I'm getting from this code. Here's the code and I'll explain as I go:

```<code>import java.io.*;
import java.util.*;

public class baseline
{

// Class level variables
   static Scanner sc = new Scanner(System.in);

   public static void main(String[] args) throws IOException,
   FileNotFoundException { // Start of main

   // Variables
   String filename;

   // Connecting to the output file with a buffer
   PrintWriter outFile = new PrintWriter(
                          new BufferedWriter(
                           new FileWriter("chatOutput.log")));

   // Get the input file
   System.out.print("Please enter full name of the file: ");
   filename = sc.next();

   // Assign the name of the input file to a file object
   File log = new File(filename);
   String textLine = null; // Null
   String outLine = "";    // Null
   BufferedWriter bw = null;

  try
  {
  // assigns the input file to a filereader object
     BufferedReader infile = new BufferedReader(new FileReader(log));

      sc = new Scanner(log);
            while(sc.hasNext())
            {
                String line=sc.nextLine();
                if(line.contains("LANTALK"))
                    System.out.println(line);
            } // End of while

  try
   {
     // Read data from the input file
    while((textLine = infile.readLine()) != null)
     {
    // Print to output file
    outLine = textLine;
    sc = new Scanner (outLine);
          while(sc.hasNext())
          {
               String line=sc.nextLine();
               if(line.contains("LANTALK"))
                    outFile.printf("%s\n",outLine);
          }// end of while
      } // end of while
    } // end of try

   finally  // This gets executed even when an exception is thrown
      {
    infile.close();
    outFile.close();
      } // End of finally
    } // End of try

  catch (FileNotFoundException nf) // Goes with first try
  {
   System.out.println("The file \""+log+"\" was not found");
  } // End of catch
  catch (IOException ioex) // Goes with second try
  {
   System.out.println("Error reading the file");
  } // End of catch

 } // end of main

} // end of class
</code>```

So I'm reading an input file, getting only the lines that display "LANTALK", and printing them out to another file. And here is a sample of what the output looks like so far:

```<code>14:29:39.731 [D] [T:000FEC] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>922</MBXID><MBXTO>5608</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>It is mailing today right?
</MSGTEXT>
14:41:33.703 [D] [T:000FF4] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>929</MBXID><MBXTO>5601</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>Either today or tomorrow -
still waiting to hear. </MSGTEXT>
</code>```

And what I need is to get all of the characters between <MSGTEXT> and </MSGTEXT> to be able to display the message cleanly. How should I write this into the code to repeat with every "LANTALK" line and still write out correctly? Thanks!

答:
Try it with Jsoup. </p>

<p>Example: </p>

```<code>import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

....

while(sc.hasNext())
        {
            String line=sc.nextLine();
            if(line.contains("LANTALK")){
               Document doc = Jsoup.parse(line);
               Element  msg = doc.select("MSGTEXT").first();
               System.out.println(msg.text());
            }
                System.out.println(line);
        } // End of while
    .....
</code>```

Body:
I'm trying to figure out how to use regular expressions to condense and sort the information I'm getting from this code. Here's the code and I'll explain as I go:

import java.io.*;
import java.util.*;

public class baseline
{

// Class level variables
   static Scanner sc = new Scanner(System.in);

   public static void main(String[] args) throws IOException,
   FileNotFoundException { // Start of main

   // Variables
   String filename;

   // Connecting to the output file with a buffer
   PrintWriter outFile = new PrintWriter(
                          new BufferedWriter(
                           new FileWriter("chatOutput.log")));

   // Get the input file
   System.out.print("Please enter full name of the file: ");
   filename = sc.next();

   // Assign the name of the input file to a file object
   File log = new File(filename);
   String textLine = null; // Null
   String outLine = "";    // Null
   BufferedWriter bw = null;

  try
  {
  // assigns the input file to a filereader object
     BufferedReader infile = new BufferedReader(new FileReader(log));

      sc = new Scanner(log);
            while(sc.hasNext())
            {
                String line=sc.nextLine();
                if(line.contains("LANTALK"))
                    System.out.println(line);
            } // End of while

  try
   {
     // Read data from the input file
    while((textLine = infile.readLine()) != null)
     {
    // Print to output file
    outLine = textLine;
    sc = new Scanner (outLine);
          while(sc.hasNext())
          {
               String line=sc.nextLine();
               if(line.contains("LANTALK"))
                    outFile.printf("%s\n",outLine);
          }// end of while
      } // end of while
    } // end of try

   finally  // This gets executed even when an exception is thrown
      {
    infile.close();
    outFile.close();
      } // End of finally
    } // End of try

  catch (FileNotFoundException nf) // Goes with first try
  {
   System.out.println("The file \""+log+"\" was not found");
  } // End of catch
  catch (IOException ioex) // Goes with second try
  {
   System.out.println("Error reading the file");
  } // End of catch

 } // end of main

} // end of class

So I'm reading an input file, getting only the lines that display "LANTALK", and printing them out to another file. And here is a sample of what the output looks like so far:

14:29:39.731 [D] [T:000FEC] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>922</MBXID><MBXTO>5608</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>It is mailing today right?
</MSGTEXT>
14:41:33.703 [D] [T:000FF4] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>929</MBXID><MBXTO>5601</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>Either today or tomorrow -
still waiting to hear. </MSGTEXT>

And what I need is to get all of the characters between <MSGTEXT> and </MSGTEXT> to be able to display the message cleanly. How should I write this into the code to repeat with every "LANTALK" line and still write out correctly? Thanks!

Body:
Try it with Jsoup.

Example:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

....

while(sc.hasNext())
        {
            String line=sc.nextLine();
            if(line.contains("LANTALK")){
               Document doc = Jsoup.parse(line);
               Element  msg = doc.select("MSGTEXT").first();
               System.out.println(msg.text());
            }
                System.out.println(line);
        } // End of while
    .....


问:
How to delete only few rows if several rows are duplicated in SQL?
How to delete only few rows (more than 1) if several rows are duplicated? When I try to put condition all rows are getting deleted. I'm using SQL server 2008.</p>

答:
Below SQL would help you.

```<code>DELETE TOP(n) TableName
WHERE (Condition which pulls duplicate rows)
</code>```

where n is the number of rows to delete.

Tip: Always try to use Primary key (A primary key is used to uniquely identify each row in a table) as it can have significant impact on the performance, usability, and the extensibility of the entire database.

Body:
Below SQL would help you.

DELETE TOP(n) TableName
WHERE (Condition which pulls duplicate rows)

where n is the number of rows to delete.

Tip: Always try to use Primary key (A primary key is used to uniquely identify each row in a table) as it can have significant impact on the performance, usability, and the extensibility of the entire database.