问:
Go-generated animated GIFs didn't work in windows
I found an example didn't work properly in Windows.
This program demonstrates basic usage of Go's standard image packages, which we'll use to create a sequence of bit-mapped images and then encode the sequence as a GIF animation.

```<code>package main

import (
    "image"
    "image/color"
    "image/gif"
    "io"
    "math"
    "math/rand"
    "os"
)

import (
    "log"
    "net/http"
    "time"
)

//!+main

var palette = []color.Color{color.White, color.Black}

const (
    whiteIndex = 0 // first color in palette
    blackIndex = 1 // next color in palette
)

func main() {
    //!-main
    // The sequence of images is deterministic unless we seed
    // the pseudo-random number generator using the current time.
    // Thanks to Randall McPherson for pointing out the omission.
    rand.Seed(time.Now().UTC().UnixNano())

    if len(os.Args) > 1 && os.Args[1] == "web" {
        //!+http
        handler := func(w http.ResponseWriter, r *http.Request) {
            lissajous(w)
        }
        http.HandleFunc("/", handler)
        //!-http
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
        return
    }
    //!+main
    lissajous(os.Stdout)
}

func lissajous(out io.Writer) {
    const (
        cycles  = 5     // number of complete x oscillator revolutions
        res     = 0.001 // angular resolution
        size    = 100   // image canvas covers [-size..+size]
        nframes = 64    // number of animation frames
        delay   = 8     // delay between frames in 10ms units
    )
    freq := rand.Float64() * 3.0 // relative frequency of y oscillator
    anim := gif.GIF{LoopCount: nframes}
    phase := 0.0 // phase difference
    for i := 0; i < nframes; i++ {
        rect := image.Rect(0, 0, 2*size+1, 2*size+1)
        img := image.NewPaletted(rect, palette)
        for t := 0.0; t < cycles*2*math.Pi; t += res {
            x := math.Sin(t)
            y := math.Sin(t*freq + phase)
            img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5),
                blackIndex)
        }
        phase += 0.1
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }
    gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
</code>```

The code runs properly in cmd, however, if I run it in Windows Power Shell like:

```<code>.\lissajous.exe >out.gif
</code>```

The out.gif can't be opened and I don't know why.

答:
The GIF file (the gif data) is a binary format, not textual. Attempting to write it to the standard output and redirecting that to a file may suffer transformations. For example, the Windows PowerShell most likely converts some control characters (like "\n" to "\r\n"), so the resulting binary will not be identical to what gif.EncodeAll() writes to the standard output. Apparently cmd.exe does not do such transformations.

I recommend writing to a file directly (you may pass an os.File as the output), or an in-memory buffer which you can dump to a file using ioutil.WriteFile().

Here's how writing directly to a file could look like:

```<code>f, err := os.Create("a.gif")
if err != nil {
    panic(err)
}
defer f.Close()
lissajous(f)
</code>```

Here's how the in-memory solution could look like:

```<code>buf := &bytes.Buffer{}
lissajous(buf)
if err := ioutil.WriteFile("a.gif", buf.Bytes(), 0666); err != nil {
    panic(err)
}
</code>```

See related issue: image/gif: result of EncodeAll not viewable in Eye of GNOME

There is still a chance the result won't be readable by some apps (see above issue), which can be fixed by converting the output image in unix with the following command:

```<code>convert original.gif -coalesce unoptimized.gif
</code>```

Source: Fix animated GIF images which eog can't open, but Firefox and ImageMagick can

Body:
I found an example didn't work properly in Windows.
This program demonstrates basic usage of Go's standard image packages, which we'll use to create a sequence of bit-mapped images and then encode the sequence as a GIF animation.

package main

import (
    "image"
    "image/color"
    "image/gif"
    "io"
    "math"
    "math/rand"
    "os"
)

import (
    "log"
    "net/http"
    "time"
)

//!+main

var palette = []color.Color{color.White, color.Black}

const (
    whiteIndex = 0 // first color in palette
    blackIndex = 1 // next color in palette
)

func main() {
    //!-main
    // The sequence of images is deterministic unless we seed
    // the pseudo-random number generator using the current time.
    // Thanks to Randall McPherson for pointing out the omission.
    rand.Seed(time.Now().UTC().UnixNano())

    if len(os.Args) > 1 && os.Args[1] == "web" {
        //!+http
        handler := func(w http.ResponseWriter, r *http.Request) {
            lissajous(w)
        }
        http.HandleFunc("/", handler)
        //!-http
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
        return
    }
    //!+main
    lissajous(os.Stdout)
}

func lissajous(out io.Writer) {
    const (
        cycles  = 5     // number of complete x oscillator revolutions
        res     = 0.001 // angular resolution
        size    = 100   // image canvas covers [-size..+size]
        nframes = 64    // number of animation frames
        delay   = 8     // delay between frames in 10ms units
    )
    freq := rand.Float64() * 3.0 // relative frequency of y oscillator
    anim := gif.GIF{LoopCount: nframes}
    phase := 0.0 // phase difference
    for i := 0; i < nframes; i++ {
        rect := image.Rect(0, 0, 2*size+1, 2*size+1)
        img := image.NewPaletted(rect, palette)
        for t := 0.0; t < cycles*2*math.Pi; t += res {
            x := math.Sin(t)
            y := math.Sin(t*freq + phase)
            img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5),
                blackIndex)
        }
        phase += 0.1
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }
    gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}

The code runs properly in cmd, however, if I run it in Windows Power Shell like:

.\lissajous.exe >out.gif

The out.gif can't be opened and I don't know why.

Body:
The GIF file (the gif data) is a binary format, not textual. Attempting to write it to the standard output and redirecting that to a file may suffer transformations. For example, the Windows PowerShell most likely converts some control characters (like "\n" to "\r\n"), so the resulting binary will not be identical to what gif.EncodeAll() writes to the standard output. Apparently cmd.exe does not do such transformations.

I recommend writing to a file directly (you may pass an os.File as the output), or an in-memory buffer which you can dump to a file using ioutil.WriteFile().

Here's how writing directly to a file could look like:

f, err := os.Create("a.gif")
if err != nil {
    panic(err)
}
defer f.Close()
lissajous(f)

Here's how the in-memory solution could look like:

buf := &bytes.Buffer{}
lissajous(buf)
if err := ioutil.WriteFile("a.gif", buf.Bytes(), 0666); err != nil {
    panic(err)
}

See related issue: image/gif: result of EncodeAll not viewable in Eye of GNOME

There is still a chance the result won't be readable by some apps (see above issue), which can be fixed by converting the output image in unix with the following command:

convert original.gif -coalesce unoptimized.gif

Source: Fix animated GIF images which eog can't open, but Firefox and ImageMagick can


来源: stackexchange

问:
How to add multilevel column name to specific column only(not all the columns) in python pandas.DataFrame?
Refer here for the question background. I want to add C to only column B.

I need output as:

```<code> df
    Out[92]:
       A  B
          C
    a  0  0
    b  1  1
    c  2  2
    d  3  3
    e  4  4
</code>```

I tried this example as :

```<code>dfnew=pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})

columns=[('c','b')]  #changed from columns=[('c','a'),('c','b')]

dfnew.columns=pd.MultiIndex.from_tuples(columns)
</code>```

But that doesn't works. ValueError: Length mismatch: Expected axis has 2 elements, new values have 1 elements

答:
You can use MultiIndex.from_arrays:

```<code>df.columns = pd.MultiIndex.from_arrays([df.columns, ['','C']])

   A  B
      C
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4
</code>```

Note that pd.MultiIndex.from_tuples is expecting a list of tuples, as the name suggests. If you check the source code, you'll see that if that is not the case, it will create one from the nested list by zipping it:

```<code>list(zip(*[df.columns, ['','C']]))
# [('A', ''), ('B', 'C')]
</code>```

Which is the reason why you don't get what you expect.

If you want to do the same by specifying a list of columns, you could do:

```<code>cols = [(i, 'C') if i in ['B','D'] else (i, '') for i in df.columns]
# [('A', ''), ('B', 'C'), ('C', ''), ('D', 'C')]
df.columns = pd.MultiIndex.from_tuples(cols)

   A  B  C  D
      C     C
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Refer here for the question background. I want to add C to only column B.

I need output as:

 df
    Out[92]:
       A  B
          C
    a  0  0
    b  1  1
    c  2  2
    d  3  3
    e  4  4

I tried this example as :

dfnew=pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})

columns=[('c','b')]  #changed from columns=[('c','a'),('c','b')]

dfnew.columns=pd.MultiIndex.from_tuples(columns)

But that doesn't works. ValueError: Length mismatch: Expected axis has 2 elements, new values have 1 elements

Body:
You can use MultiIndex.from_arrays:

df.columns = pd.MultiIndex.from_arrays([df.columns, ['','C']])

   A  B
      C
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

Note that pd.MultiIndex.from_tuples is expecting a list of tuples, as the name suggests. If you check the source code, you'll see that if that is not the case, it will create one from the nested list by zipping it:

list(zip(*[df.columns, ['','C']]))
# [('A', ''), ('B', 'C')]

Which is the reason why you don't get what you expect.

If you want to do the same by specifying a list of columns, you could do:

cols = [(i, 'C') if i in ['B','D'] else (i, '') for i in df.columns]
# [('A', ''), ('B', 'C'), ('C', ''), ('D', 'C')]
df.columns = pd.MultiIndex.from_tuples(cols)

   A  B  C  D
      C     C
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4


问:
On using "confirm('message')" in JavaScript, making the browser navigation buttons disabled
I have a situation where in, when the user clicks the "back" button, I have to prompt for a "confirm" on a page using JavaScript. The result would decide whether to stay on the page or not.

I have used, the following:

```<code>   window.onbeforeunload = function () {

         var answer = return confirm("Please note by clicking the back button will reset your selection")

         if (!answer) {
            event.preventDefault();
         }
         else{

         // do something
         }
 };
</code>```

Now, even if this prompts a popup on the page, the back button can still be clicked taking the user to the previous page.

On the other hand, by using the following.

```<code>   window.onbeforeunload = () => {return '';}
</code>```

I get the message "Changes you made may not be saved.", with the prevention of "back", "forward", "refresh" and all such buttons on the page.

I want this same thing (the prevention of these buttons), to happen on "confirm('message')".

答:
```<code>function Confirm_something() {
    history.pushState(null, null, location.href);
      window.onpopstate = function () {
        history.go(1);
      };
    return confirm("Text you want?");
}

if(Confirm_something){
   console.log('user say yes'); //then call your save edit or delete functions.
}
else{
   console.log('user say no');
}
</code>```

Body:
I have a situation where in, when the user clicks the "back" button, I have to prompt for a "confirm" on a page using JavaScript. The result would decide whether to stay on the page or not.

I have used, the following:

   window.onbeforeunload = function () {

         var answer = return confirm("Please note by clicking the back button will reset your selection")

         if (!answer) {
            event.preventDefault();
         }
         else{

         // do something
         }
 };

Now, even if this prompts a popup on the page, the back button can still be clicked taking the user to the previous page.

On the other hand, by using the following.

   window.onbeforeunload = () => {return '';}

I get the message "Changes you made may not be saved.", with the prevention of "back", "forward", "refresh" and all such buttons on the page.

I want this same thing (the prevention of these buttons), to happen on "confirm('message')".


问:
Change/swap values one after another in pandas dataframe for selected rows
Dataframe:

```<code>col1 col2
  A    0
  A    1
  A    nan
  B    0
  B    1
  C    and so on...
</code>```

I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2 wherever col1=='A'.

Code so far:

```<code>df.loc[(df.col1=='A') & (df.col2==0),'col2'] = 2
df.loc[(df.col1=='A') & (df.col2==1),'col2'] = 0
df.loc[(df.col1=='A') & (df.col2==2),'col2'] = 1

# Hope you understand why I am converting 0 to 2 first then to 1.
# Because if I convert all zeroes to 1 then all 1's will be converted to
# 0 in subsequent conversion.
</code>```

Unique values in col2 are 0,1 and nan.
Is there a correct/better way of doing this?
Also, is there a way to directly swap these numbers instead of assignment operators?

答:
In this case, you can also use your own function in combination with apply().

```<code># import pandas
import pandas as pd

# make a sample data
list_of_rows = [
  {'col1': A, 'col2': 1},
  {'col1': A, 'col2': 0},
  {'col1': A, 'col2': None},
  {'col1': B, 'col2': 0},
  {'col1': B, 'col2': 1},
  {'col1': B, 'col2': None},
]

# make a pandas data frame
df = pd.DataFrame(list_of_rows)

# define a function
def change_values(row):
    if row['col2'] == 0:
        return 1
    if row['col2'] == 1:
        return 0
    return row['col2']

# apply function to dataframe
df['col2'] = df.apply(lambda row: change_values(row), axis=1)
</code>```

Body:
Dataframe:

col1 col2
  A    0
  A    1
  A    nan
  B    0
  B    1
  C    and so on...

I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2 wherever col1=='A'.

Code so far:

df.loc[(df.col1=='A') & (df.col2==0),'col2'] = 2
df.loc[(df.col1=='A') & (df.col2==1),'col2'] = 0
df.loc[(df.col1=='A') & (df.col2==2),'col2'] = 1

# Hope you understand why I am converting 0 to 2 first then to 1.
# Because if I convert all zeroes to 1 then all 1's will be converted to
# 0 in subsequent conversion.

Unique values in col2 are 0,1 and nan.
Is there a correct/better way of doing this?
Also, is there a way to directly swap these numbers instead of assignment operators?

Body:
In this case, you can also use your own function in combination with apply().

# import pandas
import pandas as pd

# make a sample data
list_of_rows = [
  {'col1': A, 'col2': 1},
  {'col1': A, 'col2': 0},
  {'col1': A, 'col2': None},
  {'col1': B, 'col2': 0},
  {'col1': B, 'col2': 1},
  {'col1': B, 'col2': None},
]

# make a pandas data frame
df = pd.DataFrame(list_of_rows)

# define a function
def change_values(row):
    if row['col2'] == 0:
        return 1
    if row['col2'] == 1:
        return 0
    return row['col2']

# apply function to dataframe
df['col2'] = df.apply(lambda row: change_values(row), axis=1)


问:
How to remove headers (colnames) after combining several csv files
I want to combine data from several csv files with the same format so I can analyse them, but I cannot remove the headers/column names from the several combined files.

I have used the lapply function in order to take a list of the context of all these files and it looks something like:

```<code>ID X1 X2 ---> header of 1st csv file
1  5  6
2  6  9
.......
10 7  8
</code>```

.

```<code>ID X1 X2 --> headers 2nd csv file
1  5  6
2  6  9
.......
10 7  8
e.t.c
</code>```

How can I remove the header characters in order to apply mathematical operations to these data?

My code:

```<code>data<-lapply(files, read.csv)
mean <-(mean(data$column2, na.rm=TRUE))
</code>```

I also tried read.csv(headers=FALSE) but R do not accept this when the function is inside the lapply

I expect the mean of the data frame of the combined files but I get the error:

In mean.default(data$column2, na.rm = TRUE) :   argument is not
  numeric or logical: returning NA

答:
You can import your data directly without column names:

```<code>read_matrix <- function (csvfile) {
    a <- read.csv(csvfile, header=FALSE)
    matrix(as.matrix(a), ncol=ncol(a), dimnames=NULL)
}
df <-  read_matrix('even_iops_Jan15.csv')
</code>```

An other option is setting them to null:

```<code>names(df) <- NULL
</code>```

Body:
I want to combine data from several csv files with the same format so I can analyse them, but I cannot remove the headers/column names from the several combined files.

I have used the lapply function in order to take a list of the context of all these files and it looks something like:

ID X1 X2 ---> header of 1st csv file
1  5  6
2  6  9
.......
10 7  8

.

ID X1 X2 --> headers 2nd csv file
1  5  6
2  6  9
.......
10 7  8
e.t.c

How can I remove the header characters in order to apply mathematical operations to these data?

My code:

data<-lapply(files, read.csv)
mean <-(mean(data$column2, na.rm=TRUE))

I also tried read.csv(headers=FALSE) but R do not accept this when the function is inside the lapply

I expect the mean of the data frame of the combined files but I get the error:

In mean.default(data$column2, na.rm = TRUE) :   argument is not
  numeric or logical: returning NA

Body:
You can import your data directly without column names:

read_matrix <- function (csvfile) {
    a <- read.csv(csvfile, header=FALSE)
    matrix(as.matrix(a), ncol=ncol(a), dimnames=NULL)
}
df <-  read_matrix('even_iops_Jan15.csv')

An other option is setting them to null:

names(df) <- NULL


问:
Using Laravel Eloquent to return multiple table columns once and a sum of another column
I have a table in my database called stocks. In the table, i have two columns product_id, supplied among other columns. So when i get a supply, i add the entries to my table and the table looking like so;

```<code>product_id             supplied
1                         10
2                         15
5                          5
2                         12
4                         10
5                         12
2                          5
1                         12
4                         12
</code>```

Now i want to use laravel eloquent to select the stock by the product_id, returning the total number of items in stock like this;

```<code>product_id       total_in_stock
    1                22
    2                32
    4                22
    5                17
</code>```

Any assistance will be appreciated.

答:
Use SUM and groupBy:</p>

```<code>Stock
    ::selectRaw('product_id, SUM(supplied) as total_in_stock')
    ->groupBy('product_id')
    ->get();
</code>```

Body:
I have a table in my database called stocks. In the table, i have two columns product_id, supplied among other columns. So when i get a supply, i add the entries to my table and the table looking like so;

product_id             supplied
1                         10
2                         15
5                          5
2                         12
4                         10
5                         12
2                          5
1                         12
4                         12

Now i want to use laravel eloquent to select the stock by the product_id, returning the total number of items in stock like this;

product_id       total_in_stock
    1                22
    2                32
    4                22
    5                17

Any assistance will be appreciated.

Body:
Use SUM and groupBy:

Stock
    ::selectRaw('product_id, SUM(supplied) as total_in_stock')
    ->groupBy('product_id')
    ->get();


问:
How do I reset the view of my map back to my location in Ionic with Leaflet and OpenStreetMap?
Right now I'm working on a locationbased App in Ionic v4. Now I want to be able to reset the map view back to my location. I guess I need to use setView again to achieve this, but I don't know the syntax to do that.

Here is all the relevant Code I've got so far:

home.page.html

<ion-content>

    <ion-icon name="navigate"></ion-icon>

</ion-content>
```

<p><strong>home.page.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>centerMap() {
    this.mapService.backToCenter();
}
</code>```

map.service.ts

loadmap(map) {
    this.map = map;
    this.map.locate({
        setView: true,
        maxZoom: 22,
        minZoom: 12
    })
    .on('locationfound', e => {
        const markerGroup = leaflet.featureGroup();
        const marker: any = leaflet
            .marker([e.latitude, e.longitude], {
                icon: positionIcon,
                zIndexOffset: -1000
            })
            .on('click', () => {
                console.log('Position marker clicked');
            });
        markerGroup.addLayer(marker);
        this.map.addLayer(markerGroup);
        this.loadMarkers(this.dropService.getDrops());
    });
    return this.map;
}
backToCenter() {
    console.log('Center Map');
}
```

Is there a way to trigger a new setView on click on a button?

答:
You can store your initial location and zoom level in variables and use map.setView method to go back to your initial location on click of your button.</p>

```<code>backToCenter(){
    map.setView([latitude, longitude], zoom);
}
</code>```

Body:
Right now I'm working on a locationbased App in Ionic v4. Now I want to be able to reset the map view back to my location. I guess I need to use setView again to achieve this, but I don't know the syntax to do that.

Here is all the relevant Code I've got so far:

home.page.html

<ion-content>

    <ion-icon name="navigate"></ion-icon>

</ion-content>

home.page.ts

centerMap() {
    this.mapService.backToCenter();
}

map.service.ts

loadmap(map) {
    this.map = map;
    this.map.locate({
        setView: true,
        maxZoom: 22,
        minZoom: 12
    })
    .on('locationfound', e => {
        const markerGroup = leaflet.featureGroup();
        const marker: any = leaflet
            .marker([e.latitude, e.longitude], {
                icon: positionIcon,
                zIndexOffset: -1000
            })
            .on('click', () => {
                console.log('Position marker clicked');
            });
        markerGroup.addLayer(marker);
        this.map.addLayer(markerGroup);
        this.loadMarkers(this.dropService.getDrops());
    });
    return this.map;
}
backToCenter() {
    console.log('Center Map');
}

Is there a way to trigger a new setView on click on a button?

Body:
You can store your initial location and zoom level in variables and use map.setView method to go back to your initial location on click of your button.

backToCenter(){
    map.setView([latitude, longitude], zoom);
}


问:
Sequelize Association getting data like JSON
I have simplified my problem with two tables as coconut and coconut_lists. Coconut table stores the specifications of coconut and coconut_lists store which seller has the coconut. For each time, a relation is created between seller and coconut it's inserted into coconut_lists table.

I have tried to use through keyword with attributes, setting different relations HasMany, HasOne, BelongsToMany.

Coconut_List

```<code>import { Column, DataType, Model, Table, ForeignKey, BelongsTo } from 'sequelize-typescript';
import Coconut from './coconut';

@Table({
  modelName: 'cononuts_list',
  timestamps: true,
  paranoid: true,
})
export default class CoconutList extends Model<CoconutList> {
  @Column({
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    type: DataType.INTEGER,
  })
  public id: number;

  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  public sellerId: string;

  @ForeignKey(() => coconut)
  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  public coconutId: number;

  @BelongsTo(() => Coconut, 'coconutId')
  public coconut: Coconut;

}

</code>```

Coconut

```<code>import { Column, DataType, Model, Table, HasMany } from 'sequelize-typescript';
import CoconutList from './coconutList';

@Table({
  modelName: 'coconuts',
  timestamps: true,
  paranoid: true,
})
export default class Coconut extends Model<Coconut> {
  @Column({
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    type: DataType.INTEGER,
  })
  public id: number;

  @HasMany(() => CoconutList, 'id')
  public coconutList: CoconutList[];

  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  public weight: number;

  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  public count: number;

  @Column({
    type: DataType.FLOAT,
    allowNull: false,
  })
  public size: number;
}

</code>```

The query :

```<code>const coconutsBySeller = await CoconutList.findAll({
    include: [
      {
        model: Coconut,
        attributes: ['weight', 'size', 'count'],
      },
    ],
    attributes: ['sellerId'],
  });
</code>```

Output of code is as follows :

```<code>[
  {
    "sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 100,
      "count": 6,
      "size": 11,
    }
  },
  {
    "sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 200,
      "count": 12,
      "size": 20,
    }
  },
  {
    "sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 300,
      "count": 18,
      "size": 50,
    }
  },
  {
    "sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 100,
      "count": 6,
      "size": 11,
    }
  }
]

</code>```

Instead I want to get

```<code>[
  {
    "sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
    [{
      "weight": 100,
      "count": 6,
      "size": 11,
    },
    {
      "weight": 200,
      "count": 12,
      "size": 20,
    }]
  },
  {
    "sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
    [{
      "weight": 300,
      "count": 18,
      "size": 50,
},
    {
      "weight": 100,
      "count": 6,
      "size": 11,
    }
  ]
]
</code>```

In addition to the format of data, I also wonder if it's possible to get min_max values of the weight, count, size fields of coconuts assigned to the seller using Sequelize within the above query.

答:
You can try this for grouping by the seller:</p>

```<code>const coconutsBySeller = await CoconutList.findAll({
    include: [
      {
        model: Coconut,
        attributes: ['weight', 'size', 'count'],
      },
    ],
    attributes: ['sellerId'],
    group: ['sellerId']
  });
</code>```

Body:
I have simplified my problem with two tables as coconut and coconut_lists. Coconut table stores the specifications of coconut and coconut_lists store which seller has the coconut. For each time, a relation is created between seller and coconut it's inserted into coconut_lists table.

I have tried to use through keyword with attributes, setting different relations HasMany, HasOne, BelongsToMany.

Coconut_List

import { Column, DataType, Model, Table, ForeignKey, BelongsTo } from 'sequelize-typescript';
import Coconut from './coconut';

@Table({
  modelName: 'cononuts_list',
  timestamps: true,
  paranoid: true,
})
export default class CoconutList extends Model<CoconutList> {
  @Column({
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    type: DataType.INTEGER,
  })
  public id: number;

  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  public sellerId: string;

  @ForeignKey(() => coconut)
  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  public coconutId: number;

  @BelongsTo(() => Coconut, 'coconutId')
  public coconut: Coconut;

}

Coconut

import { Column, DataType, Model, Table, HasMany } from 'sequelize-typescript';
import CoconutList from './coconutList';

@Table({
  modelName: 'coconuts',
  timestamps: true,
  paranoid: true,
})
export default class Coconut extends Model<Coconut> {
  @Column({
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    type: DataType.INTEGER,
  })
  public id: number;

  @HasMany(() => CoconutList, 'id')
  public coconutList: CoconutList[];

  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  public weight: number;

  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  public count: number;

  @Column({
    type: DataType.FLOAT,
    allowNull: false,
  })
  public size: number;
}

The query :

const coconutsBySeller = await CoconutList.findAll({
    include: [
      {
        model: Coconut,
        attributes: ['weight', 'size', 'count'],
      },
    ],
    attributes: ['sellerId'],
  });

Output of code is as follows :

[
  {
    "sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 100,
      "count": 6,
      "size": 11,
    }
  },
  {
    "sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 200,
      "count": 12,
      "size": 20,
    }
  },
  {
    "sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 300,
      "count": 18,
      "size": 50,
    }
  },
  {
    "sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
    "coconut": {
      "weight": 100,
      "count": 6,
      "size": 11,
    }
  }
]

Instead I want to get

[
  {
    "sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
    [{
      "weight": 100,
      "count": 6,
      "size": 11,
    },
    {
      "weight": 200,
      "count": 12,
      "size": 20,
    }]
  },
  {
    "sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
    [{
      "weight": 300,
      "count": 18,
      "size": 50,
},
    {
      "weight": 100,
      "count": 6,
      "size": 11,
    }
  ]
]

In addition to the format of data, I also wonder if it's possible to get min_max values of the weight, count, size fields of coconuts assigned to the seller using Sequelize within the above query.

Body:
You can try this for grouping by the seller:

const coconutsBySeller = await CoconutList.findAll({
    include: [
      {
        model: Coconut,
        attributes: ['weight', 'size', 'count'],
      },
    ],
    attributes: ['sellerId'],
    group: ['sellerId']
  });


问:
How to generate H2 embedded database during Mockito unit test?
I'm currently working on a springboot API where it has been decided that me and my coworkers will be using an H2 embedded database during development.

The database is generating itself fine upon starting the application, but I can't make it work during unit test : they all fail saying org.h2.jdbc.JdbcSQLException: Table '[...]' not found.

I basically did not write most of this code, please let me know if you need more :

application.properties file where the H2 database is initialized :

```<code>datasources.member-request.url=jdbc:h2:mem:db;IGNORECASE=TRUE;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS DMDEOWNER\\;SET SCHEMA DMDEOWNER\\;runscript from 'classpath:h2_init_script.sql'
datasources.member-request.username=sa
datasources.member-request.password=
datasources.member-request.driver-class-name=org.h2.Driver
datasources.member-request.initialize=true
</code>```

As you can see above, we execute a SQL script at the initialisation of H2 called h2_init_script.sql, in this file we have some SQL statement like this (I'll show you the T_THEME table for example)

/* CREATE statements */
CREATE TABLE DMDEOWNER.T_THEME (
    F_NUM_THEME NUMBER(14) NOT NULL,
    F_REF_THEME VARCHAR2(30) NOT NULL,
    F_LIB_THEME VARCHAR2(50) NOT NULL,
    F_POS_THEME NUMBER(4) NOT NULL,
    F_BOOL_ACTIF NUMBER(1) NOT NULL,
    F_UTILISATEUR_MAJ VARCHAR2(40) NOT NULL,
    F_DT_CREATION DATE NOT NULL,
    F_DT_MAJ DATE,
    PRIMARY KEY (F_NUM_THEME)
);

/* INSERT statements */
/* ... */
```

<p>Here is my test class (and its parent) :</p>

<pre class="lang-java prettyprint-override"><code>public class ThemeRepositoryTest extends AbstractRepositoryTest {

  private final static int NB_ACTIVE_ENTITIES = 2;
  private final static int NB_INACTIVE_ENTITIES = 1;

  @Autowired
  private ThemeRepository repository;

  @Autowired
  private ThemeMapper mapper;

  // -------------------------------------------------------------------------
  // CREATE
  // -------------------------------------------------------------------------
  @Before
  public void init() {
    for (int i = INTEGER_ZERO; i < NB_ACTIVE_ENTITIES; i++) {
      insertTheme(true);
    }
    for (int i = INTEGER_ZERO; i < NB_INACTIVE_ENTITIES; i++) {
      insertTheme(false);
    }
    entityManager.flush();
  }

  // -------------------------------------------------------------------------
  // READ
  // -------------------------------------------------------------------------
  @Test
  public void findAll() {
    List<ThemeEntity> list = repository.findAll();
    assertEquals(NB_ACTIVE_ENTITIES + NB_INACTIVE_ENTITIES, list.size());
  }
}

@RunWith(SpringRunner.class)
@DataJpaTest
public abstract class AbstractRepositoryTest {

  @Autowired
  protected TestEntityManager entityManager;

  protected ThemeEntity insertTheme(boolean active) {
    ThemeEntity entity =  newThemeEntity(3L, "NAME", active, "USER");
    return entityManager.merge(entity);
  }
}
</code>```

Here is where my error happens, in the init() function when I call insertTheme() :

```<code>findAll(io.lacipav.repository.ThemeRepositoryTest)  Time elapsed: 0.227 s  <<< ERROR!
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at io.lacipav.repository.ThemeRepositoryTest.init(ThemeRepositoryTest.java:38)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at io.lacipav.repository.ThemeRepositoryTest.init(ThemeRepositoryTest.java:38)
Caused by: org.h2.jdbc.JdbcSQLException:
Table "T_THEME" not found; SQL statement:
select themeentit0_.f_num_theme as f_num_th1_11_0_, themeentit0_.f_bool_actif as f_bool_a2_11_0_, themeentit0_.f_dt_creation as f_dt_cre3_11_0_, themeentit0_.f_dt_maj as f_dt_maj4_11_0_, themeentit0_.f_lib_theme as f_lib_th5_11_0_, themeentit0_.f_pos_theme as f_pos_th6_11_0_, themeentit0_.f_ref_theme as f_ref_th7_11_0_, themeentit0_.f_utilisateur_maj as f_utilis8_11_0_ from t_theme themeentit0_ where themeentit0_.f_num_theme=? [42102-197]
    at io.lacipav.repository.ThemeRepositoryTest.init(ThemeRepositoryTest.java:38)
</code>```

Since the error is telling me that it did not find my table, I'm guessing it is because my database isn't running when I'm building my .war file, if so how can I initialize it quicker ?

EDIT :
As asked for, here's the Entity class for T_THEME :

@Entity
@Getter
@Setter
@Table(name = "T_THEME")
public class ThemeEntity {

  /** Primary key of the table. */
  @Id
  @NotNull
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "theme_generator")
  @SequenceGenerator(name = "theme_generator", sequenceName = "SEQ_NUM_THEME", allocationSize = 1)
  @Column(name = "f_num_theme")
  private Long idTechnique;

  /** Theme functional identifier */
  @NotNull
  @Column(name = "f_ref_theme")
  private String reference;

  /** Theme simple short length label */
  @NotNull
  @Column(name = "f_lib_theme")
  private String name;

  //...
}
```

<p>NOTE : The SQL sequence "SEQ_NUM_THEME" is generated and associated to F_NUM_THEME in the SQL script.</p>

<p>EDIT 2 :</p>

<p>As Lesiak pointed out, my error might be coming from my DataSource being replace by the annotation <code>@DataJpaTest</code>. By carefully watching the logs, I found some interesting lines.</p>

```[INFO ] 2019-05-24 16:22:20.341 [main] org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceBeanFactoryPostProcessor.process(TestDatabaseAutoConfiguration.java:106) : Replacing 'dataSource' DataSource bean with embedded version
[INFO ] 2019-05-24 16:22:20.346 [main] org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition(DefaultListableBeanFactory.java:824) : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
[INFO ] 2019-05-24 16:22:21.050 [main] org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory.initDatabase(EmbeddedDatabaseFactory.java:189) : Starting embedded database: url='jdbc:h2:mem:4ef27020-c472-4be9-a9af-73f5e0175846;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
```

We can see on the last line that my url connection jdbc:h2:mem:db has been replaced by jdbc:h2:mem:4ef27020-c472-4be9-a9af-73f5e0175846. This might be why I'm getting some Table not found errors.

答:
I've ended up trying so much things that I'm not quite sure why it is working now...

In the documentation, it is said that by default it will try to find schema.sql to create the database and data.sql to populate it. I was using my own .sql file that did both jobs, so I separated it as recommended and it started to work !

So now my application.properties is as follow :

```<code># Datasource connection settings to H2 in-memory database
# To init db with h2_init_script.sql add the following to the url : INIT=CREATE SCHEMA IF NOT EXISTS DMDEOWNER\\;SET SCHEMA DMDEOWNER\\;runscript from 'classpath:h2_init_script.sql'
datasources.member-request.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;IGNORECASE=TRUE;
datasources.member-request.username=sa
datasources.member-request.password=
datasources.member-request.driver-class-name=org.h2.Driver
datasources.member-request.initialize=true

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.h2.console.settings.web-allow-others=true

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
</code>```

Since I'm not creating the schema in the application.properties anymore, I added it to the schema.sql file :

CREATE SCHEMA IF NOT EXISTS DMDEOWNER;
SET SCHEMA DMDEOWNER;
```

<p>Finally, I added the schema's name prefix to my sequence declaration in the Entity classes because I had some <code>SEQUENCE NOT FOUND</code> errors :</p>

<pre class="lang-java prettyprint-override"><code>@Entity
@Getter
@Setter
@Table(name = "T_THEME")
public class ThemeEntity {

  /** Primary key of the table. */
  @Id
  @NotNull
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "theme_generator")
  @SequenceGenerator(name = "theme_generator", sequenceName = "DMDEOWNER.SEQ_NUM_THEME", allocationSize = 1)
  @Column(name = "f_num_theme")
  private Long idTechnique;

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

Body:
I'm currently working on a springboot API where it has been decided that me and my coworkers will be using an H2 embedded database during development.

The database is generating itself fine upon starting the application, but I can't make it work during unit test : they all fail saying org.h2.jdbc.JdbcSQLException: Table '[...]' not found.

I basically did not write most of this code, please let me know if you need more :

application.properties file where the H2 database is initialized :

datasources.member-request.url=jdbc:h2:mem:db;IGNORECASE=TRUE;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS DMDEOWNER\\;SET SCHEMA DMDEOWNER\\;runscript from 'classpath:h2_init_script.sql'
datasources.member-request.username=sa
datasources.member-request.password=
datasources.member-request.driver-class-name=org.h2.Driver
datasources.member-request.initialize=true

As you can see above, we execute a SQL script at the initialisation of H2 called h2_init_script.sql, in this file we have some SQL statement like this (I'll show you the T_THEME table for example)

/* CREATE statements */
CREATE TABLE DMDEOWNER.T_THEME (
    F_NUM_THEME NUMBER(14) NOT NULL,
    F_REF_THEME VARCHAR2(30) NOT NULL,
    F_LIB_THEME VARCHAR2(50) NOT NULL,
    F_POS_THEME NUMBER(4) NOT NULL,
    F_BOOL_ACTIF NUMBER(1) NOT NULL,
    F_UTILISATEUR_MAJ VARCHAR2(40) NOT NULL,
    F_DT_CREATION DATE NOT NULL,
    F_DT_MAJ DATE,
    PRIMARY KEY (F_NUM_THEME)
);

/* INSERT statements */
/* ... */

Here is my test class (and its parent) :

public class ThemeRepositoryTest extends AbstractRepositoryTest {

  private final static int NB_ACTIVE_ENTITIES = 2;
  private final static int NB_INACTIVE_ENTITIES = 1;

  @Autowired
  private ThemeRepository repository;

  @Autowired
  private ThemeMapper mapper;

  // -------------------------------------------------------------------------
  // CREATE
  // -------------------------------------------------------------------------
  @Before
  public void init() {
    for (int i = INTEGER_ZERO; i < NB_ACTIVE_ENTITIES; i++) {
      insertTheme(true);
    }
    for (int i = INTEGER_ZERO; i < NB_INACTIVE_ENTITIES; i++) {
      insertTheme(false);
    }
    entityManager.flush();
  }

  // -------------------------------------------------------------------------
  // READ
  // -------------------------------------------------------------------------
  @Test
  public void findAll() {
    List<ThemeEntity> list = repository.findAll();
    assertEquals(NB_ACTIVE_ENTITIES + NB_INACTIVE_ENTITIES, list.size());
  }
}

@RunWith(SpringRunner.class)
@DataJpaTest
public abstract class AbstractRepositoryTest {

  @Autowired
  protected TestEntityManager entityManager;

  protected ThemeEntity insertTheme(boolean active) {
    ThemeEntity entity =  newThemeEntity(3L, "NAME", active, "USER");
    return entityManager.merge(entity);
  }
}

Here is where my error happens, in the init() function when I call insertTheme() :

findAll(io.lacipav.repository.ThemeRepositoryTest)  Time elapsed: 0.227 s  <<< ERROR!
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at io.lacipav.repository.ThemeRepositoryTest.init(ThemeRepositoryTest.java:38)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at io.lacipav.repository.ThemeRepositoryTest.init(ThemeRepositoryTest.java:38)
Caused by: org.h2.jdbc.JdbcSQLException:
Table "T_THEME" not found; SQL statement:
select themeentit0_.f_num_theme as f_num_th1_11_0_, themeentit0_.f_bool_actif as f_bool_a2_11_0_, themeentit0_.f_dt_creation as f_dt_cre3_11_0_, themeentit0_.f_dt_maj as f_dt_maj4_11_0_, themeentit0_.f_lib_theme as f_lib_th5_11_0_, themeentit0_.f_pos_theme as f_pos_th6_11_0_, themeentit0_.f_ref_theme as f_ref_th7_11_0_, themeentit0_.f_utilisateur_maj as f_utilis8_11_0_ from t_theme themeentit0_ where themeentit0_.f_num_theme=? [42102-197]
    at io.lacipav.repository.ThemeRepositoryTest.init(ThemeRepositoryTest.java:38)

Since the error is telling me that it did not find my table, I'm guessing it is because my database isn't running when I'm building my .war file, if so how can I initialize it quicker ?

EDIT :
As asked for, here's the Entity class for T_THEME :

@Entity
@Getter
@Setter
@Table(name = "T_THEME")
public class ThemeEntity {

  /** Primary key of the table. */
  @Id
  @NotNull
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "theme_generator")
  @SequenceGenerator(name = "theme_generator", sequenceName = "SEQ_NUM_THEME", allocationSize = 1)
  @Column(name = "f_num_theme")
  private Long idTechnique;

  /** Theme functional identifier */
  @NotNull
  @Column(name = "f_ref_theme")
  private String reference;

  /** Theme simple short length label */
  @NotNull
  @Column(name = "f_lib_theme")
  private String name;

  //...
}

NOTE : The SQL sequence "SEQ_NUM_THEME" is generated and associated to F_NUM_THEME in the SQL script.

EDIT 2 :

As Lesiak pointed out, my error might be coming from my DataSource being replace by the annotation @DataJpaTest. By carefully watching the logs, I found some interesting lines.

[INFO ] 2019-05-24 16:22:20.341 [main] org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceBeanFactoryPostProcessor.process(TestDatabaseAutoConfiguration.java:106) : Replacing 'dataSource' DataSource bean with embedded version
[INFO ] 2019-05-24 16:22:20.346 [main] org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition(DefaultListableBeanFactory.java:824) : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
[INFO ] 2019-05-24 16:22:21.050 [main] org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory.initDatabase(EmbeddedDatabaseFactory.java:189) : Starting embedded database: url='jdbc:h2:mem:4ef27020-c472-4be9-a9af-73f5e0175846;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'

We can see on the last line that my url connection jdbc:h2:mem:db has been replaced by jdbc:h2:mem:4ef27020-c472-4be9-a9af-73f5e0175846. This might be why I'm getting some Table not found errors.

Body:
I've ended up trying so much things that I'm not quite sure why it is working now...

In the documentation, it is said that by default it will try to find schema.sql to create the database and data.sql to populate it. I was using my own .sql file that did both jobs, so I separated it as recommended and it started to work !

So now my application.properties is as follow :

# Datasource connection settings to H2 in-memory database
# To init db with h2_init_script.sql add the following to the url : INIT=CREATE SCHEMA IF NOT EXISTS DMDEOWNER\\;SET SCHEMA DMDEOWNER\\;runscript from 'classpath:h2_init_script.sql'
datasources.member-request.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;IGNORECASE=TRUE;
datasources.member-request.username=sa
datasources.member-request.password=
datasources.member-request.driver-class-name=org.h2.Driver
datasources.member-request.initialize=true

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.h2.console.settings.web-allow-others=true

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

Since I'm not creating the schema in the application.properties anymore, I added it to the schema.sql file :

CREATE SCHEMA IF NOT EXISTS DMDEOWNER;
SET SCHEMA DMDEOWNER;

Finally, I added the schema's name prefix to my sequence declaration in the Entity classes because I had some SEQUENCE NOT FOUND errors :

@Entity
@Getter
@Setter
@Table(name = "T_THEME")
public class ThemeEntity {

  /** Primary key of the table. */
  @Id
  @NotNull
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "theme_generator")
  @SequenceGenerator(name = "theme_generator", sequenceName = "DMDEOWNER.SEQ_NUM_THEME", allocationSize = 1)
  @Column(name = "f_num_theme")
  private Long idTechnique;

  //...
}


问:
SQL Server Management Studio 2012 does not start
I installed Windows Server 2012 as a VM using Oracle VirtualBox. In this VM MS SQL Server 2012 is running. When starting SQL Server Managment Studio, the splash screen appears for some seconds or minutes. The CPU usage of "SQL Server Management Studio" and "System Interrupts" increases to approximately 20%, where it stays. When ending the SSMS task, the CPU usage of System interrupts falls back to 0%. The GUI of SSMS does not appear. There are no error in the event viewer.
What i tried so far:

Uninstall/Install SSMS

Repaired the installed software

The software is up to date

Deleted C:\Users\Administrator\AppData\Local\Microsoft\SQL Server Management Studio\11.0 to restore the default settings

Deactivated all SQL Server Services expect "SQL Server"

Other software which is installed: jdk-7u51-windows-x64, apache-tomcat-7.0.50, Ant 1.9.3, Netbeans; However, i can not start SMS after a system reboot and none of these programs are running.

During these days I've been working with this machine, SSMS was running sometimes. However, I spent quite some time to solve this problem and after the last uninstall/install SSMS worked again. This morning i came back and started the server and SSMS didn't start again. Between that I swichted off the machine and enjoyed my weekend off...

Thank you for any hints or solutions!

答: This also is occurring with my Microsoft SQL Server Management Studio Version 18.0 (GA). I have copied the assembly file name "Microsoft.VisualStudio.Shell.Interop.8.0.dll" is present in C:\Program Files (x86)\Microsoft SQL Server Management Studio 18\Common7\IDE\PrivateAssemblies\Interop and pasted it to C:\Program Files (x86)\Microsoft SQL Server Management Studio 18\Common7\IDE\PublicAssemblies. Now SSMS 18 is starting normally.

ContentLicense: CC BY-SA 3.0


问:
How to perform multiple simultaneous actions in one thread?
I need ships to load and unload cargo at the same time.
Is there a way to do that in java?

I managed to make multiple ships work in port at the same time, but they first unload cargo and then load new crates.

That is my variant of Ship class

```<code>public class Ship implements Runnable {
    String name;
    Port port;
    Queue<Goods> storage;
    Pier pier;
    int capacity;
    int numOnBoard;

    public Ship(String name, Port port, int capacity) {
        this.name = name;
        this.port = port;
        storage = new LinkedBlockingDeque<>(capacity);
        this.capacity = capacity;
        int num=(int)(Math.random()*capacity);
        numOnBoard=num;
        for (int i = 0; i < num; i++) {
            storage.add(new Goods());
        }
    }

    public void run() {
        try {
            int unl = 0;
            int l = 0;
            pier = port.getPier();
            System.out.println("Ship " + name + " taken " + pier.name);
            while (unload()) {
                if(unl>=numOnBoard) break;
                unl++;
                System.out.println("Ship " + name + " unloaded cargo.");
                Thread.sleep(new Random(100).nextInt(500));
            }
            System.out.println("Ship " + name + " unloaded " + unl + " crates.");
            Thread.sleep(100);
            while (load()) {
                l++;
                System.out.println("Ship " + name + " loaded cargo.");
                Thread.sleep(new Random(100).nextInt(500));
            }
            System.out.println("Ship " + name + " loaded " + l + " crates.");
            port.releasePier(pier);
            System.out.println("Ship " + name + " released " + pier.name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private boolean unload() {
        if (storage.size() <= 0) return false;
        return port.addGoods(storage.poll());
    }

    private boolean load() {
        if (storage.size() >= capacity) return false;
        return port.takeGoods(storage,numOnBoard);
    }
}
</code>```

And the Port

public class Port {
    Queue<Pier> piers;
    Queue<Goods> goods;
    int capacity;

    public Port(int pierCount, int capacity) {
        goods = new LinkedBlockingDeque<>(capacity);
        piers = new LinkedBlockingDeque<>(pierCount);
        this.capacity = capacity;
        for (int i = 0; i < pierCount; i++)
            piers.add(new Pier("Pier " + (i + 1)));
        int num=(int)(Math.random()*capacity);
        for (int i = 0; i < num; i++) {
            goods.add(new Goods());
        }
    }

    public boolean addGoods(Goods item) {
        if (goods.size() >= capacity) return false;
        return goods.add(item);
    }

    public boolean takeGoods(Queue<Goods> storage, int wasOnBoard) {
        if (goods.size() <= wasOnBoard) return false;
        return storage.add(goods.poll());
    }

    public Pier getPier() {
        Pier taken = piers.poll();
        while (taken == null) {
            try {
                System.out.println("There aren't any free piers. Waiting...");
                Thread.sleep(1000);
                taken = piers.poll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return taken;
    }

    public void releasePier(Pier pier) {
        piers.add(pier);
    }

    public static void main(String[] args) {
        Port port = new Port(4, 50);
        ArrayList<Thread> ships = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ships.add(new Thread(new Ship("ship " + (i+1), port, 30)));
        }
        for (Thread t : ships)
            t.start();
    }
}
```

I need each ship to load and unload cargo at the same time

答:
What you're trying to accomplish within a single thread is exactly what multiple threads are for. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program:

A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.

By definition, multitasking is when multiple processes share common
  processing resources such as a CPU. Multi-threading extends the idea
  of multitasking into applications where you can subdivide specific
  operations within a single application into individual threads. Each
  of the threads can run in parallel. The OS divides processing time not
  only among different applications, but also among each thread within
  an application.

Read more about Java multi-threading here.

Body:
I need ships to load and unload cargo at the same time.
Is there a way to do that in java?

I managed to make multiple ships work in port at the same time, but they first unload cargo and then load new crates.

That is my variant of Ship class

public class Ship implements Runnable {
    String name;
    Port port;
    Queue<Goods> storage;
    Pier pier;
    int capacity;
    int numOnBoard;

    public Ship(String name, Port port, int capacity) {
        this.name = name;
        this.port = port;
        storage = new LinkedBlockingDeque<>(capacity);
        this.capacity = capacity;
        int num=(int)(Math.random()*capacity);
        numOnBoard=num;
        for (int i = 0; i < num; i++) {
            storage.add(new Goods());
        }
    }

    public void run() {
        try {
            int unl = 0;
            int l = 0;
            pier = port.getPier();
            System.out.println("Ship " + name + " taken " + pier.name);
            while (unload()) {
                if(unl>=numOnBoard) break;
                unl++;
                System.out.println("Ship " + name + " unloaded cargo.");
                Thread.sleep(new Random(100).nextInt(500));
            }
            System.out.println("Ship " + name + " unloaded " + unl + " crates.");
            Thread.sleep(100);
            while (load()) {
                l++;
                System.out.println("Ship " + name + " loaded cargo.");
                Thread.sleep(new Random(100).nextInt(500));
            }
            System.out.println("Ship " + name + " loaded " + l + " crates.");
            port.releasePier(pier);
            System.out.println("Ship " + name + " released " + pier.name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private boolean unload() {
        if (storage.size() <= 0) return false;
        return port.addGoods(storage.poll());
    }

    private boolean load() {
        if (storage.size() >= capacity) return false;
        return port.takeGoods(storage,numOnBoard);
    }
}

And the Port

public class Port {
    Queue<Pier> piers;
    Queue<Goods> goods;
    int capacity;

    public Port(int pierCount, int capacity) {
        goods = new LinkedBlockingDeque<>(capacity);
        piers = new LinkedBlockingDeque<>(pierCount);
        this.capacity = capacity;
        for (int i = 0; i < pierCount; i++)
            piers.add(new Pier("Pier " + (i + 1)));
        int num=(int)(Math.random()*capacity);
        for (int i = 0; i < num; i++) {
            goods.add(new Goods());
        }
    }

    public boolean addGoods(Goods item) {
        if (goods.size() >= capacity) return false;
        return goods.add(item);
    }

    public boolean takeGoods(Queue<Goods> storage, int wasOnBoard) {
        if (goods.size() <= wasOnBoard) return false;
        return storage.add(goods.poll());
    }

    public Pier getPier() {
        Pier taken = piers.poll();
        while (taken == null) {
            try {
                System.out.println("There aren't any free piers. Waiting...");
                Thread.sleep(1000);
                taken = piers.poll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return taken;
    }

    public void releasePier(Pier pier) {
        piers.add(pier);
    }

    public static void main(String[] args) {
        Port port = new Port(4, 50);
        ArrayList<Thread> ships = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ships.add(new Thread(new Ship("ship " + (i+1), port, 30)));
        }
        for (Thread t : ships)
            t.start();
    }
}

I need each ship to load and unload cargo at the same time


问:
componentDidMount not called on HashRouter Route change
First of all: I know that this question has already been asked here and that there is also already a solution. Please read the whole post before marking this as a duplicate

I am using the HashRouter from react-router-dom and I have this simple route:

```<code><Route path='/folder/:folderId' component={FileArea} />
</code>```

The routing works fine but unfortunately my componentDidMount function is not being called after a route change. This is crutial for my application to work as I have to make an API Call every time the route changes to retrieve the corresponding data (according to the folderId url parameter).

I found a solution in the internet using componentWillReceiveProps and this would work fine for me but apparently this function will no longer work in future react versions: React Documentation

I also know that I could theoretically use static getDerivedStateFromProps(nextProps, prevState) but this function is called way to often and it would be rediculous to make an api call each time.

Is there an alternative for componentWillReceiveProps or some way to invoke componentDidMount?

答:
you can use componentDidUpdate() life cycle hooks.

and to get the route data in your component use this.props.match.params.folderId in that method

and to stop continuous call add if condition it will only call whenever route change.

I hope it will work!!

Body:
First of all: I know that this question has already been asked here and that there is also already a solution. Please read the whole post before marking this as a duplicate

I am using the HashRouter from react-router-dom and I have this simple route:

<Route path='/folder/:folderId' component={FileArea} />

The routing works fine but unfortunately my componentDidMount function is not being called after a route change. This is crutial for my application to work as I have to make an API Call every time the route changes to retrieve the corresponding data (according to the folderId url parameter).

I found a solution in the internet using componentWillReceiveProps and this would work fine for me but apparently this function will no longer work in future react versions: React Documentation

I also know that I could theoretically use static getDerivedStateFromProps(nextProps, prevState) but this function is called way to often and it would be rediculous to make an api call each time.

Is there an alternative for componentWillReceiveProps or some way to invoke componentDidMount?


问:
How do I remove the "Unresolved issue" banner from App Store Connect?
One of my previous builds had a problem that made it through to the Apple Review, which resulted in a banner at the top of the app saying

There are one or more issues with the following platform(s):

1 unresolved iOS issue

The issue was fixed, a new build was submitted, reviewed, approved and released - yet the banner persists.

How can I make this erroneous and confusing banner go away?

答: In the "Testflight" tab, under "Builds" click the rejected build(s) and then the "Expire build" button on the top right.</p>


问:
How to keep client and server talking
I am trying to build my own asynchronous client/server app using .net sockets.

Using these two examples, the basic functionality works.

Server

Client

This example sends a string to the server upon connection, and the server replies, echoing the string that it received, back to the client.

After this reply, the client then shuts down.

```<code>// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
</code>```

In my scenario, I am trying to connect to the server and then send data to the server from the client via input from the user. I reply back with <OK>.

In this example I linked above, the client always waits for a callback after sending (Hence my reply of <OK>).

I am not shutting down the client like in the example, as I want to send consecutive strings on demand. I need the server to keep listening and replying  to confirm receipt of string.

I am quite sure I am missing some core understanding of what should and should not happen.

Right now, I can send a string, the server replies  and the client receives this <ok>. I then try to send another string, but the server never "receives" this string. I guess the server is now also waiting for a callback after sending the  string, but If I return something to the server after receiving the  client side, the whole loop continues and repeats?

How do I make my server wait for more "new" data after replying ok?

Do I have to tell it to "listen" again for any new data? This seems like restarting the connection, which is not my intention...

I would appreciate some insight into what I am missing here...

(P.S. the server is wired with a callback event when sending. I left it like this as this was what the code example that I linked, implemented. DO I have to change my server send routines? (Not to wait for a callback)?

My Server Code:

```<code>          public static void StartListening()
        {
            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[1];

            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
            xServerLog.AddLine("Server started: Listening on: " + localEndPoint.Address.ToString());
            xServerLog.ipAddress = localEndPoint.Address.ToString();
            xServerLog.port = port;

            // Create a TCP/IP socket.
            Socket myTCPserver = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                myTCPserver.Bind(localEndPoint);
                myTCPserver.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.
                    Console.WriteLine("Waiting for a connection...");

                    xServerLog.AddLine("Waiting for connections...");

                    myTCPserver.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        myTCPserver);

                    // Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            xServerLog.AddLine("I think things are done here...");

         //   Console.Read();

        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            allDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(
                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                content = state.sb.ToString();
                if (content.IndexOf("<EOF>") > -1)
                {
                    // All the data has been read from the
                    // client. Display it on the console.
                   // Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                    //    content.Length, content);

                    xServerLog.AddLine("RX:" + content);

                    // Echo the data back to the client.
                    Send(handler, "<OK>");
                }
                else
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
                }
            }
        }

        private static void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
        }

        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                //Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                xServerLog.AddLine("TX:OK"); // + bytesSent.ToString() + " bytes to client");

             //   handler.Shutdown(SocketShutdown.Both);
             //   handler.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        public void Start()
        {
            StartListening();
            //  return 0;
        }
</code>```

My Client Code:

```<code>  class xtcpClient
{

    // State object for receiving data from remote device.
    public class StateObject
    {
        // Client socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 256;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sb = new StringBuilder();
    }

    public class AsynchronousClient
    {
        //remote ip port
        //  private static string remoteServerIP = "0.0.0.1";

        private static IPAddress rIP;// = IPAddress.Parse(remoteServerIP);
        private static IPEndPoint remoteEP; // = new IPEndPoint(rIP, port);

        // Create a TCP/IP socket.
        private static Socket myTCPClient; // = new Socket(rIP.AddressFamily,SocketType.Stream, ProtocolType.Tcp);

        // The port number for the remote device.
        private static int port; // = 11000;

        // ManualResetEvent instances signal completion.
        private static ManualResetEvent connectDone =
            new ManualResetEvent(false);
        private static ManualResetEvent sendDone =
            new ManualResetEvent(false);
        private static ManualResetEvent receiveDone =
            new ManualResetEvent(false);

        // The response from the remote device.
        //  private static String response = String.Empty;

        private static string serverResponse = string.Empty;

        private static void _open_client()
        {

            remoteEP = new IPEndPoint(rIP, port);

            myTCPClient = new Socket(rIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            myTCPClient.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), myTCPClient);
            connectDone.WaitOne();
        }

        //////////private static void StartClient(IPAddress remoteIP, int remotePort)
        //////////{
        //////////    // Connect to a remote device.
        //////////    try
        //////////    {
        //////////        _open_client();
        //////////        //rIP = remoteIP;
        //////////        //port = remotePort;

        //////////        // Establish the remote endpoint for the socket.
        //////////        // The name of the
        //////////        // remote device is "host.contoso.com".
        //////////        //IPHostEntry ipHostInfo = Dns.GetHostEntry("host.contoso.com");
        //////////        //IPAddress ipAddress = ipHostInfo.AddressList[1];

        //////////        // Send test data to the remote device.
        //////////        //   string sendReply = "";

        //////////        //  sendReply = Send(myTCPClient, "echo 123<EOF>"); //send an initial test echo
        //////////        //   xClientLog.AddLine("Sent: Echo<EOF>");
        //////////        //  xClientLog.AddLine("Server Replied: " + sendReply);

        //////////        // Write the response to the console.
        //////////        //  Console.WriteLine("Response received : {0}", response);
        //////////        //  xClientLog.AddLine("Response received: " + response);

        //////////    }
        //////////    catch (Exception e)
        //////////    {
        //////////        Console.WriteLine(e.ToString());
        //////////    }
        //////////}

        public void _close_connection()
        {
            // Release the socket.
            myTCPClient.Shutdown(SocketShutdown.Both);
            myTCPClient.Close();
        }
        private static string Send(Socket client, String data)
        {

            if (client is null)
            {
                _open_client();
            }

            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client); //fire sendcallback when done sending...

            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(myTCPClient);
            receiveDone.WaitOne();

            return serverResponse; //return server response

        }
        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to server.", bytesSent);
                xClientLog.AddLine("Sent bytes to server: " + bytesSent);

                // Signal that all bytes have been sent.
                sendDone.Set(); //signal the send event to finish, it will start listening for a reply...
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                Console.WriteLine("Socket connected to {0}",
                    client.RemoteEndPoint.ToString());
                xClientLog.AddLine("Socket connected to: " + client.RemoteEndPoint.ToString());

                // Signal that the connection has been made.
                connectDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state); //fire receivcallback event when done receining
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    serverResponse = state.sb.ToString();
                    if (serverResponse.IndexOf("<OK>") > -1) {
                        // All the data has been read from the server
                        xClientLog.AddLine("RX:" + serverResponse);
                        receiveDone.Set();
                    }
                    else
                    {
                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                            new AsyncCallback(ReceiveCallback), state);
                    }

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        //public static int Main(String[] args)
        //{
        //    StartClient();
        //    return 0;
        //}
        public void startClient(string remoteIP, int remotePort)
        {
            try
            {
                rIP = IPAddress.Parse(remoteIP);
                port = remotePort;

                _open_client();
            }
            catch (Exception e)
            {

                System.Windows.MessageBox.Show(e.Message + Environment.NewLine + e.InnerException.Message);
            }

        }
        public string sendData(string DataToSend)
        {
            return (Send(myTCPClient, DataToSend));
        }
    }
}
</code>```

答:
Probably because each 'call to accept' on your server accepts a new client. If you want to keep accepting indefinitely you can try something like this to make sure there is always a 'call to accept' available for new clients:

```<code>while (true) {
var clientSocket = listeningSocket.Accept();
Task.Factory.StartNew(() => HandleClient(clientSocket));
}
</code>```

It's also possible that the client closes the connection. If the server shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete and return nothing.

Title: How to keep client and server talking

Body:
I am trying to build my own asynchronous client/server app using .net sockets.

Using these two examples, the basic functionality works.

Server

Client

This example sends a string to the server upon connection, and the server replies, echoing the string that it received, back to the client.

After this reply, the client then shuts down.

// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();

In my scenario, I am trying to connect to the server and then send data to the server from the client via input from the user. I reply back with <OK>.

In this example I linked above, the client always waits for a callback after sending (Hence my reply of <OK>).

I am not shutting down the client like in the example, as I want to send consecutive strings on demand. I need the server to keep listening and replying  to confirm receipt of string.

I am quite sure I am missing some core understanding of what should and should not happen.

Right now, I can send a string, the server replies  and the client receives this <ok>. I then try to send another string, but the server never "receives" this string. I guess the server is now also waiting for a callback after sending the  string, but If I return something to the server after receiving the  client side, the whole loop continues and repeats?

How do I make my server wait for more "new" data after replying ok?

Do I have to tell it to "listen" again for any new data? This seems like restarting the connection, which is not my intention...

I would appreciate some insight into what I am missing here...

(P.S. the server is wired with a callback event when sending. I left it like this as this was what the code example that I linked, implemented. DO I have to change my server send routines? (Not to wait for a callback)?

My Server Code:

          public static void StartListening()
        {
            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[1];

            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
            xServerLog.AddLine("Server started: Listening on: " + localEndPoint.Address.ToString());
            xServerLog.ipAddress = localEndPoint.Address.ToString();
            xServerLog.port = port;

            // Create a TCP/IP socket.
            Socket myTCPserver = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                myTCPserver.Bind(localEndPoint);
                myTCPserver.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.
                    Console.WriteLine("Waiting for a connection...");

                    xServerLog.AddLine("Waiting for connections...");

                    myTCPserver.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        myTCPserver);

                    // Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            xServerLog.AddLine("I think things are done here...");

         //   Console.Read();

        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            allDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(
                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                content = state.sb.ToString();
                if (content.IndexOf("<EOF>") > -1)
                {
                    // All the data has been read from the
                    // client. Display it on the console.
                   // Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                    //    content.Length, content);

                    xServerLog.AddLine("RX:" + content);

                    // Echo the data back to the client.
                    Send(handler, "<OK>");
                }
                else
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
                }
            }
        }

        private static void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
        }

        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                //Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                xServerLog.AddLine("TX:OK"); // + bytesSent.ToString() + " bytes to client");

             //   handler.Shutdown(SocketShutdown.Both);
             //   handler.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        public void Start()
        {
            StartListening();
            //  return 0;
        }

My Client Code:

  class xtcpClient
{

    // State object for receiving data from remote device.
    public class StateObject
    {
        // Client socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 256;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sb = new StringBuilder();
    }

    public class AsynchronousClient
    {
        //remote ip port
        //  private static string remoteServerIP = "0.0.0.1";

        private static IPAddress rIP;// = IPAddress.Parse(remoteServerIP);
        private static IPEndPoint remoteEP; // = new IPEndPoint(rIP, port);

        // Create a TCP/IP socket.
        private static Socket myTCPClient; // = new Socket(rIP.AddressFamily,SocketType.Stream, ProtocolType.Tcp);

        // The port number for the remote device.
        private static int port; // = 11000;

        // ManualResetEvent instances signal completion.
        private static ManualResetEvent connectDone =
            new ManualResetEvent(false);
        private static ManualResetEvent sendDone =
            new ManualResetEvent(false);
        private static ManualResetEvent receiveDone =
            new ManualResetEvent(false);

        // The response from the remote device.
        //  private static String response = String.Empty;

        private static string serverResponse = string.Empty;

        private static void _open_client()
        {

            remoteEP = new IPEndPoint(rIP, port);

            myTCPClient = new Socket(rIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            myTCPClient.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), myTCPClient);
            connectDone.WaitOne();
        }

        //////////private static void StartClient(IPAddress remoteIP, int remotePort)
        //////////{
        //////////    // Connect to a remote device.
        //////////    try
        //////////    {
        //////////        _open_client();
        //////////        //rIP = remoteIP;
        //////////        //port = remotePort;

        //////////        // Establish the remote endpoint for the socket.
        //////////        // The name of the
        //////////        // remote device is "host.contoso.com".
        //////////        //IPHostEntry ipHostInfo = Dns.GetHostEntry("host.contoso.com");
        //////////        //IPAddress ipAddress = ipHostInfo.AddressList[1];

        //////////        // Send test data to the remote device.
        //////////        //   string sendReply = "";

        //////////        //  sendReply = Send(myTCPClient, "echo 123<EOF>"); //send an initial test echo
        //////////        //   xClientLog.AddLine("Sent: Echo<EOF>");
        //////////        //  xClientLog.AddLine("Server Replied: " + sendReply);

        //////////        // Write the response to the console.
        //////////        //  Console.WriteLine("Response received : {0}", response);
        //////////        //  xClientLog.AddLine("Response received: " + response);

        //////////    }
        //////////    catch (Exception e)
        //////////    {
        //////////        Console.WriteLine(e.ToString());
        //////////    }
        //////////}

        public void _close_connection()
        {
            // Release the socket.
            myTCPClient.Shutdown(SocketShutdown.Both);
            myTCPClient.Close();
        }
        private static string Send(Socket client, String data)
        {

            if (client is null)
            {
                _open_client();
            }

            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client); //fire sendcallback when done sending...

            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(myTCPClient);
            receiveDone.WaitOne();

            return serverResponse; //return server response

        }
        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to server.", bytesSent);
                xClientLog.AddLine("Sent bytes to server: " + bytesSent);

                // Signal that all bytes have been sent.
                sendDone.Set(); //signal the send event to finish, it will start listening for a reply...
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                Console.WriteLine("Socket connected to {0}",
                    client.RemoteEndPoint.ToString());
                xClientLog.AddLine("Socket connected to: " + client.RemoteEndPoint.ToString());

                // Signal that the connection has been made.
                connectDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state); //fire receivcallback event when done receining
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    serverResponse = state.sb.ToString();
                    if (serverResponse.IndexOf("<OK>") > -1) {
                        // All the data has been read from the server
                        xClientLog.AddLine("RX:" + serverResponse);
                        receiveDone.Set();
                    }
                    else
                    {
                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                            new AsyncCallback(ReceiveCallback), state);
                    }

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        //public static int Main(String[] args)
        //{
        //    StartClient();
        //    return 0;
        //}
        public void startClient(string remoteIP, int remotePort)
        {
            try
            {
                rIP = IPAddress.Parse(remoteIP);
                port = remotePort;

                _open_client();
            }
            catch (Exception e)
            {

                System.Windows.MessageBox.Show(e.Message + Environment.NewLine + e.InnerException.Message);
            }

        }
        public string sendData(string DataToSend)
        {
            return (Send(myTCPClient, DataToSend));
        }
    }
}

Body:
Probably because each 'call to accept' on your server accepts a new client. If you want to keep accepting indefinitely you can try something like this to make sure there is always a 'call to accept' available for new clients:

while (true) {
var clientSocket = listeningSocket.Accept();
Task.Factory.StartNew(() => HandleClient(clientSocket));
}

It's also possible that the client closes the connection. If the server shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete and return nothing.