问:
Auto close JavaFX application due to innactivity
I want to close my JavaFX application if the user is inactive for a period of time. I have this code in Swing and I want to do the same in JavaFX. This class redirect the user to the login panel if no event happens during the time indicated.</p>

```<code>import javax.swing.Timer;

public class AutoClose {

    private Timer timer;

    public AutoClose(JFrame centralpanel) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {

                Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

                    @Override
                    public void eventDispatched(AWTEvent event) {
                        Object source = event.getSource();
                        if (source instanceof Component) {
                            Component comp = (Component) source;
                            Window win = null;
                            if (comp instanceof Window) {
                                win = (Window) comp;
                            } else {
                                win = SwingUtilities.windowForComponent(comp);
                            }
                            if (win == centralpanel) {
                                timer.restart();
                            }
                        }
                    }
                }, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK);

                timer = new Timer(3600000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {

                        centralpanel.dispose();

                        //Redirect to the login panel.
                        Login login = new Login();
                        login.setVisible(true);
                        timer.stop();
                        JOptionPane.showMessageDialog(null,"Connection closed due to inactivity");
                    }
                });
                timer.start();
            }
        });
    }
}
</code>```

答:
I have done this code and now it works correctly as I wanted.</p>

```<code>public class AutoClose {
    private Timeline timer;

    public AutoClose(VBox mainPanel) {

        timer = new Timeline(new KeyFrame(Duration.seconds(3600), new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent evt) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("Inactivity");
                alert.setHeaderText("Connection closed due to inactivity");
                alert.show();

                try {
                    Stage mainWindowStage = Login.getPrimaryStage();

                    Parent root = FXMLLoader.load(getClass().getResource("/view/Login.fxml"));

                    Scene scene = new Scene(root);
                    mainWindowStage.setScene(scene);
                    mainWindowStage.show();

                    timer.stop();
                } catch (IOException ex) {
                }
            }
        }));
        timer.setCycleCount(Timeline.INDEFINITE);
        timer.play();

        mainPanel.addEventFilter(MouseEvent.ANY, new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                timer.playFromStart();
            }
        });
    }
}
</code>```

Body:
I want to close my JavaFX application if the user is inactive for a period of time. I have this code in Swing and I want to do the same in JavaFX. This class redirect the user to the login panel if no event happens during the time indicated.

import javax.swing.Timer;

public class AutoClose {

    private Timer timer;

    public AutoClose(JFrame centralpanel) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {

                Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

                    @Override
                    public void eventDispatched(AWTEvent event) {
                        Object source = event.getSource();
                        if (source instanceof Component) {
                            Component comp = (Component) source;
                            Window win = null;
                            if (comp instanceof Window) {
                                win = (Window) comp;
                            } else {
                                win = SwingUtilities.windowForComponent(comp);
                            }
                            if (win == centralpanel) {
                                timer.restart();
                            }
                        }
                    }
                }, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK);

                timer = new Timer(3600000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {

                        centralpanel.dispose();

                        //Redirect to the login panel.
                        Login login = new Login();
                        login.setVisible(true);
                        timer.stop();
                        JOptionPane.showMessageDialog(null,"Connection closed due to inactivity");
                    }
                });
                timer.start();
            }
        });
    }
}

Body:
I have done this code and now it works correctly as I wanted.

public class AutoClose {
    private Timeline timer;

    public AutoClose(VBox mainPanel) {

        timer = new Timeline(new KeyFrame(Duration.seconds(3600), new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent evt) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("Inactivity");
                alert.setHeaderText("Connection closed due to inactivity");
                alert.show();

                try {
                    Stage mainWindowStage = Login.getPrimaryStage();

                    Parent root = FXMLLoader.load(getClass().getResource("/view/Login.fxml"));

                    Scene scene = new Scene(root);
                    mainWindowStage.setScene(scene);
                    mainWindowStage.show();

                    timer.stop();
                } catch (IOException ex) {
                }
            }
        }));
        timer.setCycleCount(Timeline.INDEFINITE);
        timer.play();

        mainPanel.addEventFilter(MouseEvent.ANY, new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                timer.playFromStart();
            }
        });
    }
}


来源: stackexchange

问:
Group Box content - hide based on cell value
I have the following code:

```<code>Private Sub Worksheet_Calculate()
Application.EnableEvents = False

    Select Case Range("B14")

    Case "Medium Risk"
        Rows("6:12").EntireRow.Hidden = True
    Case Else
        Rows("6:12").EntireRow.Hidden = False

    End Select
Application.EnableEvents = True
End Sub
</code>```

What I need is: to hide Group Box "content" based on the value in B14.
Group Box 15 surrounds a CheckBox8_Click.

Any ideas?

Thanks

答:
I decided that I will simply settle with hiding a row [based on cell criteria] where the object is:</p>

```<code>Private Sub Worksheet_Calculate()
Application.EnableEvents = False

    Select Case Range("B14")

    Case "Medium Risk"
        Rows("6:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
        Case Else
        Rows("6:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    End Select
Application.EnableEvents = True
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code:

Private Sub Worksheet_Calculate()
Application.EnableEvents = False

    Select Case Range("B14")

    Case "Medium Risk"
        Rows("6:12").EntireRow.Hidden = True
    Case Else
        Rows("6:12").EntireRow.Hidden = False

    End Select
Application.EnableEvents = True
End Sub

What I need is: to hide Group Box "content" based on the value in B14.
Group Box 15 surrounds a CheckBox8_Click.

Any ideas?

Thanks

Body:
I decided that I will simply settle with hiding a row [based on cell criteria] where the object is:

Private Sub Worksheet_Calculate()
Application.EnableEvents = False

    Select Case Range("B14")

    Case "Medium Risk"
        Rows("6:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
        Case Else
        Rows("6:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    End Select
Application.EnableEvents = True
End Sub


问:
Selenium testing on Frames
I am trying to learn Selenium from Youtube. I have written the simple code below on Frames. I want to click on linkText which is not visible but manually can scroll and click on it. I am trying with the below code but getting the error:

```<code>org.openqa.selenium.WebDriverException: unknown error: Element is not clickable
</code>```

My code:

```<code>public class Frame_Test {

    WebDriver driver;

    @Test
    public void test1() {

        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        driver = new ChromeDriver(options);

        driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html");
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        driver.switchTo().frame("packageListFrame");
        driver.findElement(By.linkText("org.openqa.selenium.safari")).click();

    }

}
</code>```

答:
You can use the below method:

```<code>public static void scrollToElement(By elementToken, WebDriver driver){
    WebElement element = driver.findElement(elementToken);
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
</code>```

Or if you don't want to use the explicit method you can use the scroll code in your code:

```<code>driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html";
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

driver.switchTo().frame("packageListFrame");

WebElement element = driver.findElement(By.linkText("org.openqa.selenium.safari"));((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

driver.findElement(By.linkText("org.openqa.selenium.safari")).click();
</code>```

ContentLicense: CC BY-SA 4.0

Title: Selenium testing on Frames

Body:
I am trying to learn Selenium from Youtube. I have written the simple code below on Frames. I want to click on linkText which is not visible but manually can scroll and click on it. I am trying with the below code but getting the error:

org.openqa.selenium.WebDriverException: unknown error: Element is not clickable

My code:

public class Frame_Test {

    WebDriver driver;

    @Test
    public void test1() {

        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        driver = new ChromeDriver(options);

        driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html");
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        driver.switchTo().frame("packageListFrame");
        driver.findElement(By.linkText("org.openqa.selenium.safari")).click();

    }

}

Body:
You can use the below method:

public static void scrollToElement(By elementToken, WebDriver driver){
    WebElement element = driver.findElement(elementToken);
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Or if you don't want to use the explicit method you can use the scroll code in your code:

driver.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html";
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

driver.switchTo().frame("packageListFrame");

WebElement element = driver.findElement(By.linkText("org.openqa.selenium.safari"));((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

driver.findElement(By.linkText("org.openqa.selenium.safari")).click();


问:
How to purge unused source/class files from Directory tree
We have about 280 Java source code spread over 10 packages, and a bunch of txt and image files for a software project. Quite a few of them are not being used currently. They do not break the system, since we can just do a "javac //*.java" and "jar cmf metafile " to build up the executable jar which works. The question:

How do we find the class files never accessed, or image/txt files never used as resources in the jar?

答: Use the Unused Code detector: http://www.ucdetector.org/</p>

ContentLicense: CC BY-SA 2.5


问:
How to put session value store into database?
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

```<code>$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');
</code>```

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

```<code>array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]
</code>```

答:
try like this,

```<code>$orders =  $request->session()->get('order');
print_r($orders);
</code>```

if you getting orders of school id array then you can get it by $orders['school_id']; and if you getting std object then you can retrieve it by $orders->school_id;
Use as per output of print_r(orders)
Then you can store it by

If std object ::

```<code>$order = new Order();
$order->school_id = $orders[0]->school_id;
$order->order_date = $orders[0]->order_date;
$order->time_slot = $orders[0]->time_slot;
$order->save();
</code>```

If array ::

```<code>$order = new Order();
$order->school_id = $orders[0]['school_id'];
$order->order_date = $orders[0]['order_date'];
$order->time_slot = $orders[0]['time_slot'];
$order->save();
</code>```

Body:
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]

Body:
try like this,

$orders =  $request->session()->get('order');
print_r($orders);

if you getting orders of school id array then you can get it by $orders['school_id']; and if you getting std object then you can retrieve it by $orders->school_id;
Use as per output of print_r(orders)
Then you can store it by

If std object ::

$order = new Order();
$order->school_id = $orders[0]->school_id;
$order->order_date = $orders[0]->order_date;
$order->time_slot = $orders[0]->time_slot;
$order->save();

If array ::

$order = new Order();
$order->school_id = $orders[0]['school_id'];
$order->order_date = $orders[0]['order_date'];
$order->time_slot = $orders[0]['time_slot'];
$order->save();


问:
Why is my search form (supposed to hide on click of button) not hiding?
I coded a simple search form that is supposed to hide/show on button click. But it is not working. Here isthe JSFiddle.

HTML:-

```<code><form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="get">
  <div class="input-group">
    <input type="hidden" name="id" value="63">
    <input type="search" name="keywords" class="form-control" placeholder="Search..">
    <div class="input-group-btn">
      <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
        <span class="glyphicon glyphicon-search"></span> <span class="sr-only">Submit</span>
      </button>
    </div>
  </div>
</form>
</code>```

Can you spot the problem in the JSFiddle?

答:
you dont need jquery for a simple show/hide.

anyway i have updated ur fiddle.

document.getElementById('hideForm').onclick = function() {
document.getElementById('hiddenSearchBox').style.display = 'none';
}

//
// hidden search bar to top right.
//

if (typeof jQuery === "undefined") { throw new Error("jQuery required"); }

+function ($) {
  'use strict';

  // SEARCHBAR CLASS DEFINITION
  // =========================

  var backdrop = '.searchbar-backdrop';
  var toggle   = '[data-toggle="searchbar"]';
  var Searchbar = function (element) {
    $(element).on('click.mr.searchbar', this.toggle);
  };

  Searchbar.VERSION = '1.0.0';

  Searchbar.prototype.toggle = function (e) {
    var $this = $(this);

    if ($this.is('.disabled, :disabled')) return;

    var $parent  = getParent($this);
    var isActive = $parent.hasClass('open') || (typeof isXS == 'function' && isXS());

    if (!isActive) {

      clearMenus();
      if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
        // if mobile we use a backdrop because click events don't delegate
        $('
').insertAfter($(this)).on('click', clearMenus);
      }

      var relatedTarget = { relatedTarget: this };
      $parent.trigger(e = $.Event('show.mr.searchbar', relatedTarget));

      if (e.isDefaultPrevented()) return;
      e.preventDefault();

      $parent.find('input').trigger('focus');

      $parent
        .toggleClass('open')
        .trigger('shown.mr.searchbar', relatedTarget);

        return false;
    }
  };

  function clearMenus(e) {
    if (e && e.which === 3) return
    $(backdrop).remove();
    $(toggle).each(function () {
      var $parent = getParent($(this));
      var relatedTarget = { relatedTarget: this };
      if (!$parent.hasClass('open')) return;
      $parent.trigger(e = $.Event('hide.mr.searchbar', relatedTarget));
      if (e.isDefaultPrevented()) return;
      $parent.removeClass('open').trigger('hidden.mr.searchbar', relatedTarget);
    });
  }

  function getParent($this) {
    var selector = $this.attr('data-target');

    if (!selector) {
      return $this.parents('form');
    }

    var $parent = selector && $(selector);

    return $parent && $parent.length ? $parent : $this.parent();
  }

  // SEARCHBAR PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this);
      var data  = $this.data('mr.searchbar');

      if (!data) $this.data('mr.searchbar', (data = new Searchbar(this)));
      if (typeof option == 'string') data[option].call($this);
    });
  }

  var old = $.fn.searchbar;

  $.fn.searchbar             = Plugin;
  $.fn.searchbar.Constructor = Searchbar;

  // SEARCHBAR NO CONFLICT
  // ====================

  $.fn.searchbar.noConflict = function () {
    $.fn.searchbar = old;
    return this;
  };

  // APPLY TO STANDARD SEARCHBAR ELEMENTS
  // ===================================

  $(document)
    .on('click.mr.searchbar.data-api', clearMenus)
    .on('click.mr.searchbar.data-api', '.searchbar', function (e) { e.stopPropagation(); })
    //.on('focus.mr.searchbar.data-api', toggle, Searchbar.prototype.toggle) // this causes the focus event to trigger twice
    .on('click.mr.searchbar.data-api', toggle, Searchbar.prototype.toggle);

}(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- hidden search bar to top right -->
        <form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="get">
          <div class="input-group">
            <input type="hidden" name="id" value="63">
            <input type="search" name="keywords" class="form-control" placeholder="Search..">
            <div class="input-group-btn">
              <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
                <span class="glyphicon glyphicon-search"></span> <span class="sr-only">Submit</span>
              </button>
            </div>
          </div>
        </form>
   <button id="hideForm">
   Hide form
   </button></code>```

Body:
I coded a simple search form that is supposed to hide/show on button click. But it is not working. Here isthe JSFiddle.

HTML:-

<form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="get">

    <input type="hidden" name="id" value="63">
    <input type="search" name="keywords" class="form-control" placeholder="Search..">

      <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
         Submit
      </button>

</form>

Can you spot the problem in the JSFiddle?

Body:
you dont need jquery for a simple show/hide.

anyway i have updated ur fiddle.

document.getElementById('hideForm').onclick = function() {
document.getElementById('hiddenSearchBox').style.display = 'none';
}

//
// hidden search bar to top right.
//

if (typeof jQuery === "undefined") { throw new Error("jQuery required"); }

+function ($) {
  'use strict';

  // SEARCHBAR CLASS DEFINITION
  // =========================

  var backdrop = '.searchbar-backdrop';
  var toggle   = '[data-toggle="searchbar"]';
  var Searchbar = function (element) {
    $(element).on('click.mr.searchbar', this.toggle);
  };

  Searchbar.VERSION = '1.0.0';

  Searchbar.prototype.toggle = function (e) {
    var $this = $(this);

    if ($this.is('.disabled, :disabled')) return;

    var $parent  = getParent($this);
    var isActive = $parent.hasClass('open') || (typeof isXS == 'function' && isXS());

    if (!isActive) {

      clearMenus();
      if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
        // if mobile we use a backdrop because click events don't delegate
        $('<div class="searchbar-backdrop"/>').insertAfter($(this)).on('click', clearMenus);
      }

      var relatedTarget = { relatedTarget: this };
      $parent.trigger(e = $.Event('show.mr.searchbar', relatedTarget));

      if (e.isDefaultPrevented()) return;
      e.preventDefault();

      $parent.find('input').trigger('focus');

      $parent
        .toggleClass('open')
        .trigger('shown.mr.searchbar', relatedTarget);

        return false;
    }
  };

  function clearMenus(e) {
    if (e && e.which === 3) return
    $(backdrop).remove();
    $(toggle).each(function () {
      var $parent = getParent($(this));
      var relatedTarget = { relatedTarget: this };
      if (!$parent.hasClass('open')) return;
      $parent.trigger(e = $.Event('hide.mr.searchbar', relatedTarget));
      if (e.isDefaultPrevented()) return;
      $parent.removeClass('open').trigger('hidden.mr.searchbar', relatedTarget);
    });
  }

  function getParent($this) {
    var selector = $this.attr('data-target');

    if (!selector) {
      return $this.parents('form');
    }

    var $parent = selector && $(selector);

    return $parent && $parent.length ? $parent : $this.parent();
  }

  // SEARCHBAR PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this);
      var data  = $this.data('mr.searchbar');

      if (!data) $this.data('mr.searchbar', (data = new Searchbar(this)));
      if (typeof option == 'string') data[option].call($this);
    });
  }

  var old = $.fn.searchbar;

  $.fn.searchbar             = Plugin;
  $.fn.searchbar.Constructor = Searchbar;

  // SEARCHBAR NO CONFLICT
  // ====================

  $.fn.searchbar.noConflict = function () {
    $.fn.searchbar = old;
    return this;
  };

  // APPLY TO STANDARD SEARCHBAR ELEMENTS
  // ===================================

  $(document)
    .on('click.mr.searchbar.data-api', clearMenus)
    .on('click.mr.searchbar.data-api', '.searchbar', function (e) { e.stopPropagation(); })
    //.on('focus.mr.searchbar.data-api', toggle, Searchbar.prototype.toggle) // this causes the focus event to trigger twice
    .on('click.mr.searchbar.data-api', toggle, Searchbar.prototype.toggle);

}(jQuery);

<!-- hidden search bar to top right -->
        <form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="get">
          <div class="input-group">
            <input type="hidden" name="id" value="63">
            <input type="search" name="keywords" class="form-control" placeholder="Search..">
            <div class="input-group-btn">
              <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
                <span class="glyphicon glyphicon-search"></span> <span class="sr-only">Submit</span>
              </button>
            </div>
          </div>
        </form>
   <button id="hideForm">
   Hide form
   </button>


问:
Config file content management for .net applications
I am looking for a proven approach for management of configuration file (app.config and web.config) and its contents for .NET applications. The objectives are:

Keep the file's content encrypted to eliminate unwanted change by unauthorised way.

Have a user interface to change tags, values for particular sections

Manage which sections are editable

Please let me know approaches taken by you or any standard tool/utility or pattern for the same.

答:
Really curious about your use case. I would consider taking your configuration that needs securing elsewhere. Creating your own separate configuration manager or at least a separate file might make this use case easier.

You can edit some web.config values from IIS management console. Editing tags will typically break your application? What would you look for in an editor that say Notepad.exe can't provide?

You could secure the ASP.NET applications files on the file system, only allowing a specific user or user group access to the web application's files. You will need to configure IIS to run as a user that has appropriate permissions in that case.

Windows file system has some encryption features that you could use to supplement this (no experience with it).

You can also consider just encrypting some relevant value strings in the web.config itself and not the whole file.


问:
Can't resolve all parameters for [Component]
In my generic component I have this squiggly saying:
'Angular: Can't resolve all parameters for BaseCollectionComponent' in [path/base-collection.component.ts: ([object.Object], [object.Object], ?, [object.Object])]'

Here is the code of the component:

```<code>import {BaseRepositoryService} from '../../services/base-repository.service';
import {Component, ComponentRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {BaseComponent} from '../base-component/base.component';
import {CreateCollectionItemModel} from '../../models/create-collection-item.model';
import {ComponentFactoryService} from '../../services/component-factory.service';
import {FrontendSelectorsIds} from '../../globals/frontend-selectors-ids';
import {BaseCollectionItemComponent} from '../base-collection-item/base-collection-item.component';

@Component({
  selector: FrontendSelectorsIds.BaseCollectionSelector,
  templateUrl: './base-collection.component.html',
  styleUrls: ['./base-collection.component.less']
})
export class BaseCollectionComponent<TypeModel> {

  @ViewChild('collectionItemsContainer', {read: ViewContainerRef}) collectionItemsContainer: ViewContainerRef;
  model: TypeModel[];
  components: ComponentRef<BaseComponent<TypeModel>>[];

  constructor(public repository: BaseRepositoryService<TypeModel>,
              public factoryService: ComponentFactoryService<TypeModel, BaseComponent<TypeModel>>,
              public componentType: Type<BaseCollectionItemComponent<TypeModel>>,
              public createCollectionItemModel?: CreateCollectionItemModel) {
    this.components = [];
  }

  loadModel(): void {
    this.repository.getAll()
      .then(results => {
        this.model = results;
        this.onLoadModelComplete();
      });
  }

  destroyChildren(): void {
    if (this.components) {
      for (const component of this.components) {
        component.destroy();
      }
    }
  }

  onLoadModelComplete() {
    this.createComponents(this.model);
  }

  mapResultsToCollection(): void {

  }

  createComponents(model: TypeModel[]): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, this.componentType);
      this.components.push(newComponent);
    }
  }
}
</code>```

Basically this component is made to inject the children list-items components for collections.

First thing I don't really get where the error is pointing me to, but I assume it points to the constructor since there are also 4 parameters. The question mark is pointing to the 3rd position and it is the type parameter that I provide in the child classes.

I have looked up existing problems of the same kind but non of the provided solutions worked for me.

The option to emit decorators metadata (toggle true/false) did't help.

Any suggestions?
In case more code is needed, let me know.
Thanks in advance!

UPDATE

The classes that are used as parameters (the way they are declared):

repository

```<code>@Injectable()
export class ProductRepositoryService extends BaseRepositoryService<Product>
@Injectable()
export abstract class BaseRepositoryService<TypeModel>
</code>```

It is a service base for communication with my bnackend api. It has HttpClient in it injected by Angular. Nothing special.

factoryService

```<code>@Injectable()
export class ComponentFactoryService<TypeModel, TypeCollectionItem extends BaseCollectionItemComponent<TypeModel>>
</code>```

This service takes care of spawning components.

componentType

```<code>export class ProductItemComponent extends BaseCollectionItemComponent<Product> implements OnInit
</code>```

This is a basic component that I use to display list items of a collection.

createCollectionItemModel

```<code>export class CreateCollectionItemModel
</code>```

This is just a class to contain data.

In my opinion this whole problem has something to do with the 3rd parameter, with that type I provide for the factory service. I think there is some kind of mismatch. I was wrestling with it to get it to work. The problem part was to generically pass the type of the desired component to instantiate. Here is the code that makes it all work (at least in the dev mode):

This is the BaseCollectionComponent class call (from the original post):

```<code>createComponents(model: TypeModel[]): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, this.componentType);
      this.components.push(newComponent);
    }
  }
</code>```

Here is the factoryService full code:

```<code>@Injectable()
export class ComponentFactoryService<TypeModel, TypeCollectionItem extends BaseCollectionItemComponent<TypeModel>> {

  rootViewContainer: ViewContainerRef;

  constructor(@Inject(ComponentFactoryResolver) private _factoryResolver: ComponentFactoryResolver) {
  }

  setRootViewContainerRef(viewContainerRef: ViewContainerRef) {
    this.rootViewContainer = viewContainerRef;
  }

  addDynamicComponentWithModel(model: TypeModel, componentType: Type<TypeCollectionItem>): ComponentRef<TypeCollectionItem> {
    const factory = this._factoryResolver.resolveComponentFactory(componentType);
    const component = factory.create(this.rootViewContainer.parentInjector);

    this.rootViewContainer.insert(component.hostView);
    component.instance.model = model;

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

The way I made it work is looking like somewhat generics hell. I hope this will add up to understanding what's wrong here.

答:
Well, it turns out that the 3rd argument to the BaseCollectionComponent constructor indeed caused the problem.
I simply started to unplug one-by-one all the code bits and see if the problem disappears. After I have removed the Type<...<...>> parameter (thew 3rd one) and instead I changed this:

```<code> createComponents(model: TypeModel[]): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, this.componentType);
      this.components.push(newComponent);
    }
  }
</code>```

to this:

```<code>    createComponents(model: TypeModel[], type: any): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, type);
      this.components.push(newComponent);
    }
  }
</code>```

the problem disappeared. Seems that passing a parameter 'of type of type of type' did confuse the angular compiler in some way. I still don't get why would it. If someone could point it out? Anyway, thanks for suggestions everyone.

Body:
In my generic component I have this squiggly saying:
'Angular: Can't resolve all parameters for BaseCollectionComponent' in [path/base-collection.component.ts: ([object.Object], [object.Object], ?, [object.Object])]'

Here is the code of the component:

import {BaseRepositoryService} from '../../services/base-repository.service';
import {Component, ComponentRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {BaseComponent} from '../base-component/base.component';
import {CreateCollectionItemModel} from '../../models/create-collection-item.model';
import {ComponentFactoryService} from '../../services/component-factory.service';
import {FrontendSelectorsIds} from '../../globals/frontend-selectors-ids';
import {BaseCollectionItemComponent} from '../base-collection-item/base-collection-item.component';

@Component({
  selector: FrontendSelectorsIds.BaseCollectionSelector,
  templateUrl: './base-collection.component.html',
  styleUrls: ['./base-collection.component.less']
})
export class BaseCollectionComponent<TypeModel> {

  @ViewChild('collectionItemsContainer', {read: ViewContainerRef}) collectionItemsContainer: ViewContainerRef;
  model: TypeModel[];
  components: ComponentRef<BaseComponent<TypeModel>>[];

  constructor(public repository: BaseRepositoryService<TypeModel>,
              public factoryService: ComponentFactoryService<TypeModel, BaseComponent<TypeModel>>,
              public componentType: Type<BaseCollectionItemComponent<TypeModel>>,
              public createCollectionItemModel?: CreateCollectionItemModel) {
    this.components = [];
  }

  loadModel(): void {
    this.repository.getAll()
      .then(results => {
        this.model = results;
        this.onLoadModelComplete();
      });
  }

  destroyChildren(): void {
    if (this.components) {
      for (const component of this.components) {
        component.destroy();
      }
    }
  }

  onLoadModelComplete() {
    this.createComponents(this.model);
  }

  mapResultsToCollection(): void {

  }

  createComponents(model: TypeModel[]): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, this.componentType);
      this.components.push(newComponent);
    }
  }
}

Basically this component is made to inject the children list-items components for collections.

First thing I don't really get where the error is pointing me to, but I assume it points to the constructor since there are also 4 parameters. The question mark is pointing to the 3rd position and it is the type parameter that I provide in the child classes.

I have looked up existing problems of the same kind but non of the provided solutions worked for me.

The option to emit decorators metadata (toggle true/false) did't help.

Any suggestions?
In case more code is needed, let me know.
Thanks in advance!

UPDATE

The classes that are used as parameters (the way they are declared):

repository

@Injectable()
export class ProductRepositoryService extends BaseRepositoryService<Product>
@Injectable()
export abstract class BaseRepositoryService<TypeModel>

It is a service base for communication with my bnackend api. It has HttpClient in it injected by Angular. Nothing special.

factoryService

@Injectable()
export class ComponentFactoryService<TypeModel, TypeCollectionItem extends BaseCollectionItemComponent<TypeModel>>

This service takes care of spawning components.

componentType

export class ProductItemComponent extends BaseCollectionItemComponent<Product> implements OnInit

This is a basic component that I use to display list items of a collection.

createCollectionItemModel

export class CreateCollectionItemModel

This is just a class to contain data.

In my opinion this whole problem has something to do with the 3rd parameter, with that type I provide for the factory service. I think there is some kind of mismatch. I was wrestling with it to get it to work. The problem part was to generically pass the type of the desired component to instantiate. Here is the code that makes it all work (at least in the dev mode):

This is the BaseCollectionComponent class call (from the original post):

createComponents(model: TypeModel[]): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, this.componentType);
      this.components.push(newComponent);
    }
  }

Here is the factoryService full code:

@Injectable()
export class ComponentFactoryService<TypeModel, TypeCollectionItem extends BaseCollectionItemComponent<TypeModel>> {

  rootViewContainer: ViewContainerRef;

  constructor(@Inject(ComponentFactoryResolver) private _factoryResolver: ComponentFactoryResolver) {
  }

  setRootViewContainerRef(viewContainerRef: ViewContainerRef) {
    this.rootViewContainer = viewContainerRef;
  }

  addDynamicComponentWithModel(model: TypeModel, componentType: Type<TypeCollectionItem>): ComponentRef<TypeCollectionItem> {
    const factory = this._factoryResolver.resolveComponentFactory(componentType);
    const component = factory.create(this.rootViewContainer.parentInjector);

    this.rootViewContainer.insert(component.hostView);
    component.instance.model = model;

    return component;
  }
}

The way I made it work is looking like somewhat generics hell. I hope this will add up to understanding what's wrong here.

Body:
Well, it turns out that the 3rd argument to the BaseCollectionComponent constructor indeed caused the problem.
I simply started to unplug one-by-one all the code bits and see if the problem disappears. After I have removed the Type<...<...>> parameter (thew 3rd one) and instead I changed this:

 createComponents(model: TypeModel[]): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, this.componentType);
      this.components.push(newComponent);
    }
  }

to this:

    createComponents(model: TypeModel[], type: any): void {
    this.factoryService.setRootViewContainerRef(this.collectionItemsContainer);

    for (const item of model) {
      const newComponent = this.factoryService.addDynamicComponentWithModel(item, type);
      this.components.push(newComponent);
    }
  }

the problem disappeared. Seems that passing a parameter 'of type of type of type' did confuse the angular compiler in some way. I still don't get why would it. If someone could point it out? Anyway, thanks for suggestions everyone.


问:
Enable Antiforgery Token with ASP.NET Core and JQuery
I am using JQuery with ASP.NET Core 1.0.1 and I have the Ajax call:

```<code>$("#send-message").on("submit", function (event) {
  event.preventDefault();
  var $form = $(this);
  $.ajax({
    url: "api/messages",
    data: JSON.stringify($form.serializeToJSON()),
    dataType: "json",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    type: "post"
  })
  .done(function (data, status, xhr) { })
  .fail(function (xhr, status, error) { });
</code>```

To the ASP.NET Core action:

```<code>[HttpPost("messages")]
public async Task<IActionResult> Post([FromBody]MessagePostApiModelModel model) {
   // Send message
}
</code>```

The form is in a shared view and it is the following:

```<code><form id="send-question" method="post">
  <textarea name="content"></textarea>
  <button class="button" type="submit">Enviar</button>
</form>
</code>```

When I submit the form I get the error:

```<code>Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery header value "RequestVerificationToken" is not present.
</code>```

How can I enable ASP.NET Core's AntiForgeryToken with JQuery Ajax calls?

UPDATE

I need to add the following asp-controller and asp-action to the form:

```<code><form asp-controller="QuestionApi" asp-action="Post" id="send-question" method="post">
</form>
</code>```

This will generate the antiforgery token. And I needed to manually add the token to the headers of the JQuery call as follows:

```<code>  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "RequestVerificationToken": $form.find("input[name='af_token']").val()
  },
</code>```

Is there a better way to do this?

How do solve this when there is not form and I have only an A tag that when clicked makes the Ajax call? Can I generate a common antiforgery token on my page head to be used by all ajax calls from that page?

答:
Note: This answer applies to ASP.NET Core 2.0. It may not fit to older versions.

Here's what I've done after digging through aspnet's source code for a short while:

```<code>public static class HttpContextExtensions
{
    public static string GetAntiforgeryToken(this HttpContext httpContext)
    {
        var antiforgery = (IAntiforgery)httpContext.RequestServices.GetService(typeof(IAntiforgery));
        var tokenSet = antiforgery.GetAndStoreTokens(httpContext);
        string fieldName = tokenSet.FormFieldName;
        string requestToken = tokenSet.RequestToken;
        return requestToken;
    }
}
</code>```

You can use it in a view like this:

```<code><script>
    var data = {
        yourData: "bla",
        "__RequestVerificationToken": "@Context.GetAntiforgeryToken()"
    };
    $.post("@Url.Action("ActionName")", data);
</script>
</code>```

You might modify the extension method to return the name of the field as well, in any form you wish, e. g. a JSON fragment.

Body:
I am using JQuery with ASP.NET Core 1.0.1 and I have the Ajax call:

$("#send-message").on("submit", function (event) {
  event.preventDefault();
  var $form = $(this);
  $.ajax({
    url: "api/messages",
    data: JSON.stringify($form.serializeToJSON()),
    dataType: "json",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    type: "post"
  })
  .done(function (data, status, xhr) { })
  .fail(function (xhr, status, error) { });

To the ASP.NET Core action:

[HttpPost("messages")]
public async Task<IActionResult> Post([FromBody]MessagePostApiModelModel model) {
   // Send message
}

The form is in a shared view and it is the following:

<form id="send-question" method="post">
  <textarea name="content"></textarea>
  <button class="button" type="submit">Enviar</button>
</form>

When I submit the form I get the error:

Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery header value "RequestVerificationToken" is not present.

How can I enable ASP.NET Core's AntiForgeryToken with JQuery Ajax calls?

UPDATE

I need to add the following asp-controller and asp-action to the form:

<form asp-controller="QuestionApi" asp-action="Post" id="send-question" method="post">
</form>

This will generate the antiforgery token. And I needed to manually add the token to the headers of the JQuery call as follows:

  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "RequestVerificationToken": $form.find("input[name='af_token']").val()
  },

Is there a better way to do this?

How do solve this when there is not form and I have only an A tag that when clicked makes the Ajax call? Can I generate a common antiforgery token on my page head to be used by all ajax calls from that page?

Body:
Note: This answer applies to ASP.NET Core 2.0. It may not fit to older versions.

Here's what I've done after digging through aspnet's source code for a short while:

public static class HttpContextExtensions
{
    public static string GetAntiforgeryToken(this HttpContext httpContext)
    {
        var antiforgery = (IAntiforgery)httpContext.RequestServices.GetService(typeof(IAntiforgery));
        var tokenSet = antiforgery.GetAndStoreTokens(httpContext);
        string fieldName = tokenSet.FormFieldName;
        string requestToken = tokenSet.RequestToken;
        return requestToken;
    }
}

You can use it in a view like this:

<script>
    var data = {
        yourData: "bla",
        "__RequestVerificationToken": "@Context.GetAntiforgeryToken()"
    };
    $.post("@Url.Action("ActionName")", data);
</script>

You might modify the extension method to return the name of the field as well, in any form you wish, e. g. a JSON fragment.


问:
Tests failing with lombok and apt gradle plugin
I have a project with mapstructs and lombok based on the mapstruct-examples/mapstruct-lombok/ but with latests versions and tests part is not working.

Even adding lombok dependency in testCompile the lombok annotations used in tests are failing when executing gradle test task.

The problem starts when I add the apt plugin:

```<code>plugins {
    id 'net.ltgt.apt' version '0.13'
}
</code>```

and the apt at depencencies:

```<code>dependencies {
    ...
    apt "org.mapstruct:mapstruct-processor:${mapstructVersion}", "org.projectlombok:lombok"
    ...
}
</code>```

At this point the lombok annotations stop working and fails in compilaJavaTest gradle task.

Not adding apt plugin makes lombok work properly but then I can't use mapstructs

Any idea?

Thanks.

答: Solved using testApt and the corresponding depencencies.

Body:
I have a project with mapstructs and lombok based on the mapstruct-examples/mapstruct-lombok/ but with latests versions and tests part is not working.

Even adding lombok dependency in testCompile the lombok annotations used in tests are failing when executing gradle test task.

The problem starts when I add the apt plugin:

plugins {
    id 'net.ltgt.apt' version '0.13'
}

and the apt at depencencies:

dependencies {
    ...
    apt "org.mapstruct:mapstruct-processor:${mapstructVersion}", "org.projectlombok:lombok"
    ...
}

At this point the lombok annotations stop working and fails in compilaJavaTest gradle task.

Not adding apt plugin makes lombok work properly but then I can't use mapstructs

Any idea?

Thanks.


问:
Scalacheck - Add parameters to commands
In the Scalacheck documentation for stateful testing an ATM maschine is mentioned as a use case. For it to work, the commands need parameters, for example the PIN or the withdrawal amount. In the given example the methods in the class Counter don't have parameters.

Now my question is how I could test a method like this in scalachecks stateful testing:

```<code>class Counter {
    private var n = 0
    def inc(i: Int) = n += i
    ...
}
</code>```

The run and nextState methods of a command don't offer a parameter. Adding a Random.nextInt wouldn't work, because in run and nextState the value would differ and the test fails:

```<code>case object Inc extends UnitCommand {
    def run(sut: Sut): Unit = sut.inc(Random.nextInt)

    def nextState(state: State): State = state + Random.nextInt
    ...
}
</code>```

Is there any way to pass a parameter to the Sut?

答:
As you may notice from how genCommand, ScalaCheck Commands actually does something like a Cartesian product between initial states generated by genInitialState and series of commands generated by genCommand. So if some of your commands actually need a parameter, you need to convert them into classes from objects and provide a Gen for them. So modifying the example from the docs you will need something like this:

```<code>/** A generator that, given the current abstract state, should produce
  * a suitable Command instance. */
def genCommand(state: State): Gen[Command] = {
  val incGen = for (v <- arbitrary[Int]) yield Inc(v)
  val decGen = for (v <- arbitrary[Int]) yield Dec(v)
  Gen.oneOf(incGen, decGen, Gen.oneOf(Get, Reset))
}

// A UnitCommand is a command that doesn't produce a result
case class Inc(dif: Int) extends UnitCommand {
  def run(sut: Sut): Unit = sut.inc(dif)

  def nextState(state: State): State = state + dif

  // This command has no preconditions
  def preCondition(state: State): Boolean = true

  // This command should always succeed (never throw an exception)
  def postCondition(state: State, success: Boolean): Prop = success
}

case class Dec(dif: Int) extends UnitCommand {
  def run(sut: Sut): Unit = sut.dec(dif)

  def nextState(state: State): State = state - dif

  def preCondition(state: State): Boolean = true

  def postCondition(state: State, success: Boolean): Prop = success
}
</code>```

Note that if your parameters are just constants rather than variables (as is in the case of PIN-code), you should either hard-code them in the commands or make the whole specification class rather than object and pass those parameters from the outside.

Title: Scalacheck - Add parameters to commands

Body:
In the Scalacheck documentation for stateful testing an ATM maschine is mentioned as a use case. For it to work, the commands need parameters, for example the PIN or the withdrawal amount. In the given example the methods in the class Counter don't have parameters.

Now my question is how I could test a method like this in scalachecks stateful testing:

class Counter {
    private var n = 0
    def inc(i: Int) = n += i
    ...
}

The run and nextState methods of a command don't offer a parameter. Adding a Random.nextInt wouldn't work, because in run and nextState the value would differ and the test fails:

case object Inc extends UnitCommand {
    def run(sut: Sut): Unit = sut.inc(Random.nextInt)

    def nextState(state: State): State = state + Random.nextInt
    ...
}

Is there any way to pass a parameter to the Sut?

Body:
As you may notice from how genCommand, ScalaCheck Commands actually does something like a Cartesian product between initial states generated by genInitialState and series of commands generated by genCommand. So if some of your commands actually need a parameter, you need to convert them into classes from objects and provide a Gen for them. So modifying the example from the docs you will need something like this:

/** A generator that, given the current abstract state, should produce
  * a suitable Command instance. */
def genCommand(state: State): Gen[Command] = {
  val incGen = for (v <- arbitrary[Int]) yield Inc(v)
  val decGen = for (v <- arbitrary[Int]) yield Dec(v)
  Gen.oneOf(incGen, decGen, Gen.oneOf(Get, Reset))
}

// A UnitCommand is a command that doesn't produce a result
case class Inc(dif: Int) extends UnitCommand {
  def run(sut: Sut): Unit = sut.inc(dif)

  def nextState(state: State): State = state + dif

  // This command has no preconditions
  def preCondition(state: State): Boolean = true

  // This command should always succeed (never throw an exception)
  def postCondition(state: State, success: Boolean): Prop = success
}

case class Dec(dif: Int) extends UnitCommand {
  def run(sut: Sut): Unit = sut.dec(dif)

  def nextState(state: State): State = state - dif

  def preCondition(state: State): Boolean = true

  def postCondition(state: State, success: Boolean): Prop = success
}

Note that if your parameters are just constants rather than variables (as is in the case of PIN-code), you should either hard-code them in the commands or make the whole specification class rather than object and pass those parameters from the outside.


问:
Data Modeling: Supertype / Subtype
Looking to figure out the proper way to model the below requirements.

There are 3 types of “parties” to be concerned with, a Fan, a Band, and a BandMember.

That BandMember will always be associated with a Band and can also be a Fan of any band.

There are common attributes between a Fan, a Band, and a BandMember, but each of these 3 will also have their own unique attributes.

A Fan can be a fan of of any Band or none at all

This is a small part of a bigger thought but it is creating confusion in expanding the model.  I believe it would have to be diagram 2 or some other option since I don't see how a BandMember can be associated with a Band in the first model.

I appreciate any input.

答:
I think this is simpler than you think. You've got two objects - Band and Person, and they can be connected in two different ways, either as a fan or a member. Here is a quickie db script with no foreign keys or anything:

```<code>CREATE TABLE [dbo].[XREFBandMembers](
    [MemberID] [int] NOT NULL,
    [BandId] [int] NOT NULL,
 CONSTRAINT [PK_XREFBandMembers] PRIMARY KEY CLUSTERED
(
    [MemberID] ASC,
    [BandId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[XREFBandFans](
    [FanId] [int] NOT NULL,
    [BandId] [int] NOT NULL,
 CONSTRAINT [PK_XREFBandFans] PRIMARY KEY CLUSTERED
(
    [FanId] ASC,
    [BandId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[People](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
 CONSTRAINT [PK_People] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Bands](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Bands] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
</code>```

As for the relationship specific attributes, you can place them in the XREF tables, e.g., FanClubMembershipNumber goes in XREFBandFans.

Title: Data Modeling: Supertype / Subtype

Body:
I think this is simpler than you think. You've got two objects - Band and Person, and they can be connected in two different ways, either as a fan or a member. Here is a quickie db script with no foreign keys or anything:

CREATE TABLE [dbo].[XREFBandMembers](
    [MemberID] [int] NOT NULL,
    [BandId] [int] NOT NULL,
 CONSTRAINT [PK_XREFBandMembers] PRIMARY KEY CLUSTERED
(
    [MemberID] ASC,
    [BandId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[XREFBandFans](
    [FanId] [int] NOT NULL,
    [BandId] [int] NOT NULL,
 CONSTRAINT [PK_XREFBandFans] PRIMARY KEY CLUSTERED
(
    [FanId] ASC,
    [BandId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[People](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
 CONSTRAINT [PK_People] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Bands](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Bands] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

As for the relationship specific attributes, you can place them in the XREF tables, e.g., FanClubMembershipNumber goes in XREFBandFans.


问:
pip install returning invalid syntax
I've just installed python 3.6 which comes with pip

However, in Windows command prompt, when I do: 'pip install bs4' it returns 'SyntaxError: invalid syntax' under the install word.

Typing 'python' returns the version, which means it is installed correctly. What could be the problem?

答:
First go to python directory where it was installed on your windows machine by using

cmd

Then go ahead as i did in the picture

Title: pip install returning invalid syntax


问:
Using the reserved word "class" as field name in Django and Django REST Framework

Description of the problem

Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grouped together into taxa (singular: taxon) and these groups are given a taxonomic rank. The principal ranks in modern use are domain, kingdom, phylum, class, order, family, genus and species.
More information on Taxonomy and Taxonomic ranks in Wikipedia.

Following the example for the red fox in the article Taxonomic rank in Wikipedia I need to create a JSON output like this:

```<code>{
    "species": "vulpes",
    "genus": "Vulpes",
    "family": "Canidae",
    "order": "Carnivora",
    "<b>class</b>": "Mammalia",
    "phylum": "Chordata",
    "kingdom": "Animalia",
    "domain": "Eukarya"
}
</code>```

Since Django REST Framework creates the keys based on the field names, the problem arises with the taxonomic rank class (bold in the example) as it is a reserved word in Python and can't be used as a variable name.

What I have tried

A model class created in Django would look like this:

```<code>class Species(models.Model):
    species = models.CharField()
    genus = models.CharField()
    family = models.CharField()
    # class = models.CharField() - class is reserved word in Python
    # class_ = models.CharField() - Django doesn't allow field names
    # ending with underscore. That wouldn't be either a satisfying solution.
    # further fields
</code>```

Question

Is there any possible way to solve this problem and generate the desired output?
If not, what is the best practice to work around this problem?

答:
Other software developers in the field of Bioinformatics might be interested in a solution of this problem, so I post here my approach as suggested by Alasdair.

The goal is to create a model for a living species, for the sake of simplicity let's say an animal, and create an endpoint with Django REST Framework representing the correct taxonomic ranks.

models.py

```<code>from django.db import models

class Animal(models.Model):
    canonical_name = models.CharField(max_length=100, unique=True)
    species = models.CharField(max_length=60, unique=True)
    genus = models.CharField(max_length=30)
    family = models.CharField(max_length=30)
    order = models.CharField(max_length=30)
    # we can't use class as field name
    class_name = models.CharField('Class', db_column='class', max_length=30)
    phylum = models.CharField(max_length=30)
    # we don't need to define kingdom and domain
    # it's clear that it is an animal and eukaryote

    def __str__(self):
        return '{} ({})'.format(self.canonical_name, self.species)
</code>```

serializers.py

```<code>from collections import OrderedDict

from rest_framework import serializers

from .models import Species

class SpeciesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Animal
        fields = ('url', 'id', 'canonical_name', 'species', 'genus',
            'subfamily', 'family', 'order', 'class_name', 'phylum')

    def to_representation(self, obj):
        # call the parent method and get an OrderedDict
        data = super(SpeciesSerializer, self).to_representation(obj)
        # generate a list of the keys and replace the key 'class_name'
        keys = list(data.keys())
        keys.insert(keys.index('class_name'), 'class')
        keys.remove('class_name')
        # remove 'class_name' and assign its value to a new key 'class'
        class_name = data.pop('class_name')
        data.update({'class': class_name})
        # create new OrderedDict with the order given by the keys
        response = OrderedDict((k, data[k]) for k in keys)
        return response
</code>```

The method to_representation helps us to manipulate the output. I have put some extra work here to get the taxonomic ranks in the desired order.

Thus for the red fox the output looks like this:

Red fox (Vulpes vulpes)

```<code>{
    "url": "http://localhost:8000/animal/1",
    "id": 1,
    "canonical_name": "Red fox",
    "species": "Vulpes vulpes",
    "genus": "Vulpes",
    "family": "Canidae",
    "order": "Carnivora",
    "class": "Mammalia",
    "phylum": "Chordata"
}
</code>```

It is a simplified example and in reality you'd have many more fields or possibly a model for every taxonomic rank, but somewhere you might come across the conflict between the reserved word class and the taxonomic rank class.

I hope this can help other people too.

Body:
Description of the problem

Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grouped together into taxa (singular: taxon) and these groups are given a taxonomic rank. The principal ranks in modern use are domain, kingdom, phylum, class, order, family, genus and species.
More information on Taxonomy and Taxonomic ranks in Wikipedia.

Following the example for the red fox in the article Taxonomic rank in Wikipedia I need to create a JSON output like this:

{
    "species": "vulpes",
    "genus": "Vulpes",
    "family": "Canidae",
    "order": "Carnivora",
    "class": "Mammalia",
    "phylum": "Chordata",
    "kingdom": "Animalia",
    "domain": "Eukarya"
}

Since Django REST Framework creates the keys based on the field names, the problem arises with the taxonomic rank class (bold in the example) as it is a reserved word in Python and can't be used as a variable name.

What I have tried

A model class created in Django would look like this:

class Species(models.Model):
    species = models.CharField()
    genus = models.CharField()
    family = models.CharField()
    # class = models.CharField() - class is reserved word in Python
    # class_ = models.CharField() - Django doesn't allow field names
    # ending with underscore. That wouldn't be either a satisfying solution.
    # further fields

Question

Is there any possible way to solve this problem and generate the desired output?
If not, what is the best practice to work around this problem?

Body:
Other software developers in the field of Bioinformatics might be interested in a solution of this problem, so I post here my approach as suggested by Alasdair.

The goal is to create a model for a living species, for the sake of simplicity let's say an animal, and create an endpoint with Django REST Framework representing the correct taxonomic ranks.

models.py

from django.db import models

class Animal(models.Model):
    canonical_name = models.CharField(max_length=100, unique=True)
    species = models.CharField(max_length=60, unique=True)
    genus = models.CharField(max_length=30)
    family = models.CharField(max_length=30)
    order = models.CharField(max_length=30)
    # we can't use class as field name
    class_name = models.CharField('Class', db_column='class', max_length=30)
    phylum = models.CharField(max_length=30)
    # we don't need to define kingdom and domain
    # it's clear that it is an animal and eukaryote

    def __str__(self):
        return '{} ({})'.format(self.canonical_name, self.species)

serializers.py

from collections import OrderedDict

from rest_framework import serializers

from .models import Species

class SpeciesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Animal
        fields = ('url', 'id', 'canonical_name', 'species', 'genus',
            'subfamily', 'family', 'order', 'class_name', 'phylum')

    def to_representation(self, obj):
        # call the parent method and get an OrderedDict
        data = super(SpeciesSerializer, self).to_representation(obj)
        # generate a list of the keys and replace the key 'class_name'
        keys = list(data.keys())
        keys.insert(keys.index('class_name'), 'class')
        keys.remove('class_name')
        # remove 'class_name' and assign its value to a new key 'class'
        class_name = data.pop('class_name')
        data.update({'class': class_name})
        # create new OrderedDict with the order given by the keys
        response = OrderedDict((k, data[k]) for k in keys)
        return response

The method to_representation helps us to manipulate the output. I have put some extra work here to get the taxonomic ranks in the desired order.

Thus for the red fox the output looks like this:

Red fox (Vulpes vulpes)

{
    "url": "http://localhost:8000/animal/1",
    "id": 1,
    "canonical_name": "Red fox",
    "species": "Vulpes vulpes",
    "genus": "Vulpes",
    "family": "Canidae",
    "order": "Carnivora",
    "class": "Mammalia",
    "phylum": "Chordata"
}

It is a simplified example and in reality you'd have many more fields or possibly a model for every taxonomic rank, but somewhere you might come across the conflict between the reserved word class and the taxonomic rank class.

I hope this can help other people too.


问:
Second subscription to a shared mapping from BehaviorSubject does not execute
When I subscribe to a shared mapping from BehaviorSubject instance (t), only first subscription is executed.

When the original BehaviorSubject (obj) emits second value, only the latest value is printed, and both subscriptions were executed.

Let check my code

```<code>const obj = new Rx.BehaviorSubject(1)
obj.subscribe(console.log)
const t = obj.map(u => {
  console.log("mapped")
  return u * 10
}).share()

t.subscribe(x => console.log("subscribe 1 " + x))
t.subscribe(x => console.log("subscribe 2 " + x))
//with the following line un-commented, both subscriptions print out new value
//obj.next(2)
</code>```

My expected result is

```<code>1
mapped
subscribe 1 10
subscribe 2 10
</code>```

but the actual result was

```<code>1
mapped
subscribe 1 10
</code>```

Sorry for the naive question. Is there anyone can explain this to me?

Thank you so much

答:
In your example you have two Subjects:

the BehaviorSubject in obj.

Subject instance inside .share().

Remember that BehaviorSubject emits its cached value only when you subscribe to it.

The first observer obj.subscribe(console.log) subscribes directly to the BehaviorSubject. This prints 1.

Then you create a chain t that ends with the share() operator.

Now you subscribe to t with t.subscribe. This means you subscribe to the Subject inside share() and since this is its first observer it needs to subscribe to its source Observable (which in turn reaches the source BehaviorSubject that emits its cached value). Note that share() is just a shortcut for using the multicast() operator with refCount().

And the last line you subscribe again with t.subscribe. Just like previously this subscribes to the Subject inside share(). However share() already is subscribed to its source Observable so it doesn't make another subscription. That's the point of multicasting and the multicast() operator.

That's why you won't see any subscribe 2 10 and you won't event see mapped printed twice. You're subscribing to the Subject inside share(), not the source BehaviorSubject.

Body:
When I subscribe to a shared mapping from BehaviorSubject instance (t), only first subscription is executed.

When the original BehaviorSubject (obj) emits second value, only the latest value is printed, and both subscriptions were executed.

Let check my code

const obj = new Rx.BehaviorSubject(1)
obj.subscribe(console.log)
const t = obj.map(u => {
  console.log("mapped")
  return u * 10
}).share()

t.subscribe(x => console.log("subscribe 1 " + x))
t.subscribe(x => console.log("subscribe 2 " + x))
//with the following line un-commented, both subscriptions print out new value
//obj.next(2)

My expected result is

1
mapped
subscribe 1 10
subscribe 2 10

but the actual result was

1
mapped
subscribe 1 10

Sorry for the naive question. Is there anyone can explain this to me?

Thank you so much


问:
How to display user input variables in single quotes in Python
I am trying to display user input data in single quotes, but something seems to be going wrong. Can you please help.

For eg:

```<code>name1 = raw_input()
print "[{0}]". format ("'"+ "','".join (str(i) for i in [name1] + "'")
</code>```

However it's working as below:

```
Input-
Jan, Feb
Actual output- ['Jan,Feb']
Expected output- ['Jan','Feb']
```

Can anyone please help

答:
If you want to split the user input to a list, why not, split it?

```<code>name1 = raw_input()
# input Jan, Feb
print name1.split(',')
# output ['Jan', ' Feb']
</code>```

Note that this outputs ['Jan', ' Feb'] so you probably want to use .strip as well, or use ', ' as the split token.

```<code>name1 = raw_input()
# input Jan, Feb
print name1.split(', ')
# output ['Jan', 'Feb']
</code>```

Body:
I am trying to display user input data in single quotes, but something seems to be going wrong. Can you please help.

For eg:

name1 = raw_input()
print "[{0}]". format ("'"+ "','".join (str(i) for i in [name1] + "'")

However it's working as below:

Input-
Jan, Feb
Actual output- ['Jan,Feb']
Expected output- ['Jan','Feb']

Can anyone please help

Body:
If you want to split the user input to a list, why not, split it?

name1 = raw_input()
# input Jan, Feb
print name1.split(',')
# output ['Jan', ' Feb']

Note that this outputs ['Jan', ' Feb'] so you probably want to use .strip as well, or use ', ' as the split token.

name1 = raw_input()
# input Jan, Feb
print name1.split(', ')
# output ['Jan', 'Feb']


问:
How can I call a custom function in "onFilter" in ant design?
I would like to call a custom function in "onFilter" property given by ant design on columns. I can go for the custom filter dropdown as an option but I would like to use the default filter option given by ant design. i.e

```<code>{
  title: 'Address',
  dataIndex: 'address',
  key: 'address',
  filters: [{
    text: 'London',
    value: 'London',
  }, {
    text: 'New York',
    value: 'New York',
  }],
  onFilter: (value, record) => record.address.indexOf(value) === 0,
}
</code>```

But the only thing I need to change here is a custom function (that will trigger the api call and set the new data in the redux state so the component will re render it self) something like

```<code>{
  ...
  onFilter: (value, record) => this.getFilteredData(value),
}
</code>```

But when I do this I get this error which does make sense too.

Warning: setState(…): Cannot update during an existing state
transition

So kindly guide me on how to do that as I am new to react and ant design both.

答:
Dispatching an action inside onFilter is probably not a good idea because it will be called a couple of times on each filter change

But you can edit your reducer to set filterLoading to true when this action getFilteredData is called and the new onFilter can be like this

```<code>  ...
  onFilter: (value) => {
    if(! this.props.filterLoading) {
      this.getFilteredData(value);
    }
    return true;
  }
</code>```

A couple of things to consider

You have to pass filterLoading to the component

Don't forget to set filterLoading to false on GET_FILTERED_DATA_SUCCESS action is called

Hope this helps

Body:
I would like to call a custom function in "onFilter" property given by ant design on columns. I can go for the custom filter dropdown as an option but I would like to use the default filter option given by ant design. i.e

{
  title: 'Address',
  dataIndex: 'address',
  key: 'address',
  filters: [{
    text: 'London',
    value: 'London',
  }, {
    text: 'New York',
    value: 'New York',
  }],
  onFilter: (value, record) => record.address.indexOf(value) === 0,
}

But the only thing I need to change here is a custom function (that will trigger the api call and set the new data in the redux state so the component will re render it self) something like

{
  ...
  onFilter: (value, record) => this.getFilteredData(value),
}

But when I do this I get this error which does make sense too.

Warning: setState(…): Cannot update during an existing state
transition

So kindly guide me on how to do that as I am new to react and ant design both.

Body:
Dispatching an action inside onFilter is probably not a good idea because it will be called a couple of times on each filter change

But you can edit your reducer to set filterLoading to true when this action getFilteredData is called and the new onFilter can be like this

  ...
  onFilter: (value) => {
    if(! this.props.filterLoading) {
      this.getFilteredData(value);
    }
    return true;
  }

A couple of things to consider

You have to pass filterLoading to the component

Don't forget to set filterLoading to false on GET_FILTERED_DATA_SUCCESS action is called

Hope this helps


问:
Using async await properly in node js
To overcome callback hell in javascript, I'm trying to use async await from legacy code written in SQLServer procedure.
But I'm not sure my code might be write properly.

My first confusing point is when async function returns, should it return resolve() as boolean, or just return reject and handle with try-catch?

Here is my code snippets.
Please correct me to right direction.

apiRoutes.js

```<code>app.route('/api/dansok/cancelDansok')
    .post(dansokCancelHandler.cancelDansok);
</code>```

dansokCancelController.js

```<code>const sequelize = models.Sequelize;
const jwt = require('jsonwebtoken');

async function jwtAccessAuthCheck(accessToken) {
  if (!accessToken) {
    return Promise.reject('Empty access token');
  }

  jwt.verify(accessToken,"dipa",function(err){
    if(err) {
      return Promise.reject('TokenExpiredError.');
    } else {
      return Promise.resolve();
    }
  });
}

async function checkFeeHist(dansokSeqNo) {
  let feeHist = await models.FeeHist.findOne({
                  where: { DansokSeqNo: dansokSeqNo}
                });
  return !!feeHist;
}

async function getNextDansokHistSerialNo(dansokSeqNo) {
  ....
}

async function getDansokFee(dansokSeqNo) {
  ....
}

async function doCancel(dansokSeqNo) {
  try {
    if (await !checkFeeHist(dansokSeqNo)) {
      log.error("doCancel() invalid dansokSeqNo for cancel, ", dansokSeqNo);
      return;
    }
    let nextDansokSerialNo =  await getNextDansokHistSerialNo(dansokSeqNo);
    await insertNewDansokHist(dansokSeqNo, nextDansokSerialNo);
    await updateDansokHist(dansokSeqNo);
    await updateVBankList(dansokSeqNo, danokFee.VBankSeqNo);
    await getVBankList(dansokSeqNo);
  } catch (e) {
    log.error("doCancel() exception:", e);
  }
}

exports.cancelDansok = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");
  const dansokSeqNo = req.body.DANSOKSEQNO;
  const discKindCode = req.body.HISTKIND;
  const worker = req.body.PROCWORKER;
  const workerIp = req.body.CREATEIP;
  const accessToken = req.headers.accesstoken;

  //check input parameter
  if (!dansokSeqNo || !discKindCode || !worker || !workerIp) {
    let e = {status:400, message:'params are empty.'};
    return res.status(e.status).json(e);
  }

  try {
    jwtAccessAuthCheck(accessToken)
    .then(() => {
      log.info("jwt success");
      doCancel(dansokSeqNo).then(() => {
        log.info("cancelDansok() finish");
        res.status(200).json({ message: 'cancelDansok success.' });
      });
    });
  } catch(e) {
    return res.status(e.status).json(e);
  }
};
</code>```

答:
You'll need to rewrite jwtAccessAuthCheck(accessToken) so that it keeps track of the outcome of its nested tasks. In the code you've written:

```<code>// Code that needs fixes!
async function jwtAccessAuthCheck(accessToken) {

  // This part is fine. We are in the main async flow.
  if (!accessToken) {
    return Promise.reject('Empty access token');
  }

  // This needs to be rewritten, as the async function itself doesn't know anything about
  // the outcome of `jwt.verify`...
  jwt.verify(accessToken,"dipa",function(err){
    if(err) {
      // This is wrapped in a `function(err)` callback, so the return value is irrelevant
      // to the async function itself
      return Promise.reject('TokenExpiredError.');
    } else {
      // Same problem here.
      return Promise.resolve();
    }
  });

  // Since the main async scope didn't handle anything related to `jwt.verify`, the content
  // below will print even before `jwt.verify()` completes! And the async call will be
  // considered complete right away.
  console.log('Completed before jwt.verify() outcome');

}
</code>```

A better rewrite would be:

```<code>// Fixed code. The outcome of `jwt.verify` is explicitly delegated back to a new Promise's
// `resolve` and `reject` handlers, Promise which we await for.
async function jwtAccessAuthCheck(accessToken) {
  await new Promise((resolve, reject) => {

    if (!accessToken) {
      reject('Empty access token');
      return;
    }

    jwt.verify(accessToken,"dipa",function(err){
      if(err) {
        reject('TokenExpiredError.');
      } else {
        resolve();
      }
    });

  });

  // We won't consider this async call done until the Promise above completes.
  console.log('Completed');

}
</code>```

An alternate signature that would also work in this specific use case:

```<code>// Also works this way without the `async` type:
function jwtAccessAuthCheck(accessToken) {
  return new Promise((resolve, reject) => {
    ...
  });
}
</code>```

Regarding your cancelDansok(req, res) middleware, since jwtAccessAuthCheck is guaranteed to return a Promise (you made it an async function), you'll also need to handle its returned Promise directly. No try / catch can handle the outcome of this asynchronous task.

```<code>exports.cancelDansok = function (req, res) {

  ...

  jwtAccessAuthCheck(accessToken)
    .then(() => {
      log.info("jwt success");
      return doCancel(dansokSeqNo);
    })
    .then(() => {
      log.info("cancelDansok() finish");
      res.status(200).json({ message: 'cancelDansok success.' });
    })
    .catch(e => {
      res.status(e.status).json(e);
    });

};
</code>```

I strongly suggest reading a few Promise-related articles to get the hang of it. They're very handy and powerful, but also bring a little pain when mixed with other JS patterns (async callbacks, try / catch...).

https://www.promisejs.org/

Node.js util.promisify

Title: Using async await properly in node js

Body:
To overcome callback hell in javascript, I'm trying to use async await from legacy code written in SQLServer procedure.
But I'm not sure my code might be write properly.

My first confusing point is when async function returns, should it return resolve() as boolean, or just return reject and handle with try-catch?

Here is my code snippets.
Please correct me to right direction.

apiRoutes.js

app.route('/api/dansok/cancelDansok')
    .post(dansokCancelHandler.cancelDansok);

dansokCancelController.js

const sequelize = models.Sequelize;
const jwt = require('jsonwebtoken');

async function jwtAccessAuthCheck(accessToken) {
  if (!accessToken) {
    return Promise.reject('Empty access token');
  }

  jwt.verify(accessToken,"dipa",function(err){
    if(err) {
      return Promise.reject('TokenExpiredError.');
    } else {
      return Promise.resolve();
    }
  });
}

async function checkFeeHist(dansokSeqNo) {
  let feeHist = await models.FeeHist.findOne({
                  where: { DansokSeqNo: dansokSeqNo}
                });
  return !!feeHist;
}

async function getNextDansokHistSerialNo(dansokSeqNo) {
  ....
}

async function getDansokFee(dansokSeqNo) {
  ....
}

async function doCancel(dansokSeqNo) {
  try {
    if (await !checkFeeHist(dansokSeqNo)) {
      log.error("doCancel() invalid dansokSeqNo for cancel, ", dansokSeqNo);
      return;
    }
    let nextDansokSerialNo =  await getNextDansokHistSerialNo(dansokSeqNo);
    await insertNewDansokHist(dansokSeqNo, nextDansokSerialNo);
    await updateDansokHist(dansokSeqNo);
    await updateVBankList(dansokSeqNo, danokFee.VBankSeqNo);
    await getVBankList(dansokSeqNo);
  } catch (e) {
    log.error("doCancel() exception:", e);
  }
}

exports.cancelDansok = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");
  const dansokSeqNo = req.body.DANSOKSEQNO;
  const discKindCode = req.body.HISTKIND;
  const worker = req.body.PROCWORKER;
  const workerIp = req.body.CREATEIP;
  const accessToken = req.headers.accesstoken;

  //check input parameter
  if (!dansokSeqNo || !discKindCode || !worker || !workerIp) {
    let e = {status:400, message:'params are empty.'};
    return res.status(e.status).json(e);
  }

  try {
    jwtAccessAuthCheck(accessToken)
    .then(() => {
      log.info("jwt success");
      doCancel(dansokSeqNo).then(() => {
        log.info("cancelDansok() finish");
        res.status(200).json({ message: 'cancelDansok success.' });
      });
    });
  } catch(e) {
    return res.status(e.status).json(e);
  }
};

Body:
You'll need to rewrite jwtAccessAuthCheck(accessToken) so that it keeps track of the outcome of its nested tasks. In the code you've written:

// Code that needs fixes!
async function jwtAccessAuthCheck(accessToken) {

  // This part is fine. We are in the main async flow.
  if (!accessToken) {
    return Promise.reject('Empty access token');
  }

  // This needs to be rewritten, as the async function itself doesn't know anything about
  // the outcome of `jwt.verify`...
  jwt.verify(accessToken,"dipa",function(err){
    if(err) {
      // This is wrapped in a `function(err)` callback, so the return value is irrelevant
      // to the async function itself
      return Promise.reject('TokenExpiredError.');
    } else {
      // Same problem here.
      return Promise.resolve();
    }
  });

  // Since the main async scope didn't handle anything related to `jwt.verify`, the content
  // below will print even before `jwt.verify()` completes! And the async call will be
  // considered complete right away.
  console.log('Completed before jwt.verify() outcome');

}

A better rewrite would be:

// Fixed code. The outcome of `jwt.verify` is explicitly delegated back to a new Promise's
// `resolve` and `reject` handlers, Promise which we await for.
async function jwtAccessAuthCheck(accessToken) {
  await new Promise((resolve, reject) => {

    if (!accessToken) {
      reject('Empty access token');
      return;
    }

    jwt.verify(accessToken,"dipa",function(err){
      if(err) {
        reject('TokenExpiredError.');
      } else {
        resolve();
      }
    });

  });

  // We won't consider this async call done until the Promise above completes.
  console.log('Completed');

}

An alternate signature that would also work in this specific use case:

// Also works this way without the `async` type:
function jwtAccessAuthCheck(accessToken) {
  return new Promise((resolve, reject) => {
    ...
  });
}

Regarding your cancelDansok(req, res) middleware, since jwtAccessAuthCheck is guaranteed to return a Promise (you made it an async function), you'll also need to handle its returned Promise directly. No try / catch can handle the outcome of this asynchronous task.

exports.cancelDansok = function (req, res) {

  ...

  jwtAccessAuthCheck(accessToken)
    .then(() => {
      log.info("jwt success");
      return doCancel(dansokSeqNo);
    })
    .then(() => {
      log.info("cancelDansok() finish");
      res.status(200).json({ message: 'cancelDansok success.' });
    })
    .catch(e => {
      res.status(e.status).json(e);
    });

};

I strongly suggest reading a few Promise-related articles to get the hang of it. They're very handy and powerful, but also bring a little pain when mixed with other JS patterns (async callbacks, try / catch...).

https://www.promisejs.org/

Node.js util.promisify


问:
How to get form field in handler Flask?
I have got some input fields in Flask form:

```<code><input type="time" name="time[0]"/>
<input type="time" name="time[1]"/>
<input type="time" name="time[2]"/>
</code>```

I tried to get these input values like:

```<code>values = request.args.get('time')

for v in values
    print v
</code>```

But it does not work for me.

Also as I know correct I can not use <input type="time" name="time[]"/>

答:
A minimal flask server I have,

```<code>from flask import request
from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def login():
    values = request.args.getlist('time[]')
    print values
    values = request.form.getlist('time[]')
    print values

    if request.method == 'POST':
      # The logic may goes here...
      return render_template('test.html')
    else:
        return render_template('test.html')
</code>```

HTML template(test.html) is,

```<code><form method="get">
<input type="time" name="time[]"/>
<input type="time" name="time[]"/>
<input type="time" name="time[]"/>
<input type="time" name="time[]"/>
<input type="submit"/>
</form>
</code>```

When the form is submitted after the times are entered, below is how I'm able to collect the data.

```<code>values = request.args.getlist('time[]')
print values # Printed [u'17:06', u'09:00', u'22:01', u'07:08']
</code>```

When the form's method is changed to "post", I'm getting the data with,

```<code>values = request.form.getlist('time[]')
print values # Printed [u'17:06', u'09:00', u'22:01', u'07:08']
</code>```

Hopefully, should work! Let me know if my snippets have been deviating from your requirement.

Title: How to get form field in handler Flask?

Body:
I have got some input fields in Flask form:

<input type="time" name="time[0]"/>
<input type="time" name="time[1]"/>
<input type="time" name="time[2]"/>

I tried to get these input values like:

values = request.args.get('time')

for v in values
    print v

But it does not work for me.

Also as I know correct I can not use <input type="time" name="time[]"/>

Body:
A minimal flask server I have,

from flask import request
from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def login():
    values = request.args.getlist('time[]')
    print values
    values = request.form.getlist('time[]')
    print values

    if request.method == 'POST':
      # The logic may goes here...
      return render_template('test.html')
    else:
        return render_template('test.html')

HTML template(test.html) is,

<form method="get">
<input type="time" name="time[]"/>
<input type="time" name="time[]"/>
<input type="time" name="time[]"/>
<input type="time" name="time[]"/>
<input type="submit"/>
</form>

When the form is submitted after the times are entered, below is how I'm able to collect the data.

values = request.args.getlist('time[]')
print values # Printed [u'17:06', u'09:00', u'22:01', u'07:08']

When the form's method is changed to "post", I'm getting the data with,

values = request.form.getlist('time[]')
print values # Printed [u'17:06', u'09:00', u'22:01', u'07:08']

Hopefully, should work! Let me know if my snippets have been deviating from your requirement.


问:
java.lang.IllegalStateException: No supported DataSource type found
Spring boot can't create my Postgres datasource. The error is starting here:

```<code>at org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder.getType(DataSourceBuilder.java:138) ~[spring-boot-autoconfigure-1.5.7.RELEASE.jar:1.5.7.RELEASE]
</code>```

Ultimately throwing error:

```<code>Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found
</code>```

I've built Spring Apps using xml configuration and Maven, but Spring Boot and Gradle are new to me. I'm used to @Autowire pulling the datasource from the config file. Based on some SO answers, I added a database config class:

```<code>import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource({ "classpath:application.properties" })
public class DatabaseConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {

        return DataSourceBuilder.create().build();

    }

}
</code>```

I'm trying to autowire the datasource to my JDBC implementation:

```<code>@Component
public class JDBCRegionNameDAO implements RegionNameDAO {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public JDBCRegionNameDAO (DataSource dataSource)  {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

}
</code>```

My application.properties, I've checked my postgres credentials, and ensured the service is running:

```<code>spring.datasource.driver-class-name=org.postgresql.Driver

spring.datasource.url=jdbc:postgresql://localhost:5432/world_builder
spring.datasource.platform=postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
</code>```

My build.gradle, from what I've looked at, it seems that I have everything here that I need, but the error being thrown above suggests I'm missing something:

```<code>buildscript {
    ext {
        springBootVersion = '1.5.7.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

group = 'group.group'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

configurations {
    providedRuntime
}

dependencies {

    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-jdbc')
    compile('org.springframework.boot:spring-boot-starter-web')

    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-devtools')

    compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'

    runtime('org.postgresql:postgresql')

    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

答:
The issue was with the     compile('org.springframework.boot:spring-boot-starter-jdbc') dependency. Changing this to the following solved the issue for me:    compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.5.6.RELEASE'

Possibly the jdbc package or one of its dependencies is no longer supported.

Body:
Spring boot can't create my Postgres datasource. The error is starting here:

at org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder.getType(DataSourceBuilder.java:138) ~[spring-boot-autoconfigure-1.5.7.RELEASE.jar:1.5.7.RELEASE]

Ultimately throwing error:

Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found

I've built Spring Apps using xml configuration and Maven, but Spring Boot and Gradle are new to me. I'm used to @Autowire pulling the datasource from the config file. Based on some SO answers, I added a database config class:

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource({ "classpath:application.properties" })
public class DatabaseConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {

        return DataSourceBuilder.create().build();

    }

}

I'm trying to autowire the datasource to my JDBC implementation:

@Component
public class JDBCRegionNameDAO implements RegionNameDAO {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public JDBCRegionNameDAO (DataSource dataSource)  {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

}

My application.properties, I've checked my postgres credentials, and ensured the service is running:

spring.datasource.driver-class-name=org.postgresql.Driver

spring.datasource.url=jdbc:postgresql://localhost:5432/world_builder
spring.datasource.platform=postgres
spring.datasource.username=postgres
spring.datasource.password=postgres

My build.gradle, from what I've looked at, it seems that I have everything here that I need, but the error being thrown above suggests I'm missing something:

buildscript {
    ext {
        springBootVersion = '1.5.7.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

group = 'group.group'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

configurations {
    providedRuntime
}

dependencies {

    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-jdbc')
    compile('org.springframework.boot:spring-boot-starter-web')

    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-devtools')

    compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'

    runtime('org.postgresql:postgresql')

    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}


问:
JSON URL specific item to DIV
```<code><html>
<script>
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: todos1
    });
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>
</code>```

how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

```<code><div id="3rd_title_here">fugiat veniam minus</div>
</code>```

to any ones curiousity this is what the JSON structure looks like if u view the URL link

```<code>{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}
</code>```

答:
thx alot guys it works now :D
i just forgot to put jquery js

```<code><html>
<head></head>
<div id="3rd_title_here"></div>
 <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="script.js"></script>
</html>
</code>```

JScript here

```<code>    function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "jsonp",
        url: TODOS,
        success: function(data) {
          $('#3rd_title_here').html(data[3].title);
        }
    });
}
setInterval(gettodo(),1000);
</code>```

Title: JSON URL specific item to DIV

Body:
how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

fugiat veniam minus

to any ones curiousity this is what the JSON structure looks like if u view the URL link

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}

Body:
thx alot guys it works now :D
i just forgot to put jquery js

<html>
<head></head>
<div id="3rd_title_here"></div>
 <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="script.js"></script>
</html>

JScript here

    function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "jsonp",
        url: TODOS,
        success: function(data) {
          $('#3rd_title_here').html(data[3].title);
        }
    });
}
setInterval(gettodo(),1000);