问:
Repeat rows in a pandas DataFrame based on column value
I have the following df:

```<code>code . role    . persons
123 .  Janitor . 3
123 .  Analyst . 2
321 .  Vallet  . 2
321 .  Auditor . 5
</code>```

The first line means that I have 3 persons with the role Janitors.
My problem is that I would need to have one line for each person. My df should look like this:

```<code>df:

code . role    . persons
123 .  Janitor . 3
123 .  Janitor . 3
123 .  Janitor . 3
123 .  Analyst . 2
123 .  Analyst . 2
321 .  Vallet  . 2
321 .  Vallet  . 2
321 .  Auditor . 5
321 .  Auditor . 5
321 .  Auditor . 5
321 .  Auditor . 5
321 .  Auditor . 5
</code>```

How could I do that using pandas?

答:
reindex+ repeat

```<code>df.reindex(df.index.repeat(df.persons))
Out[951]:
   code  .     role ..1  persons
0   123  .  Janitor   .        3
0   123  .  Janitor   .        3
0   123  .  Janitor   .        3
1   123  .  Analyst   .        2
1   123  .  Analyst   .        2
2   321  .   Vallet   .        2
2   321  .   Vallet   .        2
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5
</code>```

PS: you can add.reset_index(drop=True) to get the new index

Body:
I have the following df:

code . role    . persons
123 .  Janitor . 3
123 .  Analyst . 2
321 .  Vallet  . 2
321 .  Auditor . 5

The first line means that I have 3 persons with the role Janitors.
My problem is that I would need to have one line for each person. My df should look like this:

df:

code . role    . persons
123 .  Janitor . 3
123 .  Janitor . 3
123 .  Janitor . 3
123 .  Analyst . 2
123 .  Analyst . 2
321 .  Vallet  . 2
321 .  Vallet  . 2
321 .  Auditor . 5
321 .  Auditor . 5
321 .  Auditor . 5
321 .  Auditor . 5
321 .  Auditor . 5

How could I do that using pandas?

Body:
reindex+ repeat

df.reindex(df.index.repeat(df.persons))
Out[951]:
   code  .     role ..1  persons
0   123  .  Janitor   .        3
0   123  .  Janitor   .        3
0   123  .  Janitor   .        3
1   123  .  Analyst   .        2
1   123  .  Analyst   .        2
2   321  .   Vallet   .        2
2   321  .   Vallet   .        2
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5
3   321  .  Auditor   .        5

PS: you can add.reset_index(drop=True) to get the new index


来源: stackexchange

问:
Angular $compile ui-grid for jasmine tests without $scope
I am trying to do use $compile to compile a ui-grid for Jasmine testing. It worked fine when I used $scope as a passable parameter to the controller. however, I am migrating away to vm. This has caused $compile to fail when compiling the ui-grid.

```<code>var rootScope = $rootScope;
var controller = $controller('Controller', {stuff: stuff, other: other});
$compile('<div ui-grid="vm.grids.grid1" ui-grid-selection ui-grid-auto-resize></div>')(rootScope);
rootScope.$apply();
</code>```

Doing it this way gives me an error of cannot read property 'data' of undefined. when ui-grid javascript is being stepped through.

I have also tried passing the controller to $compile, using controller.grids.grid1 instead, and rootScope.$digest() instead of $apply().

Is there something I am missing, or am I going about this incorrectly?

答:
Okay, so I found the answer to my question.

This answer on a different question helped me get the answer.

```<code>var rootScope = $rootScope;
var controller = $controller(/**controller stuff**/);
rootScope.vm = controller;
$compile('html to compile')(rootScope);
rootScope.$apply();
</code>```

With this, I was able to get things to compile without using $scope.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to do use $compile to compile a ui-grid for Jasmine testing. It worked fine when I used $scope as a passable parameter to the controller. however, I am migrating away to vm. This has caused $compile to fail when compiling the ui-grid.

var rootScope = $rootScope;
var controller = $controller('Controller', {stuff: stuff, other: other});
$compile('

')(rootScope);
rootScope.$apply();

Doing it this way gives me an error of cannot read property 'data' of undefined. when ui-grid javascript is being stepped through.

I have also tried passing the controller to $compile, using controller.grids.grid1 instead, and rootScope.$digest() instead of $apply().

Is there something I am missing, or am I going about this incorrectly?

Body:
Okay, so I found the answer to my question.

This answer on a different question helped me get the answer.

var rootScope = $rootScope;
var controller = $controller(/**controller stuff**/);
rootScope.vm = controller;
$compile('html to compile')(rootScope);
rootScope.$apply();

With this, I was able to get things to compile without using $scope.


问:
Simulated Shift+Right key does not always work on Windows
I have the following code written in Delphi 10.1 Berlin, that tries to simulate a Shift+Right Arrow key on Windows in order to select text in a memo. This is a Delphi Firemonkey project, but that should not matter for my problem. The problem is that this code does what it is supposed to do on some Windows machines (selects text letter by letter), but it fails on others (only moves cursor pos, as if shift key is ignored). The failing of the code appears not to be specific to a Windows version, as it works on win 8.1 as well as on some Win 10 Fall Creatores Updates, but fails on some Win 10 Fall Creators installations. It seems also not specific to the SendInput mehtod, as the same phenomenon shows up using keybd_event.
Anybody any ideas ?</p>

```<code> unit Unit63;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
  FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo;

type
  TForm63 = class(TForm)
    mmo1: TMemo;
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form63: TForm63;

implementation

uses windows;

{$R *.fmx}

procedure SendShiftRight;
var
  KeyInputs: array of TInput;
  KeyInputCount: Integer;

  procedure KeybdInput(VKey: Byte; Flags: DWORD);
  begin
    Inc(KeyInputCount);
    SetLength(KeyInputs, KeyInputCount);
    KeyInputs[KeyInputCount - 1].Itype := INPUT_KEYBOARD;
    with  KeyInputs[KeyInputCount - 1].ki do
    begin
      wVk := VKey;
      wScan := MapVirtualKey(wVk, 0);
      dwFlags := Flags;
      time := 0;
      dwExtraInfo := 0;
    end;
  end;
begin
  KeyInputCount := 0;
  KeybdInput(VK_SHIFT, 0);                // Shift
  KeybdInput(VK_RIGHT, 0);                 // Right
  KeybdInput(VK_RIGHT, KEYEVENTF_KEYUP);   // Right
  KeybdInput(VK_SHIFT, KEYEVENTF_KEYUP); // Shift
  SendInput(KeyInputCount, KeyInputs[0], SizeOf(KeyInputs[0]));
end;

procedure PostKeyEx32(key: Word; const shift: TShiftState; specialkey: Boolean);
{************************************************************
* Procedure PostKeyEx32
*
* Parameters:
*  key    : virtual keycode of the key to send. For printable
*           keys this is simply the ANSI code (Ord(character)).
*  shift  : state of the modifier keys. This is a set, so you
*           can set several of these keys (shift, control, alt,
*           mouse buttons) in tandem. The TShiftState type is
*           declared in the Classes Unit.
*  specialkey: normally this should be False. Set it to True to
*           specify a key on the numeric keypad, for example.
* Description:
*  Uses keybd_event to manufacture a series of key events matching
*  the passed parameters. The events go to the control with focus.
*  Note that for characters key is always the upper-case version of
*  the character. Sending without any modifier keys will result in
*  a lower-case character, sending it with [ssShift] will result
*  in an upper-case character!
// Code by P. Below
************************************************************}
type
  TShiftKeyInfo = record
    shift: Byte;
    vkey: Byte;
  end;
  byteset = set of 0..7;
const
  shiftkeys: array [1..3] of TShiftKeyInfo =
    ((shift: Ord(ssCtrl); vkey: VK_CONTROL),
    (shift: Ord(ssShift); vkey: VK_SHIFT),
    (shift: Ord(ssAlt); vkey: VK_MENU));
var
  flag: DWORD;
  bShift: ByteSet absolute shift;
  i: Integer;
begin
  for i := 1 to 3 do
  begin
    if shiftkeys[i].shift in bShift then
      keybd_event(shiftkeys[i].vkey, MapVirtualKey(shiftkeys[i].vkey, 0), 0, 0);
  end; { For }
  if specialkey then
    flag := KEYEVENTF_EXTENDEDKEY
  else
    flag := 0;

  keybd_event(key, MapvirtualKey(key, 0), flag, 0);
  flag := flag or KEYEVENTF_KEYUP;
  keybd_event(key, MapvirtualKey(key, 0), flag, 0);

  for i := 3 downto 1 do
  begin
    if shiftkeys[i].shift in bShift then
      keybd_event(shiftkeys[i].vkey, MapVirtualKey(shiftkeys[i].vkey, 0),
        KEYEVENTF_KEYUP, 0);
  end; { For }
end; { PostKeyEx32 }

procedure TForm63.btn1Click(Sender: TObject);
begin
  mmo1.SetFocus;
  SendShiftRight;
  // PostKeyEx32(vkRight, [ssShift], False);    // doesn't work either
end;

end.
</code>```

答:
Turns out that SendInput still requires KEYEVENTF_EXTENDEDKEY for Extended Keys. Yet MapVirtualKey cannot be relied on to return the Extended Key Value (224) starting with Vista.

Modify your code to use ExtendedKeyFlag:

```<code>begin
  KeyInputCount := 0;
  KeybdInput(VK_SHIFT, ExtendedKeyFlag(VK_SHIFT));                   // Shift
  KeybdInput(VK_RIGHT, ExtendedKeyFlag(VK_RIGHT));                   // Right
  KeybdInput(VK_RIGHT, ExtendedKeyFlag(VK_RIGHT) or KEYEVENTF_KEYUP);// Right
  KeybdInput(VK_SHIFT, ExtendedKeyFlag(VK_SHIFT) or KEYEVENTF_KEYUP);// Shift
  SendInput(KeyInputCount, KeyInputs[0], SizeOf(KeyInputs[0]));
end;
</code>```

ExtendedKeyFlag bypasses MapVirtualKey and maps the Extended Keys:

```<code>/// <summary>
///   Returns KEYEVENTF_EXTENDEDKEY if part of ExtendedKeys
/// </summary>
/// <remarks>
///   No API exists to properly return the Extended Keys in Vista+
///   <note type="warning">
///     Do NOT trust in MapVirtualKeyEx(MAPVK_VK_TO_VSC_EX) (>= Vista) because it does not return the extended flag for some keys although they are extended keys
///   </note>
/// </remarks>
/// <seealso href="http://letcoderock.blogspot.ca/2011/10/sendinput-with-shift-key-not-work.html">
///   SendInput with SHIFT key does not work!?
/// </seealso>
/// <seealso href="https://stackoverflow.com/questions/21197257/keybd-event-keyeventf-extendedkey-explanation-required#21202784">
///   keybd_event KEYEVENTF_EXTENDEDKEY explanation required
/// </seealso>
function ExtendedKeyFlag(const VKey : Word): Cardinal;
begin
  If (VKey in [VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_HOME, VK_END, VK_PRIOR, VK_NEXT, VK_INSERT, VK_DELETE]) then Result := KEYEVENTF_EXTENDEDKEY
  else Result := 0;
end;
</code>```

Body:
I have the following code written in Delphi 10.1 Berlin, that tries to simulate a Shift+Right Arrow key on Windows in order to select text in a memo. This is a Delphi Firemonkey project, but that should not matter for my problem. The problem is that this code does what it is supposed to do on some Windows machines (selects text letter by letter), but it fails on others (only moves cursor pos, as if shift key is ignored). The failing of the code appears not to be specific to a Windows version, as it works on win 8.1 as well as on some Win 10 Fall Creatores Updates, but fails on some Win 10 Fall Creators installations. It seems also not specific to the SendInput mehtod, as the same phenomenon shows up using keybd_event.
Anybody any ideas ?

 unit Unit63;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
  FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo;

type
  TForm63 = class(TForm)
    mmo1: TMemo;
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form63: TForm63;

implementation

uses windows;

{$R *.fmx}

procedure SendShiftRight;
var
  KeyInputs: array of TInput;
  KeyInputCount: Integer;

  procedure KeybdInput(VKey: Byte; Flags: DWORD);
  begin
    Inc(KeyInputCount);
    SetLength(KeyInputs, KeyInputCount);
    KeyInputs[KeyInputCount - 1].Itype := INPUT_KEYBOARD;
    with  KeyInputs[KeyInputCount - 1].ki do
    begin
      wVk := VKey;
      wScan := MapVirtualKey(wVk, 0);
      dwFlags := Flags;
      time := 0;
      dwExtraInfo := 0;
    end;
  end;
begin
  KeyInputCount := 0;
  KeybdInput(VK_SHIFT, 0);                // Shift
  KeybdInput(VK_RIGHT, 0);                 // Right
  KeybdInput(VK_RIGHT, KEYEVENTF_KEYUP);   // Right
  KeybdInput(VK_SHIFT, KEYEVENTF_KEYUP); // Shift
  SendInput(KeyInputCount, KeyInputs[0], SizeOf(KeyInputs[0]));
end;

procedure PostKeyEx32(key: Word; const shift: TShiftState; specialkey: Boolean);
{************************************************************
* Procedure PostKeyEx32
*
* Parameters:
*  key    : virtual keycode of the key to send. For printable
*           keys this is simply the ANSI code (Ord(character)).
*  shift  : state of the modifier keys. This is a set, so you
*           can set several of these keys (shift, control, alt,
*           mouse buttons) in tandem. The TShiftState type is
*           declared in the Classes Unit.
*  specialkey: normally this should be False. Set it to True to
*           specify a key on the numeric keypad, for example.
* Description:
*  Uses keybd_event to manufacture a series of key events matching
*  the passed parameters. The events go to the control with focus.
*  Note that for characters key is always the upper-case version of
*  the character. Sending without any modifier keys will result in
*  a lower-case character, sending it with [ssShift] will result
*  in an upper-case character!
// Code by P. Below
************************************************************}
type
  TShiftKeyInfo = record
    shift: Byte;
    vkey: Byte;
  end;
  byteset = set of 0..7;
const
  shiftkeys: array [1..3] of TShiftKeyInfo =
    ((shift: Ord(ssCtrl); vkey: VK_CONTROL),
    (shift: Ord(ssShift); vkey: VK_SHIFT),
    (shift: Ord(ssAlt); vkey: VK_MENU));
var
  flag: DWORD;
  bShift: ByteSet absolute shift;
  i: Integer;
begin
  for i := 1 to 3 do
  begin
    if shiftkeys[i].shift in bShift then
      keybd_event(shiftkeys[i].vkey, MapVirtualKey(shiftkeys[i].vkey, 0), 0, 0);
  end; { For }
  if specialkey then
    flag := KEYEVENTF_EXTENDEDKEY
  else
    flag := 0;

  keybd_event(key, MapvirtualKey(key, 0), flag, 0);
  flag := flag or KEYEVENTF_KEYUP;
  keybd_event(key, MapvirtualKey(key, 0), flag, 0);

  for i := 3 downto 1 do
  begin
    if shiftkeys[i].shift in bShift then
      keybd_event(shiftkeys[i].vkey, MapVirtualKey(shiftkeys[i].vkey, 0),
        KEYEVENTF_KEYUP, 0);
  end; { For }
end; { PostKeyEx32 }

procedure TForm63.btn1Click(Sender: TObject);
begin
  mmo1.SetFocus;
  SendShiftRight;
  // PostKeyEx32(vkRight, [ssShift], False);    // doesn't work either
end;

end.

Body:
Turns out that SendInput still requires KEYEVENTF_EXTENDEDKEY for Extended Keys. Yet MapVirtualKey cannot be relied on to return the Extended Key Value (224) starting with Vista.

Modify your code to use ExtendedKeyFlag:

begin
  KeyInputCount := 0;
  KeybdInput(VK_SHIFT, ExtendedKeyFlag(VK_SHIFT));                   // Shift
  KeybdInput(VK_RIGHT, ExtendedKeyFlag(VK_RIGHT));                   // Right
  KeybdInput(VK_RIGHT, ExtendedKeyFlag(VK_RIGHT) or KEYEVENTF_KEYUP);// Right
  KeybdInput(VK_SHIFT, ExtendedKeyFlag(VK_SHIFT) or KEYEVENTF_KEYUP);// Shift
  SendInput(KeyInputCount, KeyInputs[0], SizeOf(KeyInputs[0]));
end;

ExtendedKeyFlag bypasses MapVirtualKey and maps the Extended Keys:

/// <summary>
///   Returns KEYEVENTF_EXTENDEDKEY if part of ExtendedKeys
/// </summary>
/// <remarks>
///   No API exists to properly return the Extended Keys in Vista+
///   <note type="warning">
///     Do NOT trust in MapVirtualKeyEx(MAPVK_VK_TO_VSC_EX) (&gt;= Vista) because it does not return the extended flag for some keys although they are extended keys
///   </note>
/// </remarks>
/// <seealso href="http://letcoderock.blogspot.ca/2011/10/sendinput-with-shift-key-not-work.html">
///   SendInput with SHIFT key does not work!?
/// </seealso>
/// <seealso href="https://stackoverflow.com/questions/21197257/keybd-event-keyeventf-extendedkey-explanation-required#21202784">
///   keybd_event KEYEVENTF_EXTENDEDKEY explanation required
/// </seealso>
function ExtendedKeyFlag(const VKey : Word): Cardinal;
begin
  If (VKey in [VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_HOME, VK_END, VK_PRIOR, VK_NEXT, VK_INSERT, VK_DELETE]) then Result := KEYEVENTF_EXTENDEDKEY
  else Result := 0;
end;


问:
How to set conditional breakpoint in anonymous inner class depending on final local variable?
suppose I have the following class and want to set a conditional breakpoint on arg==null at the marked location. This won't work in eclipse and gives the error "conditional breakpoint has compilation error(s). Reason: arg cannot be resolved to a variable".

I found some related information here, but even if I change the condition to "val$arg==null" (val$arg is the variable name displayed in the debugger's variable view), eclipse gives me the same error.

```<code>public abstract class Test {

    public static void main(String[] args) {
        Test t1 = foo("123");
        Test t2 = foo(null);
        t1.bar();
        t2.bar();
    }

    abstract void bar();

    static Test foo(final String arg) {
        return new Test() {
            @Override
                void bar() {
                // I want to set a breakpoint here with the condition "arg==null"
                System.out.println(arg);
            }
        };
    }
}
</code>```

答:
I can only offer an ugly workaround:</p>

```<code>if (arg == null) {
     int foo = 0; // add breakpoint here
}
System.out.println(arg);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
suppose I have the following class and want to set a conditional breakpoint on arg==null at the marked location. This won't work in eclipse and gives the error "conditional breakpoint has compilation error(s). Reason: arg cannot be resolved to a variable".

I found some related information here, but even if I change the condition to "val$arg==null" (val$arg is the variable name displayed in the debugger's variable view), eclipse gives me the same error.

public abstract class Test {

    public static void main(String[] args) {
        Test t1 = foo("123");
        Test t2 = foo(null);
        t1.bar();
        t2.bar();
    }

    abstract void bar();

    static Test foo(final String arg) {
        return new Test() {
            @Override
                void bar() {
                // I want to set a breakpoint here with the condition "arg==null"
                System.out.println(arg);
            }
        };
    }
}

Body:
I can only offer an ugly workaround:

if (arg == null) {
     int foo = 0; // add breakpoint here
}
System.out.println(arg);


问:
using wp_get_attachment_image_src in foreach loop
I have 10 images added to a post via Advanced Custom Fields, they're named from 1 to 10 e.g 'image_*', ACF is set to return the ID.

I'm trying to get the full size image URL of each image in the loop and use it as a href attribute to open a full size popup of the image, however I don't understand how wp_get_attachment_image_src works.

Since I am unable to use Advanced Custom Field's Repeater, this is the loop i'm using to get an array of the images with a custom image size of scaled, it works fine to generate the responsive image markup that I need:

```<code>// args

$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

    <a href="" class="open-viewer">

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

    </a>

<?php } ?>
</code>```

I need to set the href attribute of the parent a element with the URL of the image. This is what I have tried with wp_get_attachment_image_src, it doesn't work, it sets every href with image_10's URL.

```<code>// args

$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
        $image_array = wp_get_attachment_image_src($img, $sizeFull);
        $link = $image_array[0];
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

    <a href="<?php echo $link; ?>" class="open-viewer">

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

    </a>

<?php } ?>
</code>```

My question is: How can I set the href of a.open-viewer with the correct URL?, and secondly, why does my code fail? (debug is switched on but no errors appear).

I realise I've horribly misunderstood something here, I'm a PHP novice so any advice about my approach would be appreciated.

答:
In your first block, in your loop, you're setting the value of $link to the value of $image_array[0], but you're overwriting it each time. You want array_push here.

```<code>$images = array();
for($x = 1; $x <= 10; $x++) {
  $img = get_field('image_' . $x);
  $image_array = wp_get_attachment_image_src($img, $sizeFull);

  if($image_array && $image_array[0]) {
    array_push($images,
        array(
           src => $image_array[0],
           id => $img
        )
    );
  } else {
    break;
  }
}
</code>```

Now, when you loop over it the second array, you can just do:

```<code><?php foreach($images as $image) { ?>
   <a href="<?php echo $image['src']; ?>" class="open-viewer">
      <?php echo wp_get_attachment_image( $image['id'], $sizeHuge ); ?>
   </a>
<?php } ?>
</code>```

And the value of href should be the image URL.

Body:
I have 10 images added to a post via Advanced Custom Fields, they're named from 1 to 10 e.g 'image_*', ACF is set to return the ID.

I'm trying to get the full size image URL of each image in the loop and use it as a href attribute to open a full size popup of the image, however I don't understand how wp_get_attachment_image_src works.

Since I am unable to use Advanced Custom Field's Repeater, this is the loop i'm using to get an array of the images with a custom image size of scaled, it works fine to generate the responsive image markup that I need:

// args

$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

<?php } ?>

I need to set the href attribute of the parent a element with the URL of the image. This is what I have tried with wp_get_attachment_image_src, it doesn't work, it sets every href with image_10's URL.

// args

$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
        $image_array = wp_get_attachment_image_src($img, $sizeFull);
        $link = $image_array[0];
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

    <a href="<?php echo $link; ?>" class="open-viewer">

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

<?php } ?>

My question is: How can I set the href of a.open-viewer with the correct URL?, and secondly, why does my code fail? (debug is switched on but no errors appear).

I realise I've horribly misunderstood something here, I'm a PHP novice so any advice about my approach would be appreciated.

Body:
In your first block, in your loop, you're setting the value of $link to the value of $image_array[0], but you're overwriting it each time. You want array_push here.

$images = array();
for($x = 1; $x <= 10; $x++) {
  $img = get_field('image_' . $x);
  $image_array = wp_get_attachment_image_src($img, $sizeFull);

  if($image_array && $image_array[0]) {
    array_push($images,
        array(
           src => $image_array[0],
           id => $img
        )
    );
  } else {
    break;
  }
}

Now, when you loop over it the second array, you can just do:

<?php foreach($images as $image) { ?>
   <a href="<?php echo $image['src']; ?>" class="open-viewer">
      <?php echo wp_get_attachment_image( $image['id'], $sizeHuge ); ?>
   </a>
<?php } ?>

And the value of href should be the image URL.


问:
Symfony2 Api-Platform bin/schema issue
I've just started Api-Platform framework and while executing:

```<code>php bin/schema generate-types src/ app/config/schema.yml
</code>```

I get this:

```<code>C:\wamp\www\sf2-api>php bin/schema generate-types src/ app/config/schema.yml

dir=$(d=${0%[/\\]*}; cd "$d"; cd "../vendor/api-platform/schema-generator/bin" &
& pwd)

# See if we are running in Cygwin by checking for cygpath program
if command -v 'cygpath' >/dev/null 2>&1; then
        # Cygwin paths start with /cygdrive/ which will break windows PHP,
        # so we need to translate the dir path to windows format. However
        # we could be using cygwin PHP which does not require this, so we
        # test if the path to PHP starts with /cygdrive/ rather than /usr/bin
        if [[ $(which php) == /cygdrive/* ]]; then
                dir=$(cygpath -m $dir);
        fi
fi

dir=$(echo $dir | sed 's/ /\ /g')
"${dir}/schema" "$@"
</code>```

I am using Symfony 2.7.8 on window7.
I have the same issue on ubunbu 14.04.

答:
The correct syntax is:

php vendor/api-platform/schema-generator/bin/schema generate-types src/ app/config/schema.yml

Title: Symfony2 Api-Platform bin/schema issue

Body:
I've just started Api-Platform framework and while executing:

php bin/schema generate-types src/ app/config/schema.yml

I get this:

C:\wamp\www\sf2-api>php bin/schema generate-types src/ app/config/schema.yml

dir=$(d=${0%[/\\]*}; cd "$d"; cd "../vendor/api-platform/schema-generator/bin" &
& pwd)

# See if we are running in Cygwin by checking for cygpath program
if command -v 'cygpath' >/dev/null 2>&1; then
        # Cygwin paths start with /cygdrive/ which will break windows PHP,
        # so we need to translate the dir path to windows format. However
        # we could be using cygwin PHP which does not require this, so we
        # test if the path to PHP starts with /cygdrive/ rather than /usr/bin
        if [[ $(which php) == /cygdrive/* ]]; then
                dir=$(cygpath -m $dir);
        fi
fi

dir=$(echo $dir | sed 's/ /\ /g')
"${dir}/schema" "$@"

I am using Symfony 2.7.8 on window7.
I have the same issue on ubunbu 14.04.


问:
Scala Quill - queries always dynamic
I am always getting dynamic queries in Quill, even with simplest query I get dynamic query compiler warning log:

type DbContext = PostgresAsyncContext[Literal]

val db: DbContext = new PostgresAsyncContext(Literal, "db.default")

import db._

implicit val implicitDbSchemaMetaUser: db.SchemaMeta[User]
   = schemaMeta [User] ("users")

val users:Future[List[User]] = run(query[User])

答:
Removing type annotation from implicitDbSchemaMetaUser solved it:

implicit val implicitDbSchemaMetaUser = schemaMeta [User] ("users")

Title: Scala Quill - queries always dynamic


问:
Docker Containers can not be stopped or removed - permission denied Error
Issue: Can not stop docker containers, whenever I try to stop containers I get the following Error message,

```<code>ERROR: for yattyadocker_web_1  cannot stop container: 1f04148910c5bac38983e6beb3f6da4c8be3f46ceeccdc8d7de0da9d2d76edd8: Cannot kill container 1f04148910c5bac38983e6beb3f6da4c8be3f46ceeccdc8d7de0da9d2d76edd8: rpc error: code = PermissionDenied desc = permission denied
</code>```

OS Version/build: Ubuntu 16.04 | Docker Version 17.09.0-ce, build afdb6d4 | Docker Compose version 1.17.1, build 6d101fb

Steps to reproduce:

Created a rails project with Dockerfile and docker-compose.yml. docker-compose.yml is of version 3.

Image is built successfully with either docker build -t <project name> . or docker-compose up --build

Containers boots up and runs successfully.

Try to stop docker compose with docker-compose down.

What I tried::

I have to run sudo service docker restart and then the containers can be removed.

Uninstalled docker, removed docker directory and then re installed everything. Still facing same issue.

Note: This configuration was working correctly earlier, but somehow file permissions might have changed and I am seeing this error. I have to run sudo service docker restart and then the containers can be removed. But this is highly inconvenient and I don't know how to troubleshoot this.

Reference Files:

```<code># docker-compose.yml
version: '3'
volumes:
  db-data:
    driver: local
  redis-data:
    driver: local
services:
  db:
    image: postgres:9.4.1
    volumes:
      - db-data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    env_file: local_envs.env
  web:
    image: yattya_docker:latest
    command: bundle exec puma -C config/puma.rb
    tty: true
    stdin_open: true
    ports:
      - "3000:3000"
    links:
      - db
      - redis
      - memcached
    depends_on:
      - db
      - redis
      - memcached
    env_file: local_envs.env
  redis:
    image: redis:3.2.4-alpine
    ports:
      # We'll bind our host's port 6379 to redis's port 6379, so we can use
      # Redis Desktop Manager (or other tools) with it:
      - 6379:6379
    volumes:
      # We'll mount the 'redis-data' volume into the location redis stores it's data:
      - redis-data:/var/lib/redis
    command: redis-server --appendonly yes
  memcached:
    image: memcached:1.5-alpine
    ports:
      - "11211:11211"
  clock:
    image: yattya_docker:latest
    command: bundle exec clockwork lib/clock.rb
    links:
      - db
    depends_on:
      - db
    env_file: local_envs.env
  worker:
    image: yattya_docker:latest
    command: bundle exec rake jobs:work
    links:
      - db
    depends_on:
      - db
    env_file: local_envs.env
</code>```

And Dockerfile:

```<code># Dockerfile
FROM ruby:2.4.1

RUN apt-get update && apt-get install -y nodejs --no-install-recommends && rm -rf /var/lib/apt/lists/*

ENV APP_HOME /app
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME

ADD Gemfile* $APP_HOME/
RUN bundle install

ADD . $APP_HOME

RUN mkdir -p ${APP_HOME}/log
RUN cat /dev/null > "$APP_HOME/log/development.log"

RUN mkdir -p ${APP_HOME}/tmp/cache \
    && mkdir -p ${APP_HOME}/tmp/pids \
    && mkdir -p ${APP_HOME}/tmp/sockets

EXPOSE 3000
</code>```

答:
I was able to fix the issue. Apparmor service in ubuntu was not working normally due to some unknown issue. The problem was similar to the issue reported in moby project https://github.com/moby/moby/issues/20554.

The /etc/apparmor.d/tunables folder was empty, and https://github.com/mlaventure suggested to purge/reinstall apparmor to get it to the initial state.

So I reinstalled apparmor, and after restarting the problem was solved.

Hope this helps.

Body:
Issue: Can not stop docker containers, whenever I try to stop containers I get the following Error message,

ERROR: for yattyadocker_web_1  cannot stop container: 1f04148910c5bac38983e6beb3f6da4c8be3f46ceeccdc8d7de0da9d2d76edd8: Cannot kill container 1f04148910c5bac38983e6beb3f6da4c8be3f46ceeccdc8d7de0da9d2d76edd8: rpc error: code = PermissionDenied desc = permission denied

OS Version/build: Ubuntu 16.04 | Docker Version 17.09.0-ce, build afdb6d4 | Docker Compose version 1.17.1, build 6d101fb

Steps to reproduce:

Created a rails project with Dockerfile and docker-compose.yml. docker-compose.yml is of version 3.

Image is built successfully with either docker build -t <project name> . or docker-compose up --build

Containers boots up and runs successfully.

Try to stop docker compose with docker-compose down.

What I tried::

I have to run sudo service docker restart and then the containers can be removed.

Uninstalled docker, removed docker directory and then re installed everything. Still facing same issue.

Note: This configuration was working correctly earlier, but somehow file permissions might have changed and I am seeing this error. I have to run sudo service docker restart and then the containers can be removed. But this is highly inconvenient and I don't know how to troubleshoot this.

Reference Files:

# docker-compose.yml
version: '3'
volumes:
  db-data:
    driver: local
  redis-data:
    driver: local
services:
  db:
    image: postgres:9.4.1
    volumes:
      - db-data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    env_file: local_envs.env
  web:
    image: yattya_docker:latest
    command: bundle exec puma -C config/puma.rb
    tty: true
    stdin_open: true
    ports:
      - "3000:3000"
    links:
      - db
      - redis
      - memcached
    depends_on:
      - db
      - redis
      - memcached
    env_file: local_envs.env
  redis:
    image: redis:3.2.4-alpine
    ports:
      # We'll bind our host's port 6379 to redis's port 6379, so we can use
      # Redis Desktop Manager (or other tools) with it:
      - 6379:6379
    volumes:
      # We'll mount the 'redis-data' volume into the location redis stores it's data:
      - redis-data:/var/lib/redis
    command: redis-server --appendonly yes
  memcached:
    image: memcached:1.5-alpine
    ports:
      - "11211:11211"
  clock:
    image: yattya_docker:latest
    command: bundle exec clockwork lib/clock.rb
    links:
      - db
    depends_on:
      - db
    env_file: local_envs.env
  worker:
    image: yattya_docker:latest
    command: bundle exec rake jobs:work
    links:
      - db
    depends_on:
      - db
    env_file: local_envs.env

And Dockerfile:

# Dockerfile
FROM ruby:2.4.1

RUN apt-get update && apt-get install -y nodejs --no-install-recommends && rm -rf /var/lib/apt/lists/*

ENV APP_HOME /app
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME

ADD Gemfile* $APP_HOME/
RUN bundle install

ADD . $APP_HOME

RUN mkdir -p ${APP_HOME}/log
RUN cat /dev/null > "$APP_HOME/log/development.log"

RUN mkdir -p ${APP_HOME}/tmp/cache \
    && mkdir -p ${APP_HOME}/tmp/pids \
    && mkdir -p ${APP_HOME}/tmp/sockets

EXPOSE 3000


问:
How do i display a FormArray of GroupLists?
I am trying to make an interactive form that on each row lists an item together with a remove button (called verwijderen in my example). These items are retrieved from the database and each instantiated as a custom object called LaborPeriod.

These objects are then transformed into FormGroup object and then added to a FormArray. The definition of this formgroup is the following:

```<code>  let formGroup = this.fb.group({
    id: this.account.laborperiods[i].id,
    beginDate: this.account.laborperiods[i].beginDate,
    endDate: this.account.laborperiods[i].endDate,
    hours: this.account.laborperiods[i].hours,
    account: this.account.laborperiods[i].account
  })
  if(!this.laborPeriodArray){
    this.laborPeriodArray = new FormArray([])
  }
  this.laborPeriodArray.push(formGroup)
}
</code>```

The definition of the laborPeriodArray in the main FormGroup is also laborPeriodArray. The main FormGroup looks like the following:

```<code>  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }
</code>```

The entire component looks like this: Here you can see that laborPeriodArray gets initialized in the onInit method.

```<code>  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

  ngOnInit(): void {
    let formGroupArray: FormGroup[] = [];
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          if(!this.laborPeriodArray){
            this.laborPeriodArray = new FormArray([])
          }
          this.laborPeriodArray.push(formGroup)
        }
        console.log("laborPeriod" + JSON.stringify(this.laborPeriodArray.length))

        this.ngOnChanges();
      });
  }

  ngOnChanges(): void {
    if (this.account !== undefined) {
      this.accountUpdateForm.reset({
        name: this.account.name,
        username: this.account.username,
        status: this.account.enabled,
        permission: this.account.admin,
        laborPeriodArray: this.laborPeriodArray
      });
    }
  }
</code>```

All the FormGroup items are added but not displayed. The rows are blank. This is the relevant snippet from my HTML page

```<code><table class="table table-hover">
      <thead>
      <tr>
        <th>Begin datum</th>
        <th>Eind datum</th>
        <th>Aantal uren</th>
        <th>Actie</th>
      </tr>
      </thead>
      <tbody>
      <tr formArrayName="laborPeriodArray" *ngFor = "let laborperiod of laborPeriodArray.controls; let i = index" [formGroupName]="i">
        <td formControlName="beginDate">{{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}</td>
        <td formControlName="endDate">{{laborperiod.value.get('endDate') | date:'yyyy-MM-dd'}}</td>
        <td formControlName="hours">{{laborperiod.value.get('hours')}}</td>
        <button type="button" class="btn btn-default">
          <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
          Verwijderen
        </button>
      </tr>
</code>```

This is giving me the browser error ERROR Error: Cannot find control with unspecified name attribute but I am specifying the formControlName for each td row. So I don't understand what is causing the error. Furthermore I would also like to know how I can link the Remove button to the data corresponding to each row. I take it I have to use the index I for this but i'm not sure.

EDIT:

After applying AJT_82's solution I still don't have it working. It appears to have something to do with the database retrieved data itself. When I add the example account array of AJT_82 to my ngOnInit() like so:

```<code>  account1 = { laborperiods: [{ id: 1, hours:11 }, { id: 2, hours:22 }, { id: 3, hours:33 }] }

  ngOnInit(): void {
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account1.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account1.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          this.laborPeriodArray.push(formGroup)
        }
        console.log(JSON.stringify(account.laborperiods[0].beginDate))
        this.ngOnChanges();
      });
  }
</code>```

it works but it shows only 3 rows. That's the total length of the example account array.

This is the account class:

```<code>export class Account {
  id: number;
  username: string;
  name: string;
  enabled: boolean
  password: string;
  person: Person;
  admin: boolean;
  laborperiods: LaborPeriod[]
  remainingLeaveHours:number;
}
</code>```

and this is the LaborPeriod class:

```<code>export class LaborPeriod{
    id: number
    beginDate: Date
    endDate: Date
    hours: number
    account: Account
}
</code>```

Is there anything wrong with its field declarations?

答:
You cannot have formArrayName on the same element as your iteration and formGroupName, you need to move the formArrayName to an upper level. Also I see no use of the formControlName, as these are not editable fields, and Angular will throw error for this. Also the use of for example...

```<code>{{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}
</code>```

is incorrect, it should be just

```<code>{{laborperiod.value.beginDate | date:'yyyy-MM-dd'}}
</code>```

Assumingly in your code, the variable laberPeriodArray is declared...

```<code>this.laborPeriodArray =
     this.accountUpdateForm.controls.laborPeriodArray as FormArray
</code>```

since you are referring to this.laborPeriodArray in your code, therefore the following:

```<code>if(!this.laborPeriodArray){
  this.laborPeriodArray = new FormArray([])
}
</code>```

is redundant, you have already declared it in the build of the form as an empty FormArray. But that is just a sidenote :)

All in all, your template should look something like this:

```<code><table formArrayName="laborPeriodArray" >
  <tr *ngFor="let laborperiod of laborPeriodArray.controls;
      let i = index" [formGroupName]="i">
    <td>{{laborperiod.value.hours}}</td>
  </tr>
</table>
</code>```

DEMO

Body:
I am trying to make an interactive form that on each row lists an item together with a remove button (called verwijderen in my example). These items are retrieved from the database and each instantiated as a custom object called LaborPeriod.

These objects are then transformed into FormGroup object and then added to a FormArray. The definition of this formgroup is the following:

  let formGroup = this.fb.group({
    id: this.account.laborperiods[i].id,
    beginDate: this.account.laborperiods[i].beginDate,
    endDate: this.account.laborperiods[i].endDate,
    hours: this.account.laborperiods[i].hours,
    account: this.account.laborperiods[i].account
  })
  if(!this.laborPeriodArray){
    this.laborPeriodArray = new FormArray([])
  }
  this.laborPeriodArray.push(formGroup)
}

The definition of the laborPeriodArray in the main FormGroup is also laborPeriodArray. The main FormGroup looks like the following:

  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

The entire component looks like this: Here you can see that laborPeriodArray gets initialized in the onInit method.

  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

  ngOnInit(): void {
    let formGroupArray: FormGroup[] = [];
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          if(!this.laborPeriodArray){
            this.laborPeriodArray = new FormArray([])
          }
          this.laborPeriodArray.push(formGroup)
        }
        console.log("laborPeriod" + JSON.stringify(this.laborPeriodArray.length))

        this.ngOnChanges();
      });
  }

  ngOnChanges(): void {
    if (this.account !== undefined) {
      this.accountUpdateForm.reset({
        name: this.account.name,
        username: this.account.username,
        status: this.account.enabled,
        permission: this.account.admin,
        laborPeriodArray: this.laborPeriodArray
      });
    }
  }

All the FormGroup items are added but not displayed. The rows are blank. This is the relevant snippet from my HTML page

        Begin datum
        Eind datum
        Aantal uren
        Actie

        {{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}
        {{laborperiod.value.get('endDate') | date:'yyyy-MM-dd'}}
        {{laborperiod.value.get('hours')}}
        <button type="button" class="btn btn-default">

          Verwijderen
        </button>

This is giving me the browser error ERROR Error: Cannot find control with unspecified name attribute but I am specifying the formControlName for each td row. So I don't understand what is causing the error. Furthermore I would also like to know how I can link the Remove button to the data corresponding to each row. I take it I have to use the index I for this but i'm not sure.

EDIT:

After applying AJT_82's solution I still don't have it working. It appears to have something to do with the database retrieved data itself. When I add the example account array of AJT_82 to my ngOnInit() like so:

  account1 = { laborperiods: [{ id: 1, hours:11 }, { id: 2, hours:22 }, { id: 3, hours:33 }] }

  ngOnInit(): void {
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account1.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account1.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          this.laborPeriodArray.push(formGroup)
        }
        console.log(JSON.stringify(account.laborperiods[0].beginDate))
        this.ngOnChanges();
      });
  }

it works but it shows only 3 rows. That's the total length of the example account array.

This is the account class:

export class Account {
  id: number;
  username: string;
  name: string;
  enabled: boolean
  password: string;
  person: Person;
  admin: boolean;
  laborperiods: LaborPeriod[]
  remainingLeaveHours:number;
}

and this is the LaborPeriod class:

export class LaborPeriod{
    id: number
    beginDate: Date
    endDate: Date
    hours: number
    account: Account
}

Is there anything wrong with its field declarations?

Body:
You cannot have formArrayName on the same element as your iteration and formGroupName, you need to move the formArrayName to an upper level. Also I see no use of the formControlName, as these are not editable fields, and Angular will throw error for this. Also the use of for example...

{{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}

is incorrect, it should be just

{{laborperiod.value.beginDate | date:'yyyy-MM-dd'}}

Assumingly in your code, the variable laberPeriodArray is declared...

this.laborPeriodArray =
     this.accountUpdateForm.controls.laborPeriodArray as FormArray

since you are referring to this.laborPeriodArray in your code, therefore the following:

if(!this.laborPeriodArray){
  this.laborPeriodArray = new FormArray([])
}

is redundant, you have already declared it in the build of the form as an empty FormArray. But that is just a sidenote :)

All in all, your template should look something like this:

<table formArrayName="laborPeriodArray" >
  <tr *ngFor="let laborperiod of laborPeriodArray.controls;
      let i = index" [formGroupName]="i">
    <td>{{laborperiod.value.hours}}</td>
  </tr>
</table>

DEMO


问:
ServiceBus Architecture Pros and Cons
What are the Pros and Cons of using a Service Bus architecture in a SOA project?

What are the suggested open source Service Bus platforms that you would recommend?

Thanks in advance

答:
pro: loose coupling, stable infrastructure

con: hard troubleshooting and monitoring

Title: ServiceBus Architecture Pros and Cons


答:
I would do this in one row rather than three:</p>

```<code>select sum(case when numissues = rcnt then 1 else 0 end) as equal,
       sum(case when numissues > rcnt then 1 else 0 end) as reduced,
       sum(case when numissues < rcnt then 1 else 0 end) as incrased
from (select b.form_id, b.numissues, count(r.form_id) as rcnt
      from baseline b left join
           revisits r
           on b.form_id = r.form_id
      group by b.form_id, b.numissues
     ) br;
</code>```

Title: SQL group by count across two tables

Body:
I have got two tables called baseline and revisits

baseline

formid-------NoOfIssues

1--------------3

2--------------4

3--------------5

revisits

id------formid-------NoOfIssues-----------date--------------fid

1---------2--------------4-------------5/06/2016------------1

2---------3--------------3-------------15/06/2016-----------1

3---------1--------------4-------------20/07/2016-----------1

4---------1--------------3-------------25/07/2016-----------1

5---------2--------------5-------------28/07/2016-----------1

6---------1--------------5-------------01/06/2016-----------1

7---------3--------------8-------------21/02/2016-----------1

8---------3--------------2-------------21/02/2016-----------2

These tables are joined by 'formid'.
I need to compare number of issues in baseline vs revisits(only first) and get a count as reduced, increased or equal

Based upon the above table i am expecting the following, for example across all three baseline entries no equals were found comparing NoOfissues in first revisit against same formid, but 1 equal and 2 increased were found

Addition: if same date and same formid is found than take the lower fid, so in the last two rows of revisits table both formid and date are equal but need to consider the lower formid which is 1

status----------Count

reduced----------0

equal------------1

increased--------2

Body:
I would do this in one row rather than three:

select sum(case when numissues = rcnt then 1 else 0 end) as equal,
       sum(case when numissues > rcnt then 1 else 0 end) as reduced,
       sum(case when numissues < rcnt then 1 else 0 end) as incrased
from (select b.form_id, b.numissues, count(r.form_id) as rcnt
      from baseline b left join
           revisits r
           on b.form_id = r.form_id
      group by b.form_id, b.numissues
     ) br;


问:
Print out all subsets in an array that equal an given sum recursively does not jump to the next iteration
I'm trying to print out all the subsets that is equal to a given sum using recursion. However, my code doesn't jump to the next iteration after the first one is finished:

```<code>import java.util.*;
public class Combinations {
public static int currentSum = 0;
public static ArrayList<Integer> usedItems = new ArrayList<>();
public static void main( String[] args ) throws Exception {

    int arr[] = {1, 2, 3, 4, 2};
    int sum = 6;
    printCombinations(arr, sum);
}

public static void printCombinations(int[] availableItems, int goal){

    for (int i = 0; i < availableItems.length; i++){
        if (currentSum + availableItems[i] == goal){
            System.out.println(Arrays.toString(usedItems.toArray()) + availableItems[i]);
            currentSum = 0;
            usedItems.clear();
        }
        if(currentSum + availableItems[i] > goal){
            continue;
        }
        if(currentSum + availableItems[i] < goal){
            currentSum += availableItems[i];
            usedItems.add(availableItems[i]);
            int[] newAvailableItems = Arrays.copyOfRange(availableItems, 1, availableItems.length);
            printCombinations(newAvailableItems, goal);
        }
    }
}
</code>```

For example if the sum equals 6 the program only prints out 1, 2, 3 but not jump to the next number and check from there.

答:
I think the problem is here:

```<code> if (currentSum + availableItems[i] == goal)
</code>```

For the given array int arr[] = {1, 2, 3, 4, 2}; and goal value int sum = 6;

Iterations:

currentSum = 0, availableItems[i] = 1 (0 + 1 = 1) fits -> if(currentSum + availableItems[i] < goal)

currentSum = 1, availableItems[i] = 2 (1 + 2 = 3) fits -> if(currentSum + availableItems[i] < goal)

currentSum = 3, availableItems[i] = 3 (3 + 3 = 6) fits -> if (currentSum + availableItems[i] == goal) and in the same iteration: currentSum = 0, availableItems[i] = 3 (0 + 3 = 3) fits -> if (currentSum + availableItems[i] < goal)

currentSum = 3, availableItems[i] = 4 (3 + 4 = 7)
fits -> if(currentSum + availableItems[i] > goal) and so on...

For the given array and sum value is not going to fit the first if never.

You need increase the iterator:

```<code>if (currentSum + availableItems[i] == goal){
    System.out.println(Arrays.toString(usedItems.toArray()) + availableItems[i]);
    currentSum = 0;
    usedItems.clear();
    i++;
}
</code>```

Body:
I'm trying to print out all the subsets that is equal to a given sum using recursion. However, my code doesn't jump to the next iteration after the first one is finished:

import java.util.*;
public class Combinations {
public static int currentSum = 0;
public static ArrayList<Integer> usedItems = new ArrayList<>();
public static void main( String[] args ) throws Exception {

    int arr[] = {1, 2, 3, 4, 2};
    int sum = 6;
    printCombinations(arr, sum);
}

public static void printCombinations(int[] availableItems, int goal){

    for (int i = 0; i < availableItems.length; i++){
        if (currentSum + availableItems[i] == goal){
            System.out.println(Arrays.toString(usedItems.toArray()) + availableItems[i]);
            currentSum = 0;
            usedItems.clear();
        }
        if(currentSum + availableItems[i] > goal){
            continue;
        }
        if(currentSum + availableItems[i] < goal){
            currentSum += availableItems[i];
            usedItems.add(availableItems[i]);
            int[] newAvailableItems = Arrays.copyOfRange(availableItems, 1, availableItems.length);
            printCombinations(newAvailableItems, goal);
        }
    }
}

For example if the sum equals 6 the program only prints out 1, 2, 3 but not jump to the next number and check from there.

Body:
I think the problem is here:

 if (currentSum + availableItems[i] == goal)

For the given array int arr[] = {1, 2, 3, 4, 2}; and goal value int sum = 6;

Iterations:

currentSum = 0, availableItems[i] = 1 (0 + 1 = 1) fits -> if(currentSum + availableItems[i] < goal)

currentSum = 1, availableItems[i] = 2 (1 + 2 = 3) fits -> if(currentSum + availableItems[i] < goal)

currentSum = 3, availableItems[i] = 3 (3 + 3 = 6) fits -> if (currentSum + availableItems[i] == goal) and in the same iteration: currentSum = 0, availableItems[i] = 3 (0 + 3 = 3) fits -> if (currentSum + availableItems[i] < goal)

currentSum = 3, availableItems[i] = 4 (3 + 4 = 7)
fits -> if(currentSum + availableItems[i] > goal) and so on...

For the given array and sum value is not going to fit the first if never.

You need increase the iterator:

if (currentSum + availableItems[i] == goal){
    System.out.println(Arrays.toString(usedItems.toArray()) + availableItems[i]);
    currentSum = 0;
    usedItems.clear();
    i++;
}


问:
Mongo Connection Error in Azure Linux App Service using docker image
I've deployed a docker image to an Azure Linux App Service which contains a node app. The app is failing to start properly because it can't connect to a Mongo version of Cosmo DB.

error:  MongoError: failed to connect to server [***.documents.azure.com:10255] on first connect [MongoError: getaddrinfo EAI_AGAIN ***.documents.azure.com:10255]

I'm using mongoose and the following to connect:

```<code>mongoose.connect(process.env.MONGODB_URL, { useMongoClient: true });
</code>```

Running the app in a container locally on my machine works. Is there something I'm missing? Some DNS/Firewall setting?

Dockerfile:

```<code>FROM mhart/alpine-node:latest

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json package-lock.json ./

RUN npm install --production

# Bundle app source
COPY . .

EXPOSE 4000

CMD [ "node", "main.js" ]
</code>```

答: Yes, open outbound ports 10250-10256 and 443 to work with Cosmos DB. Also, make sure your mongodb connection string has ?ssl=true parameter set.</p>

Body:
I've deployed a docker image to an Azure Linux App Service which contains a node app. The app is failing to start properly because it can't connect to a Mongo version of Cosmo DB.

error:  MongoError: failed to connect to server [***.documents.azure.com:10255] on first connect [MongoError: getaddrinfo EAI_AGAIN ***.documents.azure.com:10255]

I'm using mongoose and the following to connect:

mongoose.connect(process.env.MONGODB_URL, { useMongoClient: true });

Running the app in a container locally on my machine works. Is there something I'm missing? Some DNS/Firewall setting?

Dockerfile:

FROM mhart/alpine-node:latest

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json package-lock.json ./

RUN npm install --production

# Bundle app source
COPY . .

EXPOSE 4000

CMD [ "node", "main.js" ]


问:
linking a website to an image
So I am using this to display images on a site

```<code>var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');

images();
function images() {
image1 = new Image();

image1.src = 'https://lh3.googleusercontent.com/7PP1DeqGfPdu-12ULf1baVkQ7B-
lZvbjef7uPg5ZWOs5OX_4psOdKJO8RpgaXKhN9OlC=w200-h300';

image1.onload = function () {
    context.drawImage(image1, 10, 10, 220, 300);
}
</code>```

But now I've decided I want to link a site to each of those images when they are clicked.

Initially, I thought I could just use the normal href way, but that cant be done in this case. Is there another way I can set this up?

答:
To expand on the previous answer you can create click events by adding event listeners.</p>

```<code>var canvas = document.getElementById('myCanvas');

canvas.addEventListener("click", function (event) {
    // User clicked on canvas
    window.location = 'https://google.com/'
});
</code>```

Title: linking a website to an image

Body:
So I am using this to display images on a site

var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');

images();
function images() {
image1 = new Image();

image1.src = 'https://lh3.googleusercontent.com/7PP1DeqGfPdu-12ULf1baVkQ7B-
lZvbjef7uPg5ZWOs5OX_4psOdKJO8RpgaXKhN9OlC=w200-h300';

image1.onload = function () {
    context.drawImage(image1, 10, 10, 220, 300);
}

But now I've decided I want to link a site to each of those images when they are clicked.

Initially, I thought I could just use the normal href way, but that cant be done in this case. Is there another way I can set this up?

Body:
To expand on the previous answer you can create click events by adding event listeners.

var canvas = document.getElementById('myCanvas');

canvas.addEventListener("click", function (event) {
    // User clicked on canvas
    window.location = 'https://google.com/'
});


问:
Is there a better conditional setTimeout pattern?
I have the following code:

```<code>if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}
</code>```

It seems like there should be a better pattern than calling flyOut in each if  condition.  Seems wasteful to me and pollutes the code.

Is there a better way?

答:
Using if else

```<code>if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}
</code>```

Using Conditional operator ?:

```<code>setTimeout(flyOut, isFlyoutAnimationDisabled ? 0 : 250);
</code>```

by using the above consider that setTimeout(fn, 0) will perform as a "nextTick" giving this seemingly unexpected result

const fn = () => console.log("A");

setTimeout(fn, 0) // "A"
console.log("B"); // "B"

// Logs:
// >> B
// >> A```

Body:
I have the following code:

if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}

It seems like there should be a better pattern than calling flyOut in each if  condition.  Seems wasteful to me and pollutes the code.

Is there a better way?

Body:
Using if else

if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}

Using Conditional operator ?:

setTimeout(flyOut, isFlyoutAnimationDisabled ? 0 : 250);

by using the above consider that setTimeout(fn, 0) will perform as a "nextTick" giving this seemingly unexpected result

const fn = () => console.log("A");

setTimeout(fn, 0) // "A"
console.log("B"); // "B"

// Logs:
// >> B
// >> A

ContentLicense: CC BY-SA 4.0


问:
Implementing numeric limit class
I am new to C# and trying to implement a numeric limit class as :

```<code>internal class NumericLimit<TValue> where TValue : IComparable
{
    public NumericLimit(TValue min, TValue max)
    {
        this.Max = max;
        this.Min = min;
    }

    internal TValue Max { get; }
    internal TValue Min { get; }
    internal bool WithinBounds(TValue min, TValue max)
    {
        if (min.CompareTo(this.Min) <= 0 &&
            max.CompareTo(this.Max) >= 0)
            return true;

        return false;
    }

    internal bool LessThan(TValue value)
    {
        return (value.CompareTo(this.Max) > 0);
    }

    internal bool GreaterThan(TValue value)
    {
        return (value.CompareTo(this.Min) < 0);
    }

    internal bool Contains(TValue value)
    {
        if (value.CompareTo(this.Max) == 0 ||
            value.CompareTo(this.Min) == 0)
            return true;

        return (value.CompareTo(this.Min) > 0) &&
               (value.CompareTo(this.Max) < 0);
    }

    internal bool Defined()
    {
        return true;
    }
}
</code>```

The problem is how to implement Defined() function. I want the NumericLimit to be invalid/undefined when both Min and Max values are -1.

Like, for NumericLimit<long> the limit is undefined when both Min and Max are -1L.

And for NumericLimit<int> the limit is undefined when both Min and Max are -1.

How to implement 'Defined' in a way that correctly represents negative one for TValue type ?

答:
What if after some time you decide to use NumericLimit<double> or some other type for T that will not accept value of -1? I suggest using special IsDefined flag and adding static method for constructing undefined limit:

```<code>internal class NumericLimit<TValue> where TValue : IComparable
{
    internal bool IsDefined { get; }

    public NumericLimit(TValue min, TValue max)
    {
        this.Max = max;
        this.Min = min;
        IsDefined = true;
    }

    private NumericLimit()
    {
        IsDefined = false;
    }

    public static NumericLimit<TValue> Undefined()
    {
        return new NumericLimit<TValue>();
    }

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

Title: Implementing numeric limit class

Body:
I am new to C# and trying to implement a numeric limit class as :

internal class NumericLimit<TValue> where TValue : IComparable
{
    public NumericLimit(TValue min, TValue max)
    {
        this.Max = max;
        this.Min = min;
    }

    internal TValue Max { get; }
    internal TValue Min { get; }
    internal bool WithinBounds(TValue min, TValue max)
    {
        if (min.CompareTo(this.Min) <= 0 &&
            max.CompareTo(this.Max) >= 0)
            return true;

        return false;
    }

    internal bool LessThan(TValue value)
    {
        return (value.CompareTo(this.Max) > 0);
    }

    internal bool GreaterThan(TValue value)
    {
        return (value.CompareTo(this.Min) < 0);
    }

    internal bool Contains(TValue value)
    {
        if (value.CompareTo(this.Max) == 0 ||
            value.CompareTo(this.Min) == 0)
            return true;

        return (value.CompareTo(this.Min) > 0) &&
               (value.CompareTo(this.Max) < 0);
    }

    internal bool Defined()
    {
        return true;
    }
}

The problem is how to implement Defined() function. I want the NumericLimit to be invalid/undefined when both Min and Max values are -1.

Like, for NumericLimit<long> the limit is undefined when both Min and Max are -1L.

And for NumericLimit<int> the limit is undefined when both Min and Max are -1.

How to implement 'Defined' in a way that correctly represents negative one for TValue type ?

Body:
What if after some time you decide to use NumericLimit<double> or some other type for T that will not accept value of -1? I suggest using special IsDefined flag and adding static method for constructing undefined limit:

internal class NumericLimit<TValue> where TValue : IComparable
{
    internal bool IsDefined { get; }

    public NumericLimit(TValue min, TValue max)
    {
        this.Max = max;
        this.Min = min;
        IsDefined = true;
    }

    private NumericLimit()
    {
        IsDefined = false;
    }

    public static NumericLimit<TValue> Undefined()
    {
        return new NumericLimit<TValue>();
    }

    // ...
}


问:
How does framework like KIF or EarlGrey access the running application?
Usually in iOS unit tests, we create new objects, call the method we wanna test, and then validate the results. This is a stand-alone procedure. The test cases always start running with the app instance but we do not access that instance directly.

However, with the framework like KIF or EarlGrey, we are able to write functional tests by accessing UI elements with accessibility labels in the running app instance. I am wondering how it is implemented. We don't have something like context or root view controller object when tests start, how does the framework find the presenting view controller from "nowhere"?

答:
Because they are based on XCTest's Unit Test paradigm. In it, the tests and the app are both in the same bundle and therefore have access to the app internals.

Using [UIApplication sharedApplication], you can actually get the UIWindow for the app and find the entire View Hierarchy.


问:
Creating SpringSource Tool Suite (STS) Hibernate Template
i've created the Hibernate project using Spring Template Project. Two domain objects, a JUnit test, app-context.xml and the persistence-context.xml were created. Now i noticed this line

<jdbc:embedded-database
  id="dataSource"></jdbc:embedded-database>

and assume that the following happens

A default HQSL db is used

The two created models Order.java & Item.java will automatically created in memory tables T_ORDER and T_ITEM and the these will be mapped as per annotations on the objects. Inside the auto created classes one of the test methods is as follows

```<code>@Test
@Transactional
public void testSaveAndGet() throws Exception {
    Session session = sessionFactory.getCurrentSession();
    Order order = new Order();
    order.getItems().add(new Item());
    session.save(order);
    session.flush();
    // Otherwise the query returns the existing order
    // (and we didn't set the parent in the item)...
    session.clear();
    Order other = (Order) session.get(Order.class, order.getId());
    assertEquals(1, other.getItems().size());
    assertEquals(other, other.getItems().iterator().next().getOrder());
}
</code>```

Questions ...

Am i correct to think that the in memory tables are created from the domain models (Order/Item), and mapped? Therefore session.flush() synchronize the object to the physical (in memory table)....

Are these tables auto mapped because if i do the following

```<code>session.save(order);
session.flush();
session.clear();
Order other = (Order) session
   .createQuery("from T_ORDER where ORDER_ID =: orderid")
   .setLong("orderid", order.getId())
   .uniqueResult();
</code>```

i get an exception...

```<code>org.hibernate.hql.ast.[B]QuerySyntaxException[/B]: \
T_ORDER is not mapped [from T_ORDER where ORDER_ID =: orderid]
............
............
</code>```

if these tables are not mapped automatically, how is flushing working at the first place?

答:
Table creation is a feature of Hibernate (and other JPA proviers). It taking place when the application/test starts. It has nothing to do with any query. Even if you only start your test, with Hibernate running and configured, it can create the tables.

If Hibernate create the tables, drop old once, and so on, depends on its configuration: the property: hibernate.hbm2ddl.auto is used what hibernate do if its starts. For example the value update will add not existing tables and columns.

More details can be found in the documentation.

Your Exception
When you uses Hibernate and write hibernate query statements, then you have to use HQL and not SQL. -- The main difference is that HQL is based on the classes but not on the tables. So in your case you must not use T_ORDER, but Order (the same is for the id, you need to use the property/field name, but not the column name).

Body:
i've created the Hibernate project using Spring Template Project. Two domain objects, a JUnit test, app-context.xml and the persistence-context.xml were created. Now i noticed this line

<jdbc:embedded-database
  id="dataSource"></jdbc:embedded-database>

and assume that the following happens

A default HQSL db is used

The two created models Order.java & Item.java will automatically created in memory tables T_ORDER and T_ITEM and the these will be mapped as per annotations on the objects. Inside the auto created classes one of the test methods is as follows

@Test
@Transactional
public void testSaveAndGet() throws Exception {
    Session session = sessionFactory.getCurrentSession();
    Order order = new Order();
    order.getItems().add(new Item());
    session.save(order);
    session.flush();
    // Otherwise the query returns the existing order
    // (and we didn't set the parent in the item)...
    session.clear();
    Order other = (Order) session.get(Order.class, order.getId());
    assertEquals(1, other.getItems().size());
    assertEquals(other, other.getItems().iterator().next().getOrder());
}

Questions ...

Am i correct to think that the in memory tables are created from the domain models (Order/Item), and mapped? Therefore session.flush() synchronize the object to the physical (in memory table)....

Are these tables auto mapped because if i do the following

session.save(order);
session.flush();
session.clear();
Order other = (Order) session
   .createQuery("from T_ORDER where ORDER_ID =: orderid")
   .setLong("orderid", order.getId())
   .uniqueResult();

i get an exception...

org.hibernate.hql.ast.[B]QuerySyntaxException[/B]: \
T_ORDER is not mapped [from T_ORDER where ORDER_ID =: orderid]
............
............

if these tables are not mapped automatically, how is flushing working at the first place?


问:
template design is bigger than bootstrap grid
I have a psd template that i would like to convert to a responsive site using bootstrap.
The template width is 1920px and the bootstrap grid is a 1170px bootstrap grid with 12columns with 15px margins left and right.
But in the design some things like the logo in this example and a part of the menu stands out of the grid, how do i interpret this design then? Or is this wrong design? Am I correct if i think the design should be between the columns?
template

答:
Generally, the menu and logo are included in the  which comes before

```<code><nav class="navbar navbar-toggleable-md navbar-inverse fixed-top bg-inverse">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="#">Navbar</a>
  </div>
</nav>

<div class="container">
  <!-- Example row of columns -->
  <div class="row">
    <div class="col-md-4">
      <h2>Heading</h2>
      <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
      <p><a class="btn btn-secondary" href="#" role="button">View details »</a></p>
    </div>
    <div class="col-md-4">
      <h2>Heading</h2>
      <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
      <p><a class="btn btn-secondary" href="#" role="button">View details »</a></p>
   </div>
    <div class="col-md-4">
      <h2>Heading</h2>
      <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
      <p><a class="btn btn-secondary" href="#" role="button">View details »</a></p>
    </div>
  </div>

  <hr>

  <footer>
    <p>© Company 2017</p>
  </footer>
</code>```

So the grid width is only referring to the width of the content in the container.

Body:
Generally, the menu and logo are included in the <nav> which comes before <div class="container">

<nav class="navbar navbar-toggleable-md navbar-inverse fixed-top bg-inverse">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="#">Navbar</a>
  </div>
</nav>

<div class="container">
  <!-- Example row of columns -->
  <div class="row">
    <div class="col-md-4">
      <h2>Heading</h2>
      <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
      <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>
    </div>
    <div class="col-md-4">
      <h2>Heading</h2>
      <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
      <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>
   </div>
    <div class="col-md-4">
      <h2>Heading</h2>
      <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
      <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>
    </div>
  </div>

  <hr>

  <footer>
    <p>&copy; Company 2017</p>
  </footer>

So the grid width is only referring to the width of the content in the container.


答:
I'm not familiar with intersystems-cache, but you can see if the following is valid SQL with that DB:

```<code>SELECT
    CASE
        WHEN BL.NoOfIssues = FR.NoOfIssues THEN 'equal'
        WHEN BL.NoOfIssues > FR.NoOfIssues THEN 'reduced'
        WHEN BL.NoOfIssues < FR.NoOfIssues THEN 'increased'
    END AS status,
    COUNT(*) AS Count
FROM
    Baseline BL
INNER JOIN Revisits FR ON FR.formid = BL.formid
LEFT OUTER JOIN Revisits R ON
    R.formid = BL.formid AND
    (
        R.date < FR.date OR
        (R.date = FR.date AND R.fid > FR.fid)
    )
WHERE
    R.formid IS NULL
GROUP BY
    CASE
        WHEN BL.NoOfIssues = FR.NoOfIssues THEN 'equal'
        WHEN BL.NoOfIssues > FR.NoOfIssues THEN 'reduced'
        WHEN BL.NoOfIssues < FR.NoOfIssues THEN 'increased'
    END
</code>```

Some quick notes on your database though - You should probably decide on a standard of plural or singular table names and stick with it. Also, try to avoid common reserved words for object names, like date. Finally, if a revisit is basically the same as a visit, just on a later date then you should consider keeping them all in the same table.

Title: SQL group by count across two tables

Body:
I'm not familiar with intersystems-cache, but you can see if the following is valid SQL with that DB:

SELECT
    CASE
        WHEN BL.NoOfIssues = FR.NoOfIssues THEN 'equal'
        WHEN BL.NoOfIssues > FR.NoOfIssues THEN 'reduced'
        WHEN BL.NoOfIssues < FR.NoOfIssues THEN 'increased'
    END AS status,
    COUNT(*) AS Count
FROM
    Baseline BL
INNER JOIN Revisits FR ON FR.formid = BL.formid
LEFT OUTER JOIN Revisits R ON
    R.formid = BL.formid AND
    (
        R.date < FR.date OR
        (R.date = FR.date AND R.fid > FR.fid)
    )
WHERE
    R.formid IS NULL
GROUP BY
    CASE
        WHEN BL.NoOfIssues = FR.NoOfIssues THEN 'equal'
        WHEN BL.NoOfIssues > FR.NoOfIssues THEN 'reduced'
        WHEN BL.NoOfIssues < FR.NoOfIssues THEN 'increased'
    END

Some quick notes on your database though - You should probably decide on a standard of plural or singular table names and stick with it. Also, try to avoid common reserved words for object names, like date. Finally, if a revisit is basically the same as a visit, just on a later date then you should consider keeping them all in the same table.