问:
Esri Arc Online using API to see filter result into a simple web page
I need to create a simple webpage where I can see the result of filters in arc online into it instead of creating the filter each day. By that, the results will be refreshed automatically each day when I log in into arc gis.

I heard that there is an API, is my idea is feasible ?

答:
Assuming you want to filter a FeatureLayer--the original question is unclear, but FeatureLayer seems logical--you should set the definitionExpression property, as described in the FeatureLayer documentation.

Here's an example:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
  <title>FeatureLayer - 4.3</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.3/esri/css/main.css">
  <script src="https://js.arcgis.com/4.3/"></script>

  <style>
    html,
    body,
    #viewDiv {
      padding: 0;
      margin: 0;
      height: 100%;
      width: 100%;
    }
    #filterDiv {
      position: absolute;
      top: 12px;
      right: 12px;
      padding: 12px;
      background-color: rgba(0, 0, 0, 0.5);
      color: white;
    }
  </style>

  <script>
    require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/FeatureLayer",
        "dojo/dom",
        "dojo/on",
        "dojo/domReady!"
      ],
      function(
        Map,
        MapView,
        FeatureLayer,
        dom,
        on
      ) {

        var map = new Map({
          basemap: "hybrid"
        });

        var view = new MapView({
          container: "viewDiv",
          map: map,

          extent: {
            xmin: -9177811,
            ymin: 4247000,
            xmax: -9176791,
            ymax: 4247784,
            spatialReference: 102100
          }
        });

        var featureLayer = new FeatureLayer({
          url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Landscape_Trees/FeatureServer/0",
          definitionExpression: "Sci_Name = 'Ulmus pumila'"
        });

        map.add(featureLayer);

        view.then(function() {
          on(dom.byId("filterInput"), "change", updateFilter);

          function updateFilter(ev) {
            featureLayer.definitionExpression = ev.target.checked ?
                "Sci_Name = 'Ulmus pumila'" :
                undefined;
          }
        });

      });
  </script>
</head>

<body>
  <div id="viewDiv"></div>
  <div id="filterDiv">
    <label>Filter
      <input id="filterInput" type="checkbox" checked="yes">
    </label>
  </div>
</body>

</html>
</code>```

Body:
Assuming you want to filter a FeatureLayer--the original question is unclear, but FeatureLayer seems logical--you should set the definitionExpression property, as described in the FeatureLayer documentation.

Here's an example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
  <title>FeatureLayer - 4.3</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.3/esri/css/main.css">
  <script src="https://js.arcgis.com/4.3/"></script>

  <style>
    html,
    body,
    #viewDiv {
      padding: 0;
      margin: 0;
      height: 100%;
      width: 100%;
    }
    #filterDiv {
      position: absolute;
      top: 12px;
      right: 12px;
      padding: 12px;
      background-color: rgba(0, 0, 0, 0.5);
      color: white;
    }
  </style>

  <script>
    require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/FeatureLayer",
        "dojo/dom",
        "dojo/on",
        "dojo/domReady!"
      ],
      function(
        Map,
        MapView,
        FeatureLayer,
        dom,
        on
      ) {

        var map = new Map({
          basemap: "hybrid"
        });

        var view = new MapView({
          container: "viewDiv",
          map: map,

          extent: {
            xmin: -9177811,
            ymin: 4247000,
            xmax: -9176791,
            ymax: 4247784,
            spatialReference: 102100
          }
        });

        var featureLayer = new FeatureLayer({
          url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Landscape_Trees/FeatureServer/0",
          definitionExpression: "Sci_Name = 'Ulmus pumila'"
        });

        map.add(featureLayer);

        view.then(function() {
          on(dom.byId("filterInput"), "change", updateFilter);

          function updateFilter(ev) {
            featureLayer.definitionExpression = ev.target.checked ?
                "Sci_Name = 'Ulmus pumila'" :
                undefined;
          }
        });

      });
  </script>
</head>

<body>
  <div id="viewDiv"></div>
  <div id="filterDiv">
    <label>Filter
      <input id="filterInput" type="checkbox" checked="yes">
    </label>
  </div>
</body>

</html>


来源: stackexchange

问:
Hide a dynamic element function on.('hide')
I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?

Thanks

```<code>function openModalFromUrl(modal_url, close_function = function(){}) {

    var token = $("meta[name='csrf-token']").attr("content");

    $.ajax({
        data: {
            '_token': token,
        },
        url: modal_url,
        type: 'POST',
        success: function(html) {

            // create a new modal div
            var modal = document.createElement("div");
            $(modal).addClass('modal fade');
            $(modal).attr( "role", "dialog" );

            $('body').append(modal);

            // place response in the modal
            $(modal).html(html)

            // open the modal
            $(modal).modal('show');

            // THIS FIRES IMMEDIATELY
            $(modal).on('hide', window[close_function]() );

        },

        error: function() {
            bootbox.alert('Error');
        }

    });

}
</code>```

答:
Thank you to all for your answers. I have found the solution.
As the modals were dynamically generated i had to change the call to:

```<code> $('body').on('hide.bs.modal', modal, window[close_function] );
</code>```

Now it works like a charm. Thanks again to everyone!

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?

Thanks

function openModalFromUrl(modal_url, close_function = function(){}) {

    var token = $("meta[name='csrf-token']").attr("content");

    $.ajax({
        data: {
            '_token': token,
        },
        url: modal_url,
        type: 'POST',
        success: function(html) {

            // create a new modal div
            var modal = document.createElement("div");
            $(modal).addClass('modal fade');
            $(modal).attr( "role", "dialog" );

            $('body').append(modal);

            // place response in the modal
            $(modal).html(html)

            // open the modal
            $(modal).modal('show');

            // THIS FIRES IMMEDIATELY
            $(modal).on('hide', window[close_function]() );

        },

        error: function() {
            bootbox.alert('Error');
        }

    });

}

Body:
Thank you to all for your answers. I have found the solution.
As the modals were dynamically generated i had to change the call to:

 $('body').on('hide.bs.modal', modal, window[close_function] );

Now it works like a charm. Thanks again to everyone!


问:
F# Unit Test Error: xUnit.net / TestDriven.Net
So the following I got from Pluralsight and the chap presenting the course apparently runs the code without a hitch, however, when I run it, I get the error message:

"Test failed ‘T:Messaging’ : Couldn’t find type with name ‘Messaging’"

Test failed 'T: Couldn't find type with name

Any Ideas (appreciated)?

```<code>namespace Ploeh.Samples

open System

module Messaging =
    type Envelope<'a> = {
        Id      : Guid
        Created : DateTimeOffset
        Item    : 'a }

    let envelop getId getTime item = {
        Id = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
        Created = DateTimeOffset.MinValue
        Item = item }

module MessagingTests =
    open Xunit

    type Foo = { Text : string; Number : int }

    [<Fact>]
    let ``enevelope returns correct results`` () =
        let getId _ = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
        let getTime _ = DateTimeOffset( 636322011751405346L,
                                        TimeSpan.FromHours(-4.0) )
        let item = { Text = "Bar"; Number = 42 }

        let actual = Messaging.envelop getId getTime item

        Assert.Equal ( Guid "1CF889F8-201F-44DF-BC86-77227651D3EE",
                       actual.Id )
        Assert.Equal ( DateTimeOffset( 636322011751405346L,
                                       TimeSpan.FromHours(-4.0) ),
                       actual.Created )
        Assert.Equal ( item, actual.Item )
</code>```

答:
I managed to get it working by separating the tests into a separate file and top-level module. For some reason, anything other than this `setup' does not work, e.g., separate file but in a lower-level module, or namespace and module declarations separately ... I am not sure whether this is something specific to say my target being .Net 4.7 rather than whatever used by the instructor or an issue with Visual Studio 2017, or something else. It seems that TestDriven.Net takes issue with the namespace/module system and gets confused by them ...

In the first file:

```<code>namespace Ploeh.Samples

open System

module Messaging =
    type Envelope<'a> = {
        Id      : Guid
        Created : DateTimeOffset
        Item    : 'a }

    let envelop getId getTime item = {
        Id = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
        Created = DateTimeOffset.MinValue
        Item = item }
</code>```

And in the second file:

```<code>module Ploeh.Samples.MessagingTests

open System
open Messaging
open Xunit

type Foo = { Text : string; Number : int }

[<Fact>]
let ``enevelope returns correct results`` () =
let getId _ = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
let getTime _ = DateTimeOffset( 636322011751405346L,
                                TimeSpan.FromHours(-4.0) )
let item = { Text = "Bar"; Number = 42 }

let actual = Messaging.envelop getId getTime item

Assert.Equal ( Guid "1CF889F8-201F-44DF-BC86-77227651D3EE",
               actual.Id )
Assert.Equal ( DateTimeOffset( 636322011751405346L,
                               TimeSpan.FromHours(-4.0) ),
               actual.Created )
Assert.Equal ( item, actual.Item )
</code>```

Body:
So the following I got from Pluralsight and the chap presenting the course apparently runs the code without a hitch, however, when I run it, I get the error message:

"Test failed ‘T:Messaging’ : Couldn’t find type with name ‘Messaging’"

Test failed 'T: Couldn't find type with name

Any Ideas (appreciated)?

namespace Ploeh.Samples

open System

module Messaging =
    type Envelope<'a> = {
        Id      : Guid
        Created : DateTimeOffset
        Item    : 'a }

    let envelop getId getTime item = {
        Id = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
        Created = DateTimeOffset.MinValue
        Item = item }

module MessagingTests =
    open Xunit

    type Foo = { Text : string; Number : int }

    [<Fact>]
    let ``enevelope returns correct results`` () =
        let getId _ = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
        let getTime _ = DateTimeOffset( 636322011751405346L,
                                        TimeSpan.FromHours(-4.0) )
        let item = { Text = "Bar"; Number = 42 }

        let actual = Messaging.envelop getId getTime item

        Assert.Equal ( Guid "1CF889F8-201F-44DF-BC86-77227651D3EE",
                       actual.Id )
        Assert.Equal ( DateTimeOffset( 636322011751405346L,
                                       TimeSpan.FromHours(-4.0) ),
                       actual.Created )
        Assert.Equal ( item, actual.Item )

Body:
I managed to get it working by separating the tests into a separate file and top-level module. For some reason, anything other than this `setup' does not work, e.g., separate file but in a lower-level module, or namespace and module declarations separately ... I am not sure whether this is something specific to say my target being .Net 4.7 rather than whatever used by the instructor or an issue with Visual Studio 2017, or something else. It seems that TestDriven.Net takes issue with the namespace/module system and gets confused by them ...

In the first file:

namespace Ploeh.Samples

open System

module Messaging =
    type Envelope<'a> = {
        Id      : Guid
        Created : DateTimeOffset
        Item    : 'a }

    let envelop getId getTime item = {
        Id = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
        Created = DateTimeOffset.MinValue
        Item = item }

And in the second file:

module Ploeh.Samples.MessagingTests

open System
open Messaging
open Xunit

type Foo = { Text : string; Number : int }

[<Fact>]
let ``enevelope returns correct results`` () =
let getId _ = Guid "1CF889F8-201F-44DF-BC86-77227651D3EE"
let getTime _ = DateTimeOffset( 636322011751405346L,
                                TimeSpan.FromHours(-4.0) )
let item = { Text = "Bar"; Number = 42 }

let actual = Messaging.envelop getId getTime item

Assert.Equal ( Guid "1CF889F8-201F-44DF-BC86-77227651D3EE",
               actual.Id )
Assert.Equal ( DateTimeOffset( 636322011751405346L,
                               TimeSpan.FromHours(-4.0) ),
               actual.Created )
Assert.Equal ( item, actual.Item )


问:
C# - FrameworkElement.FindName returns null
I spent the past one hour trying to figure this out. I have a CheckBox inside DataGrid as follows:

```<code><DataGridTemplateColumn>
    <DataGridTemplateColumn.Header>
        <CheckBox Name="chkall" Content="Select All" Checked="chkall_Checked" Unchecked="chkall_Unchecked"/>
    </DataGridTemplateColumn.Header>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Tag="{Binding Path=id}" x:Name="chksingle"  Checked="chksingle_Checked" Unchecked="chksingle_Unchecked"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code>```

As you can see I am trying to check and uncheck the CheckBoxes inside DataGrid rows when the CheckBox in the header is checked or unchecked. This is the code where I am trying to retrieve the CheckBox and mark it as checked:

```<code>private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row =(DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        FW_element.ApplyTemplate();
        var checkbox = FW_element.FindName("chksingle") as CheckBox;
        checkbox.IsChecked = false;
    }
}
</code>```

I have already tried RegisterName() method and I've tried VisualTreeHelper but nothing works.

This line always returns null:

```<code>var checkbox = FW_element.FindName("chksingle") as CheckBox;
</code>```

Here is a WPF visualizer screenshot for my FrameworkElement where I can clearly see the checkbox I am trying to find:

Please tell me what am I doing wrong? Thank you.

答:
The thing is that a DataTemplate is a name scope boundary, that is the templated element (a ContentPresenter in this case) or any of it's ancestors are not aware of named elements defined inside the template. In order to find a named element inside the template you need to use  the DataTemplate.FindName method instead (inherited from FrameworkTemplate). Notice that it takes two parameters instead of one, the second one being the templated element. This should do the trick for you:

```<code>private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row = (DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        //We use the CellTemplate defined on the column to find the CheckBox
        var checkbox = ((DataGridTemplateColumn)userDG.Columns[0]).CellTemplate.FindName("chksingle", FW_element) as CheckBox;
        checkbox.IsChecked = true;
    }
}
</code>```

Body:
I spent the past one hour trying to figure this out. I have a CheckBox inside DataGrid as follows:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.Header>
        <CheckBox Name="chkall" Content="Select All" Checked="chkall_Checked" Unchecked="chkall_Unchecked"/>
    </DataGridTemplateColumn.Header>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Tag="{Binding Path=id}" x:Name="chksingle"  Checked="chksingle_Checked" Unchecked="chksingle_Unchecked"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

As you can see I am trying to check and uncheck the CheckBoxes inside DataGrid rows when the CheckBox in the header is checked or unchecked. This is the code where I am trying to retrieve the CheckBox and mark it as checked:

private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row =(DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        FW_element.ApplyTemplate();
        var checkbox = FW_element.FindName("chksingle") as CheckBox;
        checkbox.IsChecked = false;
    }
}

I have already tried RegisterName() method and I've tried VisualTreeHelper but nothing works.

This line always returns null:

var checkbox = FW_element.FindName("chksingle") as CheckBox;

Here is a WPF visualizer screenshot for my FrameworkElement where I can clearly see the checkbox I am trying to find:

Please tell me what am I doing wrong? Thank you.

Body:
The thing is that a DataTemplate is a name scope boundary, that is the templated element (a ContentPresenter in this case) or any of it's ancestors are not aware of named elements defined inside the template. In order to find a named element inside the template you need to use  the DataTemplate.FindName method instead (inherited from FrameworkTemplate). Notice that it takes two parameters instead of one, the second one being the templated element. This should do the trick for you:

private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row = (DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        //We use the CellTemplate defined on the column to find the CheckBox
        var checkbox = ((DataGridTemplateColumn)userDG.Columns[0]).CellTemplate.FindName("chksingle", FW_element) as CheckBox;
        checkbox.IsChecked = true;
    }
}


问:
Why is my event on body called before event on specific element?
I have this code in my project which is using Foundation 5.5.3

```<code>$(function() {
  var $carsDropdown = $("#cars-dropdown");

  // Close cars dropdown when clicking outside of it or on close button
  $("body, #cars-dropdown .btn-close").click(function(ev) {
    if ($carsDropdown.hasClass("open")) {
      console.log("Dropdown is open");
      console.log("Closing dropdown.\n");
      Foundation.libs.dropdown.close($carsDropdown);
      // ev.stopPropagation();
    }
    else {
      console.log("Dropdown is closed\n");
    }
  });
);
</code>```

I am expecting this to close the div when I click on body and that works.
It also works perfectly when I click on .btn-close.

But when I click on element which should open and close the dropdown using foundation code, nothing happens.
Console output is this:

```<code>Dropdown is open.
Closing dropdown.
</code>```

Just like when I click on .btn-close.

From this I am concluding that somehow event on body gets triggered before foundation event on button which should toggle the dropdown.
My event closes the dropdown and foundation code toggles it open.

How is it possible that body event is not triggered last? Aren't events supposed to bubble from inner most element to body tag last?

Now when I uncomment the ev.stopPropagation() line, everything works as expected. Click on body prevents propagation to some other element? How is this possible?

For testing please using this codepen: https://codepen.io/anon/pen/BZyRLp

答:
Their event listener is most likely delegated to document so you can add such functionality dynamically.

That is why you see the body event before class is added

Check the target and don't do anything if it is a data-dropdown element

```<code>$("body, #cars-dropdown .btn-close").click(function(e) {

  if (!$(e.target).closest('[data-dropdown]').length) {

    if ($carsDropdown.hasClass("open")) {
      console.log("Dropdown is open");
      console.log("Closing dropdown.\n");
      Foundation.libs.dropdown.close($carsDropdown);
    } else {
      console.log("Dropdown is closed\n");
    }
  } else {
    console.log('Foundation Dropdown button');
  }
});
</code>```

Body:
I have this code in my project which is using Foundation 5.5.3

$(function() {
  var $carsDropdown = $("#cars-dropdown");

  // Close cars dropdown when clicking outside of it or on close button
  $("body, #cars-dropdown .btn-close").click(function(ev) {
    if ($carsDropdown.hasClass("open")) {
      console.log("Dropdown is open");
      console.log("Closing dropdown.\n");
      Foundation.libs.dropdown.close($carsDropdown);
      // ev.stopPropagation();
    }
    else {
      console.log("Dropdown is closed\n");
    }
  });
);

I am expecting this to close the div when I click on body and that works.
It also works perfectly when I click on .btn-close.

But when I click on element which should open and close the dropdown using foundation code, nothing happens.
Console output is this:

Dropdown is open.
Closing dropdown.

Just like when I click on .btn-close.

From this I am concluding that somehow event on body gets triggered before foundation event on button which should toggle the dropdown.
My event closes the dropdown and foundation code toggles it open.

How is it possible that body event is not triggered last? Aren't events supposed to bubble from inner most element to body tag last?

Now when I uncomment the ev.stopPropagation() line, everything works as expected. Click on body prevents propagation to some other element? How is this possible?

For testing please using this codepen: https://codepen.io/anon/pen/BZyRLp

Body:
Their event listener is most likely delegated to document so you can add such functionality dynamically.

That is why you see the body event before class is added

Check the target and don't do anything if it is a data-dropdown element

$("body, #cars-dropdown .btn-close").click(function(e) {

  if (!$(e.target).closest('[data-dropdown]').length) {

    if ($carsDropdown.hasClass("open")) {
      console.log("Dropdown is open");
      console.log("Closing dropdown.\n");
      Foundation.libs.dropdown.close($carsDropdown);
    } else {
      console.log("Dropdown is closed\n");
    }
  } else {
    console.log('Foundation Dropdown button');
  }
});


问:
Asdocs seems unable to find embedded assets
I'm running asdocs from a .bat file with flex sdk 3.2.0 (I have replaced my long project root folder with PROJECTROOT):

```<code>"C:\Program Files (x86)\Adobe\Flex Builder 3\sdks\3.2.0\bin\asdoc" -source-path . "C:\Program Files (x86)\Adobe\Flex Builder 3\sdks\3.2.0" "_PROJECTROOT_\Components\src" "C:\_PROJECTROOT_\assets" -doc-sources .
PAUSE"
</code>```

Unforunately, I keep getting errors similar to this:

```<code>"_PROJECTROOT_\assets\styles.css(344): Error: Invalid Embed directive in stylesheet - can't resolve source 'Embed(source = "close_button.png")'.

downSkin: Embed(source="close_button.png");"
</code>```

I really don't understand this as "close_button.png" is in the same folder as styles.css. When I build the project from within flexbuilder, it compiles it fine and does not throw any errors.

Does anyone know what I'm doing wrong?

答:
I had a similar problem, and an answer I found elsewhere indicated to put a slash at the beginning of the asset path. That is, instead of </p>

```<code>Embed(source="close_button.png")
</code>```

<p>rather </p>

```<code>Embed(source="/close_button.png")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm running asdocs from a .bat file with flex sdk 3.2.0 (I have replaced my long project root folder with PROJECTROOT):

"C:\Program Files (x86)\Adobe\Flex Builder 3\sdks\3.2.0\bin\asdoc" -source-path . "C:\Program Files (x86)\Adobe\Flex Builder 3\sdks\3.2.0" "_PROJECTROOT_\Components\src" "C:\_PROJECTROOT_\assets" -doc-sources .
PAUSE"

Unforunately, I keep getting errors similar to this:

"_PROJECTROOT_\assets\styles.css(344): Error: Invalid Embed directive in stylesheet - can't resolve source 'Embed(source = "close_button.png")'.

downSkin: Embed(source="close_button.png");"

I really don't understand this as "close_button.png" is in the same folder as styles.css. When I build the project from within flexbuilder, it compiles it fine and does not throw any errors.

Does anyone know what I'm doing wrong?

Body:
I had a similar problem, and an answer I found elsewhere indicated to put a slash at the beginning of the asset path. That is, instead of

Embed(source="close_button.png")

rather

Embed(source="/close_button.png")


问:
Embeding bokeh plot into a template (django)
I'm trying to embed a bokeh plot into a template (home.html), but nothing is displayed after executing the code.
here's the code.

views.py (all packages are imported)

def home(request):

```<code>s = [1,4,6,8]
h = [1,5,9,8]

p = figure(plot_width=600, plot_height=600)
p.vbar(x=s, width=0.5, bottom=0,
       top=h, color="black")

script, div = components(p, CDN)
return render(request, 'home.html', {'div': div, 'script': script})
</code>```

home.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Experiment with Bokeh</title>

    <link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">

hello

    {{ div|safe }}

    {{ script|safe }}

```

it displays nothing at the end, there's no error message, but and the page is completely blank

Help, Please!!

答:
You are loading an ancient version of BokehJS from CDN:

```<code><script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">
</code>```

The 0.8.1 release is now several years old. By contrast, the vbar glyph method that you are using was only added quite recently. You need to make sure that the version of the BokehJS resources that you load in your template actually match the version of the Bokeh library that you are using.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to embed a bokeh plot into a template (home.html), but nothing is displayed after executing the code.
here's the code.

views.py (all packages are imported)

def home(request):

s = [1,4,6,8]
h = [1,5,9,8]

p = figure(plot_width=600, plot_height=600)
p.vbar(x=s, width=0.5, bottom=0,
       top=h, color="black")

script, div = components(p, CDN)
return render(request, 'home.html', {'div': div, 'script': script})

home.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Experiment with Bokeh</title>

    <link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">

hello

    {{ div|safe }}

    {{ script|safe }}

it displays nothing at the end, there's no error message, but and the page is completely blank

Help, Please!!

Body:
You are loading an ancient version of BokehJS from CDN:

<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">

The 0.8.1 release is now several years old. By contrast, the vbar glyph method that you are using was only added quite recently. You need to make sure that the version of the BokehJS resources that you load in your template actually match the version of the Bokeh library that you are using.


问:
Count keywords occurrence in a file to another file
I have two files File1 and File2. I have to find keywords in File2 to File1 and count it. Lines in File1 that don't have any keywords in File2 shall be counted as OTHERS and probably save it in File3 (for validation).

File1

```<code> 000001111YYYY0000
 122334YYYY9999
 89898989AAAA89899
 AAAA7678989812234
 ZZZZ878098098098
 0000000000000000
</code>```

File2

```<code>YYYY
AAAA
ZZZZ
</code>```

Output

```<code>YYYY: 2
AAAA: 2
ZZZZ: 1
OTHERS: 1
</code>```

File3 (OTHERS)

```<code>0000000000000000
</code>```

The way I know is to count the keywords using grep and wc -l, and its not ideal especially when I have many keywords to find.

答:
try: If you are not bothering about the sequence of the output as per file1 or file2 then following may help you.

```<code>awk 'FNR==NR{A[$0];next} {gsub(/[0-9]/,"");} ($0 in A){B[$0]++;next} !($0 in A) && $0{OTHERS[$0]++} END{for(i in B){print i": "B[i]};for(j in OTHERS){print j": "OTHERS[j]}}' file2  file1
</code>```

Will add description shortly too.

EDIT1: Adding code in non-one liner form and with proper explanation too here.

```<code>awk 'FNR==NR{                                                 #### FNR==NR condition will be TRUE when first file file2 is being read, FNR and NR are awks built-in variables, both re-present line numbers of files only difference between them is FNR gets re-set whenever a new file is getting started and NRs value will be keep on increasing till all files get read.
                A[$0];                                        #### creating an array whose index is $0(current line) of file2.
                next                                          #### using next keyword for skipping all the next statements.
            }
            {
                VAL=$0;                                       #### creating a variable named VAL which has current lines value.
                gsub(/[0-9]/,"");                             #### gsub is awks built-in function to globally substituting all the digits to NULL in lines for file1.
            }
     ($0 in A){                                               #### now checking if new-edited $0(current line) is present in array A then do following statements.
                B[$0]++;                                      #### creating an array named B with index of $0 and incrementing its value with 1 each time.
                next                                          #### using next keyword for skipping all the next statements.
              }
     !($0 in A){                                              #### If current line is NOT present in array A.
                        OTHERS[VAL]++                         #### create an array named OTHERS with index of variable VAL and increment its value with 1 each time it comes in this section.
                     }
     END{                                                     #### Starting END section here for awk.
                for(i in B){                                  #### Traversing through array B now.
                                print i": "B[i]               #### printing the index of array B and its respective value now.
                           };
                for(j in OTHERS){                             #### Traversing through array OTHERS now.
                                        print j": "OTHERS[j]  #### printing index of array B with its value too.
                                }
        }
    ' file2  file1                                            #### Mentioning the Input_files now.
</code>```

Body:
I have two files File1 and File2. I have to find keywords in File2 to File1 and count it. Lines in File1 that don't have any keywords in File2 shall be counted as OTHERS and probably save it in File3 (for validation).

File1

 000001111YYYY0000
 122334YYYY9999
 89898989AAAA89899
 AAAA7678989812234
 ZZZZ878098098098
 0000000000000000

File2

YYYY
AAAA
ZZZZ

Output

YYYY: 2
AAAA: 2
ZZZZ: 1
OTHERS: 1

File3 (OTHERS)

0000000000000000

The way I know is to count the keywords using grep and wc -l, and its not ideal especially when I have many keywords to find.

Body:
try: If you are not bothering about the sequence of the output as per file1 or file2 then following may help you.

awk 'FNR==NR{A[$0];next} {gsub(/[0-9]/,"");} ($0 in A){B[$0]++;next} !($0 in A) && $0{OTHERS[$0]++} END{for(i in B){print i": "B[i]};for(j in OTHERS){print j": "OTHERS[j]}}' file2  file1

Will add description shortly too.

EDIT1: Adding code in non-one liner form and with proper explanation too here.

awk 'FNR==NR{                                                 #### FNR==NR condition will be TRUE when first file file2 is being read, FNR and NR are awks built-in variables, both re-present line numbers of files only difference between them is FNR gets re-set whenever a new file is getting started and NRs value will be keep on increasing till all files get read.
                A[$0];                                        #### creating an array whose index is $0(current line) of file2.
                next                                          #### using next keyword for skipping all the next statements.
            }
            {
                VAL=$0;                                       #### creating a variable named VAL which has current lines value.
                gsub(/[0-9]/,"");                             #### gsub is awks built-in function to globally substituting all the digits to NULL in lines for file1.
            }
     ($0 in A){                                               #### now checking if new-edited $0(current line) is present in array A then do following statements.
                B[$0]++;                                      #### creating an array named B with index of $0 and incrementing its value with 1 each time.
                next                                          #### using next keyword for skipping all the next statements.
              }
     !($0 in A){                                              #### If current line is NOT present in array A.
                        OTHERS[VAL]++                         #### create an array named OTHERS with index of variable VAL and increment its value with 1 each time it comes in this section.
                     }
     END{                                                     #### Starting END section here for awk.
                for(i in B){                                  #### Traversing through array B now.
                                print i": "B[i]               #### printing the index of array B and its respective value now.
                           };
                for(j in OTHERS){                             #### Traversing through array OTHERS now.
                                        print j": "OTHERS[j]  #### printing index of array B with its value too.
                                }
        }
    ' file2  file1                                            #### Mentioning the Input_files now.


问:
How do I track down an "Exception thrown without a stack frame in Unknown on line 0" in PHP?
I'm working on a large (inherited) codebase in PHP, and the error Exception thrown without a stack frame in Unknown on line 0 has started showing up at the bottom of every page.  I understand what the error means: an exception is getting thrown someplace it can't be thrown.  I've even managed to track it down somewhat—it's happening during the time shutdown functions are being called.

I've put logging in all the functions which get registered with register_shutdown_function, and it's not happening in any of those.  Unfortunately, I can't seem to get any more information than that; I know what the last shutdown function to get called successfully is, but I have no idea what code gets executed between that and the point where the error happens.  I don't even know what part of the PHP machinery is calling that last shutdown function.  It might be something with the logging framework, or the session framework, or anything of a half-dozen things.

Does anyone know how to pinpoint where the error is occurring?

答:
I was getting this issue in PHPUnit. I have added below code in function tearDown and helps me to get the actual error. You should wrap destructor inside a try-catch block, as the stack-frame only gets lost as soon as the exception is getting outside the destructor. Might be this can help someone else too. Source

```<code>function __destruct()
{
    try
    {
    /*
    your code
    */
    }
    catch(Exception $e)
    {
    echo $e->__toString();
    }
}
</code>```

Body:
I was getting this issue in PHPUnit. I have added below code in function tearDown and helps me to get the actual error. You should wrap destructor inside a try-catch block, as the stack-frame only gets lost as soon as the exception is getting outside the destructor. Might be this can help someone else too. Source

function __destruct()
{
    try
    {
    /*
    your code
    */
    }
    catch(Exception $e)
    {
    echo $e->__toString();
    }
}


问:
Cannot find module environment when running in server side with Angular Universal
I have a simple Angular 4 app that I want to run in server side with Angular Universal (nodeJs server side rendering).
I followed these steps to configure the Angular Universal with the angular-cli help and it's all good until I try to use the angular environment.
When I try to access a property within the environment constant it works perfectly being rendered in client side (with ng serve) but in server side (ts-node src/server.ts) it throws the following error:

```<code>Error: Cannot find module 'environments/environment'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Dev\code-carama\src\app\auth.service.ts:3:1)
    at Module._compile (module.js:571:32)
    at Module.m._compile (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:385:23)
    at Module._extensions..js (module.js:580:10)
    at Object.require.extensions.(anonymous function) [as .ts] (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:388:12)
    at Module.load (module.js:488:32)

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v7.10.0
npm ERR! npm  v4.2.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! code-carama@0.0.0 start: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the code-carama@0.0.0 start script 'ts-node src/server.ts'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the code-carama package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ts-node src/server.ts
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs code-carama
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls code-carama
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\dima\AppData\Roaming\npm-cache\_logs\2017-06-05T12_00_03_595Z-debug.log
</code>```

This is my server.ts:

```<code>import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  //it serves html from the compiled angular app from the server
  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});
</code>```

And the simple service trying to access environment variables is the auth.service.ts:

```<code>import { Injectable } from '@angular/core';
import { environment } from 'environments/environment';

@Injectable()
export class AuthService {

  private userManager = null;
  constructor() {
    console.log('AuthService instantiated in environment ' + environment.envName); //this will fail in server-side rendering
  }
}
</code>```

Any idea what's going with nodeJs (or angular universal) not to find that environment module?

Thanks

答:
Never mind, it seems the problem is that although for client side rendering the line:

import { environment } from 'environments/environment';

works well, for server side rendering the line must be:

import { environment } from '../environments/environment';

and by the way, I don't know why but by default for server-side rendering it will pick the PROD environment file.

on console: AuthService instantiated in environment prod

Body:
I have a simple Angular 4 app that I want to run in server side with Angular Universal (nodeJs server side rendering).
I followed these steps to configure the Angular Universal with the angular-cli help and it's all good until I try to use the angular environment.
When I try to access a property within the environment constant it works perfectly being rendered in client side (with ng serve) but in server side (ts-node src/server.ts) it throws the following error:

Error: Cannot find module 'environments/environment'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Dev\code-carama\src\app\auth.service.ts:3:1)
    at Module._compile (module.js:571:32)
    at Module.m._compile (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:385:23)
    at Module._extensions..js (module.js:580:10)
    at Object.require.extensions.(anonymous function) [as .ts] (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:388:12)
    at Module.load (module.js:488:32)

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v7.10.0
npm ERR! npm  v4.2.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! code-carama@0.0.0 start: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the code-carama@0.0.0 start script 'ts-node src/server.ts'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the code-carama package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ts-node src/server.ts
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs code-carama
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls code-carama
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\dima\AppData\Roaming\npm-cache\_logs\2017-06-05T12_00_03_595Z-debug.log

This is my server.ts:

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  //it serves html from the compiled angular app from the server
  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

And the simple service trying to access environment variables is the auth.service.ts:

import { Injectable } from '@angular/core';
import { environment } from 'environments/environment';

@Injectable()
export class AuthService {

  private userManager = null;
  constructor() {
    console.log('AuthService instantiated in environment ' + environment.envName); //this will fail in server-side rendering
  }
}

Any idea what's going with nodeJs (or angular universal) not to find that environment module?

Thanks


问:
explanation for "properties" object in the response of neo4j
using:

node.js - version 8.0.0

neo4j-driver: 1.3.0

neo4j database: community edition, version: 3.2.0

i am running a cypher (not important what exactly is the cypher) and getting back a result.

after parsing the result using the follwing code:

```<code>result.records[0].get('instanceStock').properties
</code>```

i am getting the following json:

```<code>{
   "quantity":{
      "low":10,
      "high":0
   }
}
</code>```

the value 10 is the correct one which actually reside inside the db.

what is the meaning of the "low" and "high" properties?

why the  correct answer reside inside the "low" property?

答:
This has to do with how 64bit integers are handled in JS. More explanation here :

https://github.com/neo4j/neo4j-javascript-driver/tree/ad0317a675d50443ca97f157f119957354b74ae3#numbers-and-the-integer-type

Body:
using:

node.js - version 8.0.0

neo4j-driver: 1.3.0

neo4j database: community edition, version: 3.2.0

i am running a cypher (not important what exactly is the cypher) and getting back a result.

after parsing the result using the follwing code:

result.records[0].get('instanceStock').properties

i am getting the following json:

{
   "quantity":{
      "low":10,
      "high":0
   }
}

the value 10 is the correct one which actually reside inside the db.

what is the meaning of the "low" and "high" properties?

why the  correct answer reside inside the "low" property?


问:
jstree jquery how to iterate through all nodes
I'm trying to iterate through every node within a treeview in jstree. The treeview is 4 levels deep but I can't seem to get past the 1st level. The following is the jQuery used to iterate.

```<code>$("#myTree").bind('ready.jstree', function (event, data) {
    $('#myTree li').each(function () {
        // Perform logic here
        }
    });
});
</code>```

Here is a jsfiddle illustrating my point. Please help on how I can iterate through every node in jstree.

答:
I wanted a library-way of iterating over the nodes of a jsTree, so I wrote this into the jstree.js file:

```<code>each_node: function(callback) {
    if (callback) {
        var id, nodes = this._model.data;
        for (id in nodes) {
            if (nodes.hasOwnProperty(id) /*&& id !== $.jstree.root*/) {
                callback.call(this, nodes[id]);
            }
        }
    }
},
</code>```

(Note: I'm using jsTree 3.3.4, and I've inserted the above code on line 3712 right after the get_json function definition.)

In code, I can iterate through the nodes of the tree like this:

```<code>$("#myTree").jstree(true).each_node(function (node) {
    // 'this' contains the jsTree reference

    // example usage: hide leaf nodes having a certain data attribute = true
    if (this.is_leaf(node) && node.data[attribute]) {
        this.hide_node(node);
    }
});
</code>```

Body:
I'm trying to iterate through every node within a treeview in jstree. The treeview is 4 levels deep but I can't seem to get past the 1st level. The following is the jQuery used to iterate.

$("#myTree").bind('ready.jstree', function (event, data) {
    $('#myTree li').each(function () {
        // Perform logic here
        }
    });
});

Here is a jsfiddle illustrating my point. Please help on how I can iterate through every node in jstree.

Body:
I wanted a library-way of iterating over the nodes of a jsTree, so I wrote this into the jstree.js file:

each_node: function(callback) {
    if (callback) {
        var id, nodes = this._model.data;
        for (id in nodes) {
            if (nodes.hasOwnProperty(id) /*&& id !== $.jstree.root*/) {
                callback.call(this, nodes[id]);
            }
        }
    }
},

(Note: I'm using jsTree 3.3.4, and I've inserted the above code on line 3712 right after the get_json function definition.)

In code, I can iterate through the nodes of the tree like this:

$("#myTree").jstree(true).each_node(function (node) {
    // 'this' contains the jsTree reference

    // example usage: hide leaf nodes having a certain data attribute = true
    if (this.is_leaf(node) && node.data[attribute]) {
        this.hide_node(node);
    }
});


问:
Getting 404 on Powershell Query of Cosmos DB
I'm using this script from the download in this link.
https://gallery.technet.microsoft.com/scriptcenter/How-to-query-Azure-Cosmos-0a9aa517
However for some reason I am getting a 404 response.

I copy-pasted the url of the db directly. Putting in a fake URL gives me a "could not be resolved" error so I know the location exists.

Based on the Azure CosmosDB API documentation here:
https://learn.microsoft.com/en-us/rest/api/documentdb/databases
the $databaseID is user-set and just has to be unique, so I've set it to be the same as the db name and assigned that to the url.

Changing it to be different still gives me the same 404 response message (below).

Edit: Removed original commenting intro for readability

Powershell Script:

```<code># add necessary assembly
#
Add-Type -AssemblyName System.Web

# generate authorization key
Function Generate-MasterKeyAuthorizationSignature
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)][String]$verb,
        [Parameter(Mandatory=$true)][String]$resourceLink,
        [Parameter(Mandatory=$true)][String]$resourceType,
        [Parameter(Mandatory=$true)][String]$dateTime,
        [Parameter(Mandatory=$true)][String]$key,
        [Parameter(Mandatory=$true)][String]$keyType,
        [Parameter(Mandatory=$true)][String]$tokenVersion
    )

    $hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
    $hmacSha256.Key = [System.Convert]::FromBase64String($key)

    $payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
    $hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
    $signature = [System.Convert]::ToBase64String($hashPayLoad);

    [System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}

# query
Function Query-CosmosDb
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)][String]$EndPoint,
        [Parameter(Mandatory=$true)][String]$DataBaseId,
        [Parameter(Mandatory=$true)][String]$CollectionId,
        [Parameter(Mandatory=$true)][String]$MasterKey,
        [Parameter(Mandatory=$true)][String]$Query
    )

    $Verb = "POST"
    $ResourceType = "docs";
    $ResourceLink = "dbs/$DatabaseId/colls/$CollectionId"

    $dateTime = [DateTime]::UtcNow.ToString("r")
    $authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
    $queryJson = @{query=$Query} | ConvertTo-Json
    $header = @{authorization=$authHeader;"x-ms-documentdb-isquery"="True";"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime}
    $contentType= "application/json "#  The original said "application/query+json", I tried both
    $queryUri = "$EndPoint$ResourceLink/docs"

    $result = Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $queryJson

    $result | ConvertTo-Json -Depth 10
}

# fill the target cosmos database endpoint uri, database id, collection id and masterkey

$DatabaseName = "" # name goes here
$MasterKey = "" #key goes here
$CollectionId = "transientUsers"

$DatabaseId = $DatabaseName
$CosmosDBEndPoint = "https://$DatabaseId.documents.azure.com:443/"

# query string
$Query = "SELECT * FROM transientUsers"

# execute
Query-CosmosDb -EndPoint $CosmosDBEndPoint -DataBaseId $DataBaseId -CollectionId $CollectionId -MasterKey $MasterKey -Query $Query
</code>```

Error I'm getting:

```<code>Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At D:\querycosmos\PowerShell\QueryCosmosDB.ps1:69 char:12
+ ...   $result = Invoke-RestMethod -Method $Verb -ContentType $contentType ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
</code>```

答:
I noticed that you used $DatabaseId in two places:

```<code>$ResourceLink = "dbs/$DatabaseId/colls/$CollectionId"
</code>```

and

```<code>$CosmosDBEndPoint = "https://$DatabaseId.documents.azure.com:443/"
</code>```

If $DatabaseId refers to your account name, then you would need to change your $ResourceLink variable and use the name of the database inside your account containing the collection. If however $DatabaseId refers to the database name, then you would need to change $CosmosDBEndPoint and use account name there.

Body:
I'm using this script from the download in this link.
https://gallery.technet.microsoft.com/scriptcenter/How-to-query-Azure-Cosmos-0a9aa517
However for some reason I am getting a 404 response.

I copy-pasted the url of the db directly. Putting in a fake URL gives me a "could not be resolved" error so I know the location exists.

Based on the Azure CosmosDB API documentation here:
https://learn.microsoft.com/en-us/rest/api/documentdb/databases
the $databaseID is user-set and just has to be unique, so I've set it to be the same as the db name and assigned that to the url.

Changing it to be different still gives me the same 404 response message (below).

Edit: Removed original commenting intro for readability

Powershell Script:

# add necessary assembly
#
Add-Type -AssemblyName System.Web

# generate authorization key
Function Generate-MasterKeyAuthorizationSignature
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)][String]$verb,
        [Parameter(Mandatory=$true)][String]$resourceLink,
        [Parameter(Mandatory=$true)][String]$resourceType,
        [Parameter(Mandatory=$true)][String]$dateTime,
        [Parameter(Mandatory=$true)][String]$key,
        [Parameter(Mandatory=$true)][String]$keyType,
        [Parameter(Mandatory=$true)][String]$tokenVersion
    )

    $hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
    $hmacSha256.Key = [System.Convert]::FromBase64String($key)

    $payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
    $hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
    $signature = [System.Convert]::ToBase64String($hashPayLoad);

    [System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}

# query
Function Query-CosmosDb
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)][String]$EndPoint,
        [Parameter(Mandatory=$true)][String]$DataBaseId,
        [Parameter(Mandatory=$true)][String]$CollectionId,
        [Parameter(Mandatory=$true)][String]$MasterKey,
        [Parameter(Mandatory=$true)][String]$Query
    )

    $Verb = "POST"
    $ResourceType = "docs";
    $ResourceLink = "dbs/$DatabaseId/colls/$CollectionId"

    $dateTime = [DateTime]::UtcNow.ToString("r")
    $authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
    $queryJson = @{query=$Query} | ConvertTo-Json
    $header = @{authorization=$authHeader;"x-ms-documentdb-isquery"="True";"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime}
    $contentType= "application/json "#  The original said "application/query+json", I tried both
    $queryUri = "$EndPoint$ResourceLink/docs"

    $result = Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $queryJson

    $result | ConvertTo-Json -Depth 10
}

# fill the target cosmos database endpoint uri, database id, collection id and masterkey

$DatabaseName = "" # name goes here
$MasterKey = "" #key goes here
$CollectionId = "transientUsers"

$DatabaseId = $DatabaseName
$CosmosDBEndPoint = "https://$DatabaseId.documents.azure.com:443/"

# query string
$Query = "SELECT * FROM transientUsers"

# execute
Query-CosmosDb -EndPoint $CosmosDBEndPoint -DataBaseId $DataBaseId -CollectionId $CollectionId -MasterKey $MasterKey -Query $Query

Error I'm getting:

Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At D:\querycosmos\PowerShell\QueryCosmosDB.ps1:69 char:12
+ ...   $result = Invoke-RestMethod -Method $Verb -ContentType $contentType ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Body:
I noticed that you used $DatabaseId in two places:

$ResourceLink = "dbs/$DatabaseId/colls/$CollectionId"

and

$CosmosDBEndPoint = "https://$DatabaseId.documents.azure.com:443/"

If $DatabaseId refers to your account name, then you would need to change your $ResourceLink variable and use the name of the database inside your account containing the collection. If however $DatabaseId refers to the database name, then you would need to change $CosmosDBEndPoint and use account name there.


问:
ViewModels or RequestModels in WebApi project and additional layer of mapping with automapper
I have Api project, business project and database context.

I am thinking of design like this:

viewmodels in api project, and mappings with automapper. Automapper
will here map viewmodel to business dto model

dto models in business project, and mappings with automapper. Automapper will here map dto model to entity model (database).

Question 1: Should I use OperationViewModel or OperationRequestModel(ResponseModel) in api project?

Question 2: Is additional mapping between viewmodel and dto model overkill, or is it good practice to separate those concerns and decouple even more, or should I map dto models with entity models and use those dto models in api project?

答:
Firstly, I would like to congratulate you on 'getting it'.  So many projects I see have the database access in the UI layer!!

Initially, you may feel that having different (but almost identical) classes for ViewModel, Business and data layers a pain, but this is where AutoMapper is brilliant.  Most of the time, you don't need to do anything and it just works.

Once your code gets a bit more meat on the bone, you will find it easier to add database fields without having to worry about the effects on your view model, and to create view models that are exactly what the view requires, without having to worry about database fields.  Win-win.   I would also create a separate view model for each function, even if they are identical (use inheritance if required, but make sure you have a different class each time).

IMO, the models should be exposed by the layer that creates and consumes them, so the ViewModel should have XXXViewModel, the businesss layer have XXXDto etc.

```<code>public IndexViewModel Index()
{
    var vm = new IndexViewModel()
    {
        Items = _mapper.map<List<Item>>(_service.GetSomeData())
    };
    return vm;
}
public GetViewModel Get(int id)
{
    var vm = _mapper.Map<GetViewModel>(_service.get(id));
    return vm;
}
</code>```

Body:
Firstly, I would like to congratulate you on 'getting it'.  So many projects I see have the database access in the UI layer!!

Initially, you may feel that having different (but almost identical) classes for ViewModel, Business and data layers a pain, but this is where AutoMapper is brilliant.  Most of the time, you don't need to do anything and it just works.

Once your code gets a bit more meat on the bone, you will find it easier to add database fields without having to worry about the effects on your view model, and to create view models that are exactly what the view requires, without having to worry about database fields.  Win-win.   I would also create a separate view model for each function, even if they are identical (use inheritance if required, but make sure you have a different class each time).

IMO, the models should be exposed by the layer that creates and consumes them, so the ViewModel should have XXXViewModel, the businesss layer have XXXDto etc.

public IndexViewModel Index()
{
    var vm = new IndexViewModel()
    {
        Items = _mapper.map<List<Item>>(_service.GetSomeData())
    };
    return vm;
}
public GetViewModel Get(int id)
{
    var vm = _mapper.Map<GetViewModel>(_service.get(id));
    return vm;
}


问:
How to filter all the fields in react?
How to filter all the fields in react?
I have written a code which only filters specified fields.

```<code> let filteredContacts=this.props.contacts.filter(
         (contact)=>{
           return contact.name.indexOf(this.state.search)!==-1;
         }
       );
</code>```

the above code only returns filtered names...but i want to filter name,age,city work.

this is the data file:

```<code>export default function(){
  return [{
    key: 1,
    name: 'Steve',
    city: 'Paris',
  }, {
    key: 2,
    name: 'Tim',
    city: 'London',
  }, {
    key: 3,
    name: 'Stella',
    city: 'Bankok',
  }, {
    key: 4,
    name: 'John',
    city: 'Paris',
  }];
}
</code>```

i want to create a search bar which which filters all the fields suppose if i search john then the list of john should be displayed and if i search paris then all the entries which have paris should be displayed..So the code which i have written only searches for name as i have specified name..i want to search the inputed data to search all the fields.

答:
Well, I fastly tried, do a loop on your keys. Maybe there's a more elegant way.</p>

```<code> let filteredContacts=this.props.contacts.filter(
     (contact)=>{
       var found = false;
       Object.keys(contact).map(function(key, index) {
         if (contact[key].indexOf(this.state.search) >= 0)
            found = true;
       }
       return found;
     }
  );
</code>```

Title: How to filter all the fields in react?

Body:
How to filter all the fields in react?
I have written a code which only filters specified fields.

 let filteredContacts=this.props.contacts.filter(
         (contact)=>{
           return contact.name.indexOf(this.state.search)!==-1;
         }
       );

the above code only returns filtered names...but i want to filter name,age,city work.

this is the data file:

export default function(){
  return [{
    key: 1,
    name: 'Steve',
    city: 'Paris',
  }, {
    key: 2,
    name: 'Tim',
    city: 'London',
  }, {
    key: 3,
    name: 'Stella',
    city: 'Bankok',
  }, {
    key: 4,
    name: 'John',
    city: 'Paris',
  }];
}

i want to create a search bar which which filters all the fields suppose if i search john then the list of john should be displayed and if i search paris then all the entries which have paris should be displayed..So the code which i have written only searches for name as i have specified name..i want to search the inputed data to search all the fields.

Body:
Well, I fastly tried, do a loop on your keys. Maybe there's a more elegant way.

 let filteredContacts=this.props.contacts.filter(
     (contact)=>{
       var found = false;
       Object.keys(contact).map(function(key, index) {
         if (contact[key].indexOf(this.state.search) >= 0)
            found = true;
       }
       return found;
     }
  );


问:
How to print values in Java?
First, do not be scared by the size of the question kkkkk

I am studying the OOP course in Java, and the teacher has passed some content there that has not had time to write the code. Then I have a little doubt! I have 3 classes in java. The classes SalaAula, Pessoa and Professor.

SalaAula.java

```<code>import java.util.Scanner;

public class SalaAula {
    private String nomeAluno;
    private int idadeAluno;
    private float pesoAluno;
    private float alturaAluno;
    private int matriculaAluno;

    SalaAula() {

        System.out.println("Seja bem vindo\n\n ");
        Scanner entrada = new Scanner(System.in);

        Professor professor = new Professor("Anderson", 32, 1.75f, 110f, 1010220, "Mestre");

        System.out.println("Qual seu nome? ");
        nomeAluno = entrada.next();
        System.out.println("Qual a sua idade? ");
        idadeAluno = entrada.nextInt();
        System.out.println("Qual o seu peso? ");
        pesoAluno = entrada.nextFloat();
        System.out.println("Qual a sua altura?");
        alturaAluno = entrada.nextFloat();
        System.out.println("Qual a sua matrícula?");
        matriculaAluno = entrada.nextInt();

        //Pessoa pessoa = new Pessoa(nome, idade, peso, altura, peso, matricula);
        System.out.println(new Professor());
        System.out.println("\n------------------------------------------");
        System.out.println("Nome:\tIdade:\tPeso:\tAltura:\tMatrícula:");
        System.out.println("------------------------------------------");
        System.out.println(nomeAluno + "\t" + idadeAluno + " anos\t" + alturaAluno + "\t" + pesoAluno + "\t" + matriculaAluno);
        System.out.println("------------------------------------------");

    }

    public static void main(String[] args) {
        SalaAula principal = new SalaAula();

    }
}
</code>```

Pessoa.java

```<code>class Pessoa {
    private int idade;
    private String nome;
    private float altura;
    private float peso;
    private int matricula;

    Pessoa() {

    }

    Pessoa(String nome, int idade, float altura, float peso, int matricula) {
        this.idade = idade;
        this.nome = nome;
        this.altura = altura;
        this.peso = peso;
        this.matricula = matricula;
    }

    public String getNome() {
        return this.nome;
    }

    public void setAltura(float altura) {
        this.altura = altura;
    }

    public void setPeso(float peso) {
        this.peso = peso;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return this.idade;
    }

    public float getAltura() {
        return this.altura;
    }

    public float getPeso() {
        return this.peso;
    }
    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }
    public int getMatricula() {
        return this.matricula;
    }
}
</code>```

Professor.java

```<code>public class Professor extends Pessoa {
    String nivelSuperior;
    Professor() {

    }
    Professor(String nome, int idade, float altura, float peso, int matricula, String nivel) {

        setNome(nome);
        setIdade(idade);
        setAltura(altura);
        setPeso(peso);
        setMatricula(matricula);

        this.nivelSuperior = nivel;
    }
    public String getNivel() {
        return this.nivelSuperior;
    }
    public void setNivel(String nivel) {
        this.nivelSuperior = nivel;
    }
}
</code>```

That's it! It is to return the information of the teacher:

```
Professor professor = new Professor("Anderson", 32, 1.75f, 110f, 1010220, "Mestre");
```

And the student information, which in this case will be entered by the user.

My question is: how do I print teacher information + student information?

答:
I suggest to implement the toString() method for each pojo and then simply use System.out.println(yourObject)

for example for the Pessoa class you could write something like this:

```<code>@Override
public String toString()
{
  return String.format("Pessoa [idade=%s, nome=%s, altura=%s, peso=%s, matricula=%s]", idade, nome, altura, peso, matricula);
}
</code>```

Title: How to print values in Java?

Body:
First, do not be scared by the size of the question kkkkk

I am studying the OOP course in Java, and the teacher has passed some content there that has not had time to write the code. Then I have a little doubt! I have 3 classes in java. The classes SalaAula, Pessoa and Professor.

SalaAula.java

import java.util.Scanner;

public class SalaAula {
    private String nomeAluno;
    private int idadeAluno;
    private float pesoAluno;
    private float alturaAluno;
    private int matriculaAluno;

    SalaAula() {

        System.out.println("Seja bem vindo\n\n ");
        Scanner entrada = new Scanner(System.in);

        Professor professor = new Professor("Anderson", 32, 1.75f, 110f, 1010220, "Mestre");

        System.out.println("Qual seu nome? ");
        nomeAluno = entrada.next();
        System.out.println("Qual a sua idade? ");
        idadeAluno = entrada.nextInt();
        System.out.println("Qual o seu peso? ");
        pesoAluno = entrada.nextFloat();
        System.out.println("Qual a sua altura?");
        alturaAluno = entrada.nextFloat();
        System.out.println("Qual a sua matrícula?");
        matriculaAluno = entrada.nextInt();

        //Pessoa pessoa = new Pessoa(nome, idade, peso, altura, peso, matricula);
        System.out.println(new Professor());
        System.out.println("\n------------------------------------------");
        System.out.println("Nome:\tIdade:\tPeso:\tAltura:\tMatrícula:");
        System.out.println("------------------------------------------");
        System.out.println(nomeAluno + "\t" + idadeAluno + " anos\t" + alturaAluno + "\t" + pesoAluno + "\t" + matriculaAluno);
        System.out.println("------------------------------------------");

    }

    public static void main(String[] args) {
        SalaAula principal = new SalaAula();

    }
}

Pessoa.java

class Pessoa {
    private int idade;
    private String nome;
    private float altura;
    private float peso;
    private int matricula;

    Pessoa() {

    }

    Pessoa(String nome, int idade, float altura, float peso, int matricula) {
        this.idade = idade;
        this.nome = nome;
        this.altura = altura;
        this.peso = peso;
        this.matricula = matricula;
    }

    public String getNome() {
        return this.nome;
    }

    public void setAltura(float altura) {
        this.altura = altura;
    }

    public void setPeso(float peso) {
        this.peso = peso;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return this.idade;
    }

    public float getAltura() {
        return this.altura;
    }

    public float getPeso() {
        return this.peso;
    }
    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }
    public int getMatricula() {
        return this.matricula;
    }
}

Professor.java

public class Professor extends Pessoa {
    String nivelSuperior;
    Professor() {

    }
    Professor(String nome, int idade, float altura, float peso, int matricula, String nivel) {

        setNome(nome);
        setIdade(idade);
        setAltura(altura);
        setPeso(peso);
        setMatricula(matricula);

        this.nivelSuperior = nivel;
    }
    public String getNivel() {
        return this.nivelSuperior;
    }
    public void setNivel(String nivel) {
        this.nivelSuperior = nivel;
    }
}

That's it! It is to return the information of the teacher:

Professor professor = new Professor("Anderson", 32, 1.75f, 110f, 1010220, "Mestre");

And the student information, which in this case will be entered by the user.

My question is: how do I print teacher information + student information?

Body:
I suggest to implement the toString() method for each pojo and then simply use System.out.println(yourObject)

for example for the Pessoa class you could write something like this:

@Override
public String toString()
{
  return String.format("Pessoa [idade=%s, nome=%s, altura=%s, peso=%s, matricula=%s]", idade, nome, altura, peso, matricula);
}


问:
No matching constructor found on class Actors.FileObserverActor for arguments
I am trying to implement websocket using akka actors in play frmework.

HomeController.scala

```<code>  def socket = WebSocket.accept[String, String] { request =>
    ActorFlow.actorRef(out => FileObserverActor.props(out))
  }
</code>```

Actors/FileUploaderActor.scala

```<code>class FileUploaderActor extends Actor{
  override def receive: Receive = {

    case UploadFile(billerId, filename, subCategory, count, dueDate) =>

      val fileOberverActor = ActorSystem().actorOf(Props[FileObserverActor])
      val billerData = BillerFileUploadMetaData(billerId,filename,count,"ACTIVE",
        new java.sql.Timestamp(new java.util.Date().getTime),subCategory,dueDate)
      val sparkSession = SparkContextHelper.sparkSession;
      import sparkSession.implicits._
      val rdd = sparkSession.sparkContext.parallelize(Seq(billerData))
      val df = rdd.toDF()
      df.write.format("org.apache.spark.sql.cassandra").options(Map("keyspace" -> "billerplatform_schema", "table" -> "biller_file_uploads")).mode(SaveMode.Append).save
      fileOberverActor ! FileUploaded(filename, count)
  }
}
</code>```

Actors/FileObserverActor.scala

```<code>class FileObserverActor(out: ActorRef) extends Actor{
  def receive = {
    case FileUploaded(fileName, totalRecords) =>
      out ! ("Got the file " + fileName)
  }

}

object FileObserverActor{
  def props(out: ActorRef)  = Props(new FileObserverActor(out))
}
</code>```

Getting trace:

```<code>java.lang.IllegalArgumentException: no matching constructor found on class Actors.FileObserverActor for arguments []
    at akka.util.Reflect$.error$1(Reflect.scala:81)
    at akka.util.Reflect$.findConstructor(Reflect.scala:105)
    at akka.actor.NoArgsReflectConstructor.<init>(IndirectActorProducer.scala:103)
    at akka.actor.IndirectActorProducer$.apply(IndirectActorProducer.scala:60)
    at akka.actor.Props.producer(Props.scala:131)
    at akka.actor.Props.<init>(Props.scala:144)
    at akka.actor.Props$.apply(Props.scala:86)
    at Actors.FileUploaderActor$$anonfun$receive$1.applyOrElse(FileUploaderActor.scala:15)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:497)
    at Actors.FileUploaderActor.aroundReceive(FileUploaderActor.scala:10)
</code>```

Is this a problem with creating an actor instance in FileUploaderActor? Can you help me to debug this issue.

Edit:
 I have created a companion object for "FileObserverActor" because its needed to establish a connection between controller and FileObserverActor through websocket,

```<code>def socket = WebSocket.accept[String, String] { request =>
    ActorFlow.actorRef(out => FileObserverActor.props(out))
  }
</code>```

Now i also want to send message to "FileObserverActor" from "FileUploadActor", but i couldnt create a instance from "FileUploadActor" since the "FileObserverActor" is parameterised with "out:ActorRef" for websocket connection. Now how can i send a message to "FileObserverActor" from "FileUploadActor" ?

答:
As the error message points out it is expecting a no-argument constructor to FileObserverActor but it's not found. Given you need the out: ActorRef while creating FileObserverActor, consider passing a reference when you create it.

The offending line is on Actors/FileUploaderActor.scala

val fileOberverActor = ActorSystem().actorOf(Props[FileObserverActor])

You might want to change it to something like

val fileOberverActor = ActorSystem().actorOf(FileObserverActor.props(outActorRef))

For more information checkout the official documentation on Props in Akka.

Body:
I am trying to implement websocket using akka actors in play frmework.

HomeController.scala

  def socket = WebSocket.accept[String, String] { request =>
    ActorFlow.actorRef(out => FileObserverActor.props(out))
  }

Actors/FileUploaderActor.scala

class FileUploaderActor extends Actor{
  override def receive: Receive = {

    case UploadFile(billerId, filename, subCategory, count, dueDate) =>

      val fileOberverActor = ActorSystem().actorOf(Props[FileObserverActor])
      val billerData = BillerFileUploadMetaData(billerId,filename,count,"ACTIVE",
        new java.sql.Timestamp(new java.util.Date().getTime),subCategory,dueDate)
      val sparkSession = SparkContextHelper.sparkSession;
      import sparkSession.implicits._
      val rdd = sparkSession.sparkContext.parallelize(Seq(billerData))
      val df = rdd.toDF()
      df.write.format("org.apache.spark.sql.cassandra").options(Map("keyspace" -> "billerplatform_schema", "table" -> "biller_file_uploads")).mode(SaveMode.Append).save
      fileOberverActor ! FileUploaded(filename, count)
  }
}

Actors/FileObserverActor.scala

class FileObserverActor(out: ActorRef) extends Actor{
  def receive = {
    case FileUploaded(fileName, totalRecords) =>
      out ! ("Got the file " + fileName)
  }

}

object FileObserverActor{
  def props(out: ActorRef)  = Props(new FileObserverActor(out))
}

Getting trace:

java.lang.IllegalArgumentException: no matching constructor found on class Actors.FileObserverActor for arguments []
    at akka.util.Reflect$.error$1(Reflect.scala:81)
    at akka.util.Reflect$.findConstructor(Reflect.scala:105)
    at akka.actor.NoArgsReflectConstructor.<init>(IndirectActorProducer.scala:103)
    at akka.actor.IndirectActorProducer$.apply(IndirectActorProducer.scala:60)
    at akka.actor.Props.producer(Props.scala:131)
    at akka.actor.Props.<init>(Props.scala:144)
    at akka.actor.Props$.apply(Props.scala:86)
    at Actors.FileUploaderActor$$anonfun$receive$1.applyOrElse(FileUploaderActor.scala:15)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:497)
    at Actors.FileUploaderActor.aroundReceive(FileUploaderActor.scala:10)

Is this a problem with creating an actor instance in FileUploaderActor? Can you help me to debug this issue.

Edit:
 I have created a companion object for "FileObserverActor" because its needed to establish a connection between controller and FileObserverActor through websocket,

def socket = WebSocket.accept[String, String] { request =>
    ActorFlow.actorRef(out => FileObserverActor.props(out))
  }

Now i also want to send message to "FileObserverActor" from "FileUploadActor", but i couldnt create a instance from "FileUploadActor" since the "FileObserverActor" is parameterised with "out:ActorRef" for websocket connection. Now how can i send a message to "FileObserverActor" from "FileUploadActor" ?


问:
Why isn't Unity allowing me to apply certain changes to a prefab?
I have a prefab called square in the asset tray, I drag it into the scene to create an instance of the square prefab (in the hierarchy it is highlighted blue and has the select, revert and apply buttons in the properties). If I move/resize the instance and then press apply, the changes are applied to the prefab.

However, the square prefab has a script with a public game object. I drag the game object from the hierarchy into the slot in the instance's properties tab and is shows that the script is now referencing the actual gameobject. However, when I press apply this change isn't applied to the prefab (the prefab's script still isn't referencing any actual gameobject). All other changes to the prefab are applied.

I have tried dragging the instance into the asset tray to create a new prefab with the changes, but, as soon as I do, the script no longer references the game object.

I shouldn't have to create an entirely new prefab every time I add a public variable to a script so why can't I apply this change?

答: Prefabs are Assets. You can reference only other Assets to an Asset, never instances of Assets.


问:
Showing tabbar on next screen in Android
Initially I have 3 screens in a tab bar...but when I navigate from any of these activities to any other activity the tab bar disappears...I want this tab bar to appear even on that screen...How to do that??</p>

答:
You could put your tabbar code into a separate XML file (say, tabbar.xml) and use

```<code><include layout="tabbar" />
</code>```

in each of the layout files.

Then, you would need to set it up in your Activities onStart methods.

Body:
You could put your tabbar code into a separate XML file (say, tabbar.xml) and use

<include layout="tabbar" />

in each of the layout files.

Then, you would need to set it up in your Activities onStart methods.


问:
Deploy rails app at sub uri of a domain
We have set up a production server for our rails app with Nginx and puma. We want to deploy our rails app at sub uri and on main domain we want to put wordpress for home page, pricing page etc.

How we configure our rails that it able to run on sub uri which have Devise gem as authentication. Will we need to change our routes for sub uri?

What will be the configuration for nginx and puma?

Thanks in advance!

答:
First put your desired sub uri path in application.rb i.e. main

```<code>...
config.relative_url_root = "/main"
...
</code>```

In config.ru, add these lines.

```<code>require ::File.expand_path('../config/environment',  __FILE__)
map SampleApplication::Application.config.relative_url_root || "/" do
  run Rails.application
end
</code>```

In production.rb, add below line.

```<code># Enable serving of images, stylesheets, and JavaScripts from an asset server
config.action_controller.asset_host = "YOUR_DOMAIN_NAME/main"

# ActionMailer Config
config.action_mailer.default_url_options = {
    :host => "YOUR_DOMAIN_NAME",
    :only_path => false,
    :script_name =>  "/main"
}
</code>```

In nginx configuration file, add these lines

```<code>location /main {
    alias /var/deploy/sample_application/current/public;
    try_files $uri @main;
}

location @main {
    proxy_http_version 1.1;
    chunked_transfer_encoding off;
    proxy_buffering off;
    proxy_cache off;

    proxy_redirect     off;
    proxy_set_header   Host             $http_host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-Proto $scheme;

    proxy_pass http://puma_sample_application;
}
</code>```

Title: Deploy rails app at sub uri of a domain

Body:
First put your desired sub uri path in application.rb i.e. main

...
config.relative_url_root = "/main"
...

In config.ru, add these lines.

require ::File.expand_path('../config/environment',  __FILE__)
map SampleApplication::Application.config.relative_url_root || "/" do
  run Rails.application
end

In production.rb, add below line.

# Enable serving of images, stylesheets, and JavaScripts from an asset server
config.action_controller.asset_host = "YOUR_DOMAIN_NAME/main"

# ActionMailer Config
config.action_mailer.default_url_options = {
    :host => "YOUR_DOMAIN_NAME",
    :only_path => false,
    :script_name =>  "/main"
}

In nginx configuration file, add these lines

location /main {
    alias /var/deploy/sample_application/current/public;
    try_files $uri @main;
}

location @main {
    proxy_http_version 1.1;
    chunked_transfer_encoding off;
    proxy_buffering off;
    proxy_cache off;

    proxy_redirect     off;
    proxy_set_header   Host             $http_host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-Proto $scheme;

    proxy_pass http://puma_sample_application;
}


问:
Code wont loop through sheets as well as rows
I am trying to write code to loop through all sheets in a workbook, apart from 1, and add a column which is a concatenation of 3 others. This seems to loop through all the rows for one worksheet, but not the others in the book</p>

```<code>Sub addConcats()
  Dim sh As Worksheet
  Dim rw As Range
  Dim RowCount As Integer

  'Run through worksheets
  Dim x As Long
  Sheet1.Select
  For x = 2 To ThisWorkbook.Sheets.Count
    If Sheets(x).Name <> "VAT Transaction Report" Then Sheets(x).Select
    Replace:=False
    Dim LastRow As Long
    LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count

    For y = 2 To LastRow
      'Concat
      ActiveSheet.Cells(y, 20).Value = ActiveSheet.Cells(y, 7).Value &
ActiveSheet.Cells(y, 9).Value & ActiveSheet.Cells(y, 12).Value
    Next y
  Next x
End Sub
</code>```

答:
Try the code below, for your For loop to take into consideration the Sheets(x) you are trying to update:

```<code>Dim LastRow As Long

For x = 2 To ThisWorkbook.Sheets.Count
    If Sheets(x).Name <> "VAT Transaction Report" Then
        With Sheets(x)
            LastRow = .UsedRange.Row - 1 + .UsedRange.Rows.Count
            For y = 2 To LastRow
                'Concat
                .Cells(y, 20).Value = .Cells(y, 7).Value & .Cells(y, 9).Value & .Cells(y, 12).Value
            Next y
        End With
    End If
Next x
</code>```

Body:
I am trying to write code to loop through all sheets in a workbook, apart from 1, and add a column which is a concatenation of 3 others. This seems to loop through all the rows for one worksheet, but not the others in the book

Sub addConcats()
  Dim sh As Worksheet
  Dim rw As Range
  Dim RowCount As Integer

  'Run through worksheets
  Dim x As Long
  Sheet1.Select
  For x = 2 To ThisWorkbook.Sheets.Count
    If Sheets(x).Name <> "VAT Transaction Report" Then Sheets(x).Select
    Replace:=False
    Dim LastRow As Long
    LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count

    For y = 2 To LastRow
      'Concat
      ActiveSheet.Cells(y, 20).Value = ActiveSheet.Cells(y, 7).Value &
ActiveSheet.Cells(y, 9).Value & ActiveSheet.Cells(y, 12).Value
    Next y
  Next x
End Sub

Body:
Try the code below, for your For loop to take into consideration the Sheets(x) you are trying to update:

Dim LastRow As Long

For x = 2 To ThisWorkbook.Sheets.Count
    If Sheets(x).Name <> "VAT Transaction Report" Then
        With Sheets(x)
            LastRow = .UsedRange.Row - 1 + .UsedRange.Rows.Count
            For y = 2 To LastRow
                'Concat
                .Cells(y, 20).Value = .Cells(y, 7).Value & .Cells(y, 9).Value & .Cells(y, 12).Value
            Next y
        End With
    End If
Next x


问:
How can I convert String to Int?
I have a TextBoxD1.Text and I want to convert it to an int to store it in a database.

How can I do this?

答:
If you're looking for the long way, just create your one method:</p>
```<code>static int convertToInt(string a)
{
    int x = 0;

    Char[] charArray = a.ToCharArray();
    int j = charArray.Length;

    for (int i = 0; i < charArray.Length; i++)
    {
        j--;
        int s = (int)Math.Pow(10, j);

        x += ((int)Char.GetNumericValue(charArray[i]) * s);
    }
    return x;
}
</code>```

Title: How can I convert String to Int?

Body:
If you're looking for the long way, just create your one method:

static int convertToInt(string a)
{
    int x = 0;

    Char[] charArray = a.ToCharArray();
    int j = charArray.Length;

    for (int i = 0; i < charArray.Length; i++)
    {
        j--;
        int s = (int)Math.Pow(10, j);

        x += ((int)Char.GetNumericValue(charArray[i]) * s);
    }
    return x;
}


问:
Angularjs: How to get value of input without ng-model
I need to make some inputs by ng-repeat, and in my json file I have in object where is a property called name, like this:

```<code>"url":"find_company",
    "values":[
      {
        "name":"company name",
        "type":"input_search"
      },{
        "name":"company_phone",
        "type":"input_search"
      }
    ]
</code>```

I want to make search in DB, in search you can find by any field or by two or more field. Field called the same as property of object. So by ng-keyup I need to send to my function

```<code>search(field, value)
</code>```

two arguments. I want to do something like this

```<code><div ng-repeat="value in param.values">
    <input ng-if="value.type == 'input_search'"
           ng-keyup="search(value.name, this.text)"
           type="text">
</code>```

How can a send to function text of this input without using ng-model? Where this.text is value of input.

答:
since you are using ng-keyup, you can retrieve input value with $event.target.value.

comment: this is fit for normal event like onclick, but not fit for angular.

refer the below example.

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.showValue = function(val) {
      alert(val);
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <input type="test" ng-keyup="showValue($event.target.value)">
</div></code>```

Body:
I need to make some inputs by ng-repeat, and in my json file I have in object where is a property called name, like this:

"url":"find_company",
    "values":[
      {
        "name":"company name",
        "type":"input_search"
      },{
        "name":"company_phone",
        "type":"input_search"
      }
    ]

I want to make search in DB, in search you can find by any field or by two or more field. Field called the same as property of object. So by ng-keyup I need to send to my function

search(field, value)

two arguments. I want to do something like this

    <input ng-if="value.type == 'input_search'"
           ng-keyup="search(value.name, this.text)"
           type="text">

How can a send to function text of this input without using ng-model? Where this.text is value of input.

Body:
since you are using ng-keyup, you can retrieve input value with $event.target.value.

comment: this is fit for normal event like onclick, but not fit for angular.

refer the below example.

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.showValue = function(val) {
      alert(val);
    }
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <input type="test" ng-keyup="showValue($event.target.value)">
</div>


问:
Count Stored Procedures in Database?
How can i count the number of stored procedures in my database and is it a bad practice to have too many stored procedures?</p>

答:
you may want to exclude system stored procedures from your count

One way would be to call:

```<code>select count(*) from sysobjects
    where xtype = 'P'
    and category = 0
    and left(name,2) <> 'sp'
</code>```

That is assuming that you do not prefix your procedures with sp

OwnerDisplayName: Jack

Title: Count Stored Procedures in Database?

LastEditorDisplayName: Cade Roux

Body:
you may want to exclude system stored procedures from your count

One way would be to call:

select count(*) from sysobjects
    where xtype = 'P'
    and category = 0
    and left(name,2) <> 'sp'

That is assuming that you do not prefix your procedures with sp

OwnerDisplayName: kristof


问:
can the caller function close the xml reader resource
I have the following function which takes url path and gets the reader. As i cannot close the reader and return it. Can the caller close the returned reader object.  </p>

```<code>public  XmlReader GetXMLContent(string Path)
        {
         XmlTextReader responseReader= new XmlTextReader(XmlUrlPath);
         return responseReader;
        }

 XmlTextReader myReader =  GetXMLContent("http://sample.xml");
 while() // loop through all the elements
 {
 }

 myReader.close(); // close the reader
</code>```

答:
Yes, absolutely. When the method returns, the caller has effectively taken ownership of the reader (in this particular case).

Admittedly I'd use a using statement instead though:

```<code>using (XmlTextReader reader = GetXmlContent("http://sample.xml"))
{
    ...
}
</code>```

... with your current proposed code, you won't close the reader if an exception is thrown.

Body:
I have the following function which takes url path and gets the reader. As i cannot close the reader and return it. Can the caller close the returned reader object.

public  XmlReader GetXMLContent(string Path)
        {
         XmlTextReader responseReader= new XmlTextReader(XmlUrlPath);
         return responseReader;
        }

 XmlTextReader myReader =  GetXMLContent("http://sample.xml");
 while() // loop through all the elements
 {
 }

 myReader.close(); // close the reader

Body:
Yes, absolutely. When the method returns, the caller has effectively taken ownership of the reader (in this particular case).

Admittedly I'd use a using statement instead though:

using (XmlTextReader reader = GetXmlContent("http://sample.xml"))
{
    ...
}

... with your current proposed code, you won't close the reader if an exception is thrown.


问:
How do I remove space between flexbox vertically centred rows?
I have two rows, with a heading in the top row, and 2 columns in the bottom row, all vertically centred within a fullscreen wrap. For some reason, I cannot get rid of the extra vertical space that the fullscreen wrap adds in between the two rows, despite adding:

```<code>align-content:centre
</code>```

as well as display: flex to both parent divs (.wrap and .row)

What am I doing wrong?

jsfiddle: https://jsfiddle.net/ar4Ltoke/2/

.wrap {
  width: 1280px;
  min-height: 100vh;
  border-style: solid;
}

.row {
  width: 100%;
  align-items: flex-start;
  margin: auto;
  border: 1;
  border-style: solid;
}

.column_left {
  flex-basis: 60%;
  border: 1;
}

.column_right {
  flex-basis: 30%;
}

@media (min-width:640px) {
  .row {
    display: flex;
    justify-content: space-between;
  }
  .wrap {
    display: flex;
    align-content: center;
    flex-direction: column;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="row">
    <p class="blue">About me</p>
  </div>
  <div class="row">
    <div class="column_left">
      <p class="leadpara">Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus
        commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi
        erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.
      </p>
    </div>
    <div class="column_right">
      <p class="leadpara">
        Email
        <br> Add me on Linkedin
        <br> Tweet at @fsd
      </p>
    </div>
  </div>
</div></code>```

答:
Two reasons:

You have margin: auto on .row. That causes both .row flex items to distribute space equally in the container, which forces them to separate.

The .wrap element is a column-direction flex container. That means that the main axis is vertical. As a result, you need justify-content to vertically center the rows.

revised demo

For a more detailed explanation see:

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

Body:
I have two rows, with a heading in the top row, and 2 columns in the bottom row, all vertically centred within a fullscreen wrap. For some reason, I cannot get rid of the extra vertical space that the fullscreen wrap adds in between the two rows, despite adding:

align-content:centre

as well as display: flex to both parent divs (.wrap and .row)

What am I doing wrong?

jsfiddle: https://jsfiddle.net/ar4Ltoke/2/

.wrap {
  width: 1280px;
  min-height: 100vh;
  border-style: solid;
}

.row {
  width: 100%;
  align-items: flex-start;
  margin: auto;
  border: 1;
  border-style: solid;
}

.column_left {
  flex-basis: 60%;
  border: 1;
}

.column_right {
  flex-basis: 30%;
}

@media (min-width:640px) {
  .row {
    display: flex;
    justify-content: space-between;
  }
  .wrap {
    display: flex;
    align-content: center;
    flex-direction: column;
  }
}

About me

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus
        commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi
        erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

        Email

 Add me on Linkedin

 Tweet at @fsd