问:
Google map autocenter with multiple markers
I created a map to display my search results as markers on the map, and it almost works perfect, however the auto center/zoom is not working as needed. The map addresses or dynamic so I can not hardcode specific coordinates.

I used some of my code from a previous question and other code to use bounds to try and get the coordinates from 2 markers and find the center, however no matter what I do it just doesn't work properly.

Here's the code I'm using ---

```<code><!--- SEARCH MAP --->
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>

<?php function getCoordinates($address){
$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=TOKEN_KEY";
$response = file_get_contents($url);
$json = json_decode($response,TRUE); //generate array object from the response from the web
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
} ?>

<script type="text/javascript">

<?php
$locations = array();
//$location_query = new WP_Query( array(
//'posts_per_page' => 100
// ) );

echo "//markers: 100\n";
echo "var locations = [";
$comma = "";
//while ( $location_query->have_posts() ) {
//$location_query->the_post();

while (have_posts()) {
the_post();

$add = get_post_meta(get_the_ID(), 'address', true);
$property_pin = get_post_meta(get_the_ID(), 'pincode', true);
$terms = wp_get_post_terms(get_the_ID(), 'city');

if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
     foreach ( $terms as $term ) {
if ($term->parent == 0) {
     $addy = getCoordinates($add, $term->name);
     }
  }

}

$title = str_replace("'", "\'", get_the_title());
echo $comma . "['" . $title . "', " . $addy . ", " . get_the_id() . "]";
$comma = ", ";
}
echo "];\n\n";

//info content
echo "var theinfo = [";
$comma2 = "";

while (have_posts()) {
the_post();

$add = get_post_meta(get_the_ID(), 'address', true);
$property_price = get_post_meta(get_the_ID(),'price',true);
$terms = wp_get_post_terms(get_the_ID(), 'city');

if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
     foreach ( $terms as $term ) {
if ($term->parent == 0) { //check for parent terms only
     $tcity = $term->name;
     }
  }

}

$title = str_replace("'", "\'", get_the_title());
$link = get_the_id();
$linkto = '<a href="/property/'.$link.'/">'.$title.'</a>';
$class = 'class="mapmarkers"';
echo $comma2 . "['<div ".$class."><h3>" . $linkto . "</h3><h4>" . $tcity . "</h4><p>$" . $property_price ."</p></div>']";
$comma2 = ", ";
}
echo "];\n\n";

?>

 var map;
   var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 0,
minZoom: 5,
maxZoom: 15,
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);

// Info Window Content
    var infoWindowContent = theinfo;

 // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map
    for( i = 0; i < locations.length; i++ ) {
        var position = new google.maps.LatLng(locations[i][1], locations[i][2]);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: locations[i][0]
        });
//bounds.extend(position);
bounds.extend(marker.getPosition());

        // Allow each marker to have an info window
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

// Automatically center the map fitting all markers on the screen
 map.fitBounds(bounds);
 map.panToBounds(bounds);
}

  // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
       this.setZoom(8);
    google.maps.event.removeListener(boundsListener);
   });
</script>
</code>```

With my code the map is rendering like so ---

But I need it to be more so like this ---

The examples are using only 2 markers but the real amount and locations will be dynamic. How can I fix this?

UPDATE

My coordinates var locations = [['1460 Broadway', 40.7551055,-73.9862093, 2299], ['246 W 18th St', 40.741807,-74.0000351, 2114]];

答:
May be this can help some one.
If you have requirement to add a ripple around you marker, you can do something like this. you can add ripple to all or some of the markers depends on your requirement.

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
   <title>Google Maps Multiple Markers</title>
  <script src="http://maps.google.com/maps/api/js?sensor=false"
          type="text/javascript"></script>
</head>
<body>
  <div id="map" style="width: 1000px; height: 500px;"></div>

   <script type="text/javascript">
     var locations = [
     ['Saudi Arabia',23.885942, 45.079162   , 6],
      ['United Arab Emirates', 23.424076, 53.847818, 4],
      ['Bahrain',25.930414  ,50.637772  , 5],
      ['Iraq',  33.223191,  43.679291   , 3],
      ['Kuwait',29.31166,   47.481766   , 2],
      ['Qatar',25.354826,   51.183884   , 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(23.885942, 45.079162),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    var icon = {
                url: "Ripple.svg", // url of ripple svg image
                scaledSize: new google.maps.Size(200, 200), // scaled size
                origin: new google.maps.Point(0,0), // origin
                anchor: new google.maps.Point(100,100) // anchor
            };

  for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({

        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
         icon: icon,
            optimized: false
      });

       google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
      }
for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

  </script>
</body>
</html>
</code>```

]3

Body:
I created a map to display my search results as markers on the map, and it almost works perfect, however the auto center/zoom is not working as needed. The map addresses or dynamic so I can not hardcode specific coordinates.

I used some of my code from a previous question and other code to use bounds to try and get the coordinates from 2 markers and find the center, however no matter what I do it just doesn't work properly.

Here's the code I'm using ---

<?php function getCoordinates($address){
$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=TOKEN_KEY";
$response = file_get_contents($url);
$json = json_decode($response,TRUE); //generate array object from the response from the web
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
} ?>

With my code the map is rendering like so ---

But I need it to be more so like this ---

The examples are using only 2 markers but the real amount and locations will be dynamic. How can I fix this?

UPDATE

My coordinates var locations = [['1460 Broadway', 40.7551055,-73.9862093, 2299], ['246 W 18th St', 40.741807,-74.0000351, 2114]];

Body:
May be this can help some one.
If you have requirement to add a ripple around you marker, you can do something like this. you can add ripple to all or some of the markers depends on your requirement.

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
   <title>Google Maps Multiple Markers</title>
  <script src="http://maps.google.com/maps/api/js?sensor=false"
          type="text/javascript"></script>
</head>
<body>
  <div id="map" style="width: 1000px; height: 500px;"></div>

   <script type="text/javascript">
     var locations = [
     ['Saudi Arabia',23.885942, 45.079162   , 6],
      ['United Arab Emirates', 23.424076, 53.847818, 4],
      ['Bahrain',25.930414  ,50.637772  , 5],
      ['Iraq',  33.223191,  43.679291   , 3],
      ['Kuwait',29.31166,   47.481766   , 2],
      ['Qatar',25.354826,   51.183884   , 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(23.885942, 45.079162),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    var icon = {
                url: "Ripple.svg", // url of ripple svg image
                scaledSize: new google.maps.Size(200, 200), // scaled size
                origin: new google.maps.Point(0,0), // origin
                anchor: new google.maps.Point(100,100) // anchor
            };

  for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({

        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
         icon: icon,
            optimized: false
      });

       google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
      }
for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

  </script>
</body>
</html>

]3


来源: stackexchange

问:
How does a wrapper work for JsonUtility
So I've been looking to convert my Json array into an array of objects in Unity. I've found my solution from a 2 yeard old thread without explanation but I'm curious as to how it actually works.

If I use Visual Studio to look for the definition of FromJson it shows me this

public static T FromJson<T>(string json);

As I understand is that FromJson asks for an object to be filled, I give the class MyWrapper but besides telling MyWrapper that he contains a list of Question I never ask it to create a new item in the list. So how does it actually fill the list?

C#

```<code>MyWrapper wrappedQuestions = JsonUtility.FromJson<MyWrapper>(jsonString);

[Serializable]
public class MyWrapper
{
    public List<Question> questions;
}

[Serializable]
public class Question
{
    public int questionType;
    public string questionString;
    public int questionAnswer;
}
</code>```

Json

```<code>{
    "questions": [
      {
        "questionType":  1,
        "questionString": "4^2",
        "questionAnswer": 16
      },
      {
        "questionType":  2,
        "questionString": "√(25)",
        "questionAnswer": 5
      }
    ]
}
</code>```

I'm still a beginner programmer so I hope I'am able to ask such questions here.

答:
If you wonder why you need a wrapper for that, that's simply because Unity engineers did not add direct support for primitive types or arrays. It's just how they programmed it. Most Json API are not like this.

So how does it actually fill the list?

Reflection.

1.It reads the json you passed to it. It detects the questions variable in the json. It detects that the questions variable is an array due to the format such as  [] and the commas that separates each item.

2.It finds the type of that  questions variable which is Question or List of Question.

3.It uses Activator.CreateInstance to create new instance of Question, read each value from each variable in the json and then fill them up with reflection with that new instance it created.

4. It returns the new instance that is filled.

If you read and understand how to do basic stuff with reflection in C#, you may be able to make your own simple Json parser with the Queue class.

Finally, you can use the JsonHelper wrapper from this answer to serialize/de-serialize arrays easily without having to make a wrapper for each class.

ContentLicense: CC BY-SA 3.0

Title: How does a wrapper work for JsonUtility

Body:
So I've been looking to convert my Json array into an array of objects in Unity. I've found my solution from a 2 yeard old thread without explanation but I'm curious as to how it actually works.

If I use Visual Studio to look for the definition of FromJson it shows me this

public static T FromJson<T>(string json);

As I understand is that FromJson asks for an object to be filled, I give the class MyWrapper but besides telling MyWrapper that he contains a list of Question I never ask it to create a new item in the list. So how does it actually fill the list?

C#

MyWrapper wrappedQuestions = JsonUtility.FromJson<MyWrapper>(jsonString);

[Serializable]
public class MyWrapper
{
    public List<Question> questions;
}

[Serializable]
public class Question
{
    public int questionType;
    public string questionString;
    public int questionAnswer;
}

Json

{
    "questions": [
      {
        "questionType":  1,
        "questionString": "4^2",
        "questionAnswer": 16
      },
      {
        "questionType":  2,
        "questionString": "√(25)",
        "questionAnswer": 5
      }
    ]
}

I'm still a beginner programmer so I hope I'am able to ask such questions here.


问:
How to get a dynamic id via 'getElementById' in javascript
First of all I've gone through most similar questions in StackOverflow and nothing is relevant.

I have a table that has dynamically created id for each td. (Example: a td has an id "0 0")

I need to access that particular td using the id.
I tried the following code:

```<code>document.getElementById("\""+rowID + " " + 0 + "\"");
</code>```

This throws "null". "rowID" is also dynamically defined.

When I try the following:

```<code>document.getElementById("0 0");
</code>```

I get the following output correctly:

```<code><td class="cell" id="0 0">20</td>
</code>```

Any help is appreciated.

答:
This boils down to: How do I do string concatenation in JavaScript?

```<code>document.getElementById(rowID + " 0");
// or if we assume a `colID` variable:
document.getElementById(rowID + " " + colID);
</code>```

However, note that you're breaking just about the only rule there is for the id attribute: It cannot contain a space. Some browsers may let you get away with having that space (in fact, Chrome, Firefox, and IE11 all do), but it's explicitly not allowed.

Replace the space with (say) an underscore (_) or an x in both the id attribute and your code. E.g., 0x0. (ids can start with digits, although people will tell you they can't because a CSS ID selector cannot start with an unescaped digit.)

Body:
First of all I've gone through most similar questions in StackOverflow and nothing is relevant.

I have a table that has dynamically created id for each td. (Example: a td has an id "0 0")

I need to access that particular td using the id.
I tried the following code:

document.getElementById("\""+rowID + " " + 0 + "\"");

This throws "null". "rowID" is also dynamically defined.

When I try the following:

document.getElementById("0 0");

I get the following output correctly:

20

Any help is appreciated.

Body:
This boils down to: How do I do string concatenation in JavaScript?

document.getElementById(rowID + " 0");
// or if we assume a `colID` variable:
document.getElementById(rowID + " " + colID);

However, note that you're breaking just about the only rule there is for the id attribute: It cannot contain a space. Some browsers may let you get away with having that space (in fact, Chrome, Firefox, and IE11 all do), but it's explicitly not allowed.

Replace the space with (say) an underscore (_) or an x in both the id attribute and your code. E.g., 0x0. (ids can start with digits, although people will tell you they can't because a CSS ID selector cannot start with an unescaped digit.)


问:
Capture changes for the last 30 minutes from tables
I need only to capture the changes for last 30 minutes only in for the below query:

```<code>  SELECT
  P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
  FROM
  TABLE1 P,
  TABLE2 C,
  TABLE3 T
  WHERE
  PM.COL1(+)  = C.COL1
  AND T.COL2(+) = C.COL2
</code>```

TABLE 1, TABLE 2 AND TABLE3 each has a modification date column, but I think adding the following to the query logically won't be right and it might degrade the query execution performance

```<code> SELECT
 P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
 FROM
 TABLE1 P,
 TABLE2 C,
 TABLE3 T
 WHERE
 PM.COL1(+)  = C.COL1
 AND T.COL2(+) = C.COL2
 AND P.MODIFICATION_DATE > SYSDATE - 30
 AND C.MODIFICATION_DATE > SYSDATE - 30
 AND T.MODIFICATION_DATE > SYSDATE - 30;
</code>```

Also not all the 3 tables are updated at the same time, TABLE2 as an example last modification_date was yesterday at 11:00 am while TABLE3 modification_date is today at 2:00 pm.

How can I capture the latest 30 minutes changes between the tables?

答:
Your query is incorrect in multiple different ways.  First, sysdate - 30 subtracts 30 days not 30 minutes from the value.

From what you describe, the following may be what you want:

```<code>SELECT . . .
FROM (SELECT P.*
      FROM TABLE1 P
      WHERE P.MODIFICATION_DATE > SYSDATE - 30 / (24 * 60)
     ) P FULL JOIN
     (SELECT C.*
      FROM TABLE2 C
      WHERE C.MODIFICATION_DATE > SYSDATE - 30 / (24 * 60)
     ) C
     ON P.COL1 = C.COL1 FULL JOIN
     (SELECT T.*
      FROM TABLE3 T
      WHERE T.MODIFICATION_DATE > SYSDATE - 30 / (24 * 60)
     )
     ON T.COL2 = C.COL2;
</code>```

Body:
I need only to capture the changes for last 30 minutes only in for the below query:

  SELECT
  P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
  FROM
  TABLE1 P,
  TABLE2 C,
  TABLE3 T
  WHERE
  PM.COL1(+)  = C.COL1
  AND T.COL2(+) = C.COL2

TABLE 1, TABLE 2 AND TABLE3 each has a modification date column, but I think adding the following to the query logically won't be right and it might degrade the query execution performance

 SELECT
 P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
 FROM
 TABLE1 P,
 TABLE2 C,
 TABLE3 T
 WHERE
 PM.COL1(+)  = C.COL1
 AND T.COL2(+) = C.COL2
 AND P.MODIFICATION_DATE > SYSDATE - 30
 AND C.MODIFICATION_DATE > SYSDATE - 30
 AND T.MODIFICATION_DATE > SYSDATE - 30;

Also not all the 3 tables are updated at the same time, TABLE2 as an example last modification_date was yesterday at 11:00 am while TABLE3 modification_date is today at 2:00 pm.

How can I capture the latest 30 minutes changes between the tables?

Body:
Your query is incorrect in multiple different ways.  First, sysdate - 30 subtracts 30 days not 30 minutes from the value.

From what you describe, the following may be what you want:

SELECT . . .
FROM (SELECT P.*
      FROM TABLE1 P
      WHERE P.MODIFICATION_DATE > SYSDATE - 30 / (24 * 60)
     ) P FULL JOIN
     (SELECT C.*
      FROM TABLE2 C
      WHERE C.MODIFICATION_DATE > SYSDATE - 30 / (24 * 60)
     ) C
     ON P.COL1 = C.COL1 FULL JOIN
     (SELECT T.*
      FROM TABLE3 T
      WHERE T.MODIFICATION_DATE > SYSDATE - 30 / (24 * 60)
     )
     ON T.COL2 = C.COL2;


问:
Python TypeError: sequence item 0: expected str instance, NoneType found
I copied this code from a book:

```<code>lyst = {'Hi':'Hello'}
def changeWord(sentence):
    def getWord(word):
        lyst.get(word, word)
    return ''.join(map(getWord, sentence.split()))
</code>```

I get this error:

```<code>Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    cambiaPronome('ciao')
  File "C:\Python33\2.py", line 6, in cambiaPronome
    return ''.join(map(getWord, list(frase)))
TypeError: sequence item 0: expected str instance, NoneType found
</code>```

What is wrong?

答:
The problem is you're trying to write to a string a type which is NoneType. That's not allowed.

If you're interested in getting the None values as well one of the things  you can do is convert them to strings.

And you can do it with a list comprehension, like:

return ''.join([str(x) for x in map(getWord, sentence.split())])

But to do it properly in this case, you have to return something on the inner function, else you have the equivalent to return None

Body:
I copied this code from a book:

lyst = {'Hi':'Hello'}
def changeWord(sentence):
    def getWord(word):
        lyst.get(word, word)
    return ''.join(map(getWord, sentence.split()))

I get this error:

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    cambiaPronome('ciao')
  File "C:\Python33\2.py", line 6, in cambiaPronome
    return ''.join(map(getWord, list(frase)))
TypeError: sequence item 0: expected str instance, NoneType found

What is wrong?


问:
Python DDL abstraction
Are there any Python libraries that provide an abstraction of SQL DDL?
I have an application that needs to dynamically add/adjust database columns, and I don't want to have to model CREATE TABLE and all the datatypes.

I am looking for something relatively lightweight; full ORMs like SQLAlchemy will unfortunately not be available.

答:
Have you looked at SQLAlchemy?

It's an object-relational mapper (abstraction layer) that sits between your python code and the (relational) database.

It does DDL such as create table.

ContentLicense: CC BY-SA 2.5

Title: Python DDL abstraction


问:
How can i edit list of class object id property in my controller class action method by loop through list object to match id obtain from another view
```<code>    // This is my controller class containing to action method

    // this is list of student type
    List<Student> std = new List<Student>();
            // here i add item in list and pass it to my index.cshtml
            public ActaionResult Index()
            {
                std.Add(new Student {Id = 1,Name = "Nazir",Roll = "13b-049-bs",Batch = "13b" });
                std.Add(new Student {Id = 2 ,Name = "Hamza", Roll = "13b-034-bs", Batch = "13b" });
                return View(std);
            }

    // this is my edit action method invoke when user click on edit to
//corresponding record make request like Student/Edit/1

            [HttpGet]
            public ActionResult Edit(int id)
            {
                Student student = null;
                foreach(Student item in std){
    // here i compare the id coming from url request to list of student type
                    if (item.Id == id) {
                        student = item;
                    }
                }
                return View(student);
            }

    // this is my edit.cshtml file

    @model Test.Models.Student

    @{
        ViewBag.Title = "Edit";
    }

    <h2>Edit</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Student</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.Id)

            <div class="form-group">
                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
   // In here display Name of student object property
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Roll, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
  // In here display Roll of student object property
                    @Html.EditorFor(model => model.Roll, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Roll, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Batch, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
        // In here display Batch of student object property
                    @Html.EditorFor(model => model.Batch, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Batch, "", new {
        @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
  }
</code>```

but data doesn't appear in html controls

答:
You are trying to access an object std in two different request contexts. You need to have some state mechanism like Session ,TempData ,Application etc to store information you wanted to later access.

For your example right way is to extract object creation outside of action and call it from another action would do it.

```<code>// this is list of student type
List<Student> std = new List<Student>();

public void GetStudents() {
 std.Add(new Student {
  Id = 1, Name = "Nazir", Roll = "13b-049-bs", Batch = "13b"
 });
 std.Add(new Student {
  Id = 2, Name = "Hamza", Roll = "13b-034-bs", Batch = "13b"
 });
}

// here i add item in list and pass it to my index.cshtml
public ActaionResult Index() {
 var std = GetStudents();
 return View(std);
}
// this is my edit action method invoke when user click on edit to
</code>```

//corresponding record make request like Student/Edit/1

```<code>        [HttpGet]
        public ActionResult Edit(int id)
        {
            GetStudents(); // notice call here...
            Student student = null;
            foreach(Student item in std){
// here i compare the id coming from url request to list of student type
                if (item.Id == id) {
                    student = item;
                }
            }
            return View(student);
        }
</code>```

and if you want to use State , Stored GetStudents Data in Session/Tempdata and then use that directly without calling GetStudents in Edit Method

I hope that helps !!

Body:
    // This is my controller class containing to action method

    // this is list of student type
    List<Student> std = new List<Student>();
            // here i add item in list and pass it to my index.cshtml
            public ActaionResult Index()
            {
                std.Add(new Student {Id = 1,Name = "Nazir",Roll = "13b-049-bs",Batch = "13b" });
                std.Add(new Student {Id = 2 ,Name = "Hamza", Roll = "13b-034-bs", Batch = "13b" });
                return View(std);
            }

    // this is my edit action method invoke when user click on edit to
//corresponding record make request like Student/Edit/1

            [HttpGet]
            public ActionResult Edit(int id)
            {
                Student student = null;
                foreach(Student item in std){
    // here i compare the id coming from url request to list of student type
                    if (item.Id == id) {
                        student = item;
                    }
                }
                return View(student);
            }

    // this is my edit.cshtml file

    @model Test.Models.Student

    @{
        ViewBag.Title = "Edit";
    }

Edit

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

Student

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.Id)

                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

   // In here display Name of student object property
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Roll, htmlAttributes: new { @class = "control-label col-md-2" })

  // In here display Roll of student object property
                    @Html.EditorFor(model => model.Roll, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Roll, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Batch, htmlAttributes: new { @class = "control-label col-md-2" })

        // In here display Batch of student object property
                    @Html.EditorFor(model => model.Batch, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Batch, "", new {
        @class = "text-danger" })

                    <input type="submit" value="Save" class="btn btn-default" />

  }

but data doesn't appear in html controls

Body:
You are trying to access an object std in two different request contexts. You need to have some state mechanism like Session ,TempData ,Application etc to store information you wanted to later access.

For your example right way is to extract object creation outside of action and call it from another action would do it.

// this is list of student type
List<Student> std = new List<Student>();

public void GetStudents() {
 std.Add(new Student {
  Id = 1, Name = "Nazir", Roll = "13b-049-bs", Batch = "13b"
 });
 std.Add(new Student {
  Id = 2, Name = "Hamza", Roll = "13b-034-bs", Batch = "13b"
 });
}

// here i add item in list and pass it to my index.cshtml
public ActaionResult Index() {
 var std = GetStudents();
 return View(std);
}
// this is my edit action method invoke when user click on edit to

//corresponding record make request like Student/Edit/1

        [HttpGet]
        public ActionResult Edit(int id)
        {
            GetStudents(); // notice call here...
            Student student = null;
            foreach(Student item in std){
// here i compare the id coming from url request to list of student type
                if (item.Id == id) {
                    student = item;
                }
            }
            return View(student);
        }

and if you want to use State , Stored GetStudents Data in Session/Tempdata and then use that directly without calling GetStudents in Edit Method

I hope that helps !!


问:
How to run tests without passing local relative path in Action class for the IE/Chrome WebDriver and run using only maven dependencies in pom file
I want to avoid giving the relative path or absolute path for IE/Chrome driver in this below method. Rather I want to call the IE/Chrome driver from pom file as maven dependencies. Instead of using the below local path I want to pass the pom dependency path to call the driver. Could you please anyone guide me on this.</p>

```<code>public static void openBrowser(String data) throws Exception{

        if(data.equals("IE")){
            File file = new File("C:\\Automation\\external jars\\IE Related\\IEDriverServer.exe");
            System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
            driver = new InternetExplorerDriver();
            driver.manage().window().maximize();
            }
        else (data.equals("Chrome")){
            File file = new File("C:\\Automation\\external jars\\Drivers\\ChromeDriver\\chromedriver.exe");
            System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
            driver=new ChromeDriver();
            driver.manage().window().maximize();
            }

}
</code>```

答:
First you copy your dependency by unpacking the artifact with its inner executable driver file somewhere into your project
Here a sample you need in your pom(profile or default build):

```<code> <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.10</version>

    <executions>
        <execution>
            <id>unpack</id>
            <phase>process-resources</phase>
            <goals>
                <goal>unpack</goal>
            </goals>
            <configuration>
                <artifactItems>
                    <artifactItem>
                       <groupId>org.seleniumhq.selenium</groupId>
                       <artifactId>selenium-ie-driver</artifactId>
                       <version>3.0.1</version>
                    </artifactItem>
                </artifactItems>
          </configuration>
      </execution>
   </executions>
</plugin>
</code>```

After this you should find the file in the folder ${project.build.directory}/dependency or configure the plugin to unpack it to a place you want.

From this place you can, if you need , copy the file wherever you want. If you want it relative to your project you can use the maven vars like "${project.build.directory}" or even source directory.

```<code>                <!-- copy driver file -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.1</version>
                    <executions>
                        <execution>
                            <id>copy-resources</id>
                            <phase>package</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/driverDir</outputDirectory>
                                <resources>
                                    <resource>
                                        <include>driver.file</include>
                                        <directory>${project.build.directory}/dependency</directory>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
</code>```

This file you can provide to selenium.Lets assume you put it into "src/main/resources" which is on classpath you should be able to find this file in Java by

```<code>MyClass.class.getResource("/driver.file");
</code>```

Body:
I want to avoid giving the relative path or absolute path for IE/Chrome driver in this below method. Rather I want to call the IE/Chrome driver from pom file as maven dependencies. Instead of using the below local path I want to pass the pom dependency path to call the driver. Could you please anyone guide me on this.

public static void openBrowser(String data) throws Exception{

        if(data.equals("IE")){
            File file = new File("C:\\Automation\\external jars\\IE Related\\IEDriverServer.exe");
            System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
            driver = new InternetExplorerDriver();
            driver.manage().window().maximize();
            }
        else (data.equals("Chrome")){
            File file = new File("C:\\Automation\\external jars\\Drivers\\ChromeDriver\\chromedriver.exe");
            System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
            driver=new ChromeDriver();
            driver.manage().window().maximize();
            }

}

Body:
First you copy your dependency by unpacking the artifact with its inner executable driver file somewhere into your project
Here a sample you need in your pom(profile or default build):

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.10</version>

    <executions>
        <execution>
            <id>unpack</id>
            <phase>process-resources</phase>
            <goals>
                <goal>unpack</goal>
            </goals>
            <configuration>
                <artifactItems>
                    <artifactItem>
                       <groupId>org.seleniumhq.selenium</groupId>
                       <artifactId>selenium-ie-driver</artifactId>
                       <version>3.0.1</version>
                    </artifactItem>
                </artifactItems>
          </configuration>
      </execution>
   </executions>
</plugin>

After this you should find the file in the folder ${project.build.directory}/dependency or configure the plugin to unpack it to a place you want.

From this place you can, if you need , copy the file wherever you want. If you want it relative to your project you can use the maven vars like "${project.build.directory}" or even source directory.

                <!-- copy driver file -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.1</version>
                    <executions>
                        <execution>
                            <id>copy-resources</id>
                            <phase>package</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/driverDir</outputDirectory>
                                <resources>
                                    <resource>
                                        <include>driver.file</include>
                                        <directory>${project.build.directory}/dependency</directory>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

This file you can provide to selenium.Lets assume you put it into "src/main/resources" which is on classpath you should be able to find this file in Java by

MyClass.class.getResource("/driver.file");


答:
alternative solution would be using distinct,</p>

```<code>select count(*) from (select distinct a, extract(hour from time) from t where time >'2017-11-26 01:00:11' and time <'2017-11-26 05:00:00' and sensor_id=123)t;
</code>```

Title: How to check if there's a record in every hour in specified time-frame and then count it?

Body:
I'm using PostgreSQL and this is my table measurement_archive:

+-----------+------------------------+------+-------+
| sensor_id | time                   | type | value |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 01:53:11+00 | PM25 | 34.32 |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 02:15:11+00 | PM25 | 32.1  |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 04:32:11+00 | PM25 | 75.3  |
+-----------+------------------------+------+-------+

I need a query that will take records from specified timeframe (eg. from 2017-01-01 00:00:00 to 2017-12-01 23:59:59) and then check if in every hour there is at least 1 record - if there is, then add 1 to result.

So, if I make that query from 2017-11-26 01:00:00 to 2017-11-26 04:59:59+00 for sensor_id == 123 on above table then the result should be 3.

Body:
alternative solution would be using distinct,

select count(*) from (select distinct a, extract(hour from time) from t where time >'2017-11-26 01:00:11' and time <'2017-11-26 05:00:00' and sensor_id=123)t;


问:
Rails Nested Singular Resource Routing
I have a simple User model with a singular nested Profile resource so in my routes.rb I have:

```<code>resources :users do
  resource :profile, :only => [:edit, :update, :show]
end
</code>```

This generates the expected routes:

```<code>edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}
</code>```

I've created a simple controller update method that updates the model and then redirects upon successful update:

```<code>def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end
</code>```

The problem is that once the form is submitted, the form redirects to mydomain.com/users/4/profile.22 where 22 happens to be the id of the profile.  Clearly this confuses the controllers since the routing interprets the '22' as the format.

My question is, how do I get this to redirect to mydomain.com/users/4/profile instead?  I've tried the following variations on the redirect_to statement to no effect, they all result in the same incorrect url:

```<code>redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )
</code>```

What's more, using 'user_profile_path(@user)' elsewhere produces the correct url.

Any ideas?  Oh, and I'm using Rails 3.0.0 and Ruby 1.9.2 if that helps.

答:
You should redirect to user_profile_path(@user) since as your routes says it is:

```<code>/users/:user_id/profile(.:format)
</code>```

If you look at it closely, then you will see, that there is only :user_id parameter needed, thou it is only @user in a path.

```<code>/users/:user_id/profile/:id(.:format)
</code>```

It would be correct if you had resource*s* :profiles in your routes.rb, then as well you could use your path as in your example.

Title: Rails Nested Singular Resource Routing

Body:
I have a simple User model with a singular nested Profile resource so in my routes.rb I have:

resources :users do
  resource :profile, :only => [:edit, :update, :show]
end

This generates the expected routes:

edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}

I've created a simple controller update method that updates the model and then redirects upon successful update:

def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end

The problem is that once the form is submitted, the form redirects to mydomain.com/users/4/profile.22 where 22 happens to be the id of the profile.  Clearly this confuses the controllers since the routing interprets the '22' as the format.

My question is, how do I get this to redirect to mydomain.com/users/4/profile instead?  I've tried the following variations on the redirect_to statement to no effect, they all result in the same incorrect url:

redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )

What's more, using 'user_profile_path(@user)' elsewhere produces the correct url.

Any ideas?  Oh, and I'm using Rails 3.0.0 and Ruby 1.9.2 if that helps.

Body:
You should redirect to user_profile_path(@user) since as your routes says it is:

/users/:user_id/profile(.:format)

If you look at it closely, then you will see, that there is only :user_id parameter needed, thou it is only @user in a path.

/users/:user_id/profile/:id(.:format)

It would be correct if you had resource*s* :profiles in your routes.rb, then as well you could use your path as in your example.


问:
Responsive Layout with same growing gaps in each row
I have a container with a random number of elements which should always align on the left side. The container width can increase or decrease.

If the container size is increasing then the first element from the row+1 should go one row back and should appear on the right side. But it should only go one row back if it can fit there with a padding on the left and right side.

While the element does not have space one row abouve, then the space between the elements should grow until the element from row+1 can fit in this row.

The same functionality should work also in the reverse way.

Here is my code:

.container {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  align-content: flex-start;
}

.container:after {
  display: block;
  content: " invisible node ";
  flex(999 999 auto);
}

.item {
  flex: 0 0 auto;
  margin: 5px;
  width: 50px;
  height: 50px;
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div></code>```

https://jsfiddle.net/p6k537ep/

My Problem ist that in the second row the space between the elements is not the same as in the first row (It depends how many elements are there).

Edit:

But it is working that the elements from the second row can only move one row abouve if they have anough space. The Gap is growing in the correct way in the first row but not in the second one.

答:
You could use the margin property on the :after pseudoelement to keep the blocks together.

fiddle

.container {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  align-content: flex-start;
}

.container:after {
  display: block;
  content: " ";
  margin-left: auto; /* added */
}

.item {
  flex: 0 0 auto;
  margin: 5px;
  width: 50px;
  height: 50px;
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div></code>```

Body:
I have a container with a random number of elements which should always align on the left side. The container width can increase or decrease.

If the container size is increasing then the first element from the row+1 should go one row back and should appear on the right side. But it should only go one row back if it can fit there with a padding on the left and right side.

While the element does not have space one row abouve, then the space between the elements should grow until the element from row+1 can fit in this row.

The same functionality should work also in the reverse way.

Here is my code:

.container {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  align-content: flex-start;
}

.container:after {
  display: block;
  content: " invisible node ";
  flex(999 999 auto);
}

.item {
  flex: 0 0 auto;
  margin: 5px;
  width: 50px;
  height: 50px;
  background-color: green;
}

https://jsfiddle.net/p6k537ep/

My Problem ist that in the second row the space between the elements is not the same as in the first row (It depends how many elements are there).

Edit:

But it is working that the elements from the second row can only move one row abouve if they have anough space. The Gap is growing in the correct way in the first row but not in the second one.

Body:
You could use the margin property on the :after pseudoelement to keep the blocks together.

fiddle

.container {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  align-content: flex-start;
}

.container:after {
  display: block;
  content: " ";
  margin-left: auto; /* added */
}

.item {
  flex: 0 0 auto;
  margin: 5px;
  width: 50px;
  height: 50px;
  background-color: green;
}

<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>


问:
Drools KieSession causes memory leak
I am using Drools 6.3.0.Final to run 100 rules in different KieSessions, one rule per session, and the engine works in STREAM mode. I am using the annotation @Expires at the code level to define the life-time of the Pojo I am pushing in the sessions.

The problem is that after running the application for few hours, I noticed a memory leak, and by analyzing the heap dump I can see millions of Pojos referenced from Drool Sessions. Which means, the Pojos are not removed from the sessions.

Any idea how to fix this issue?

Here is my Pojo:

```<code>@Role(Role.Type.EVENT)
@Expires("10s")
public class DataStreamRecord {
......
.....
}
</code>```

答:
The issue could be fixed using Drools 6.5.0-Final which has conflicts with EAP 6.2 as explained here https://issues.jboss.org/browse/DROOLS-1165

I fixed this issue by adding the following line to the rule just before passing it to Drools :

declare DataStreamRecord @role( event ) @expires( 10s ) end```
</div>
</div>
</p>

<p>Here is an example :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> String drl = "package org.test.common.beans;\r\n"+
 "rule my_rule \r\n"+
 "when\r\n"+
 "$streamRecord:DataStreamRecord()\r\n"+
 "then\r\n"+
  "System.out.println(\"Received data:\" + $streamRecord);\r\n"+
  "end"+
  " declare DataStreamRecord @role( event ) @expires( 10s ) end  ";

 KieServices ks = KieServices.Factory.get();
 KieFileSystem kfs =
 ks.newKieFileSystem().write(ResourceFactory.newByteArrayResource(drl.getBytes())</code>```

Title: Drools KieSession causes memory leak

Body:
I am using Drools 6.3.0.Final to run 100 rules in different KieSessions, one rule per session, and the engine works in STREAM mode. I am using the annotation @Expires at the code level to define the life-time of the Pojo I am pushing in the sessions.

The problem is that after running the application for few hours, I noticed a memory leak, and by analyzing the heap dump I can see millions of Pojos referenced from Drool Sessions. Which means, the Pojos are not removed from the sessions.

Any idea how to fix this issue?

Here is my Pojo:

@Role(Role.Type.EVENT)
@Expires("10s")
public class DataStreamRecord {
......
.....
}

Body:
The issue could be fixed using Drools 6.5.0-Final which has conflicts with EAP 6.2 as explained here https://issues.jboss.org/browse/DROOLS-1165

I fixed this issue by adding the following line to the rule just before passing it to Drools :

declare DataStreamRecord @role( event ) @expires( 10s ) end

Here is an example :

 String drl = "package org.test.common.beans;\r\n"+
 "rule my_rule \r\n"+
 "when\r\n"+
 "$streamRecord:DataStreamRecord()\r\n"+
 "then\r\n"+
  "System.out.println(\"Received data:\" + $streamRecord);\r\n"+
  "end"+
  " declare DataStreamRecord @role( event ) @expires( 10s ) end  ";

 KieServices ks = KieServices.Factory.get();
 KieFileSystem kfs =
 ks.newKieFileSystem().write(ResourceFactory.newByteArrayResource(drl.getBytes())


问:
Timer can not be repeated on android How to fix?
I want Timer execute repeat.
so I try this source

```<code>public static void init() {
    TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           Looper.prepare();
           recordWork();
           Looper.loop();
       }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 1000, 30000);
}
</code>```

init() called when record button click.

why recordWork() only one execute?
this timer not execute repeat.

How to fix this problem?

thanks.

答:
Use handler</p>

```<code>Handler handler = new Handler();
int delay = 2000; //milliseconds

handler.postDelayed(new Runnable(){
    public void run(){
        recordWork();
        handler.postDelayed(this, delay);
    }
}, delay);
</code>```

Body:
I want Timer execute repeat.
so I try this source

public static void init() {
    TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           Looper.prepare();
           recordWork();
           Looper.loop();
       }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 1000, 30000);
}

init() called when record button click.

why recordWork() only one execute?
this timer not execute repeat.

How to fix this problem?

thanks.

Body:
Use handler

Handler handler = new Handler();
int delay = 2000; //milliseconds

handler.postDelayed(new Runnable(){
    public void run(){
        recordWork();
        handler.postDelayed(this, delay);
    }
}, delay);


问:
How to access a constant in an Angular 2 component and service?
I have a constants file constants.ts:

```<code>export const C0NST = "constant";
</code>```

I access it in a service some.service.ts like so:

```<code>import { C0NST } from './constants';

console.log(C0NST); // "constant"
</code>```

However, when I access it in a component template:

some.component.ts:

```<code>import { C0NST } from './constants';
</code>```

some.component.html:

```<code>{{ C0NST }} <!-- Outputs nothing -->
</code>```

However defining a member in the component class works:

some.component.ts

```<code>public const constant = C0NST;
</code>```

some.component.html

```<code>{{ constant }} <!-- constant -->
</code>```

I don't understand why I was able to access the imported constant directly in the service class but not in the component template even though I imported it in the component class.

答:
Since in the Component's template you can only use attributes of the Component's class, you can't directly use any external constants (or external variables).

The most elegant way that I've found so far is the following:

```<code>import { MY_CONSTANT } from '../constants';

@Component({
  // ...
})
export class MyTestComponent implements OnInit {

  readonly MY_CONSTANT = MY_CONSTANT;

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

which basically just creates a new attribute MY_CONSTANT inside the component class. Using readonly we make sure that the new attribute cannot be modified.

Doing so, in your template you can now use:

```<code>{{ MY_CONSTANT }}
</code>```

Body:
I have a constants file constants.ts:

export const C0NST = "constant";

I access it in a service some.service.ts like so:

import { C0NST } from './constants';

console.log(C0NST); // "constant"

However, when I access it in a component template:

some.component.ts:

import { C0NST } from './constants';

some.component.html:

{{ C0NST }}

However defining a member in the component class works:

some.component.ts

public const constant = C0NST;

some.component.html

{{ constant }}

I don't understand why I was able to access the imported constant directly in the service class but not in the component template even though I imported it in the component class.

Body:
Since in the Component's template you can only use attributes of the Component's class, you can't directly use any external constants (or external variables).

The most elegant way that I've found so far is the following:

import { MY_CONSTANT } from '../constants';

@Component({
  // ...
})
export class MyTestComponent implements OnInit {

  readonly MY_CONSTANT = MY_CONSTANT;

  // ...
}

which basically just creates a new attribute MY_CONSTANT inside the component class. Using readonly we make sure that the new attribute cannot be modified.

Doing so, in your template you can now use:

{{ MY_CONSTANT }}

ContentLicense: CC BY-SA 4.0


问:
Logstash 6.0.0: Unknown setting ‘index_type’ for elasticsearch
I'm trying to run logstash config files on ELK 6.0.0 docker image but I got this error:
Unknown setting 'index_type' for elasticsearch

I am retrieving Spark streaming stats and send it to elasticsearch, but even this simple task returns an error. Here is my code:

```<code>input {
  graphite {
    codec => "json"
    port => 10513
    host => "0.0.0.0"
  }
}

output {
  #stdout { codec => "json" }

  elasticsearch {
    codec => "json"
    hosts => "localhost"
    index => "spark-%{+YYYY.MM.DD}"
    index_type => "spark"
  }
}
</code>```

答:
The correct syntax is document_type not index_type:

```<code>  elasticsearch {
    codec => "json"
    hosts => "localhost"
    index => "spark-%{+YYYY.MM.DD}"
    document_type => "spark"          <--- change this
  }
</code>```

Body:
I'm trying to run logstash config files on ELK 6.0.0 docker image but I got this error:
Unknown setting 'index_type' for elasticsearch

I am retrieving Spark streaming stats and send it to elasticsearch, but even this simple task returns an error. Here is my code:

input {
  graphite {
    codec => "json"
    port => 10513
    host => "0.0.0.0"
  }
}

output {
  #stdout { codec => "json" }

  elasticsearch {
    codec => "json"
    hosts => "localhost"
    index => "spark-%{+YYYY.MM.DD}"
    index_type => "spark"
  }
}

Body:
The correct syntax is document_type not index_type:

  elasticsearch {
    codec => "json"
    hosts => "localhost"
    index => "spark-%{+YYYY.MM.DD}"
    document_type => "spark"          <--- change this
  }


问:
Fetching data from Json
I have a json object. I need to get the values after decoding the json object.

However, some values are blank at times. This brings an error to the way I am fetching.

Kindly see below and advice.

```<code>$json = '{
  "Customers": {
    "IdentityStrings": [
      {
        "UniqueSystemIdentifier": "202000000000007004",
        "MSISDN": "211920494162",
        "FirstName": "Donald",
        "MiddleName": {

        },
        "LastName": "Twesiga",
        "DateOfBirth": "2000-01-01",
        "DateIdentityActivated": "20170816153810",
        "DateIdentityRegistered": "20170816153448",
        "OperatorNameRegisteredBy": {

        },

      }
    ]
  },
}';
</code>```

To get the values, I json decode and fetch as below.

```<code>$jsonData = json_decode($json);

   foreach ($jsonData->Customers->IdentityStrings[0] as $key => $value) {

        $UniqueSystemIdentifier = ($jsonData->Customers->IdentityStrings[0]->UniqueSystemIdentifier);
        $MSISDN = ($jsonData->Customers->IdentityStrings[0]->MSISDN);
        $FirstName = ($jsonData->Customers->IdentityStrings[0]->FirstName);
        $MiddleName = ($jsonData->Customers->IdentityStrings[0]->MiddleName);
        $LastName = $jsonData->Customers->IdentityStrings[0]->LastName;
        $DateOfBirth = $jsonData->Customers->IdentityStrings[0]->DateOfBirth;
        $OperatorNameRegisteredBy = $jsonData->Customers->IdentityStrings[0]->OperatorNameRegisteredBy;

    }
</code>```

The problem comes when some are empty like in this case MiddleName and OperatorNameRegisteredBy.

How can I fetch in case they have values or not?

Thank you.

答:
Use ternary conditions so that you can get rid of the error;

```<code>$MSISDN = (isset($jsonData->Customers->IdentityStrings[0]->MSISDN) && !empty($jsonData->Customers->IdentityStrings[0]->MSISDN))? $jsonData->Customers->IdentityStrings[0]->MSISDN : "";
</code>```

So the same for all the values.

Title: Fetching data from Json

Body:
I have a json object. I need to get the values after decoding the json object.

However, some values are blank at times. This brings an error to the way I am fetching.

Kindly see below and advice.

$json = '{
  "Customers": {
    "IdentityStrings": [
      {
        "UniqueSystemIdentifier": "202000000000007004",
        "MSISDN": "211920494162",
        "FirstName": "Donald",
        "MiddleName": {

        },
        "LastName": "Twesiga",
        "DateOfBirth": "2000-01-01",
        "DateIdentityActivated": "20170816153810",
        "DateIdentityRegistered": "20170816153448",
        "OperatorNameRegisteredBy": {

        },

      }
    ]
  },
}';

To get the values, I json decode and fetch as below.

$jsonData = json_decode($json);

   foreach ($jsonData->Customers->IdentityStrings[0] as $key => $value) {

        $UniqueSystemIdentifier = ($jsonData->Customers->IdentityStrings[0]->UniqueSystemIdentifier);
        $MSISDN = ($jsonData->Customers->IdentityStrings[0]->MSISDN);
        $FirstName = ($jsonData->Customers->IdentityStrings[0]->FirstName);
        $MiddleName = ($jsonData->Customers->IdentityStrings[0]->MiddleName);
        $LastName = $jsonData->Customers->IdentityStrings[0]->LastName;
        $DateOfBirth = $jsonData->Customers->IdentityStrings[0]->DateOfBirth;
        $OperatorNameRegisteredBy = $jsonData->Customers->IdentityStrings[0]->OperatorNameRegisteredBy;

    }

The problem comes when some are empty like in this case MiddleName and OperatorNameRegisteredBy.

How can I fetch in case they have values or not?

Thank you.

Body:
Use ternary conditions so that you can get rid of the error;

$MSISDN = (isset($jsonData->Customers->IdentityStrings[0]->MSISDN) && !empty($jsonData->Customers->IdentityStrings[0]->MSISDN))? $jsonData->Customers->IdentityStrings[0]->MSISDN : "";

So the same for all the values.


问:
I have confusion in Git workflow need recommendation

Question is so simple but help me to clear my concepts :)

I am working on a project and make a branch for any new feature, so sometimes in a day, I create more than 4 branches.

For every branch first I check master then create a new branch.

Question:

When we merge all branches one by one its results become all code is merged like I show in the picture or something different than that.

答:
There will be conflicts, assuming first you merge br1, then br2 and br3:

when you merge branch1 with master, line 1-> same, line 2 added by 'DEF' and no merge conflicts.

when you merge branch2 with master, there is conflict in line 2 as line 2 of master contains DEF, so you have to resolve it.

similarly for branch3, will depend on how you resolved above conflict.


问:
PERL How to skip error in while loop
I have this script which automates a process of like on Instagram.
It does exactly what it should do except for one thing. Within the while loop, if a user does not exist the script dies.
In this case, the error should be ignored and the script should continue processing the other users of the list.

This is the error i get:

Error GETing https://www.instagram.com/usernamethatdoesntexist/?__
a=1: Not Found at instagram-post-liker.pl line 29

Thanks for any help

```<code>use WWW::Mechanize;
use JSON;

my $filename = 'data.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";

my $mech_get = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14');

my $mecho = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Linux; U; Android 2.2; de-de; HTC Desire HD 1.18.161.2 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1');

$mecho->get('https://www.instagram.com/');

$mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

my $post_data = {
    username    =>  'username',
    password    =>  'password'
};

$mecho->post('https://www.instagram.com/accounts/login/ajax/', $post_data);

  while (my $row = <$fh>) {
  chomp $row;
  print "getting user $row\n";

    $mech_get->get('https://www.instagram.com/'.$row.'/?__a=1');

    my $decoded_json = decode_json( $mech_get->response()->decoded_content() );

     print "Found Post \n";

    $mech_get->get('https://api.instagram.com/oembed/?url=https://www.instagram.com/p/'.$decoded_json->{user}->{media}->{nodes}[0]->{code}.'/');

    my $decoded_json2 = decode_json( $mech_get->response()->decoded_content() );

    print "Linking Post by Id";
    my $post;

    if($decoded_json2->{media_id} =~ /^([^_]*);*)   {
        $post = $1;
    }

    $mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

    $mecho->post('https://www.instagram.com/web/likes/'.$post.'/like/');

}

sub getcsrf {

    my ($somemech) = @_;

    my $cookies2  = $somemech->response->header('Set-Cookie');

    my $csrf_token2;
    if ($cookies2 =~ /csrftoken=([^;]+);/i){
        return $1;
    }
    else {
        die "Unable to find csrftoken in cookie headers, did something change?";

        }

};
</code>```

答:
you will have to use eval block

here's some documentation:
https://perldoc.perl.org/functions/eval.html

Also, you forgot a / at if($decoded_json2->{media_id} =~ /^([^_]*);*)

your code will be then

```<code>#your code until line 29

eval {$mech_get->get('https://www.instagram.com/'.$row.'/?__a=1');};

if(not $@)
{
    my $decoded_json = decode_json( $mech_get->response()->decoded_content() );

     print "Found Post \n";

    $mech_get->get('https://api.instagram.com/oembed/?url=https://www.instagram.com/p/'.$decoded_json->{user}->{media}->{nodes}[0]->{code}.'/');

    my $decoded_json2 = decode_json( $mech_get->response()->decoded_content() );

    print "Linking Post by Id";
    my $post;

    if($decoded_json2->{media_id} =~ /^([^_]*);*)/   {
        $post = $1;
    }

    $mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

    $mecho->post('https://www.instagram.com/web/likes/'.$post.'/like/');
}
</code>```

Title: PERL How to skip error in while loop

Body:
I have this script which automates a process of like on Instagram.
It does exactly what it should do except for one thing. Within the while loop, if a user does not exist the script dies.
In this case, the error should be ignored and the script should continue processing the other users of the list.

This is the error i get:

Error GETing https://www.instagram.com/usernamethatdoesntexist/?__
a=1: Not Found at instagram-post-liker.pl line 29

Thanks for any help

use WWW::Mechanize;
use JSON;

my $filename = 'data.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";

my $mech_get = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14');

my $mecho = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Linux; U; Android 2.2; de-de; HTC Desire HD 1.18.161.2 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1');

$mecho->get('https://www.instagram.com/');

$mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

my $post_data = {
    username    =>  'username',
    password    =>  'password'
};

$mecho->post('https://www.instagram.com/accounts/login/ajax/', $post_data);

  while (my $row = <$fh>) {
  chomp $row;
  print "getting user $row\n";

    $mech_get->get('https://www.instagram.com/'.$row.'/?__a=1');

    my $decoded_json = decode_json( $mech_get->response()->decoded_content() );

     print "Found Post \n";

    $mech_get->get('https://api.instagram.com/oembed/?url=https://www.instagram.com/p/'.$decoded_json->{user}->{media}->{nodes}[0]->{code}.'/');

    my $decoded_json2 = decode_json( $mech_get->response()->decoded_content() );

    print "Linking Post by Id";
    my $post;

    if($decoded_json2->{media_id} =~ /^([^_]*);*)   {
        $post = $1;
    }

    $mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

    $mecho->post('https://www.instagram.com/web/likes/'.$post.'/like/');

}

sub getcsrf {

    my ($somemech) = @_;

    my $cookies2  = $somemech->response->header('Set-Cookie');

    my $csrf_token2;
    if ($cookies2 =~ /csrftoken=([^;]+);/i){
        return $1;
    }
    else {
        die "Unable to find csrftoken in cookie headers, did something change?";

        }

};

Body:
you will have to use eval block

here's some documentation:
https://perldoc.perl.org/functions/eval.html

Also, you forgot a / at if($decoded_json2->{media_id} =~ /^([^_]*);*)

your code will be then

#your code until line 29

eval {$mech_get->get('https://www.instagram.com/'.$row.'/?__a=1');};

if(not $@)
{
    my $decoded_json = decode_json( $mech_get->response()->decoded_content() );

     print "Found Post \n";

    $mech_get->get('https://api.instagram.com/oembed/?url=https://www.instagram.com/p/'.$decoded_json->{user}->{media}->{nodes}[0]->{code}.'/');

    my $decoded_json2 = decode_json( $mech_get->response()->decoded_content() );

    print "Linking Post by Id";
    my $post;

    if($decoded_json2->{media_id} =~ /^([^_]*);*)/   {
        $post = $1;
    }

    $mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

    $mecho->post('https://www.instagram.com/web/likes/'.$post.'/like/');
}


问:
In Asp.net Core 2.0 is IHostingEnvironment extendable
Currently, Asp.Net core 2 IHostingEnvironment has three boolean properties

IsProduction

IsStaging

IsDevelopment

is it extendable if I wanted to create two additional properties? (e.g. IsTesting, IsCloudDb)

Since I am not a professional programmer I'm not sure how to go about this IF it is doable.

答:
Those are not properties but extension methods for IHostingEnvironment interface. All those extension methods do is compare IHostingEnvironment.EnvironmentName with predefined string. You can do the same:

```<code>public static class EnvironmentExtensions {
    const string CloudDbEnvironment = "CloudDb";
    const string TestingEnvironment = "Testing";

    public static bool IsCloudDb(this IHostingEnvironment env) {
        return env.IsEnvironment(CloudDbEnvironment);
    }

    public static bool IsTesting(this IHostingEnvironment env) {
        return env.IsEnvironment(TestingEnvironment);
    }
}
</code>```

Of course you should set EnvironmentName to the related string for those methods to return true.

Body:
Those are not properties but extension methods for IHostingEnvironment interface. All those extension methods do is compare IHostingEnvironment.EnvironmentName with predefined string. You can do the same:

public static class EnvironmentExtensions {
    const string CloudDbEnvironment = "CloudDb";
    const string TestingEnvironment = "Testing";

    public static bool IsCloudDb(this IHostingEnvironment env) {
        return env.IsEnvironment(CloudDbEnvironment);
    }

    public static bool IsTesting(this IHostingEnvironment env) {
        return env.IsEnvironment(TestingEnvironment);
    }
}

Of course you should set EnvironmentName to the related string for those methods to return true.


问:
How can I debug javascript on Android?
I'm working on a project that involves Raphaeljs. Turns out, it doesn't work on Android. It does on the iPhone.

How the heck to I go about debugging something on the Android browser? It's WebKit, so if I know the version, will debugging it on that full version of WebKit produce the same results?

答: FYI, the reason why RaphaelJS doesn't work on android is that android webkit (unlike iPhone webkit) doesn't support SVG at this time. Google has only recently come to the conclusion that SVG support an android is a good idea, so it won't be available yet for some time.</p>

Title: How can I debug javascript on Android?


问:
Windows scheduler with Python script that saves a file
I currently have a Python script that scrapes some data from the internet, then saves it as a pickle file. When running this from a terminal with python filename.py it saves correctly, since the Date Modified field of the pickle file changes. However, when running with the built-in scheduler it doesn't actually save the pickle file, since the Date Modified isn't changed, despite seeing the Python script being executed (terminal opens up and I see the script running).

I ticked the Run with highest privileges box in the scheduler, and despite that it doesn't save the pickle file. I thought it had to do with it not having write permission, but if it has the highest priviliges, surely it can save a file?

At the scheduled time a terminal opens, so I know it is actually being executed (print a message to make sure), but it doesn't show an error about the fact that it couldn't save the file or anything like that. The only reason I know it's not working is the Date Modified field not changing. How can I fix this?

答:
Windows Task Scheduler has a default working directory of C:\Windows\System32. If you set a relative path to the file you are trying to write, it will likely be written into that directory. If you open a Command Prompt in the directory of your script and run it, the relative path will be that directory. So, you actually have two copies of the pickle file.

If you set an absolute path in your script to the file you want to write to, both methods of running your script will write to the same file.


问:
No composer.json found in the current directory

Hi guys, really sorry if this has a basic answer as I'm quite new to this. I am following a YouTube tutorial Hyperledger Composer Development Tutorial (2/5) - Modeling Language (Mac OS X) https://www.youtube.com/watch?v=S2S5cEcmx7Q&t=100s.

Following all steps up to 3:22 (and tutorial 1/5) I try to command:

```<code>composer archive create -a /dist/perishables.bna --sourceType dir --sourceName
</code>```

Where the result should be:

```<code>Creating Business Network Archive

Looking for package.json of Business Network Definition
Input directory: /Users/joeheade/composer-sample-networks/packages/perishable-network

Found:
Description: Shipping Perishable Goods Business Network
Name: perishable-network
Identifier: perishable-network@0.1.11

Written Business Network Definition Archive file to
Output file: ./dist/perishable-network.bna

Command succeeded
</code>```

When I try, I get this:

```<code>Joe-Heades-MBP:perishable-network joeheade$ composer archive create -a /dist/perishables.bna --sourceType dir --sourceName

  [Symfony\Component\Console\Exception\RuntimeException]
  The "-a" option does not exist.

archive [-f|--format FORMAT] [--dir DIR] [--file FILE] [--ignore-filters] [--] [<package>] [<version>]
</code>```

If I check the version I get this:

```<code>Joe-Heades-MBP:perishable-network joeheade$ composer --version
Composer version 1.5.5 2017-12-01 14:42:57
</code>```

And for a generic command, I get this:

```<code>Joe-Heades-MBP:perishable-network joeheade$ composer archive create
Searching for the specified package.
No composer.json found in the current directory, searching packages from packagist.org
Could not find a package matching create.
</code>```

Please could somebody help? I'm also sorry if I'm following any Stack Overflow rules incorrectly; this is my first post.

Thank you in advance!

UPDATE: In addition if I take a step back I get this result for:

```<code>Joe-Heades-MacBook-Pro:dist joeheade$ compose archive create -a dist/perishables.bna --sourceType dir --sourceName
-bash: compose: command not found
</code>```

Following the steps https://github.com/composer/composer/issues/6303, I also get the following response:

```<code>Joe-Heades-MacBook-Pro:perishable-network joeheade$ composer update
Composer could not find a composer.json file in /Users/joeheade/composer-sample-networks/packages/perishable-network
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section
</code>```

答:
You missed a small dot(.) on this command.

Before executing this command please make sure you have a dist in this directory folder.

```<code>composer archive create --sourceType dir --sourceName . -a ./dist/perishables.bna
</code>```

Use this command to create a .bna (Business Network Archive) file. This should return the expected value.

Body:
Hi guys, really sorry if this has a basic answer as I'm quite new to this. I am following a YouTube tutorial Hyperledger Composer Development Tutorial (2/5) - Modeling Language (Mac OS X) https://www.youtube.com/watch?v=S2S5cEcmx7Q&t=100s.

Following all steps up to 3:22 (and tutorial 1/5) I try to command:

composer archive create -a /dist/perishables.bna --sourceType dir --sourceName

Where the result should be:

Creating Business Network Archive

Looking for package.json of Business Network Definition
Input directory: /Users/joeheade/composer-sample-networks/packages/perishable-network

Found:
Description: Shipping Perishable Goods Business Network
Name: perishable-network
Identifier: perishable-network@0.1.11

Written Business Network Definition Archive file to
Output file: ./dist/perishable-network.bna

Command succeeded

When I try, I get this:

Joe-Heades-MBP:perishable-network joeheade$ composer archive create -a /dist/perishables.bna --sourceType dir --sourceName

  [Symfony\Component\Console\Exception\RuntimeException]
  The "-a" option does not exist.

archive [-f|--format FORMAT] [--dir DIR] [--file FILE] [--ignore-filters] [--] [<package>] [<version>]

If I check the version I get this:

Joe-Heades-MBP:perishable-network joeheade$ composer --version
Composer version 1.5.5 2017-12-01 14:42:57

And for a generic command, I get this:

Joe-Heades-MBP:perishable-network joeheade$ composer archive create
Searching for the specified package.
No composer.json found in the current directory, searching packages from packagist.org
Could not find a package matching create.

Please could somebody help? I'm also sorry if I'm following any Stack Overflow rules incorrectly; this is my first post.

Thank you in advance!

UPDATE: In addition if I take a step back I get this result for:

Joe-Heades-MacBook-Pro:dist joeheade$ compose archive create -a dist/perishables.bna --sourceType dir --sourceName
-bash: compose: command not found

Following the steps https://github.com/composer/composer/issues/6303, I also get the following response:

Joe-Heades-MacBook-Pro:perishable-network joeheade$ composer update
Composer could not find a composer.json file in /Users/joeheade/composer-sample-networks/packages/perishable-network
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section

Body:
You missed a small dot(.) on this command.

Before executing this command please make sure you have a dist in this directory folder.

composer archive create --sourceType dir --sourceName . -a ./dist/perishables.bna

Use this command to create a .bna (Business Network Archive) file. This should return the expected value.


问:
How to access 'this' in Vuex store module state
For example, say I have a "store" directory like this:

```<code>...
store
├── auth
│   └── user.js
└── index.js
...
</code>```

index.js

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import {user} from './auth/user';

Vue.use(Vuex);

/* eslint-disable no-new */
const store = new Vuex.Store({
  modules: {
    user
  },
});

export default store;
</code>```

Now in the user store I have some constants and other state variables in it's state prop. How can I access state props from within itself? For example user store may look like this:

user.js

```<code>export const user = {
  namespaced: true,

  state: {

    // hardcoded string assigned to user.state.constants.SOME_CONST
    constants: {
      SOME_CONST: 'testString'
    },

    // Another property where I would like to reference the constant above

    someOtherStateProp: {

      // Trying to access the constant in any of these ways throws
      // 'Uncaught ReferenceError: .... undefined'
      // Where '...' above is interchangeable with any root I try to access the constant from (this, state etc)

      test1: this.state.constants.SOME_CONST,
      test2: user.state.constants.SOME_CONST
      test3: state.constants.SOME_CONST
      test4: constants.SOME_CONST
      test5: SOME_CONST
      // .... etc. All the above throw ReferenceError's
    }
  }
};
</code>```

How can I reference user.state.constants.SOME_CONST from user.state.someOtherStateProp.test1?

Feel like I'm missing something very fundamental here.

答:
You can do this by doing this in two steps.

```<code>let user = {
    namespaced: true,
    state: {
        SOME_CONST: 'testString'
    }
};

Object.assign(user, {
    state: {
        someOtherStateProp: {
            test1: user.state.SOME_CONST
        }
    }
});

export default user;
</code>```

Read more about Object.assign here - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Body:
For example, say I have a "store" directory like this:

...
store
├── auth
│   └── user.js
└── index.js
...

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import {user} from './auth/user';

Vue.use(Vuex);

/* eslint-disable no-new */
const store = new Vuex.Store({
  modules: {
    user
  },
});

export default store;

Now in the user store I have some constants and other state variables in it's state prop. How can I access state props from within itself? For example user store may look like this:

user.js

export const user = {
  namespaced: true,

  state: {

    // hardcoded string assigned to user.state.constants.SOME_CONST
    constants: {
      SOME_CONST: 'testString'
    },

    // Another property where I would like to reference the constant above

    someOtherStateProp: {

      // Trying to access the constant in any of these ways throws
      // 'Uncaught ReferenceError: .... undefined'
      // Where '...' above is interchangeable with any root I try to access the constant from (this, state etc)

      test1: this.state.constants.SOME_CONST,
      test2: user.state.constants.SOME_CONST
      test3: state.constants.SOME_CONST
      test4: constants.SOME_CONST
      test5: SOME_CONST
      // .... etc. All the above throw ReferenceError's
    }
  }
};

How can I reference user.state.constants.SOME_CONST from user.state.someOtherStateProp.test1?

Feel like I'm missing something very fundamental here.

Body:
You can do this by doing this in two steps.

let user = {
    namespaced: true,
    state: {
        SOME_CONST: 'testString'
    }
};

Object.assign(user, {
    state: {
        someOtherStateProp: {
            test1: user.state.SOME_CONST
        }
    }
});

export default user;

Read more about Object.assign here - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign


问:
upgrade android.arch.persistence.room version error on build
I'm trying to upgrade android.arch.persistence.room in my android project.

Now I'm using the alpha-9 and all is working correctly.
If I try to use the "released" version 1.0.0 I'll recive the error reported below on the line compile 'com.android.support:appcompat-v7:26.0.2'.

Error:Execution failed for task ':app:processDebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:design:26.0.2] AndroidManifest.xml:28:13-35
      is also present at [com.android.support:support-core-utils:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:26:9-28:38 to override.

The gradle file is

apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            useLibrary 'org.apache.http.legacy'
        }
    }
}
dependencies {
    debugCompile 'com.amitshekhar.android:debug-db:1.0.1'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.android.support:support-v4:26.0.2'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'android.arch.persistence.room:runtime:1.0.0'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
}```

Does someone kwnow how I can fix it?

Thanks

答:
See if the changes to following versions would work for you:</p>

```<code>(archLifecycleVersion = '1.0.0'
roomLifecycleVersion = '1.0.0')

annotationProcessor "android.arch.lifecycle:compiler:$rootProject.ext.archLifecycleVersion"
compile "android.arch.lifecycle:runtime:$rootProject.ext.archLifecycleVersion"
compile "android.arch.lifecycle:extensions:$rootProject.ext.archLifecycleVersion"

compile "android.arch.persistence.room:runtime:$rootProject.roomLifecycleVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomLifecycleVersion"
</code>```

Body:
I'm trying to upgrade android.arch.persistence.room in my android project.

Now I'm using the alpha-9 and all is working correctly.
If I try to use the "released" version 1.0.0 I'll recive the error reported below on the line compile 'com.android.support:appcompat-v7:26.0.2'.

Error:Execution failed for task ':app:processDebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:design:26.0.2] AndroidManifest.xml:28:13-35
      is also present at [com.android.support:support-core-utils:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:26:9-28:38 to override.

The gradle file is

apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            useLibrary 'org.apache.http.legacy'
        }
    }
}
dependencies {
    debugCompile 'com.amitshekhar.android:debug-db:1.0.1'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.android.support:support-v4:26.0.2'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'android.arch.persistence.room:runtime:1.0.0'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
}

Does someone kwnow how I can fix it?

Thanks

Body:
See if the changes to following versions would work for you:

(archLifecycleVersion = '1.0.0'
roomLifecycleVersion = '1.0.0')

annotationProcessor "android.arch.lifecycle:compiler:$rootProject.ext.archLifecycleVersion"
compile "android.arch.lifecycle:runtime:$rootProject.ext.archLifecycleVersion"
compile "android.arch.lifecycle:extensions:$rootProject.ext.archLifecycleVersion"

compile "android.arch.persistence.room:runtime:$rootProject.roomLifecycleVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomLifecycleVersion"