问:
creating new column by running a function with input from several datasets on each row
I want to aggregate som data, combining two datasets lsr and adherence (examples for reproducability):

```<code>adherence <- cbind.data.frame(c("1", "2", "3", "1", "2", "3"), c("2013.1", "2013.1", "2013.1", "2013.2", "2013.2", "2013.2"))
library(dplyr)
library(tidyr)
names(adherence)[1] <- "ID"
names(adherence)[2] <- "year"
adherence$year <- as.numeric(as.character(adherence$year))

lsr <- cbind.data.frame(
        c("1", "1", "1", "2", "2", "2", "3", "3"), #ID
        c("2012.3", "2012.8", "2013.1","2012.8", "2013.3", "2013.9", "2011", "2013"), #eksd
        c("60", "90", "90", "60", "120", "60", "30", "90") # DDD
        )
names(lsr)[1] <- "ID"
names(lsr)[2] <- "eksd"
names(lsr)[3] <- "DDD"

lsr$eksd <- as.numeric(as.character(lsr$eksd))
lsr$DDD <- as.numeric(as.character(lsr$DDD))
lsr$ENDDATE <- lsr$eksd + lsr$DDD/365.25
</code>```

So in the adherence dataset I want a new column, containing information from the lsr dataset depending on the ID variable and year variable of each row in the adherence dataset. I made this function that I thinks does just that:

```<code>function.DDAV <- function() {
        Y <- lsr %>% #dummy variable
          filter(., .$ID == adherence$ID) %>% #filters lsr by ID from relevant row in adherence dataset
          filter(., .$eksd <= adherence$year & adherence$year <= .$ENDDATE) # filters further to include relevant time period
          Y$DIFF <- (Y$ENDDATE - adherence$year)*365.25 # calculates relevant drug dosage available for implementation of dosis regimen at time = adhererence$year i.e. uses the time from adherence dataset and compares with time until dose runs out
          z <- sum(Y$DIFF) #sum available drugs doses
          return(z) # returns sum to be inputted in one row in new column in adherence dataset
      }
</code>```

and the I want to apply this once for every row in the adherence dataset, creating a new column using the relevant row values.

I tried using the apply family functions, and aggregate function. I've struggling with this for a few days, and I get different errors, that I haven't shown, because I think that I may be thinking about using the problem all wrong ? When searching for it I only find questions about applying over the entire row or column in one single dataset.

EDIT I show the ideal output below:
The ideal output looks like this:

adherence$adherence <- as.numeric(c("90","0","53.475","16.95","120","0"))

In essense the calculation is simple after filtering: if a row is included after filtering the values are calculated as this example from first row with adherence$ID = 1 and adherence$year = 2013.1. only the last row of ID=1 remains, the sum is (2013.1 (adherence$year)-2013.346 (lsr$ENDDATE))*365.25 = 90.

答:
OK. So the above solution took way way to much ressources to run on a large dataset, so I ended up with this solution:</p>

```<code>function.AH <- function(x) {
  A <- subset(lsr, ID == x[1] & eksd <= x[2] & ENDDATE > x[2])
  if (nrow(A) == 0) {
    0
  } else {
   sum(A$ENDDATE-as.numeric(x[2]))*365.25
  }
}

apply (adherence, 1,  FUN = function.AH)
</code>```

Body:
I want to aggregate som data, combining two datasets lsr and adherence (examples for reproducability):

adherence <- cbind.data.frame(c("1", "2", "3", "1", "2", "3"), c("2013.1", "2013.1", "2013.1", "2013.2", "2013.2", "2013.2"))
library(dplyr)
library(tidyr)
names(adherence)[1] <- "ID"
names(adherence)[2] <- "year"
adherence$year <- as.numeric(as.character(adherence$year))

lsr <- cbind.data.frame(
        c("1", "1", "1", "2", "2", "2", "3", "3"), #ID
        c("2012.3", "2012.8", "2013.1","2012.8", "2013.3", "2013.9", "2011", "2013"), #eksd
        c("60", "90", "90", "60", "120", "60", "30", "90") # DDD
        )
names(lsr)[1] <- "ID"
names(lsr)[2] <- "eksd"
names(lsr)[3] <- "DDD"

lsr$eksd <- as.numeric(as.character(lsr$eksd))
lsr$DDD <- as.numeric(as.character(lsr$DDD))
lsr$ENDDATE <- lsr$eksd + lsr$DDD/365.25

So in the adherence dataset I want a new column, containing information from the lsr dataset depending on the ID variable and year variable of each row in the adherence dataset. I made this function that I thinks does just that:

function.DDAV <- function() {
        Y <- lsr %>% #dummy variable
          filter(., .$ID == adherence$ID) %>% #filters lsr by ID from relevant row in adherence dataset
          filter(., .$eksd <= adherence$year & adherence$year <= .$ENDDATE) # filters further to include relevant time period
          Y$DIFF <- (Y$ENDDATE - adherence$year)*365.25 # calculates relevant drug dosage available for implementation of dosis regimen at time = adhererence$year i.e. uses the time from adherence dataset and compares with time until dose runs out
          z <- sum(Y$DIFF) #sum available drugs doses
          return(z) # returns sum to be inputted in one row in new column in adherence dataset
      }

and the I want to apply this once for every row in the adherence dataset, creating a new column using the relevant row values.

I tried using the apply family functions, and aggregate function. I've struggling with this for a few days, and I get different errors, that I haven't shown, because I think that I may be thinking about using the problem all wrong ? When searching for it I only find questions about applying over the entire row or column in one single dataset.

EDIT I show the ideal output below:
The ideal output looks like this:

adherence$adherence <- as.numeric(c("90","0","53.475","16.95","120","0"))

In essense the calculation is simple after filtering: if a row is included after filtering the values are calculated as this example from first row with adherence$ID = 1 and adherence$year = 2013.1. only the last row of ID=1 remains, the sum is (2013.1 (adherence$year)-2013.346 (lsr$ENDDATE))*365.25 = 90.

Body:
OK. So the above solution took way way to much ressources to run on a large dataset, so I ended up with this solution:

function.AH <- function(x) {
  A <- subset(lsr, ID == x[1] & eksd <= x[2] & ENDDATE > x[2])
  if (nrow(A) == 0) {
    0
  } else {
   sum(A$ENDDATE-as.numeric(x[2]))*365.25
  }
}

apply (adherence, 1,  FUN = function.AH)


来源: stackexchange

问:
Trying to regex for strings longer than 22 characters
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

```<code>$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
</code>```

And here is the regex that I have come up with so far, which doesn't seem to work at all

```<code>'[A-Za-z]{20,40}'
</code>```

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

答:
This will match "At least 22 any characters"</p>

```<code>.{22,}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');

And here is the regex that I have come up with so far, which doesn't seem to work at all

'[A-Za-z]{20,40}'

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

Body:
This will match "At least 22 any characters"

.{22,}


问:
Location of images for Xamarin Forms projects
I've a Xamarin Forms project - with the 3 projects for UWP, iOS and Android.
Now I want to use images in my Xamarin Pages. As intended by Xamarin I want to use the same code for all three targets ... e.g.:

```<code><Image Source="Assets/appIcon-256.png"/>
</code>```

This works for iOS and UWP - both have a folder "Assets" where I placed the image. Ok, I've to maintain the image twice, but I've the same XAML code for both project.

But for Android, that doesn't seems to work. The image is not displayed in Android, if I put the png in the Assets folder of the Anroid project.

What can I do to use the same location for all images for all the three projects?

答:
It's very easy.

IOS => You need put the images on "Resources" (note: no more routes) , for ANDROID => you need put the images on "Resources/drawable" .for UWP => put the images on root project UWP.

On Diferents platforms the images have diferents routes.

Then on the xaml files you can put <Image Source="imageName.jpg" />

Send feedback please.

UPDATE

You can put the images on UWP/Assets and then :

```<code><ToolbarItem
        Text="Search">
        <ToolbarItem.Icon>
            <OnPlatform x:TypeArguments="FileImageSource">
                <On Platform="Android, iOS" Value="movies-search.png"/>
                <On Platform="UWP" Value="Assets/movies-search.png"/>
            </OnPlatform>
        </ToolbarItem.Icon>
    </ToolbarItem>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've a Xamarin Forms project - with the 3 projects for UWP, iOS and Android.
Now I want to use images in my Xamarin Pages. As intended by Xamarin I want to use the same code for all three targets ... e.g.:

<Image Source="Assets/appIcon-256.png"/>

This works for iOS and UWP - both have a folder "Assets" where I placed the image. Ok, I've to maintain the image twice, but I've the same XAML code for both project.

But for Android, that doesn't seems to work. The image is not displayed in Android, if I put the png in the Assets folder of the Anroid project.

What can I do to use the same location for all images for all the three projects?

Body:
It's very easy.

IOS => You need put the images on "Resources" (note: no more routes) , for ANDROID => you need put the images on "Resources/drawable" .for UWP => put the images on root project UWP.

On Diferents platforms the images have diferents routes.

Then on the xaml files you can put <Image Source="imageName.jpg" />

Send feedback please.

UPDATE

You can put the images on UWP/Assets and then :

<ToolbarItem
        Text="Search">
        <ToolbarItem.Icon>
            <OnPlatform x:TypeArguments="FileImageSource">
                <On Platform="Android, iOS" Value="movies-search.png"/>
                <On Platform="UWP" Value="Assets/movies-search.png"/>
            </OnPlatform>
        </ToolbarItem.Icon>
    </ToolbarItem>


问:
how to write multiple vtkUnstructuredGrid in one .vtu file
I want to write multiple unstructured grids in one .vtu file.

I tried below. MakeHexagonalPrism() and MakeHexahedron() return vtkSmartPointer type.
The result is there was only one unstructured grid in the output file.

```<code>  vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
    vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
  writer->SetFileName(filename.c_str());
  writer->SetInputData(MakeHexagonalPrism());
  writer->SetInputData(MakeHexahedron());
  writer->Write();
</code>```

I also tried below. The type of cellArray1 and cellArray2  is vtkSmartPointer. The result is there was only one type of unstructured grid in the output file.

```<code>  vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid =
    vtkSmartPointer<vtkUnstructuredGrid>::New();
  unstructuredGrid->SetPoints(points);
  unstructuredGrid->SetCells(VTK_TETRA, cellArray1);
  unstructuredGrid->SetCells(VTK_WEDGE, cellArray2);
</code>```

I do not know how to write multiple unstructured grids in one .vtu file.
I'd be grateful for any hints.

答:
Quoting from the documentation for vtkXMLUnstructuredGridWriter available here

One unstructured grid input can be written into one file in any number
  of streamed pieces (if supported by the rest of the pipeline).

So I think it is not possible to write multiple unstructured grid datasets to one file using this writer class.

Do you want multiple types of cells inside the same unstructured grid (which can be written to a single .vtu file) rather than multiple unstructured grids in the same .vtu file? If yes, you must first combine the two cell arrays into a single cell array and also create a int array which contains type of each cell in the total cell array. For example,

```<code>// Create a Type vector to store cell types
std::vector<int> types;

// Create a new cell array composed of cellArray1 and cellArray2
vtkSmartPointer<vtkCellArray> allCells =
    vtkSmartPointer<vtkCellArray>::New();

// Traverse cellArray1 and add it's cells to allCells
vtkSmartPointer<vtkIdList> nextCell =
    vtkSmartPointer<vtkIdList>::New();
cellArray1->InitTraversal()
while( cellArray1->GetNextCell( nextCell ) ){
    allCells->InsertNextCell( nextCell );
    types.push_back( VTK_TETRA );
}
// Traverse cellArray2 and add it's cells to allCells
cellArray2->InitTraversal()
while( cellArray2->GetNextCell( nextCell ) ){
    allCells->InsertNextCell( nextCell );
    types.push_back( VTK_WEDGE );
}

//Finally, set allCells to unstructuredGrid
unstructuredGrid->SetCells( &(types[0]), allCells );
</code>```

Now when you write this unstructured grid to a .vtu file, I think you should have both wedge type and tetra type of cells in one file.

Body:
I want to write multiple unstructured grids in one .vtu file.

I tried below. MakeHexagonalPrism() and MakeHexahedron() return vtkSmartPointer type.
The result is there was only one unstructured grid in the output file.

  vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
    vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
  writer->SetFileName(filename.c_str());
  writer->SetInputData(MakeHexagonalPrism());
  writer->SetInputData(MakeHexahedron());
  writer->Write();

I also tried below. The type of cellArray1 and cellArray2  is vtkSmartPointer. The result is there was only one type of unstructured grid in the output file.

  vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid =
    vtkSmartPointer<vtkUnstructuredGrid>::New();
  unstructuredGrid->SetPoints(points);
  unstructuredGrid->SetCells(VTK_TETRA, cellArray1);
  unstructuredGrid->SetCells(VTK_WEDGE, cellArray2);

I do not know how to write multiple unstructured grids in one .vtu file.
I'd be grateful for any hints.

Body:
Quoting from the documentation for vtkXMLUnstructuredGridWriter available here

One unstructured grid input can be written into one file in any number
  of streamed pieces (if supported by the rest of the pipeline).

So I think it is not possible to write multiple unstructured grid datasets to one file using this writer class.

Do you want multiple types of cells inside the same unstructured grid (which can be written to a single .vtu file) rather than multiple unstructured grids in the same .vtu file? If yes, you must first combine the two cell arrays into a single cell array and also create a int array which contains type of each cell in the total cell array. For example,

// Create a Type vector to store cell types
std::vector<int> types;

// Create a new cell array composed of cellArray1 and cellArray2
vtkSmartPointer<vtkCellArray> allCells =
    vtkSmartPointer<vtkCellArray>::New();

// Traverse cellArray1 and add it's cells to allCells
vtkSmartPointer<vtkIdList> nextCell =
    vtkSmartPointer<vtkIdList>::New();
cellArray1->InitTraversal()
while( cellArray1->GetNextCell( nextCell ) ){
    allCells->InsertNextCell( nextCell );
    types.push_back( VTK_TETRA );
}
// Traverse cellArray2 and add it's cells to allCells
cellArray2->InitTraversal()
while( cellArray2->GetNextCell( nextCell ) ){
    allCells->InsertNextCell( nextCell );
    types.push_back( VTK_WEDGE );
}

//Finally, set allCells to unstructuredGrid
unstructuredGrid->SetCells( &(types[0]), allCells );

Now when you write this unstructured grid to a .vtu file, I think you should have both wedge type and tetra type of cells in one file.


问:
TextField loses focus to other window
Within a java-swing application, I have a textfield with some kind of help-popup.

I.e., when the user double clicks with the mouse within the textfield, this popup (implemented as an undecorated JFrame) is shown.

As soon as the textfield loses the focus, this popup is hidden again.

The problem is that showing this popup, the focus moves automatically to that frame, firing a lostFocus event on the textfield. This of course, closes the popup again.

I would like the lostFocus event to be triggered only if the textfield loses its focus to another component within the same window.

Any idea how to accomplish this?

答:
Check which object has received the focus and hide the window depending on it.

this is a rough example

```<code>public class MainFrame extends JFrame {

    private JWindow popupWindow;

    public MainFrame() throws HeadlessException {
        super("Main Frame");
        createGUI();
    }

    private void createGUI() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setPreferredSize(new Dimension(600, 400));

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

        JTextField hintTextField = new JTextField();

        popupWindow = new JWindow(this);
        popupWindow.getRootPane().setBorder(BorderFactory.createLineBorder(Color.RED));
        popupWindow.getRootPane().setLayout(new BorderLayout());
        popupWindow.getRootPane().add(hintTextField, BorderLayout.CENTER);

        for(int i = 0; i < 10; i++) {
            JTextField textField = new JTextField();
            textField.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if(e.getClickCount() == 2) {
                        Point point = textField.getLocationOnScreen();
                        popupWindow.setBounds(point.x, point.y + textField.getPreferredSize().height, 200, 200);
                        popupWindow.setVisible(true);
                    }
                }
            });

            textField.addFocusListener(new FocusAdapter() {
                @Override
                public void focusLost(FocusEvent e) {
                    if(e.getOppositeComponent() != hintTextField) {
                        popupWindow.setVisible(false);
                    }
                }
            });

            panel.add(textField);
        }

        add(panel, BorderLayout.PAGE_START);

        pack();
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
    }
}
</code>```

Title: TextField loses focus to other window

Body:
Check which object has received the focus and hide the window depending on it.

this is a rough example

public class MainFrame extends JFrame {

    private JWindow popupWindow;

    public MainFrame() throws HeadlessException {
        super("Main Frame");
        createGUI();
    }

    private void createGUI() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setPreferredSize(new Dimension(600, 400));

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

        JTextField hintTextField = new JTextField();

        popupWindow = new JWindow(this);
        popupWindow.getRootPane().setBorder(BorderFactory.createLineBorder(Color.RED));
        popupWindow.getRootPane().setLayout(new BorderLayout());
        popupWindow.getRootPane().add(hintTextField, BorderLayout.CENTER);

        for(int i = 0; i < 10; i++) {
            JTextField textField = new JTextField();
            textField.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if(e.getClickCount() == 2) {
                        Point point = textField.getLocationOnScreen();
                        popupWindow.setBounds(point.x, point.y + textField.getPreferredSize().height, 200, 200);
                        popupWindow.setVisible(true);
                    }
                }
            });

            textField.addFocusListener(new FocusAdapter() {
                @Override
                public void focusLost(FocusEvent e) {
                    if(e.getOppositeComponent() != hintTextField) {
                        popupWindow.setVisible(false);
                    }
                }
            });

            panel.add(textField);
        }

        add(panel, BorderLayout.PAGE_START);

        pack();
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
    }
}


问:
Web application becomes slow after executing stored procedure
I have a web application in which I am showing a report by executing a stored procedure. Execution takes too long time but after showing report that means after finishing execution of stored procedure, app becomes very slow. Just even if I navigate to some other page it takes quite a long time.

Is it possible after executing stored procedure, still something is going on behind. Still stored procedure is running or tables are locked or something like this. How to find out the reason.

My server is SQL server 2008R2.

答:
You might need to run few diagnostics , i would rather follow a stepwise approach

1) Check for any blocking processes

```<code>SELECT * FROM dbo.sysprocesses WHERE blocked <> 0;
SELECT * FROM dbo.sysprocesses WHERE spid IN (SELECT blocked FROM dbo.sysprocesses where blocked <> 0)
</code>```

2) Check for any slow running queries

```<code>SELECT r.session_id
    ,s.TEXT
    ,r.[status]
    ,r.blocking_session_id
    ,r.cpu_time
    ,r.total_elapsed_time
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s
</code>```

3) run cmd in windows and check for webservices status

```<code>   sc query <servicename>
</code>```

Body:
You might need to run few diagnostics , i would rather follow a stepwise approach

1) Check for any blocking processes

SELECT * FROM dbo.sysprocesses WHERE blocked <> 0;
SELECT * FROM dbo.sysprocesses WHERE spid IN (SELECT blocked FROM dbo.sysprocesses where blocked <> 0)

2) Check for any slow running queries

SELECT r.session_id
    ,s.TEXT
    ,r.[status]
    ,r.blocking_session_id
    ,r.cpu_time
    ,r.total_elapsed_time
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s

3) run cmd in windows and check for webservices status

   sc query <servicename>


问:
How to manage shutdown of ExecutorService when we allow to inject it?
Suppose I am writing a service, which needs some executor service/separate thread. I give ability to use factory method to not worry about executor service, but still want to allow passing existing executor service (dependency injection).

How can I manage for executorService.shutdown()?

Example code:

```<code>public class ThingsScheduler {

    private final ExecutorService executorService;

    public ThingsScheduler(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public static ThingsScheduler createDefaultSingleThreaded() {
        return new ThingsScheduler(Executors.newSingleThreadExecutor());
    }

    public scheduleThing() {
        executorService.submit(new SomeTask());
    }

    // implement Closeable?
    // @PreDestory?
    // .shutdown() + JavaDoc?
}
</code>```

There are several problems

We should have ability to shutdown internally created executor, or in best case handle it automatically (Spring @PreDestory, or in worst case finalize())

We shold rather not shutdown executor if it's externally managed (injected)

We could create some attribute stating if executor is created by our class or if it's injected, and then on finalize/@PreDestroy/shutdown hook we could shut down it, but it not feels elegant for me.

Maybe we should completely resign from factory method and always require injection pushing executor lifecycle management to the client?

答: More "elegant" solution would be to extend your ExecutorService and in it override shutdown method (whichever you choose). In case of injection, you would return that extended type and it would have it's own shutdown logic. In case of factory - you still have original logic.</p>

Body:
Suppose I am writing a service, which needs some executor service/separate thread. I give ability to use factory method to not worry about executor service, but still want to allow passing existing executor service (dependency injection).

How can I manage for executorService.shutdown()?

Example code:

public class ThingsScheduler {

    private final ExecutorService executorService;

    public ThingsScheduler(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public static ThingsScheduler createDefaultSingleThreaded() {
        return new ThingsScheduler(Executors.newSingleThreadExecutor());
    }

    public scheduleThing() {
        executorService.submit(new SomeTask());
    }

    // implement Closeable?
    // @PreDestory?
    // .shutdown() + JavaDoc?
}

There are several problems

We should have ability to shutdown internally created executor, or in best case handle it automatically (Spring @PreDestory, or in worst case finalize())

We shold rather not shutdown executor if it's externally managed (injected)

We could create some attribute stating if executor is created by our class or if it's injected, and then on finalize/@PreDestroy/shutdown hook we could shut down it, but it not feels elegant for me.

Maybe we should completely resign from factory method and always require injection pushing executor lifecycle management to the client?


问:
Vue model is not working and doesn't perform the function
This is my form file and it includes the VUE input-field, I want to only show that field only when I checked that option Manually set new password. That is the last field where the issue is present.

      var app = new Vue({
        el: '#app',
        data: {
          password_options: 'keep'
        }
        computed: {
          canShowThis() {
            return ['auto', 'manual'].includes(this.password_options)
          }
        }
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <script src="https://npmcdn.com/vue/dist/vue.js"></script>

    <div class="field">
        <label for="password" class="label">Password</label>
        <p class="control">
            <b-radio-group v-model="password_options">
                <div class="field">
                    <b-radio name="password_options" value="keep" selected>
                        Do Not Change Password
                    </b-radio>
                </div>
                <div class="field">
                    <b-radio name="password_options" value="auto">
                        Auto Generate New Password
                    </b-radio>
                </div>
                <div class="field">
                    <b-radio name="password_options" value="manual">
                        Manually Set New Password
                    </b-radio>
                    <p class="control">
                        <input type="text" class="input m-b-10 m-t-10" name="password" id="password"
                               v-if="canShowThis" placeholder="Manually give a password to this user">
                    </p>
                </div>
            </b-radio-group>
        </p>
    </div>

    <button class="button is-primary">
        <i class="fa fa-refresh m-r-10"></i>Update User
    </button>

 </code>```

答:
Maybe your problem lies here?

v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.

Or

If the initial value of your v-model expression does not match any of the options, the  element will render in an “unselected” state. On iOS this will cause the user not being able to select the first item because iOS does not fire a change event in this case. It is therefore recommended to provide a disabled option with an empty value.

So, if you initialized the 'password_options' to 'keep', also make this option as selected in you form:

  Do Not Change Password

```

<p>And give to the other options same <code>name</code> attribute:</p>

<pre class="lang-html prettyprint-override"><code><div class="field">
  <b-radio name="password_options" value="keep">Do Not Change Password</b-radio>
</div>
<div class="field">
  <b-radio name="password_options" value="auto">Auto Generate New Password</b-radio>
</div>
</code>```

Look for this demo:

new Vue({
  el: '#app',
  data: {
    option: 'val1'
  },
  computed: {
    canShowThis () {
      return ['val3', 'val4'].includes(this.option)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <input name="group" type="radio" v-model="option" value="val1" selected>
  <input name="group" type="radio" v-model="option" value="val2">
  <input name="group" type="radio" v-model="option" value="val3">
  <input name="group" type="radio" v-model="option" value="val4" v-if="canShowThis">
  <p>Selected option value: {{ option }}</p>
</div>

<script src="https://unpkg.com/vue"></script></code>```

  Password

          Do Not Change Password

          Auto Generate New Password

          Manually Set New Password

          <input
            type="text"
            class="input m-b-10 m-t-10"
            name="password"
            id="password"
            v-if="canShowThis"
            placeholder="Manually give a password to this user"
          >

<button class="button is-primary">
  Update User
</button>

```

ContentLicense: CC BY-SA 4.0

Body:
This is my form file and it includes the VUE input-field, I want to only show that field only when I checked that option Manually set new password. That is the last field where the issue is present.

      var app = new Vue({
        el: '#app',
        data: {
          password_options: 'keep'
        }
        computed: {
          canShowThis() {
            return ['auto', 'manual'].includes(this.password_options)
          }
        }
      });

        Password

                        Do Not Change Password

                        Auto Generate New Password

                        Manually Set New Password

                        <input type="text" class="input m-b-10 m-t-10" name="password" id="password"
                               v-if="canShowThis" placeholder="Manually give a password to this user">

    <button class="button is-primary">
        Update User
    </button>

Body:
Maybe your problem lies here?

v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.

Or

If the initial value of your v-model expression does not match any of the options, the  element will render in an “unselected” state. On iOS this will cause the user not being able to select the first item because iOS does not fire a change event in this case. It is therefore recommended to provide a disabled option with an empty value.

So, if you initialized the 'password_options' to 'keep', also make this option as selected in you form:

<div class="field">
  <b-radio value="keep" selected>Do Not Change Password</b-radio>
</div>

And give to the other options same name attribute:

<div class="field">
  <b-radio name="password_options" value="keep">Do Not Change Password</b-radio>
</div>
<div class="field">
  <b-radio name="password_options" value="auto">Auto Generate New Password</b-radio>
</div>

Look for this demo:

new Vue({
  el: '#app',
  data: {
    option: 'val1'
  },
  computed: {
    canShowThis () {
      return ['val3', 'val4'].includes(this.option)
    }
  }
})

<div id="app">
  <input name="group" type="radio" v-model="option" value="val1" selected>
  <input name="group" type="radio" v-model="option" value="val2">
  <input name="group" type="radio" v-model="option" value="val3">
  <input name="group" type="radio" v-model="option" value="val4" v-if="canShowThis">
  <p>Selected option value: {{ option }}</p>
</div>

<script src="https://unpkg.com/vue"></script>

<div class="field">
  <label for="password" class="label">Password</label>
  <p class="control">
    <b-radio-group>
      <div class="field">
        <b-radio name="password_options" value="keep" selected v-model="password_options">
          Do Not Change Password
        </b-radio>
      </div>
      <div class="field">
        <b-radio name="password_options" value="auto" v-model="password_options">
          Auto Generate New Password
        </b-radio>
      </div>
      <div class="field">
        <b-radio name="password_options" value="manual" v-model="password_options">
          Manually Set New Password
        </b-radio>
        <p class="control">
          <input
            type="text"
            class="input m-b-10 m-t-10"
            name="password"
            id="password"
            v-if="canShowThis"
            placeholder="Manually give a password to this user"
          >
        </p>
      </div>
    </b-radio-group>
  </p>
</div>

<button class="button is-primary">
  <i class="fa fa-refresh m-r-10"></i>Update User
</button>

<script>
  var app = new Vue({
    el: '#app',
    data: {
      password_options: 'keep'
    }
    computed: {
      canShowThis () {
        return this.password_options === 'manual'
      }
    }
  });
</script>


问:
Need a Regex to Parse This Line 58.21 -13.73 57 -1
Need help parsing the numbers from this line in Lua.

```<code>58.21 -13.73 57 -1
</code>```

I currently am at this: [1-9][0-9] which I know is not correct as it does not return the minus and does not handle the decimal.

Thanks,

Dave

答:
This is not a job for regex. Here is the simple implementation in python:

```<code>>>> s = '58.21 -13.73 57 -1'
>>> [float(i) for i in s.split()]
[58.21, -13.73, 57.0, -1.0]
</code>```

The principle however is universal: split on space and convert to numeric type if necessary.

Body:
Need help parsing the numbers from this line in Lua.

58.21 -13.73 57 -1

I currently am at this: [1-9][0-9] which I know is not correct as it does not return the minus and does not handle the decimal.

Thanks,

Dave

Body:
This is not a job for regex. Here is the simple implementation in python:

>>> s = '58.21 -13.73 57 -1'
>>> [float(i) for i in s.split()]
[58.21, -13.73, 57.0, -1.0]

The principle however is universal: split on space and convert to numeric type if necessary.


问:
Release project with previous release version of a snapshot dependency on Jenkins
I have seen some similar questions but didn't find any working solution. Now Its been a day finding to solve it.
So, below is the problem.

I have a project which I want to maven release through a Jenkins job. But this project has a snapshot dependency.

```<code><dependency>
    <groupId>com.domain</groupId>
    <artifactId>market</artifactId>
    <version>121b4-SNAPSHOT</version>
</dependency>
</code>```

Below is my project info:

```<code>    <groupId>com.domain.tools</groupId>
    <artifactId>cash</artifactId>
    <name>Cash Flow</name>
    <version>123b4-SNAPSHOT</version>
</code>```

When I try to release project manually with below commands:

```<code>mvn release:clean release:prepare release:perform
</code>```

I got a prompt for resolving dependency snapshot version, So then I just input the previous released version of 'market'  - 121b3 and then everything worked fine.

But when I try to set up a Jenkins job to release the project, the problem is that how can I resolve the snapshot dependency on Jenkins (as we get the prompt when doing manually), as maven release plugin doesn't allow the dependencies with snapshot version.

Can somebody tell me

Whether It is feasible in Jenkins to replace the snapshot versions with previous release versions of dependency ?

If possible, How can we do that?

Thanks in advance.

答:
You can not have any dependency with the word 'SNAPSHOT' in the version.

You will have to either

1) Release 123b4-SNAPSHOT so it is in the shared repository that Jenkins uses

2) Have an embedded repository (where you have a mini repository that is added to the project) and rename the 123b4-SNAPSHOT to 123b4, see here for an example

```<code> <repositories>
    <repository>
      <id>in-project</id>
      <name>In Project Repo</name>
      <url>file://${project.basedir}/libs2</url>
    </repository>
  </repositories>
</code>```

I recommend option 1.

Body:
I have seen some similar questions but didn't find any working solution. Now Its been a day finding to solve it.
So, below is the problem.

I have a project which I want to maven release through a Jenkins job. But this project has a snapshot dependency.

<dependency>
    <groupId>com.domain</groupId>
    <artifactId>market</artifactId>
    <version>121b4-SNAPSHOT</version>
</dependency>

Below is my project info:

    <groupId>com.domain.tools</groupId>
    <artifactId>cash</artifactId>
    <name>Cash Flow</name>
    <version>123b4-SNAPSHOT</version>

When I try to release project manually with below commands:

mvn release:clean release:prepare release:perform

I got a prompt for resolving dependency snapshot version, So then I just input the previous released version of 'market'  - 121b3 and then everything worked fine.

But when I try to set up a Jenkins job to release the project, the problem is that how can I resolve the snapshot dependency on Jenkins (as we get the prompt when doing manually), as maven release plugin doesn't allow the dependencies with snapshot version.

Can somebody tell me

Whether It is feasible in Jenkins to replace the snapshot versions with previous release versions of dependency ?

If possible, How can we do that?

Thanks in advance.

Body:
You can not have any dependency with the word 'SNAPSHOT' in the version.

You will have to either

1) Release 123b4-SNAPSHOT so it is in the shared repository that Jenkins uses

2) Have an embedded repository (where you have a mini repository that is added to the project) and rename the 123b4-SNAPSHOT to 123b4, see here for an example

 <repositories>
    <repository>
      <id>in-project</id>
      <name>In Project Repo</name>
      <url>file://${project.basedir}/libs2</url>
    </repository>
  </repositories>

I recommend option 1.


问:
Binding data to another window wpf
I'm trying to bind something to my wpf, which consists of 2 windows. I am able to bind the data to first window, but can't really put my mind into how it should be done in the second window:

MainWindow code:

```<code> public partial class MainWindow : Window
{
    private string repeatNumber;
    public MainWindow()
    {
        InitializeComponent();

        string[] assignments = new string[] { "https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png" };
        Random rnd = new Random();

        string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();

    List<Images> animals = new List<Images>();

        for (int i = 1; i < 100; i++)
        {
            if (i == 9)
            {
                repeatNumber = randomingArray[i % randomingArray.Length];
                animals.Add(new Images() { Source = repeatNumber, Number = i });
            }
            else if ((i % 9) == 0)
            {
                animals.Add(new Images() { Source = repeatNumber, Number = i });
            }
            else
            {
                animals.Add(new Images() { Source = randomingArray[i % rnd.Next(1,5)], Number = i });
            }
            ItemsControl1.ItemsSource = animals;
        }
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("test");
    }
    private void btn2_Click(object sender, RoutedEventArgs e)
    {
       Window1 window1 = new Window1();
       window1.Show();
        }
    }
}

class Images
{
    public int Number { get; set; }
    public string Source { get; set; }
}
</code>```

Mainwindow xaml:

```<code><Grid>
    <ListBox x:Name="ItemsControl1">

        <ListBox.ItemsPanel>

            <ItemsPanelTemplate>

                <UniformGrid Columns="5">
                </UniformGrid>

            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness="3" Width="Auto" Height="Auto">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Number}"/>
                        <Image Source="{Binding Source}" Margin="0,0,5,0"/>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>
    <Grid>
        <Button x:Name="btn1" Click="btn1_Click" Height="20" VerticalAlignment="Bottom" Margin="127,0,316,0" Content="Instruction"></Button>
        <Button x:Name="btn2" Click="btn2_Click" Height="20" VerticalAlignment="Bottom" Margin="300,0,109,0" Content="Results" Width="74"> </Button>

    </Grid>
</Grid>
</code>```

Window2 code right now is just:

```<code>    public class Window2 : Window
{
  //should return the value of repeatNumber
}
</code>```

xaml for windows2 right now i just:

```<code> <Grid>

</Grid>
</code>```

Im trying to get the value out of MainWindow repeatNumber. How am i able to achieve that?

答:
You can pass it as parameter to the constructur as shown below.

```<code>public class Window2 : Window
{
  public string RepeatNumber{get;set;}

  public Window2(string repeatNumber)
  {
    RepeatNumber = repeatNumber;
  }
}
</code>```

Also you can access it back in MainWindow

```<code>private void btn2_Click(object sender, RoutedEventArgs e)
{
       Window1 window1 = new Window1();
       window1.Show();
      string value =  window1.RepeatNumber; //Do what you want.
}
</code>```

Best approach (my opinion) is to use MVVM Pattern for dealing with problems like yours.

Title: Binding data to another window wpf

Body:
I'm trying to bind something to my wpf, which consists of 2 windows. I am able to bind the data to first window, but can't really put my mind into how it should be done in the second window:

MainWindow code:

 public partial class MainWindow : Window
{
    private string repeatNumber;
    public MainWindow()
    {
        InitializeComponent();

        string[] assignments = new string[] { "https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png" };
        Random rnd = new Random();

        string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();

    List<Images> animals = new List<Images>();

        for (int i = 1; i < 100; i++)
        {
            if (i == 9)
            {
                repeatNumber = randomingArray[i % randomingArray.Length];
                animals.Add(new Images() { Source = repeatNumber, Number = i });
            }
            else if ((i % 9) == 0)
            {
                animals.Add(new Images() { Source = repeatNumber, Number = i });
            }
            else
            {
                animals.Add(new Images() { Source = randomingArray[i % rnd.Next(1,5)], Number = i });
            }
            ItemsControl1.ItemsSource = animals;
        }
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("test");
    }
    private void btn2_Click(object sender, RoutedEventArgs e)
    {
       Window1 window1 = new Window1();
       window1.Show();
        }
    }
}

class Images
{
    public int Number { get; set; }
    public string Source { get; set; }
}

Mainwindow xaml:

<Grid>
    <ListBox x:Name="ItemsControl1">

        <ListBox.ItemsPanel>

            <ItemsPanelTemplate>

                <UniformGrid Columns="5">
                </UniformGrid>

            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness="3" Width="Auto" Height="Auto">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Number}"/>
                        <Image Source="{Binding Source}" Margin="0,0,5,0"/>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>
    <Grid>
        <Button x:Name="btn1" Click="btn1_Click" Height="20" VerticalAlignment="Bottom" Margin="127,0,316,0" Content="Instruction"></Button>
        <Button x:Name="btn2" Click="btn2_Click" Height="20" VerticalAlignment="Bottom" Margin="300,0,109,0" Content="Results" Width="74"> </Button>

    </Grid>
</Grid>

Window2 code right now is just:

    public class Window2 : Window
{
  //should return the value of repeatNumber
}

xaml for windows2 right now i just:

 <Grid>

</Grid>

Im trying to get the value out of MainWindow repeatNumber. How am i able to achieve that?

Body:
You can pass it as parameter to the constructur as shown below.

public class Window2 : Window
{
  public string RepeatNumber{get;set;}

  public Window2(string repeatNumber)
  {
    RepeatNumber = repeatNumber;
  }
}

Also you can access it back in MainWindow

private void btn2_Click(object sender, RoutedEventArgs e)
{
       Window1 window1 = new Window1();
       window1.Show();
      string value =  window1.RepeatNumber; //Do what you want.
}

Best approach (my opinion) is to use MVVM Pattern for dealing with problems like yours.


问:
Looping never happens while the condition is never being satisfied?

Thanks for 000 suggested ans, but im still a newbie, would like to know the concept behind this result.         Anyone can make explicit?

```<code>0hi
3hello
3world
</code>```

instead of

```<code>0hi
0hello
0world
</code>```

(assumption: num is never be ++ as the value is 0.)

```<code>application.args=hi hello world

public static void main (String[] args){
    int num;
    num=0;

    for (String s:args) {
        System.out.println(num+s);
        for(num=0;2>=num;num++);
    }

}
</code>```

答:
Try this code, As you want the output: 0hi 0hello 0world</p>

```<code>    int num = 0;
    for (String s : args) {
        //To get array of words data[0] = "hi", data[1] = "hello", data[2] = "world"
        String[] data = s.split(" ");
        //Loop through all words
        for (String element : data) {
            System.out.println(num + element);
        }
    }
</code>```

Body:
Thanks for 000 suggested ans, but im still a newbie, would like to know the concept behind this result.         Anyone can make explicit?

0hi
3hello
3world

instead of

0hi
0hello
0world

(assumption: num is never be ++ as the value is 0.)

application.args=hi hello world

public static void main (String[] args){
    int num;
    num=0;

    for (String s:args) {
        System.out.println(num+s);
        for(num=0;2>=num;num++);
    }

}

Body:
Try this code, As you want the output: 0hi 0hello 0world

    int num = 0;
    for (String s : args) {
        //To get array of words data[0] = "hi", data[1] = "hello", data[2] = "world"
        String[] data = s.split(" ");
        //Loop through all words
        for (String element : data) {
            System.out.println(num + element);
        }
    }


问:
How to know which header declare the specified function by Visual Studio?
Such I have such code

```<code>#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
    vector<int> values = { 5,3,4,6 };
    sort(values.begin(), values.end(), less<>());
    for_each(values.begin(), values.end(), [](int i) {cout << i <<endl; });
    return 0;
    }
</code>```

I want to know which header included by me(iostream, vector or algorithm) have declared the function less. Of course, we can use Google to search it. But I mean, I want to know this information just by Visual Studio . It is possible? I don't know how to do. And I can button the F12 to know less is in header xstddef, but I don't know which header(iostream, vector or algorithm) include xstddef still. Can anybody can tell me something?

ps: Actually I know the less in the header of <functional>. But note my code have not #include<functional>. But it also can run normally. I think must one of this three header include it already. But I don't know which it is

答: You can use the show includes flag to see which file included each of the included headers

Body:
Such I have such code

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
    vector<int> values = { 5,3,4,6 };
    sort(values.begin(), values.end(), less<>());
    for_each(values.begin(), values.end(), [](int i) {cout << i <<endl; });
    return 0;
    }

I want to know which header included by me(iostream, vector or algorithm) have declared the function less. Of course, we can use Google to search it. But I mean, I want to know this information just by Visual Studio . It is possible? I don't know how to do. And I can button the F12 to know less is in header xstddef, but I don't know which header(iostream, vector or algorithm) include xstddef still. Can anybody can tell me something?

ps: Actually I know the less in the header of <functional>. But note my code have not #include<functional>. But it also can run normally. I think must one of this three header include it already. But I don't know which it is


问:
How to pass traceIds in Hystrix Observables?
I have multiple services, some of which use Hystrix's HystrixObservableCommand to call other services and others use HystrixCommand. How do I pass on traceIds from the calling service to the Observables in HystrixObservableCommand and also have them be passed on if the fallback is called?

All services are using grpc-java.

Sample code that I have:

```<code>WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
        String messageFromWorldService = "";
        String idFromWorldService = "";
        try {

            Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
            messageFromWorldService = greeterReply.getMessage();
            idFromWorldService = greeterReply.getId();
            logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
        } catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
            logger.warn("Exception when calling WorldService\n" +  e);
        }
</code>```

WorldCommand.java

```<code>public class WorldCommand extends HystrixObservableCommand<Greeter.GreeterReply> {

    private static final Logger logger = LoggerFactory.getLogger(WorldCommand.class.getName());

    private final Greeter.GreeterRequest greeterRequest;
    private final WorldServiceGrpc.WorldServiceStub worldServiceStub;

    public WorldCommand(Greeter.GreeterRequest greeterRequest, WorldServiceGrpc.WorldServiceStub worldServiceStub) {
        super(HystrixCommandGroupKey.Factory.asKey("WorldService"));
        this.greeterRequest = greeterRequest;
        this.worldServiceStub = worldServiceStub;
    }

    @Override
    protected Observable<Greeter.GreeterReply> construct() {
        Context context = Context.current();
        return Observable.create(new Observable.OnSubscribe<Greeter.GreeterReply>() {
            @Override
            public void call(Subscriber<? super Greeter.GreeterReply> observer) {
                logger.info("In WorldCommand");
                if (!observer.isUnsubscribed()) {
                    //pass on the context, if you want only certain headers to pass on then create a new Context and attach it.
                    context.attach();
                    logger.info("In WorldCommand after attach");
                    worldServiceStub.greetWithHelloOrWorld(greeterRequest, new StreamObserver<Greeter.GreeterReply>() {
                        @Override
                        public void onNext(Greeter.GreeterReply greeterReply) {
                            logger.info("Response from WorldService  -- {}, id = {}", greeterReply.getMessage(), greeterReply.getId());
                            observer.onNext(greeterReply);
                            observer.onCompleted();
                        }

                        @Override
                        public void onError(Throwable t) {
                            logger.info("Exception from WorldService  -- {}", t);
                        }

                        @Override
                        public void onCompleted() {

                        }
                    });
                }
            }
        } ).subscribeOn(Schedulers.io());
    }

    @Override
    protected Observable<Greeter.GreeterReply> resumeWithFallback() {
        logger.info("Response from fallback");
        Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("teammate").setId("-1").build();
        return Observable.just(greeterReply);
    }
</code>```

I am using Zipkin grpc tracing and MDCCurrentTraceContext to print the traceId and spanId in the logs.

Both the log entries in the WorldCommand do not print out the trace and span ids, they are called on RxIoScheduler thread.

EDIT

Added ConcurrencyStrategy as suggested by Mike.

```<code>public class CustomHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {

    private static final Logger log = LoggerFactory.getLogger(CustomHystrixConcurrencyStrategy.class);

    public <T> Callable<T> wrapCallable(Callable<T> callable){
        log.info("In CustomHystrixConcurrencyStrategy: callable="+ callable.toString());
        return new ContextCallable<>(callable);
    }
}
</code>```

HelloService calls two services World and Team. The WorldCommand is a HystrixObservableCommand, the TeamCommand is a HystrixCommand.

```<code>logger.info("In the HelloService:greetWithHelloWorld");
Greeter.GreeterRequest greeterRequest = Greeter.GreeterRequest.newBuilder().setId(request.getId()).build();

//Call WorldService
ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
//Async stub instead of blockingStub
WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);

WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
String messageFromWorldService = "";
String idFromWorldService = "";
try {

    Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
    messageFromWorldService = greeterReply.getMessage();
    idFromWorldService = greeterReply.getId();
    logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling WorldService\n" +  e);
}

//Call TeamService
ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

String messageFromTeamService = "";
String idFromTeamService = "";
try {
    Greeter.GreeterReply greeterReply = teamCommand.construct().toBlocking().toFuture().get();
    messageFromTeamService = greeterReply.getMessage();
    idFromTeamService = greeterReply.getId();
    logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling TeamService\n" +  e);
}

assert(idFromWorldService.equals(idFromTeamService));
Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
responseObserver.onNext(greeterReply);
responseObserver.onCompleted();
</code>```

PreservableContext class

```<code>public class PreservableContexts {

    //private final TraceContext traceContext;
    private static final Logger logger = LoggerFactory.getLogger(PreservableContexts.class.getName());

    public PreservableContexts() {
        logger.info("Creating new PreservableContexts");
        //this.traceContext = TraceContextHolder.getContext();
    }

    public void set() {
       // if (traceContext != null) {
            //TraceContextHolder.setContext(traceContext);
       // }
    }

    public void clear() {
        //TraceContextHolder.clearContext();
    }
</code>```

The log in PreservableContexts and CustomHystrixConcurrencyStrategy never get printed. I am registering the startegy when I start the HelloServer.

```<code>HystrixConcurrencyStrategy strategy = new CustomHystrixConcurrencyStrategy();
        HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
        context = HystrixRequestContext.initializeContext();
</code>```

EDIT 2

Updated how the Observables are set up:

```<code>    ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
    //Async stub instead of blockingStub
    WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);
    WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);

    //Call TeamService
    ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
    TeamServiceGrpc.TeamServiceStub teamServiceStub = TeamServiceGrpc.newStub(teamChannel);
    //TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
    TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

    try {
        rx.Observable<Greeter.GreeterReply> worldReplyObservable = worldCommand.observe().subscribeOn(Schedulers.computation());
        rx.Observable<Greeter.GreeterReply> teamReplyObservable = teamCommand.observe().subscribeOn(Schedulers.computation());
        Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
            @Override
            public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                String messageFromWorldService = worldReply.getMessage();
                String idFromWorldService = worldReply.getId();
                logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);

                String messageFromTeamService = teamReply.getMessage();
                String idFromTeamService = teamReply.getId();
                logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);

                assert(idFromWorldService.equals(idFromTeamService));
                Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
                logger.info("Final response=" + greeterReply.getMessage());
                responseObserver.onNext(greeterReply);
                responseObserver.onCompleted();
                return null;
            }
        });
    } catch (StatusRuntimeException e) {
        logger.warn("Exception when calling WorldService and/or TeamService\n" +  e);
    }
</code>```

I have a weird problem now, the calls to TeamCommand and WorldCommand doesn't complete as in this code is never executed:

```<code>Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
                @Override
                public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                    String messageFromWorldService = worldReply.getMessage();
</code>```

Also, if there is a fallback, the hystrix-timer threads doesn't have the MDC anymore.

答:
You need to use ...

HystrixPlugins.getInstance().registerConcurrencyStrategy(...)

... to register a custom HystrixConcurrencyStrategy that uses your own Callable ...

```<code>public class ConcurrencyStrategy extends HystrixConcurrencyStrategy {
    @Override
    public <K> Callable<K> wrapCallable(Callable<K> c) {
        return new ContextCallable<>(c);
    }
}
</code>```

... that applies context preservation around the circuit ...

```<code>public class ContextCallable<K> implements Callable<K> {

    private final Callable<K> callable;
    private final PreservableContexts contexts;

    public ContextCallable(Callable<K> actual) {
        this.callable = actual;
        this.contexts = new PreservableContexts();
    }

    @Override
    public K call() throws Exception {
        contexts.set();
        try {
            return callable.call();
        } finally {
            contexts.clear();
        }
    }
}
</code>```

... via is a helper class capable of preserving the Zipkin context ...

```<code>public class PreservableContexts {

    private final TraceContext traceContext;

    public PreservableContexts() {
        this.traceContext = TraceContextHolder.getContext();
    }

    public void set() {
        if (traceContext != null) {
            TraceContextHolder.setContext(traceContext);
        }
    }

    public void clear() {
        TraceContextHolder.clearContext();
    }

}
</code>```

... and allowing an easy method of adding other contexts you may wish to preserve e.g. MDC, SecurityContext etc ...

Body:
I have multiple services, some of which use Hystrix's HystrixObservableCommand to call other services and others use HystrixCommand. How do I pass on traceIds from the calling service to the Observables in HystrixObservableCommand and also have them be passed on if the fallback is called?

All services are using grpc-java.

Sample code that I have:

WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
        String messageFromWorldService = "";
        String idFromWorldService = "";
        try {

            Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
            messageFromWorldService = greeterReply.getMessage();
            idFromWorldService = greeterReply.getId();
            logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
        } catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
            logger.warn("Exception when calling WorldService\n" +  e);
        }

WorldCommand.java

public class WorldCommand extends HystrixObservableCommand<Greeter.GreeterReply> {

    private static final Logger logger = LoggerFactory.getLogger(WorldCommand.class.getName());

    private final Greeter.GreeterRequest greeterRequest;
    private final WorldServiceGrpc.WorldServiceStub worldServiceStub;

    public WorldCommand(Greeter.GreeterRequest greeterRequest, WorldServiceGrpc.WorldServiceStub worldServiceStub) {
        super(HystrixCommandGroupKey.Factory.asKey("WorldService"));
        this.greeterRequest = greeterRequest;
        this.worldServiceStub = worldServiceStub;
    }

    @Override
    protected Observable<Greeter.GreeterReply> construct() {
        Context context = Context.current();
        return Observable.create(new Observable.OnSubscribe<Greeter.GreeterReply>() {
            @Override
            public void call(Subscriber<? super Greeter.GreeterReply> observer) {
                logger.info("In WorldCommand");
                if (!observer.isUnsubscribed()) {
                    //pass on the context, if you want only certain headers to pass on then create a new Context and attach it.
                    context.attach();
                    logger.info("In WorldCommand after attach");
                    worldServiceStub.greetWithHelloOrWorld(greeterRequest, new StreamObserver<Greeter.GreeterReply>() {
                        @Override
                        public void onNext(Greeter.GreeterReply greeterReply) {
                            logger.info("Response from WorldService  -- {}, id = {}", greeterReply.getMessage(), greeterReply.getId());
                            observer.onNext(greeterReply);
                            observer.onCompleted();
                        }

                        @Override
                        public void onError(Throwable t) {
                            logger.info("Exception from WorldService  -- {}", t);
                        }

                        @Override
                        public void onCompleted() {

                        }
                    });
                }
            }
        } ).subscribeOn(Schedulers.io());
    }

    @Override
    protected Observable<Greeter.GreeterReply> resumeWithFallback() {
        logger.info("Response from fallback");
        Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("teammate").setId("-1").build();
        return Observable.just(greeterReply);
    }

I am using Zipkin grpc tracing and MDCCurrentTraceContext to print the traceId and spanId in the logs.

Both the log entries in the WorldCommand do not print out the trace and span ids, they are called on RxIoScheduler thread.

EDIT

Added ConcurrencyStrategy as suggested by Mike.

public class CustomHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {

    private static final Logger log = LoggerFactory.getLogger(CustomHystrixConcurrencyStrategy.class);

    public <T> Callable<T> wrapCallable(Callable<T> callable){
        log.info("In CustomHystrixConcurrencyStrategy: callable="+ callable.toString());
        return new ContextCallable<>(callable);
    }
}

HelloService calls two services World and Team. The WorldCommand is a HystrixObservableCommand, the TeamCommand is a HystrixCommand.

logger.info("In the HelloService:greetWithHelloWorld");
Greeter.GreeterRequest greeterRequest = Greeter.GreeterRequest.newBuilder().setId(request.getId()).build();

//Call WorldService
ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
//Async stub instead of blockingStub
WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);

WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
String messageFromWorldService = "";
String idFromWorldService = "";
try {

    Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
    messageFromWorldService = greeterReply.getMessage();
    idFromWorldService = greeterReply.getId();
    logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling WorldService\n" +  e);
}

//Call TeamService
ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

String messageFromTeamService = "";
String idFromTeamService = "";
try {
    Greeter.GreeterReply greeterReply = teamCommand.construct().toBlocking().toFuture().get();
    messageFromTeamService = greeterReply.getMessage();
    idFromTeamService = greeterReply.getId();
    logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling TeamService\n" +  e);
}

assert(idFromWorldService.equals(idFromTeamService));
Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
responseObserver.onNext(greeterReply);
responseObserver.onCompleted();

PreservableContext class

public class PreservableContexts {

    //private final TraceContext traceContext;
    private static final Logger logger = LoggerFactory.getLogger(PreservableContexts.class.getName());

    public PreservableContexts() {
        logger.info("Creating new PreservableContexts");
        //this.traceContext = TraceContextHolder.getContext();
    }

    public void set() {
       // if (traceContext != null) {
            //TraceContextHolder.setContext(traceContext);
       // }
    }

    public void clear() {
        //TraceContextHolder.clearContext();
    }

The log in PreservableContexts and CustomHystrixConcurrencyStrategy never get printed. I am registering the startegy when I start the HelloServer.

HystrixConcurrencyStrategy strategy = new CustomHystrixConcurrencyStrategy();
        HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
        context = HystrixRequestContext.initializeContext();

EDIT 2

Updated how the Observables are set up:

    ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
    //Async stub instead of blockingStub
    WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);
    WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);

    //Call TeamService
    ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
    TeamServiceGrpc.TeamServiceStub teamServiceStub = TeamServiceGrpc.newStub(teamChannel);
    //TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
    TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

    try {
        rx.Observable<Greeter.GreeterReply> worldReplyObservable = worldCommand.observe().subscribeOn(Schedulers.computation());
        rx.Observable<Greeter.GreeterReply> teamReplyObservable = teamCommand.observe().subscribeOn(Schedulers.computation());
        Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
            @Override
            public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                String messageFromWorldService = worldReply.getMessage();
                String idFromWorldService = worldReply.getId();
                logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);

                String messageFromTeamService = teamReply.getMessage();
                String idFromTeamService = teamReply.getId();
                logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);

                assert(idFromWorldService.equals(idFromTeamService));
                Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
                logger.info("Final response=" + greeterReply.getMessage());
                responseObserver.onNext(greeterReply);
                responseObserver.onCompleted();
                return null;
            }
        });
    } catch (StatusRuntimeException e) {
        logger.warn("Exception when calling WorldService and/or TeamService\n" +  e);
    }

I have a weird problem now, the calls to TeamCommand and WorldCommand doesn't complete as in this code is never executed:

Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
                @Override
                public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                    String messageFromWorldService = worldReply.getMessage();

Also, if there is a fallback, the hystrix-timer threads doesn't have the MDC anymore.

Body:
You need to use ...

HystrixPlugins.getInstance().registerConcurrencyStrategy(...)

... to register a custom HystrixConcurrencyStrategy that uses your own Callable ...

public class ConcurrencyStrategy extends HystrixConcurrencyStrategy {
    @Override
    public <K> Callable<K> wrapCallable(Callable<K> c) {
        return new ContextCallable<>(c);
    }
}

... that applies context preservation around the circuit ...

public class ContextCallable<K> implements Callable<K> {

    private final Callable<K> callable;
    private final PreservableContexts contexts;

    public ContextCallable(Callable<K> actual) {
        this.callable = actual;
        this.contexts = new PreservableContexts();
    }

    @Override
    public K call() throws Exception {
        contexts.set();
        try {
            return callable.call();
        } finally {
            contexts.clear();
        }
    }
}

... via is a helper class capable of preserving the Zipkin context ...

public class PreservableContexts {

    private final TraceContext traceContext;

    public PreservableContexts() {
        this.traceContext = TraceContextHolder.getContext();
    }

    public void set() {
        if (traceContext != null) {
            TraceContextHolder.setContext(traceContext);
        }
    }

    public void clear() {
        TraceContextHolder.clearContext();
    }

}

... and allowing an easy method of adding other contexts you may wish to preserve e.g. MDC, SecurityContext etc ...


问:
How to Migrate from Plain Entities to Self-Tracking Entities?
I'm working in a project that uses .NET Entity Framework 4 with EntityObjects. Since we have found that we need to evolve into self-tracking entities for the remaining modules that haven't been implemented, I want to ask this:

1) Can we delete the existent plain entities and regenerate self-tracking entities from the database without modifying our currently written code using them?

2) If the answer of 1) is 'yes', is that easily done? How would you proceed to migrate from the first scheme to the second?

答: Change the namespces of your existing POCO classes to the one you expect EF will generate and so that your references will be updated.Then delete old POCO classes and generate EF classesThen compile your solution</p>


问:
How can I check the 410 status of an iframe?
I'm building a page that uses the Slideshare API to pull a limited set of presentations from a specific Slideshare user and output a series of iframes with those presentations embedded.

For the most part the page is working as intended, however one of the presentations that the API is calling was recently deleted, and therefore when the page loads that iframe the browser returns a 410. Unfortunately there is no object in the XML returned by Slideshare that can be used to determine if that particular presentation has been deleted.

Therefore I would like to check for the 410 error prior to adding that particular iframe to the page. What's making this difficult for me is that the error doesn't appear when making the API call, but rather when the embedded iframe loads, so I don't know where or how to make the appropriate check.

Here's the relevant code:

```<code>$.ajax({
url: slideShareURL,
dataType: 'XML',
success: function(data) {
    var allSlides = x2js.xml2json(data);
    allSlides = allSlides.User.Slideshow;
    for (i = 0; i < allSlides.length; i++) {
        document.getElementById('slides').innerHTML += allSlides[i].Embed;
    }
}
});
</code>```

Notes:

slideShareURL is defined earlier in the code using the API

I'm using xml2json.js to convert the XML received from the API to a json object

allSlides is an array of presentations each containing a set of objects such as slide title, id, download URL, etc

Embed is the object that contains the full iframe embed code

EDIT: Answer provided by Christophe below was almost perfect, but I had to add a closure to make the second ajax call work within the for loop.

答:
The answer provided by Christophe put me on the right track, but it wasn't possible to run the second ajax call properly within the for loop. After some more research I learned about closures, and came up with the following:</p>

```<code>$.ajax({
    url: slideShareURL,
    dataType: 'XML',
    success: function(data) {
        var allSlides = x2js.xml2json(data);
        allSlides = allSlides.User.Slideshow;

        for (i = 0; i < allSlides.length; i++) {

        (function(i) {
                var slideURL = allSlides[i].SlideshowEmbedUrl;
                $.ajax({
                    url: slideURL,
                    success: function () {
                        document.getElementById('slides').innerHTML += allSlides[i].Embed;
                    },
                    error: function () {
                        console.log('Failed to load');
                    }
                })
            })(i);
        }
    }
});
</code>```

Body:
I'm building a page that uses the Slideshare API to pull a limited set of presentations from a specific Slideshare user and output a series of iframes with those presentations embedded.

For the most part the page is working as intended, however one of the presentations that the API is calling was recently deleted, and therefore when the page loads that iframe the browser returns a 410. Unfortunately there is no object in the XML returned by Slideshare that can be used to determine if that particular presentation has been deleted.

Therefore I would like to check for the 410 error prior to adding that particular iframe to the page. What's making this difficult for me is that the error doesn't appear when making the API call, but rather when the embedded iframe loads, so I don't know where or how to make the appropriate check.

Here's the relevant code:

$.ajax({
url: slideShareURL,
dataType: 'XML',
success: function(data) {
    var allSlides = x2js.xml2json(data);
    allSlides = allSlides.User.Slideshow;
    for (i = 0; i < allSlides.length; i++) {
        document.getElementById('slides').innerHTML += allSlides[i].Embed;
    }
}
});

Notes:

slideShareURL is defined earlier in the code using the API

I'm using xml2json.js to convert the XML received from the API to a json object

allSlides is an array of presentations each containing a set of objects such as slide title, id, download URL, etc

Embed is the object that contains the full iframe embed code

EDIT: Answer provided by Christophe below was almost perfect, but I had to add a closure to make the second ajax call work within the for loop.

Body:
The answer provided by Christophe put me on the right track, but it wasn't possible to run the second ajax call properly within the for loop. After some more research I learned about closures, and came up with the following:

$.ajax({
    url: slideShareURL,
    dataType: 'XML',
    success: function(data) {
        var allSlides = x2js.xml2json(data);
        allSlides = allSlides.User.Slideshow;

        for (i = 0; i < allSlides.length; i++) {

        (function(i) {
                var slideURL = allSlides[i].SlideshowEmbedUrl;
                $.ajax({
                    url: slideURL,
                    success: function () {
                        document.getElementById('slides').innerHTML += allSlides[i].Embed;
                    },
                    error: function () {
                        console.log('Failed to load');
                    }
                })
            })(i);
        }
    }
});


问:
PostgreSQL add EXCLUDE constraint on alter table
I'm trying to add an EXCLUDE constraint to one of my existing tables this is the sql I'm running:

```<code>ALTER TABLE appointment_service
  ADD COLUMN start_time bigint,
  ADD COLUMN end_time bigint,
  EXCLUDE USING gist (
            professional_id WITH =,
            int8range(start_time, end_time) WITH &&
  ),
  ADD COLUMN professional_id text REFERENCES professionals ON DELETE CASCADE ON UPDATE CASCADE
</code>```

And this is the error I get.

```<code>ERROR:  syntax error at or near "EXCLUDE"
LINE 4:   EXCLUDE USING gist (
</code>```

What is the correct SQL syntax to accomplish this?

答:
You need to add the exclusion constraint separately.

First add the columns:

```<code>ALTER TABLE appointment_service
  ADD COLUMN start_time bigint,
  ADD COLUMN end_time bigint,
  ADD COLUMN professional_id text
     REFERENCES professionals ON DELETE CASCADE ON UPDATE CASCADE;
</code>```

Then add the constraint:

```<code>ALTER TABLE appointment_service
  add constraint unique_professional_id
  EXCLUDE USING gist (
            professional_id WITH =,
            int8range(start_time, end_time) WITH &&
  )
</code>```

Body:
I'm trying to add an EXCLUDE constraint to one of my existing tables this is the sql I'm running:

ALTER TABLE appointment_service
  ADD COLUMN start_time bigint,
  ADD COLUMN end_time bigint,
  EXCLUDE USING gist (
            professional_id WITH =,
            int8range(start_time, end_time) WITH &&
  ),
  ADD COLUMN professional_id text REFERENCES professionals ON DELETE CASCADE ON UPDATE CASCADE

And this is the error I get.

ERROR:  syntax error at or near "EXCLUDE"
LINE 4:   EXCLUDE USING gist (

What is the correct SQL syntax to accomplish this?

Body:
You need to add the exclusion constraint separately.

First add the columns:

ALTER TABLE appointment_service
  ADD COLUMN start_time bigint,
  ADD COLUMN end_time bigint,
  ADD COLUMN professional_id text
     REFERENCES professionals ON DELETE CASCADE ON UPDATE CASCADE;

Then add the constraint:

ALTER TABLE appointment_service
  add constraint unique_professional_id
  EXCLUDE USING gist (
            professional_id WITH =,
            int8range(start_time, end_time) WITH &&
  )