问:
Unable to use dot layout (graphviz as a library)
I use graphviz (v2.28.0) as a library in a C++ application and I would like to render graphs using the dot layout. Everything works fine until I call the gvLayout(_context, _graph, "dot"); function which outputs the following error :

```<code> Error: Layout type: "dot" not recognized. Use one of:
</code>```

I use the following library flags when linking :

```<code>-lgvc -lgraph -lpathplan -lcdt -lgvplugin_dot_layout
</code>```

Calling dot from the Unix command line works as expected. What am I doing wrong ?

答:
According to a reply by Emden R. Gansner on the 'graphviz-interest' mailing list, this error message indicates that the software was unable to find the graphviz config file.

The graphviz config file (config6) is used by the gvc library to load the various libgvplugin_... libraries on demand.

Gansner also mentions that graphviz supports a GVBINDIR environment variable which, if defined, is used to specify the directory containing the graphviz config file. This is also discussed at How to configure & package Graphviz for Mac App Store?.

In my case (where I'm trying to include the graphviz libraries in an macOS/Objective-C framework), a framework subdirectory (called "Libraries") contains the config6 file plus these libgvplugin_... libraries (next to the regular graphviz libraries):

```<code>Libraries:
    config6
    libgvplugin_core.6.dylib
    libgvplugin_dot_layout.6.dylib
    libgvplugin_gd.6.dylib
    libgvplugin_neato_layout.6.dylib
    libgvplugin_quartz.6.dylib
</code>```

From within one of the framework's classes, one could then set the GVBINDIR environment variable like this:

NSBundle *containingBundle = [NSBundle bundleForClass:[self class]];
NSURL *librariesDirURL = [[containingBundle bundleURL] URLByAppendingPathComponent:@"Versions/A/Libraries" isDirectory:YES];
if (librariesDirURL) {
    setenv("GVBINDIR", (char*)[[librariesDirURL path] UTF8String], 1);
}
```

<p>Setting the <code>GVBINDIR</code> environment variable is the only solution that worked for me.</p>

<p>I've also tried the solutions mentioned by others above including loading the default graphviz plugins explicitly. E.g., with <code>_graphContext</code> being defined as <code>static GVC_t *_graphContext</code>, this code:</p>

<pre class="lang-c prettyprint-override"><code>extern gvplugin_library_t gvplugin_dot_layout_LTX_library;
extern gvplugin_library_t gvplugin_neato_layout_LTX_library;
extern gvplugin_library_t gvplugin_core_LTX_library;
extern gvplugin_library_t gvplugin_quartz_LTX_library;

lt_symlist_t lt_preloaded_symbols[] =
{
    { "gvplugin_dot_layout_LTX_library", &gvplugin_dot_layout_LTX_library},
    { "gvplugin_neato_layout_LTX_library", &gvplugin_neato_layout_LTX_library},
    { "gvplugin_core_LTX_library", &gvplugin_core_LTX_library},
    { "gvplugin_quartz_LTX_library", &gvplugin_quartz_LTX_library},
    { 0, 0}
};

_graphContext = gvContextPlugins(lt_preloaded_symbols, 1);
</code>```

actually worked for me. I.e., this caused the graphviz plugins to load and the above mentioned error message ('Error: Layout type: "dot" not recognized. Use one of:') vanished. However, any subsequent call to gvLayout() then caused a graphviz crash (EXC_BAD_ACCESS) for me.

So for now I'm taking the environment variable approach.

Body:
I use graphviz (v2.28.0) as a library in a C++ application and I would like to render graphs using the dot layout. Everything works fine until I call the gvLayout(_context, _graph, "dot"); function which outputs the following error :

 Error: Layout type: "dot" not recognized. Use one of:

I use the following library flags when linking :

-lgvc -lgraph -lpathplan -lcdt -lgvplugin_dot_layout

Calling dot from the Unix command line works as expected. What am I doing wrong ?

Body:
According to a reply by Emden R. Gansner on the 'graphviz-interest' mailing list, this error message indicates that the software was unable to find the graphviz config file.

The graphviz config file (config6) is used by the gvc library to load the various libgvplugin_... libraries on demand.

Gansner also mentions that graphviz supports a GVBINDIR environment variable which, if defined, is used to specify the directory containing the graphviz config file. This is also discussed at How to configure & package Graphviz for Mac App Store?.

In my case (where I'm trying to include the graphviz libraries in an macOS/Objective-C framework), a framework subdirectory (called "Libraries") contains the config6 file plus these libgvplugin_... libraries (next to the regular graphviz libraries):

Libraries:
    config6
    libgvplugin_core.6.dylib
    libgvplugin_dot_layout.6.dylib
    libgvplugin_gd.6.dylib
    libgvplugin_neato_layout.6.dylib
    libgvplugin_quartz.6.dylib

From within one of the framework's classes, one could then set the GVBINDIR environment variable like this:

NSBundle *containingBundle = [NSBundle bundleForClass:[self class]];
NSURL *librariesDirURL = [[containingBundle bundleURL] URLByAppendingPathComponent:@"Versions/A/Libraries" isDirectory:YES];
if (librariesDirURL) {
    setenv("GVBINDIR", (char*)[[librariesDirURL path] UTF8String], 1);
}

Setting the GVBINDIR environment variable is the only solution that worked for me.

I've also tried the solutions mentioned by others above including loading the default graphviz plugins explicitly. E.g., with _graphContext being defined as static GVC_t *_graphContext, this code:

extern gvplugin_library_t gvplugin_dot_layout_LTX_library;
extern gvplugin_library_t gvplugin_neato_layout_LTX_library;
extern gvplugin_library_t gvplugin_core_LTX_library;
extern gvplugin_library_t gvplugin_quartz_LTX_library;

lt_symlist_t lt_preloaded_symbols[] =
{
    { "gvplugin_dot_layout_LTX_library", &gvplugin_dot_layout_LTX_library},
    { "gvplugin_neato_layout_LTX_library", &gvplugin_neato_layout_LTX_library},
    { "gvplugin_core_LTX_library", &gvplugin_core_LTX_library},
    { "gvplugin_quartz_LTX_library", &gvplugin_quartz_LTX_library},
    { 0, 0}
};

_graphContext = gvContextPlugins(lt_preloaded_symbols, 1);

actually worked for me. I.e., this caused the graphviz plugins to load and the above mentioned error message ('Error: Layout type: "dot" not recognized. Use one of:') vanished. However, any subsequent call to gvLayout() then caused a graphviz crash (EXC_BAD_ACCESS) for me.

So for now I'm taking the environment variable approach.


来源: stackexchange

问:
Pairwise distance between all centroid coordinate combinations - Matlab
The script below label objects in an image based on their centroids. How can I preform a pairwise distance between all the centroid coordinate combinations (without overlapping) and return the results in a table? I was thinking about using pdist2 but I do not know how to construct the for loop.

Thanks.

Script:

```<code>clc;
clear all;
I = imread('E:/Elli.png');
imshow(I);
BW  =imbinarize(I);
BW = imfill(BW, 'holes');
BW = bwlabel(BW);

s = regionprops(BW,'Area', 'BoundingBox', 'Eccentricity', 'MajorAxisLength', 'MinorAxisLength', 'Orientation', 'Perimeter','Centroid');

imshow(BW)
hold on
for k = 1:numel(s)
    c = s(k).Centroid;
    text(c(1), c(2), sprintf('%d', k), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
hold off
</code>```

答:
Rather than using pdist2, which finds the distances between points in two lists, use pdist. pdist takes all of the points in a single list and finds the distance between each pair.

In your example, s.Centroid gives a comma-separated list of points, so we need to coerce it into an array of points using vertcat:

```<code>point_list = vertcat(s.Centroid);
</code>```

Now we can feed this list to pdist:

```<code>dist_list = pdist(point_list);
</code>```

pdist returns a list of distances from centroid i to centroid j such that i < j:

```<code>{1->2}, {1->3}, {1->4}, ... {1->n}, {2->3}, {2->4}, ..., {2->n}, {3->4}, etc.
</code>```

In your example with 28 centroids, this will give you a total of 378 distances.

If you want that in a matrix form instead where element (i,j) is the distance from centroid i to centroid j, you can use squareform:

```<code>dist_mat = squareform(dist_list);
</code>```

For 28 centroids, this will give you the full 28x28 matrix of distances.

ContentLicense: CC BY-SA 4.0

Body:
The script below label objects in an image based on their centroids. How can I preform a pairwise distance between all the centroid coordinate combinations (without overlapping) and return the results in a table? I was thinking about using pdist2 but I do not know how to construct the for loop.

Thanks.

Script:

clc;
clear all;
I = imread('E:/Elli.png');
imshow(I);
BW  =imbinarize(I);
BW = imfill(BW, 'holes');
BW = bwlabel(BW);

s = regionprops(BW,'Area', 'BoundingBox', 'Eccentricity', 'MajorAxisLength', 'MinorAxisLength', 'Orientation', 'Perimeter','Centroid');

imshow(BW)
hold on
for k = 1:numel(s)
    c = s(k).Centroid;
    text(c(1), c(2), sprintf('%d', k), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
hold off

Body:
Rather than using pdist2, which finds the distances between points in two lists, use pdist. pdist takes all of the points in a single list and finds the distance between each pair.

In your example, s.Centroid gives a comma-separated list of points, so we need to coerce it into an array of points using vertcat:

point_list = vertcat(s.Centroid);

Now we can feed this list to pdist:

dist_list = pdist(point_list);

pdist returns a list of distances from centroid i to centroid j such that i < j:

{1->2}, {1->3}, {1->4}, ... {1->n}, {2->3}, {2->4}, ..., {2->n}, {3->4}, etc.

In your example with 28 centroids, this will give you a total of 378 distances.

If you want that in a matrix form instead where element (i,j) is the distance from centroid i to centroid j, you can use squareform:

dist_mat = squareform(dist_list);

For 28 centroids, this will give you the full 28x28 matrix of distances.


问:
Pass an additional counter as parameter to a callback
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

```<code>for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("<div><div id='event"+i+"'></div><div id='date"+i+"'>"+tmd+"</div></div>");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}
</code>```

答: I couldn't find any better way, but you can send index with ajax request with data parameter and then return it with the response in your callback.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("

"+tmd+"

");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}


问:
How to update child's(from the created list) props from parent
This might refer to other relevant general questions like how to update a child component from the parent, though I'd like to hear any fair judgement of my design solution to the following scenario.

I have a parent class where I store css attributes for 2 children objects.

```<code>import React from 'react'
import Item from './item/Item'

class Small_gallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chosenVal: 0,
    };

    this.listObjParams = [
    // Style 1
      {
        left: 300,
        zIndex: 0
      },
     //Style 2
      {
        left: 320,
        zIndex: 1
      }
    ];

    this.handleClick = this.handleClick.bind(this);
    this.calculateShift = this.applyNewStyle.bind(this);
    this.listItems = this.listObjParams.map((objStyle, i) =>
        <Item
            key={i}
            id={i}
            objStyle={objStyle}
            onClick={this.handleClick}
        />
    );
  }

  handleClick = (indexFromChild) => {
    this.setState({chosenVal: indexFromChild});
    this.applyNewStyle(indexFromChild)
  };

  applyNewStyle = (clickedIndex) => {
   if (clickedIndex === 0) {
   // somehow I want to apply new css style 2 to the clicked? <Item> child
  };
  render() {
    return (
        <div>
          {this.listItems}
        </div>
    )
  }
</code>```

Child component is rather trivial:

```<code>class Item extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
        <div
            onClick={(e) => {
              e.preventDefault();
              this.props.onClick(this.props.id)
            }}
            style={{
              left: this.props.objStyle.left,
              zIndex: this.props.objStyle.zIndex
            }}
        >
        </div>
    );
  }
}
</code>```

The question is: how can I apply style 1 or 2 to the clicked Item component(depending on the index I am returning)? I've read about getDerivedStateFromProps instead of using deprecated componentWillReceiveProps here https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607 but it's not a solution for me.

I expect number of created Items to grow in the future to 10-20, so it makes no sense to populate state of Item with this.listObjParams when creating it, or am I wrong here?

答:
For <Item/> you can use simple functional component. Optimal for simple, not so complex use cases.

E.g

```<code>const Item = ({ id, clickHandler, objStyle }) => (
  <div
    onClick={e => {
      e.preventDefault();

      clickHandler(id);
    }}
    style={...objStyle}
  />
);
</code>```

PureComponent will be updated on props change, too.

In full class component you can use shouldComponentUpdate() to force rerendering on props change. No need to duplicate data (into state) using getDerivedStateFromProps (depends on use case).

Search for some tutorials (f.e. typical todo examples) since you have no idea about state management, updating etc.

Placing listObjParams outside of state won't force rerendering on update. BTW it looks more like a style pool - maybe you should have a child params array... you can combine it with style index array or keep them (and pass as props) separately.

```<code>  constructor(props) {
    super(props);
    this.state = {
      // chosenVal: 0, // temporary handler param? probably no need to store in the state
      listObjStyles: [0, 1] // style indexes
    };

    this.stylePool = [
    // Style 1
      {
        left: 300,
        zIndex: 0
      },
     //Style 2
      {
        left: 320,
        zIndex: 1
      }
    ];
</code>```

usage:

```<code>this.listItems = this.state.listObjStyles.map((styleIndex, i) => <Item
        key={i}
        id={i}
        objStyle={this.stylePool[ styleIndex ]}
        clickHandler={this.handleClick}
    />
</code>```

Updating listObjStyles (setState()) will force rerendering, updating this.stylePool won't (move to the state if rerendering required).

Of course stylePool can contain more than 2 styles for different item 'states'. You can make styles for selected, liked, unliked - by storing indexes in an array you can mix any of them with custom logic (f.e. only one selected, many liked).

10-20 items is not the case where you need special optimizations (other than avoiding unnecessary rerenderings).

Body:
This might refer to other relevant general questions like how to update a child component from the parent, though I'd like to hear any fair judgement of my design solution to the following scenario.

I have a parent class where I store css attributes for 2 children objects.

import React from 'react'
import Item from './item/Item'

class Small_gallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chosenVal: 0,
    };

    this.listObjParams = [
    // Style 1
      {
        left: 300,
        zIndex: 0
      },
     //Style 2
      {
        left: 320,
        zIndex: 1
      }
    ];

    this.handleClick = this.handleClick.bind(this);
    this.calculateShift = this.applyNewStyle.bind(this);
    this.listItems = this.listObjParams.map((objStyle, i) =>
        <Item
            key={i}
            id={i}
            objStyle={objStyle}
            onClick={this.handleClick}
        />
    );
  }

  handleClick = (indexFromChild) => {
    this.setState({chosenVal: indexFromChild});
    this.applyNewStyle(indexFromChild)
  };

  applyNewStyle = (clickedIndex) => {
   if (clickedIndex === 0) {
   // somehow I want to apply new css style 2 to the clicked? <Item> child
  };
  render() {
    return (

          {this.listItems}

    )
  }

Child component is rather trivial:

class Item extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (

 {
              e.preventDefault();
              this.props.onClick(this.props.id)
            }}
            style={{
              left: this.props.objStyle.left,
              zIndex: this.props.objStyle.zIndex
            }}
        >

    );
  }
}

The question is: how can I apply style 1 or 2 to the clicked Item component(depending on the index I am returning)? I've read about getDerivedStateFromProps instead of using deprecated componentWillReceiveProps here https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607 but it's not a solution for me.

I expect number of created Items to grow in the future to 10-20, so it makes no sense to populate state of Item with this.listObjParams when creating it, or am I wrong here?

Body:
For <Item/> you can use simple functional component. Optimal for simple, not so complex use cases.

E.g

const Item = ({ id, clickHandler, objStyle }) => (
  <div
    onClick={e => {
      e.preventDefault();

      clickHandler(id);
    }}
    style={...objStyle}
  />
);

PureComponent will be updated on props change, too.

In full class component you can use shouldComponentUpdate() to force rerendering on props change. No need to duplicate data (into state) using getDerivedStateFromProps (depends on use case).

Search for some tutorials (f.e. typical todo examples) since you have no idea about state management, updating etc.

Placing listObjParams outside of state won't force rerendering on update. BTW it looks more like a style pool - maybe you should have a child params array... you can combine it with style index array or keep them (and pass as props) separately.

  constructor(props) {
    super(props);
    this.state = {
      // chosenVal: 0, // temporary handler param? probably no need to store in the state
      listObjStyles: [0, 1] // style indexes
    };

    this.stylePool = [
    // Style 1
      {
        left: 300,
        zIndex: 0
      },
     //Style 2
      {
        left: 320,
        zIndex: 1
      }
    ];

usage:

this.listItems = this.state.listObjStyles.map((styleIndex, i) => <Item
        key={i}
        id={i}
        objStyle={this.stylePool[ styleIndex ]}
        clickHandler={this.handleClick}
    />

Updating listObjStyles (setState()) will force rerendering, updating this.stylePool won't (move to the state if rerendering required).

Of course stylePool can contain more than 2 styles for different item 'states'. You can make styles for selected, liked, unliked - by storing indexes in an array you can mix any of them with custom logic (f.e. only one selected, many liked).

10-20 items is not the case where you need special optimizations (other than avoiding unnecessary rerenderings).


问:
Beginner trying to make a line ggplot with categorical X axis and customising color settings
I am trying to

(1) create a line ggplot using some variables as factors and

(2) set a specific color and a thicker line width for one of the color variable groups (group "0" in ID1).

For my first problem I keep getting the error message:

"geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?"

and for the second, I have no idea where to begin.

My data looks like this:

```<code>ID1 ID2 Q   V
503 503-2879    1   6.9
503 503-2879    2   14.21
503 503-2879    3   20.76
503 503-2879    6   36.64
503 503-2879    12  56.39
503 503-2879    20  68.87
503 503-2879    30  74.85
503 503-2879    40  76.87
504 504-2880    1   24.23
504 504-2880    2   34.41
504 504-2880    3   42.74
504 504-2880    6   59.7
504 504-2880    12  74.1
504 504-2880    20  79.04
504 504-2880    30  80.12
504 504-2880    40  80.27
755 755-3021    1   15.2
755 755-3021    2   19.5
755 755-3021    3   23.63
755 755-3021    6   35.02
755 755-3021    12  53.86
755 755-3021    20  72.57
755 755-3021    30  88.56
755 755-3021    40  99.01
0   N   1   1.526709
0   N   2   3.053418
0   N   3   4.580127
0   N   6   9.226632
0   N   12  18.453264
0   N   20  30.733313
0   N   30  46.06678
0   N   40  61.47
</code>```

My initial code produced a graph that is very close to what I want  (without adding the color and line width settings for the "0" color group) but the X axis is continuous when in fact this variable is categorical.

Initial code:

```<code>GPlot <- ggplot(VbyQG, aes(x = Q, y = V, color = ID1)) +
           geom_path() +
           theme_bw() +
           theme(legend.position = 'none') +
           theme_classic() +
           theme(legend.position = 'none') +
           expand_limits(y = 210)
GPlot
</code>```

I would like the X axis to show the correct breaks and labels (1, 2, 3, 6, 12, 20, 30, 40) of the "Q" variable.

I have tried changing the "Q" variable into a factor using str() and also factor() within the ggplot aes() but while either of these changes take care of the error message and result in the X axis displaying the correct breaks and labels, they also make all the data disappear.

How can I make the data appear again? Also, what sort of coding do I need to add to set a specific color and a thicker line width for one of the color variable groups (group "0" in ID1)?

I have searched for solutions for my second problem but the solutions I have found are beyond my beginner coding skills. Many thanks again for the help!

答:
For the first question, this should work. The idea is to convert Q to a character, and then make it an ordered factor using fct_reorder from the forcats package included in tidyverse. (I am assuming Q is numeric in your source.)

```<code>library(tidyverse)

df2 <- df %>%
  # Takes Q, assumed numeric, saves as character, then converts to ordered factor
  mutate(Q = as.character(Q) %>% fct_reorder(Q))

GPlot <- ggplot(df2, aes(x= Q, y = V, color = ID1, group = ID1)) +
  geom_path() +
  # Here's one way to highlight -- just draw on top with manual color & size
  # geom_path(data = df2 %>% filter(ID1 == 503),
  #           size = 2, color = "slateblue") +
  theme_bw() +
  theme(legend.position = 'none') +
  theme_classic() +
  theme(legend.position = 'none') +
  expand_limits(y = 210)
GPlot
</code>```

To highlight one series, the simplest thing might be to use the gghightlight package. https://cran.r-project.org/web/packages/gghighlight/vignettes/gghighlight.html

Or you could use a manual scale for color and thickness and make just that series highlighted. Or you could plot another layer on top with a manually defined color and thickness, but that won't automatically integrate with any legend labels.

Body:
I am trying to

(1) create a line ggplot using some variables as factors and

(2) set a specific color and a thicker line width for one of the color variable groups (group "0" in ID1).

For my first problem I keep getting the error message:

"geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?"

and for the second, I have no idea where to begin.

My data looks like this:

ID1 ID2 Q   V
503 503-2879    1   6.9
503 503-2879    2   14.21
503 503-2879    3   20.76
503 503-2879    6   36.64
503 503-2879    12  56.39
503 503-2879    20  68.87
503 503-2879    30  74.85
503 503-2879    40  76.87
504 504-2880    1   24.23
504 504-2880    2   34.41
504 504-2880    3   42.74
504 504-2880    6   59.7
504 504-2880    12  74.1
504 504-2880    20  79.04
504 504-2880    30  80.12
504 504-2880    40  80.27
755 755-3021    1   15.2
755 755-3021    2   19.5
755 755-3021    3   23.63
755 755-3021    6   35.02
755 755-3021    12  53.86
755 755-3021    20  72.57
755 755-3021    30  88.56
755 755-3021    40  99.01
0   N   1   1.526709
0   N   2   3.053418
0   N   3   4.580127
0   N   6   9.226632
0   N   12  18.453264
0   N   20  30.733313
0   N   30  46.06678
0   N   40  61.47

My initial code produced a graph that is very close to what I want  (without adding the color and line width settings for the "0" color group) but the X axis is continuous when in fact this variable is categorical.

Initial code:

GPlot <- ggplot(VbyQG, aes(x = Q, y = V, color = ID1)) +
           geom_path() +
           theme_bw() +
           theme(legend.position = 'none') +
           theme_classic() +
           theme(legend.position = 'none') +
           expand_limits(y = 210)
GPlot

I would like the X axis to show the correct breaks and labels (1, 2, 3, 6, 12, 20, 30, 40) of the "Q" variable.

I have tried changing the "Q" variable into a factor using str() and also factor() within the ggplot aes() but while either of these changes take care of the error message and result in the X axis displaying the correct breaks and labels, they also make all the data disappear.

How can I make the data appear again? Also, what sort of coding do I need to add to set a specific color and a thicker line width for one of the color variable groups (group "0" in ID1)?

I have searched for solutions for my second problem but the solutions I have found are beyond my beginner coding skills. Many thanks again for the help!

Body:
For the first question, this should work. The idea is to convert Q to a character, and then make it an ordered factor using fct_reorder from the forcats package included in tidyverse. (I am assuming Q is numeric in your source.)

library(tidyverse)

df2 <- df %>%
  # Takes Q, assumed numeric, saves as character, then converts to ordered factor
  mutate(Q = as.character(Q) %>% fct_reorder(Q))

GPlot <- ggplot(df2, aes(x= Q, y = V, color = ID1, group = ID1)) +
  geom_path() +
  # Here's one way to highlight -- just draw on top with manual color & size
  # geom_path(data = df2 %>% filter(ID1 == 503),
  #           size = 2, color = "slateblue") +
  theme_bw() +
  theme(legend.position = 'none') +
  theme_classic() +
  theme(legend.position = 'none') +
  expand_limits(y = 210)
GPlot

To highlight one series, the simplest thing might be to use the gghightlight package. https://cran.r-project.org/web/packages/gghighlight/vignettes/gghighlight.html

Or you could use a manual scale for color and thickness and make just that series highlighted. Or you could plot another layer on top with a manually defined color and thickness, but that won't automatically integrate with any legend labels.


问:
Find what genre is most frequent in each age category
I am thinking about making age groups per decade and find out what genre is more frequent. It is more difficult than I expected but here is what I have tried:

One table is like this, called: sell_log

```<code>id id_film id_cust
1   2      2
2   3      4
3   1      5
4   4      3
5   5      1
6   2      4
7   2      3
8   3      1
9   5      3
</code>```

2nd here is a table about the films that has the id and the genres:

```<code>id_film      genres
    1        comedy
    2        fantasy
    3        sci-fi
    4        drama
    5        thriller
</code>```

and 3rd table, customers is this:

```<code>id_cust  date_of_birth_cust
1          1992-03-12
2          1999-06-25
3          1986-01-14
4          1985-09-18
5          1992-05-19
</code>```

This is the code I did:

```<code>select  id_cust,date_of_birth_cust,
    CASE
    WHEN date_of_birth_cust > 1980-01-01 and date_of_birth_cust < 1990-01-01 then ##show genre##
    WHEN date_of_birth_cust > 1990-01-01 and date_of_birth_cust < 2000-01-01 then ##show genre##
    ELSE ##show genre##
    END
from purchases
INNER JOIN (
    select  id_cust
    FROM sell_log
    group by id_cust
  ) customer.id_cust = sell_log.id_cust
</code>```

How is the correct form in your opinion?

Expected results: for example
based on the most frequent number of genres find that genre and pass it for that age group.

```<code>ages                most frequent genre
from 1980 to 1990     comedy
from 1990 to 2000     fantasy
rest ages             drama
</code>```

Update:
doing the code in the answer gives this:

```<code>ages                most_frequent_genre
from 1980 to 1989   Comedy
from 1990 to 1999   Thriller
from 1990 to 1999   Action
from 1990 to 1999   Comedy
rest                Comedy
</code>```

What am I doing wrong

答:
You can use a CTE to get the results per age and genre and then use it to get the maximum number of purchases per age. Finally join again to the CTE:

```<code>with cte as (
  select
    CASE
      WHEN year(c.date_of_birth_cust) between 1980 and 1989 then 'from 1980 to 1989'
      WHEN year(c.date_of_birth_cust) between 1990 and 1999 then 'from 1990 to 1999'
      ELSE 'rest'
    END ages,
    f.genres,
    count(*) counter
  from sell_log s
  inner join films f on f.id_film = s.id_film
  inner join customers c on c.id_cust = s.id_cust
  group by ages, f.genres
)

select c.ages, c.genres most_frequent_genre
from cte c inner join (
  select c.ages, max(counter) counter
  from cte c
  group by c.ages
) g on g.ages = c.ages and g.counter = c.counter
order by c.ages
</code>```

See the demo.

In your sample data there are ties which will all be at the results.

Results:

```<code>| ages              | most_frequent_genre |
| ----------------- | ------------------- |
| from 1980 to 1989 | fantasy             |
| from 1990 to 1999 | comedy              |
| rest              | fantasy             |
</code>```

Body:
I am thinking about making age groups per decade and find out what genre is more frequent. It is more difficult than I expected but here is what I have tried:

One table is like this, called: sell_log

id id_film id_cust
1   2      2
2   3      4
3   1      5
4   4      3
5   5      1
6   2      4
7   2      3
8   3      1
9   5      3

2nd here is a table about the films that has the id and the genres:

id_film      genres
    1        comedy
    2        fantasy
    3        sci-fi
    4        drama
    5        thriller

and 3rd table, customers is this:

id_cust  date_of_birth_cust
1          1992-03-12
2          1999-06-25
3          1986-01-14
4          1985-09-18
5          1992-05-19

This is the code I did:

select  id_cust,date_of_birth_cust,
    CASE
    WHEN date_of_birth_cust > 1980-01-01 and date_of_birth_cust < 1990-01-01 then ##show genre##
    WHEN date_of_birth_cust > 1990-01-01 and date_of_birth_cust < 2000-01-01 then ##show genre##
    ELSE ##show genre##
    END
from purchases
INNER JOIN (
    select  id_cust
    FROM sell_log
    group by id_cust
  ) customer.id_cust = sell_log.id_cust

How is the correct form in your opinion?

Expected results: for example
based on the most frequent number of genres find that genre and pass it for that age group.

ages                most frequent genre
from 1980 to 1990     comedy
from 1990 to 2000     fantasy
rest ages             drama

Update:
doing the code in the answer gives this:

ages                most_frequent_genre
from 1980 to 1989   Comedy
from 1990 to 1999   Thriller
from 1990 to 1999   Action
from 1990 to 1999   Comedy
rest                Comedy

What am I doing wrong

Body:
You can use a CTE to get the results per age and genre and then use it to get the maximum number of purchases per age. Finally join again to the CTE:

with cte as (
  select
    CASE
      WHEN year(c.date_of_birth_cust) between 1980 and 1989 then 'from 1980 to 1989'
      WHEN year(c.date_of_birth_cust) between 1990 and 1999 then 'from 1990 to 1999'
      ELSE 'rest'
    END ages,
    f.genres,
    count(*) counter
  from sell_log s
  inner join films f on f.id_film = s.id_film
  inner join customers c on c.id_cust = s.id_cust
  group by ages, f.genres
)

select c.ages, c.genres most_frequent_genre
from cte c inner join (
  select c.ages, max(counter) counter
  from cte c
  group by c.ages
) g on g.ages = c.ages and g.counter = c.counter
order by c.ages

See the demo.

In your sample data there are ties which will all be at the results.

Results:

| ages              | most_frequent_genre |
| ----------------- | ------------------- |
| from 1980 to 1989 | fantasy             |
| from 1990 to 1999 | comedy              |
| rest              | fantasy             |


问:
How to Clean tags from html using BeautifulSoup
I'm trying to train data using the NLTK library. I follow a step-by-step process. I did the first step, but while doing the second step I'm getting the following error:

```<code>TypeError: a bytes-like object is required, not 'list'
</code>```

I tried my best to rectify it but I'm getting the same error again.

Here is my code:

```<code>from bs4 import BeautifulSoup
import urllib.request
response = urllib.request.urlopen('http://php.net/')
html = response.read()
soup = BeautifulSoup(html,"html5lib")
text = soup.get_text(strip=True)
print (text)
</code>```

this is my error

```<code>C:\python\lib\site-packages\bs4\__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 8 of the file E:/secure secure/chatbot-master/nltk.py. To get rid of this warning, change code that looks like this:

 BeautifulSoup(YOUR_MARKUP})

to this:

 BeautifulSoup(YOUR_MARKUP, "html5lib")

  markup_type=markup_type))
Traceback (most recent call last):
  File "E:/secure secure/chatbot-master/nltk.py", line 8, in <module>
    soup = BeautifulSoup(html)
  File "C:\python\lib\site-packages\bs4\__init__.py", line 228, in __init__
    self._feed()
  File "C:\python\lib\site-packages\bs4\__init__.py", line 289, in _feed
    self.builder.feed(self.markup)
  File "C:\python\lib\site-packages\bs4\builder\_html5lib.py", line 72, in feed
    doc = parser.parse(markup, **extra_kwargs)
  File "C:\python\lib\site-packages\html5lib\html5parser.py", line 236, in parse
    parseMeta=parseMeta, useChardet=useChardet)
  File "C:\python\lib\site-packages\html5lib\html5parser.py", line 89, in _parse
    parser=self, **kwargs)
  File "C:\python\lib\site-packages\html5lib\tokenizer.py", line 40, in __init__
    self.stream = HTMLInputStream(stream, encoding, parseMeta, useChardet)
  File "C:\python\lib\site-packages\html5lib\inputstream.py", line 148, in HTMLInputStream
    return HTMLBinaryInputStream(source, encoding, parseMeta, chardet)
  File "C:\python\lib\site-packages\html5lib\inputstream.py", line 416, in __init__
    self.rawStream = self.openStream(source)
  File "C:\python\lib\site-packages\html5lib\inputstream.py", line 453, in openStream
    stream = BytesIO(source)
TypeError: a bytes-like object is required, not 'list'
</code>```

答:
For anyone looking for an answer that works in python 3</p>

```<code>invalidTags = ['br','b','font']
def stripTags(html, invalid_tags):
    soup = BeautifulSoup(html, "lxml")

    for tag in soup.findAll(True):
        if tag.name in invalid_tags:
            s = "::"
            for c in tag.contents:
                if not isinstance(c, NavigableString):
                    c = stripTags(str(c), invalid_tags)
                s += str(c)
            tag.replaceWith(s)
    return soup
</code>```

Body:
I'm trying to train data using the NLTK library. I follow a step-by-step process. I did the first step, but while doing the second step I'm getting the following error:

TypeError: a bytes-like object is required, not 'list'

I tried my best to rectify it but I'm getting the same error again.

Here is my code:

from bs4 import BeautifulSoup
import urllib.request
response = urllib.request.urlopen('http://php.net/')
html = response.read()
soup = BeautifulSoup(html,"html5lib")
text = soup.get_text(strip=True)
print (text)

this is my error

C:\python\lib\site-packages\bs4\__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 8 of the file E:/secure secure/chatbot-master/nltk.py. To get rid of this warning, change code that looks like this:

 BeautifulSoup(YOUR_MARKUP})

to this:

 BeautifulSoup(YOUR_MARKUP, "html5lib")

  markup_type=markup_type))
Traceback (most recent call last):
  File "E:/secure secure/chatbot-master/nltk.py", line 8, in <module>
    soup = BeautifulSoup(html)
  File "C:\python\lib\site-packages\bs4\__init__.py", line 228, in __init__
    self._feed()
  File "C:\python\lib\site-packages\bs4\__init__.py", line 289, in _feed
    self.builder.feed(self.markup)
  File "C:\python\lib\site-packages\bs4\builder\_html5lib.py", line 72, in feed
    doc = parser.parse(markup, **extra_kwargs)
  File "C:\python\lib\site-packages\html5lib\html5parser.py", line 236, in parse
    parseMeta=parseMeta, useChardet=useChardet)
  File "C:\python\lib\site-packages\html5lib\html5parser.py", line 89, in _parse
    parser=self, **kwargs)
  File "C:\python\lib\site-packages\html5lib\tokenizer.py", line 40, in __init__
    self.stream = HTMLInputStream(stream, encoding, parseMeta, useChardet)
  File "C:\python\lib\site-packages\html5lib\inputstream.py", line 148, in HTMLInputStream
    return HTMLBinaryInputStream(source, encoding, parseMeta, chardet)
  File "C:\python\lib\site-packages\html5lib\inputstream.py", line 416, in __init__
    self.rawStream = self.openStream(source)
  File "C:\python\lib\site-packages\html5lib\inputstream.py", line 453, in openStream
    stream = BytesIO(source)
TypeError: a bytes-like object is required, not 'list'

Body:
For anyone looking for an answer that works in python 3

invalidTags = ['br','b','font']
def stripTags(html, invalid_tags):
    soup = BeautifulSoup(html, "lxml")

    for tag in soup.findAll(True):
        if tag.name in invalid_tags:
            s = "::"
            for c in tag.contents:
                if not isinstance(c, NavigableString):
                    c = stripTags(str(c), invalid_tags)
                s += str(c)
            tag.replaceWith(s)
    return soup


问:
Processing large arrays in PowerShell
I am having a difficult time understanding the most efficient to process large datasets/arrays in PowerShell. I have arrays that have several million items that I need to process and group. This list is always different in size meaning it could be 3.5 million items or 10 million items.

Example: 3.5 million items they group by "4's" like the following:

Items 0,1,2,3 Group together 4,5,6,7 Group Together and so on.

I have tried processing the array using a single thread by looping through the list and assigning to a pscustomobject which works it just takes 45-50+ minutes to complete.

I have also attempted to break up the array into smaller arrays but that causes the process to run even longer.

$i=0
$d_array = @()
$item_array # Large dataset

While ($i -lt $item_array.length){

    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++

    $items = [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    $d_array += $items

}
```

I would imagine if I applied a job scheduler that would allow me to run the multiple jobs would cut the process time down by a significant amount, but I wanted to get others takes on a quick effective way to tackle this.

答:
You could optimize this somewhat using an ArrayList, or perhaps even better by using a strongly typed List but going through millions of elements in an array will still take time..

As for your code: there is no need to capture the array item values in a variable first and use that later to add to the PSCustomObject.

```<code>$item_array = 'a','b','c','d','e','f','g','h' # Large dataset
$result = New-Object System.Collections.Generic.List[PSCustomObject]
# or use an ArrayList: $result = New-Object System.Collections.ArrayList

$i = 0
While ($i -lt $item_array.Count) {
    [void]$result.Add(
        [PSCustomObject]@{
            'field1' = "Test" # $o
            'field2' = "Test" # $oo
            'field3' = $item_array[$i++]  #$n
            'field4' = $item_array[$i++]  #$id
            'field5' = $item_array[$i++]  #$ir
            'field6' = $item_array[$i++]  #$cs
        }
    )
}

# save to a CSV file maybe ?
$result | Export-Csv 'D:\blah.csv' -NoTypeInformation
</code>```

If you need the result to become a 'normal' array again, use $result.ToArray()

Title: Processing large arrays in PowerShell

Body:
I am having a difficult time understanding the most efficient to process large datasets/arrays in PowerShell. I have arrays that have several million items that I need to process and group. This list is always different in size meaning it could be 3.5 million items or 10 million items.

Example: 3.5 million items they group by "4's" like the following:

Items 0,1,2,3 Group together 4,5,6,7 Group Together and so on.

I have tried processing the array using a single thread by looping through the list and assigning to a pscustomobject which works it just takes 45-50+ minutes to complete.

I have also attempted to break up the array into smaller arrays but that causes the process to run even longer.

$i=0
$d_array = @()
$item_array # Large dataset

While ($i -lt $item_array.length){

    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++

    $items = [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    $d_array += $items

}

I would imagine if I applied a job scheduler that would allow me to run the multiple jobs would cut the process time down by a significant amount, but I wanted to get others takes on a quick effective way to tackle this.

Body:
You could optimize this somewhat using an ArrayList, or perhaps even better by using a strongly typed List but going through millions of elements in an array will still take time..

As for your code: there is no need to capture the array item values in a variable first and use that later to add to the PSCustomObject.

$item_array = 'a','b','c','d','e','f','g','h' # Large dataset
$result = New-Object System.Collections.Generic.List[PSCustomObject]
# or use an ArrayList: $result = New-Object System.Collections.ArrayList

$i = 0
While ($i -lt $item_array.Count) {
    [void]$result.Add(
        [PSCustomObject]@{
            'field1' = "Test" # $o
            'field2' = "Test" # $oo
            'field3' = $item_array[$i++]  #$n
            'field4' = $item_array[$i++]  #$id
            'field5' = $item_array[$i++]  #$ir
            'field6' = $item_array[$i++]  #$cs
        }
    )
}

# save to a CSV file maybe ?
$result | Export-Csv 'D:\blah.csv' -NoTypeInformation

If you need the result to become a 'normal' array again, use $result.ToArray()


问:
Is Java overkill for news websites?
A client of mine wants a news website designed in Java, and I told him that Java is overkill for that kind of website. I suggested to him that there are dozens of CMS that we can customize for him, as well as other programming languages that are better suited for websites but he insisted.

Is Java overkill for news websites?

答:
I think the real issue here is that whoever your client is has this notion that problems can be solved by name-dropping programming languages. I understand that you recognize this problem too, but in any business "the customer is always right" and you'll have to give in.

So is Java overkill for news websites? That depends. If what he's asking for is available in Drupal or even Wordpress out of the box, then the answer is yes. The real questions further on will be:

How much expertise does his organization have on Java (you have to consider the possibility that he wants to maintain the system by himself -- if his employees know Java, you now know why he insists on it)

What are the features that he actually wants? How will the site evolve in the future? (There will be features that will be more difficult to implement in PHP than in Java)

What are the cost implications? (If he wants it cheaper, you can offer to simply customize Drupal or Wordpress, but if budget is not a major consideration, going with Java would be fine).

OwnerDisplayName: Ainab

ContentLicense: CC BY-SA 2.5

Title: Is Java overkill for news websites?

LastEditorDisplayName: LFSR Consulting

OwnerDisplayName: Jon Limjap


问:
Problems uploading blobs onto App Engine
Hi i'm trying to upload some mp3s as blobs using the Complete Sample App code provided in the App Engine tutorial here and i'm getting the following error `HTTP ERROR 404

Problem accessing /_ah/upload/ag5jb2xsZWN0aXZlZ3dhcHIbCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGHQM. Reason:

```<code>No upload session: ag5jb2xsZWN0aXZlZ3dhcHIbCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGHQM`
</code>```

Anyone have any ideas why i'm getting this?  Tried running locally and even tried deploying the App and still having issues!

答:
Seems to be a bug with SDK 1.4.3
This seems to work just fine with SDK 1.4.2

Does this resolve your problem?

Body:
Hi i'm trying to upload some mp3s as blobs using the Complete Sample App code provided in the App Engine tutorial here and i'm getting the following error `HTTP ERROR 404

Problem accessing /_ah/upload/ag5jb2xsZWN0aXZlZ3dhcHIbCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGHQM. Reason:

No upload session: ag5jb2xsZWN0aXZlZ3dhcHIbCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGHQM`

Anyone have any ideas why i'm getting this?  Tried running locally and even tried deploying the App and still having issues!


问:
roles.forEach not a function
So basically what is happening, is this code is running when a command is run. If the user's string (UserID) fits into the array, it responds as true and sets the access level to 6. If that is false, it checks for roles and sets the access level if they have certain roles by the role names. However, the role names part is not working. For example, a user with the Moderator role (normally access level 3 / perms.three), is showing up as access level 0 and I cannot figure out why.

The way this is supposed to work is that it checks the ID of a user. If that ID is in a pre-defined array located in a .json file, it overrides all other access levels by giving an access level of 6. If the array doesn't exist it moves onto the roles function and searches to see if the role exists in the persons list of roles.

This is what I use to check the roles/userID.

```<code>if (command.accessLevel > perms.getAccess(message.member.roles) || command.accessLevel > perms.getAccess(message.member.id)){
      return message.channel.send("``Error: Access Denied.``");
    }
</code>```

This is the permissions.js file:

```<code>const bot = require('./bot').skynet;
const config = require('./config.json');
const perms = require('./permissions.json').access;

function arrayHas(arr, val){
    var result = false;

    for (var item in arr){
        if (arr[item] == val){
            result = true;
            break;
        }
    }

    return result;
}

function getAccess(user){
    var access = 0;

    if (typeof(user) == 'string'){
        if (arrayHas(perms.six, user)){
            return 6;
        }
    }

    var roles = user;
    roles.forEach(function(role){
        if (arrayHas(perms.five, role.name)){
            access = 5;
            return;
        }
        else if (arrayHas(perms.four, role.name)){
            access = 4;
            return;
        }
        else if (arrayHas(perms.three, role.name)){
            access = 3;
            return;
        }
        else if (arrayHas(perms.two, role.name)){
            access = 2;
            return;
        }
        else if (arrayHas(perms.one, role.name)){
            access = 1;
            return;
        }
    });

    return access;
}

bot.on('message', message => {
    console.log(getAccess(message.member.id));
    console.log(getAccess(message.member.roles));
})

module.exports = {
    arrayHas: arrayHas,
    getAccess: getAccess,
};
</code>```

答:
In your function getAccess(), you're setting the access variable but never actually returning the value. Try this revised version.

const Discord = require('discord.js');
const { skynet: bot } = require('./bot');
const config = require('./config.json');
const { access: perms } = require('./permissions.json');

/**
 * Return the access level of a member.
 * @param {Discord.GuildMember} member
*/
function getAccess(member) {
  if (!(member instanceof Discord.GuildMember)) return new TypeError('Expected a GuildMember.');

  if (arrayHas(perms.six, member.user.id)) return 6;

  const roles = member.roles;

  for (const role of roles) {
    if (arrayHas(perms.five, role.name)) return 5;
    if (arrayHas(perms.four, role.name)) return 4;
    if (arrayHas(perms.three, role.name)) return 3;
    if (arrayHas(perms.two, role.name)) return 2;
    if (arrayHas(perms.one, role.name)) return 1;
  }

  return 0;
}
```

Title: roles.forEach not a function

Body:
So basically what is happening, is this code is running when a command is run. If the user's string (UserID) fits into the array, it responds as true and sets the access level to 6. If that is false, it checks for roles and sets the access level if they have certain roles by the role names. However, the role names part is not working. For example, a user with the Moderator role (normally access level 3 / perms.three), is showing up as access level 0 and I cannot figure out why.

The way this is supposed to work is that it checks the ID of a user. If that ID is in a pre-defined array located in a .json file, it overrides all other access levels by giving an access level of 6. If the array doesn't exist it moves onto the roles function and searches to see if the role exists in the persons list of roles.

This is what I use to check the roles/userID.

if (command.accessLevel > perms.getAccess(message.member.roles) || command.accessLevel > perms.getAccess(message.member.id)){
      return message.channel.send("``Error: Access Denied.``");
    }

This is the permissions.js file:

const bot = require('./bot').skynet;
const config = require('./config.json');
const perms = require('./permissions.json').access;

function arrayHas(arr, val){
    var result = false;

    for (var item in arr){
        if (arr[item] == val){
            result = true;
            break;
        }
    }

    return result;
}

function getAccess(user){
    var access = 0;

    if (typeof(user) == 'string'){
        if (arrayHas(perms.six, user)){
            return 6;
        }
    }

    var roles = user;
    roles.forEach(function(role){
        if (arrayHas(perms.five, role.name)){
            access = 5;
            return;
        }
        else if (arrayHas(perms.four, role.name)){
            access = 4;
            return;
        }
        else if (arrayHas(perms.three, role.name)){
            access = 3;
            return;
        }
        else if (arrayHas(perms.two, role.name)){
            access = 2;
            return;
        }
        else if (arrayHas(perms.one, role.name)){
            access = 1;
            return;
        }
    });

    return access;
}

bot.on('message', message => {
    console.log(getAccess(message.member.id));
    console.log(getAccess(message.member.roles));
})

module.exports = {
    arrayHas: arrayHas,
    getAccess: getAccess,
};


问:
Time Complexity of Adding Edge to Graph using Adjacency List
I've been studying up on graphs using the Adjacency List implementation, and I am reading that adding an edge is an O(1) operation.

This makes sense if you are just tacking an edge on to the Vertex's Linked List of edges, but I don't understand how this could be the case so long as you care about removing the old edge if one already exists. Finding that edge would take O(V) time.

If you don't do this, and you add an edge that already exists, you would have duplicate entries for that edge, which means they could have different weights, etc.

Can anyone explain what I seem to be missing? Thanks!

答:
What people usually do to have both optimal search time complexity and the advantages of adjacency lists is to use an array of hashsets instead of an array of lists.

Alternatively,

If you want a worst-case optimal solution, use RadixSort to order the
  list of all edges in O(v+e) time, remove duplicates, and then build
  the adjacency list representation in the usual way.

source: https://www.quora.com/What-are-the-various-approaches-you-can-use-to-build-adjacency-list-representation-of-a-undirected-graph-having-time-complexity-better-than-O-V-*-E-and-avoiding-duplicate-edges


问:
How to get only one answer if there is no match after loop
My code has a for loop in array and has if statement, and I want to get only one answer if there is no match.

```<code>for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && i].GetSomeValue() <= 5)
        Console.WriteLine(arr[i]);
    else
       Console.WriteLine("No data");
}
</code>```

However, I get these:

```<code>No data
No data
No data
No data
</code>```

I want only one "No data" if there is no match.
I tried adding

```<code>    else break;
}
Console.WriteLine("No data");
</code>```

But it does not work.

How do I get what I want?

答:
Alternative based on linq:</p>

```<code>using System.Linq;

...

var withinSpecs = arr.Where(e => e.GetSomeValue() >= 1 && e.GetSomeValue() < 5).ToArray();
if(withinSpecs.Length == 0)
{
    Console.WriteLine("No data");
}
else
{
    foreach(var element in withinSpecs)
        Console.WriteLine(element);
}
</code>```

Body:
My code has a for loop in array and has if statement, and I want to get only one answer if there is no match.

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && i].GetSomeValue() <= 5)
        Console.WriteLine(arr[i]);
    else
       Console.WriteLine("No data");
}

However, I get these:

No data
No data
No data
No data

I want only one "No data" if there is no match.
I tried adding

    else break;
}
Console.WriteLine("No data");

But it does not work.

How do I get what I want?

Body:
Alternative based on linq:

using System.Linq;

...

var withinSpecs = arr.Where(e => e.GetSomeValue() >= 1 && e.GetSomeValue() < 5).ToArray();
if(withinSpecs.Length == 0)
{
    Console.WriteLine("No data");
}
else
{
    foreach(var element in withinSpecs)
        Console.WriteLine(element);
}


问:
Redirect to a file STDOUT first and then STDERR
I have a gawk code like this.

```<code>#!/usr/bin/gawk -f

1 {
    for (i=0;i<5;i++){
        print $0
        print $0, i > "/dev/stderr"
    }
}
</code>```

I want to redirect to a file tmp, first the stdout and then the stderr. I tried this:

gawk -f Documents/gawk_script.awk ./file &> tmp
```
<p>But this call append to the file first stderr. I don't want to divide them into two files, so I'm asking if there's a way to do that.</p>
<p>In ./file there's such a line:</p>
```hello
hello
howareyou
well
well
```
<p>while in tmp file</p>
```hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
howareyou
howareyou
howareyou
howareyou
howareyou
well
well
well
well
well
well
well
well
well
well
well
hello 0
hello 1
hello 2
hello 3
hello 4
hello 0
hello 1
hello 2
hello 3
hello 4
howareyou 0
howareyou 1
howareyou 2
howareyou 3
howareyou 4
well 0
well 1
well 2
well 3
well 4
well 0
well 1
well 2
well 3
well 4
```

答:
There is no good way* to tell awk or the shell that it must buffer stderr until the tool finishes executing. Keep it simple and just do this:

```<code>awk -f script.awk file > out 2>tmp; cat tmp >> out && rm -f tmp
</code>```

Otherwise you could buffer stderr yourself and print at the end (but this will only work for stderr messages you are manually printing, not messages gawk is generating itself):

```<code>{
    for (i=0;i<5;i++){
        print $0
        errs = errs $0 OFS i ORS
    }
}
END {
    printf "%s", errs > "/dev/stderr"
}
</code>```

and then call as:

```<code>awk -f script.awk file > out 2>&1
</code>```

Of course you don't actually need to use stderr at all if that's all you're doing with it, just print to stdout.

*There may be some arcane incantation you can use to make this happen if the planets align a certain way and/or you have certain tools or a certain shell but just keep it simple as shown above.

Body:
I have a gawk code like this.

#!/usr/bin/gawk -f

1 {
    for (i=0;i<5;i++){
        print $0
        print $0, i > "/dev/stderr"
    }
}

I want to redirect to a file tmp, first the stdout and then the stderr. I tried this:

gawk -f Documents/gawk_script.awk ./file &> tmp

But this call append to the file first stderr. I don't want to divide them into two files, so I'm asking if there's a way to do that.

In ./file there's such a line:

hello
hello
howareyou
well
well

while in tmp file

hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
howareyou
howareyou
howareyou
howareyou
howareyou
well
well
well
well
well
well
well
well
well
well
well
hello 0
hello 1
hello 2
hello 3
hello 4
hello 0
hello 1
hello 2
hello 3
hello 4
howareyou 0
howareyou 1
howareyou 2
howareyou 3
howareyou 4
well 0
well 1
well 2
well 3
well 4
well 0
well 1
well 2
well 3
well 4

Body:
There is no good way* to tell awk or the shell that it must buffer stderr until the tool finishes executing. Keep it simple and just do this:

awk -f script.awk file > out 2>tmp; cat tmp >> out && rm -f tmp

Otherwise you could buffer stderr yourself and print at the end (but this will only work for stderr messages you are manually printing, not messages gawk is generating itself):

{
    for (i=0;i<5;i++){
        print $0
        errs = errs $0 OFS i ORS
    }
}
END {
    printf "%s", errs > "/dev/stderr"
}

and then call as:

awk -f script.awk file > out 2>&1

Of course you don't actually need to use stderr at all if that's all you're doing with it, just print to stdout.

*There may be some arcane incantation you can use to make this happen if the planets align a certain way and/or you have certain tools or a certain shell but just keep it simple as shown above.


问:
Image Resize with constraint proportion and tranparancy
How do i resize image preserving its dimension ratio proportion and transparancy in php</p>

答: Use the GD library from MicroMVC. It's the smallest, fastest GD lib out there.</p>


问:
How to use latitude and longitude retrieved from a service and show them on map?
I have defined a service (i.e. LocationService ) which gives me users's current latitude and longitude as an intent extras to my_activity. Now , I want to use  them to show current location on map (using Google maps) . I passed these latlng in mMap.animateCamera and mMap.moveCamera methods but they are not showing any Marker or zoom in to the current location . Please tell me if I am doing anything wrong .

Code for the LocationService and my MainActivity is pasted below :

LocationServices.java

```<code>public class LocationServicesForLocationUpdates extends Service implements LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{

private static final String TAG = LocationServicesForLocationUpdates.class.getSimpleName();

public static final String ACTION_LOCATION_BROADCAST
        = LocationServicesForLocationUpdates.class.getName() + "LocationBroadcast";

public static final String EXTRA_LATITUDE = "extra_latitude";
public static final String EXTRA_LONGITUDE = "extra_longitude";

private GoogleApiClient mLocationClient;
private LocationRequest mLocationRequest = new LocationRequest();

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    mLocationClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    mLocationRequest.setInterval(5000);
    mLocationRequest.setFastestInterval(3000);

    mLocationClient.connect();

   // return super.onStartCommand(intent, flags, startId);

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

/*
 * LOCATION CALLBACKS
 */
@Override
public void onConnected(Bundle dataBundle) {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED

            && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

        Log.d(TAG, "== Error On onConnected() Permission not granted");
        //Permission not granted by user so cancel the further execution.

        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest ,this);

    Log.d(TAG, "Connected to Google API");
}

//to get the location change
@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "Location changed");

    if (location != null) {
        Log.d(TAG, "== location != null");

        //Send result to activities
        sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));

    }
}

private void sendMessageToUI(String lat, String lng) {

    Log.d(TAG, "Sending info...");

    Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
    intent.putExtra(EXTRA_LATITUDE, lat);
    intent.putExtra(EXTRA_LONGITUDE, lng);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}
</code>```

New MainActivity.java

```<code> public class MainActivity extends AppCompatActivity implements OnMapReadyCallback{

private TextView mLatlngTxtVu , mAddressTxtVu;

private boolean mAlreadyStartedService;

private static final String TAG = ParentHomeActivity.class.getSimpleName();

private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;

private GoogleMap mGoogleMap;

Double mlattitude , mlongitude;

Marker mCurrentMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_parent_home);

    Log.d(TAG, "onCreate: Called");
    mLatlngTxtVu = (TextView) findViewById(R.id.latlng_txtview);
    mAddressTxtVu = (TextView) findViewById(R.id.address_txtvu);

    LocalBroadcastManager.getInstance(this).registerReceiver(
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    mlattitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LATITUDE));
                    mlongitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LONGITUDE));

                    Log.d("latlng", "onReceive: " + mlongitude + mlattitude);

                    if (mlattitude != null && mlongitude != null) {
                        mLatlngTxtVu.setText("Latitude : " + mlattitude + "Longitude: " + mlongitude);
                    }
                }
            }, new IntentFilter(LocationServicesForLocationUpdates.ACTION_LOCATION_BROADCAST)
    );

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.main_map);
    mapFragment.getMapAsync(MainActivity.this);

}

@Override
protected void onResume() {
    super.onResume();

    checkGooglePlayServices();

}

@Override
public void onMapReady(GoogleMap googleMap) {

    mGoogleMap = googleMap ;

    Log.d(TAG, "onMapReady: called");

    Log.d("coord", mlattitude + "   " + mlongitude);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    mGoogleMap.setMyLocationEnabled(true);
    mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
    mGoogleMap.getUiSettings().setMapToolbarEnabled(false);

    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(mlattitude, mlongitude))      // Sets the center of the map to location user
            .zoom(14)                   // Sets the zoom
            .bearing(0)                // Sets the orientation of the camera to east
            .tilt(90)                   // Sets the tilt of the camera to 30 degrees
            .build();                   // Creates a CameraPosition from the builder
    mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    LatLng latLng = new LatLng(mlattitude  , mlongitude);

    mGoogleMap.addMarker(new MarkerOptions().position(latLng).title("YOU"));

   // mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

   /* CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(mlattitude, mlongitude))      // Sets the center of the map to location user
            .zoom(17)                   // Sets the zoom
            .bearing(90)                // Sets the orientation of the camera to east
            .tilt(40)                   // Sets the tilt of the camera to 30 degrees
            .build();                   // Creates a CameraPosition from the builder
    mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/

}

private void checkGooglePlayServices() {

    //Check whether this user has installed Google play service which is being used by Location updates.
    if (isGooglePlayServicesAvailable()) {

        //Passing null to indicate that it is executing for the first time.
        checkAndPromptForInternetConnection(null);

    } else {
        Toast.makeText(getApplicationContext(), "Play services Not Available", Toast.LENGTH_LONG).show();
    }

}

private boolean checkAndPromptForInternetConnection(DialogInterface dialog) {

    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

    if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
        promptInternetConnect();
        return false;
    }

    if (dialog != null) {
        dialog.dismiss();
    }

    //Yes there is active internet connection. Next check Location is granted by user or not.

    if (checkPermissions()) { //Yes permissions are granted by the user. Go to the next step.
        startedLocationServices();
    } else {  //No user has not granted the permissions yet. Request now.
        requestPermissions();
    }
    return true;
}

/**
 * Step 3: Start the Location Monitor Service
 */
private void startedLocationServices() {

    //And it will be keep running until you close the entire application from task manager.
    //This method will executed only once.

    if (!mAlreadyStartedService && mLatlngTxtVu != null) {

        mLatlngTxtVu.setText("Running ");

        //Start location sharing service to app server.........
        Intent intent = new Intent(this, LocationServicesForLocationUpdates.class);
        startService(intent);

        mAlreadyStartedService = true;
        //Ends................................................
    }
}
/**
 * Show A Dialog with button to refresh the internet state.
 */
private void promptInternetConnect() {
    AlertDialog.Builder builder = new AlertDialog.Builder(ParentHomeActivity.this);
    builder.setTitle("No internet connection");
    builder.setMessage("Please Check your internet connection");

    String positiveText = "Refresh";
    builder.setPositiveButton(positiveText,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //Block the Application Execution until user grants the permissions
                    if (checkAndPromptForInternetConnection(dialog)) {

                        //Now make sure about location permission.
                        if (checkPermissions()) {

                            //Step 2: Start the Location Monitor Service
                            //Everything is there to start the service.
                            startedLocationServices();
                        } else if (!checkPermissions()) {
                            requestPermissions();
                        }

                    }
                }
            });

    AlertDialog dialog = builder.create();
    dialog.show();
}

/**
 * Return the availability of GooglePlayServices
 */
public boolean isGooglePlayServicesAvailable() {
    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
    int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
    if (status != ConnectionResult.SUCCESS) {
        if (googleApiAvailability.isUserResolvableError(status)) {
            googleApiAvailability.getErrorDialog(this, status, 2404).show();
        }
        return false;
    }
    return true;
}

/**
 * Return the current state of the permissions needed.
 */
private boolean checkPermissions() {
    int permissionState1 = ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION);

    int permissionState2 = ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION);

    return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;

}

/**
 * Start permissions requests.
 */
private void requestPermissions() {

    boolean shouldProvideRationale =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION);

    boolean shouldProvideRationale2 =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION);

    // Provide an additional rationale to the img_user. This would happen if the img_user denied the
    // request previously, but didn't check the "Don't ask again" checkbox.
    if (shouldProvideRationale || shouldProvideRationale2) {
        Log.i(TAG, "Displaying permission rationale to provide additional context.");
        showSnackbar(R.string.grantPermission,
                android.R.string.ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Request permission
                        ActivityCompat.requestPermissions(ParentHomeActivity.this,
                                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                                REQUEST_PERMISSIONS_REQUEST_CODE);
                    }
                });
    } else {
        Log.i(TAG, "Requesting permission");
        // Request permission. It's possible this can be auto answered if device policy
        // sets the permission in a given state or the img_user denied the permission
        // previously and checked "Never ask again".
        ActivityCompat.requestPermissions(ParentHomeActivity.this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

/**
 * Shows a {@link Snackbar}.
 *
 * @param mainTextStringId The id for the string resource for the Snackbar text.
 * @param actionStringId   The text of the action item.
 * @param listener         The listener associated with the Snackbar action.
 */
private void showSnackbar(final int mainTextStringId, final int actionStringId,
                          View.OnClickListener listener) {
    Snackbar.make(
            findViewById(android.R.id.content),
            getString(mainTextStringId),
            Snackbar.LENGTH_INDEFINITE)
            .setAction(getString(actionStringId), listener).show();
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    Log.i(TAG, "onRequestPermissionResult");
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
        if (grantResults.length <= 0) {
            // If img_user interaction was interrupted, the permission request is cancelled and you
            // receive empty arrays.
            Log.i(TAG, "User interaction was cancelled.");
        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Log.i(TAG, "Permission granted, updates requested, starting location updates");
            startedLocationServices();

        } else {
            // Permission denied.

            // Notify the img_user via a SnackBar that they have rejected a core permission for the
            // app, which makes the Activity useless. In a real app, core permissions would
            // typically be best requested during a welcome-screen flow.

            // Additionally, it is important to remember that a permission might have been
            // rejected without asking the img_user for permission (device policy or "Never ask
            // again" prompts). Therefore, a img_user interface affordance is typically implemented
            // when permissions are denied. Otherwise, your app could appear unresponsive to
            // touches or interactions which have required permissions.
            showSnackbar(R.string.permissionDenied,
                R.string.settings, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Build intent that displays the App settings screen.
                        Intent intent = new Intent();
                        intent.setAction(
                                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package",
                                BuildConfig.APPLICATION_ID, null);
                        intent.setData(uri);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
        }
    }
}

@Override
public void onDestroy() {

    //Stop location sharing service to app server.........

    stopService(new Intent(this, LocationServicesForLocationUpdates.class));
    mAlreadyStartedService = false;
    //Ends................................................

    super.onDestroy();
}

}
</code>```

Feel free to ask any queries in case you don't understand my problem and tell me the correct approach to solve my problem . I am new to android app development.

答:
You can do like that :

```<code>public class MapsMarkerActivity extends AppCompatActivity
    implements OnMapReadyCallback {
   // Include the OnCreate() method here too, as described above.
   @Override
   public void onMapReady(GoogleMap googleMap) {
       // Add a marker in Sydney, Australia,
       // and move the map's camera to the same location.
       LatLng sydney = new LatLng(-33.852, 151.211);
       googleMap.addMarker(new MarkerOptions().position(sydney)
            .title("Marker in Sydney"));
       googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
   }
}
</code>```

The code is from the Google documentation page

Body:
I have defined a service (i.e. LocationService ) which gives me users's current latitude and longitude as an intent extras to my_activity. Now , I want to use  them to show current location on map (using Google maps) . I passed these latlng in mMap.animateCamera and mMap.moveCamera methods but they are not showing any Marker or zoom in to the current location . Please tell me if I am doing anything wrong .

Code for the LocationService and my MainActivity is pasted below :

LocationServices.java

public class LocationServicesForLocationUpdates extends Service implements LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{

private static final String TAG = LocationServicesForLocationUpdates.class.getSimpleName();

public static final String ACTION_LOCATION_BROADCAST
        = LocationServicesForLocationUpdates.class.getName() + "LocationBroadcast";

public static final String EXTRA_LATITUDE = "extra_latitude";
public static final String EXTRA_LONGITUDE = "extra_longitude";

private GoogleApiClient mLocationClient;
private LocationRequest mLocationRequest = new LocationRequest();

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    mLocationClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    mLocationRequest.setInterval(5000);
    mLocationRequest.setFastestInterval(3000);

    mLocationClient.connect();

   // return super.onStartCommand(intent, flags, startId);

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

/*
 * LOCATION CALLBACKS
 */
@Override
public void onConnected(Bundle dataBundle) {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED

            && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

        Log.d(TAG, "== Error On onConnected() Permission not granted");
        //Permission not granted by user so cancel the further execution.

        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest ,this);

    Log.d(TAG, "Connected to Google API");
}

//to get the location change
@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "Location changed");

    if (location != null) {
        Log.d(TAG, "== location != null");

        //Send result to activities
        sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));

    }
}

private void sendMessageToUI(String lat, String lng) {

    Log.d(TAG, "Sending info...");

    Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
    intent.putExtra(EXTRA_LATITUDE, lat);
    intent.putExtra(EXTRA_LONGITUDE, lng);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

New MainActivity.java

 public class MainActivity extends AppCompatActivity implements OnMapReadyCallback{

private TextView mLatlngTxtVu , mAddressTxtVu;

private boolean mAlreadyStartedService;

private static final String TAG = ParentHomeActivity.class.getSimpleName();

private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;

private GoogleMap mGoogleMap;

Double mlattitude , mlongitude;

Marker mCurrentMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_parent_home);

    Log.d(TAG, "onCreate: Called");
    mLatlngTxtVu = (TextView) findViewById(R.id.latlng_txtview);
    mAddressTxtVu = (TextView) findViewById(R.id.address_txtvu);

    LocalBroadcastManager.getInstance(this).registerReceiver(
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    mlattitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LATITUDE));
                    mlongitude = Double.parseDouble(intent.getStringExtra(LocationServicesForLocationUpdates.EXTRA_LONGITUDE));

                    Log.d("latlng", "onReceive: " + mlongitude + mlattitude);

                    if (mlattitude != null && mlongitude != null) {
                        mLatlngTxtVu.setText("Latitude : " + mlattitude + "Longitude: " + mlongitude);
                    }
                }
            }, new IntentFilter(LocationServicesForLocationUpdates.ACTION_LOCATION_BROADCAST)
    );

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.main_map);
    mapFragment.getMapAsync(MainActivity.this);

}

@Override
protected void onResume() {
    super.onResume();

    checkGooglePlayServices();

}

@Override
public void onMapReady(GoogleMap googleMap) {

    mGoogleMap = googleMap ;

    Log.d(TAG, "onMapReady: called");

    Log.d("coord", mlattitude + "   " + mlongitude);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    mGoogleMap.setMyLocationEnabled(true);
    mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
    mGoogleMap.getUiSettings().setMapToolbarEnabled(false);

    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(mlattitude, mlongitude))      // Sets the center of the map to location user
            .zoom(14)                   // Sets the zoom
            .bearing(0)                // Sets the orientation of the camera to east
            .tilt(90)                   // Sets the tilt of the camera to 30 degrees
            .build();                   // Creates a CameraPosition from the builder
    mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    LatLng latLng = new LatLng(mlattitude  , mlongitude);

    mGoogleMap.addMarker(new MarkerOptions().position(latLng).title("YOU"));

   // mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

   /* CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(mlattitude, mlongitude))      // Sets the center of the map to location user
            .zoom(17)                   // Sets the zoom
            .bearing(90)                // Sets the orientation of the camera to east
            .tilt(40)                   // Sets the tilt of the camera to 30 degrees
            .build();                   // Creates a CameraPosition from the builder
    mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/

}

private void checkGooglePlayServices() {

    //Check whether this user has installed Google play service which is being used by Location updates.
    if (isGooglePlayServicesAvailable()) {

        //Passing null to indicate that it is executing for the first time.
        checkAndPromptForInternetConnection(null);

    } else {
        Toast.makeText(getApplicationContext(), "Play services Not Available", Toast.LENGTH_LONG).show();
    }

}

private boolean checkAndPromptForInternetConnection(DialogInterface dialog) {

    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

    if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
        promptInternetConnect();
        return false;
    }

    if (dialog != null) {
        dialog.dismiss();
    }

    //Yes there is active internet connection. Next check Location is granted by user or not.

    if (checkPermissions()) { //Yes permissions are granted by the user. Go to the next step.
        startedLocationServices();
    } else {  //No user has not granted the permissions yet. Request now.
        requestPermissions();
    }
    return true;
}

/**
 * Step 3: Start the Location Monitor Service
 */
private void startedLocationServices() {

    //And it will be keep running until you close the entire application from task manager.
    //This method will executed only once.

    if (!mAlreadyStartedService && mLatlngTxtVu != null) {

        mLatlngTxtVu.setText("Running ");

        //Start location sharing service to app server.........
        Intent intent = new Intent(this, LocationServicesForLocationUpdates.class);
        startService(intent);

        mAlreadyStartedService = true;
        //Ends................................................
    }
}
/**
 * Show A Dialog with button to refresh the internet state.
 */
private void promptInternetConnect() {
    AlertDialog.Builder builder = new AlertDialog.Builder(ParentHomeActivity.this);
    builder.setTitle("No internet connection");
    builder.setMessage("Please Check your internet connection");

    String positiveText = "Refresh";
    builder.setPositiveButton(positiveText,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //Block the Application Execution until user grants the permissions
                    if (checkAndPromptForInternetConnection(dialog)) {

                        //Now make sure about location permission.
                        if (checkPermissions()) {

                            //Step 2: Start the Location Monitor Service
                            //Everything is there to start the service.
                            startedLocationServices();
                        } else if (!checkPermissions()) {
                            requestPermissions();
                        }

                    }
                }
            });

    AlertDialog dialog = builder.create();
    dialog.show();
}

/**
 * Return the availability of GooglePlayServices
 */
public boolean isGooglePlayServicesAvailable() {
    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
    int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
    if (status != ConnectionResult.SUCCESS) {
        if (googleApiAvailability.isUserResolvableError(status)) {
            googleApiAvailability.getErrorDialog(this, status, 2404).show();
        }
        return false;
    }
    return true;
}

/**
 * Return the current state of the permissions needed.
 */
private boolean checkPermissions() {
    int permissionState1 = ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION);

    int permissionState2 = ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION);

    return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;

}

/**
 * Start permissions requests.
 */
private void requestPermissions() {

    boolean shouldProvideRationale =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION);

    boolean shouldProvideRationale2 =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION);

    // Provide an additional rationale to the img_user. This would happen if the img_user denied the
    // request previously, but didn't check the "Don't ask again" checkbox.
    if (shouldProvideRationale || shouldProvideRationale2) {
        Log.i(TAG, "Displaying permission rationale to provide additional context.");
        showSnackbar(R.string.grantPermission,
                android.R.string.ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Request permission
                        ActivityCompat.requestPermissions(ParentHomeActivity.this,
                                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                                REQUEST_PERMISSIONS_REQUEST_CODE);
                    }
                });
    } else {
        Log.i(TAG, "Requesting permission");
        // Request permission. It's possible this can be auto answered if device policy
        // sets the permission in a given state or the img_user denied the permission
        // previously and checked "Never ask again".
        ActivityCompat.requestPermissions(ParentHomeActivity.this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

/**
 * Shows a {@link Snackbar}.
 *
 * @param mainTextStringId The id for the string resource for the Snackbar text.
 * @param actionStringId   The text of the action item.
 * @param listener         The listener associated with the Snackbar action.
 */
private void showSnackbar(final int mainTextStringId, final int actionStringId,
                          View.OnClickListener listener) {
    Snackbar.make(
            findViewById(android.R.id.content),
            getString(mainTextStringId),
            Snackbar.LENGTH_INDEFINITE)
            .setAction(getString(actionStringId), listener).show();
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    Log.i(TAG, "onRequestPermissionResult");
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
        if (grantResults.length <= 0) {
            // If img_user interaction was interrupted, the permission request is cancelled and you
            // receive empty arrays.
            Log.i(TAG, "User interaction was cancelled.");
        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Log.i(TAG, "Permission granted, updates requested, starting location updates");
            startedLocationServices();

        } else {
            // Permission denied.

            // Notify the img_user via a SnackBar that they have rejected a core permission for the
            // app, which makes the Activity useless. In a real app, core permissions would
            // typically be best requested during a welcome-screen flow.

            // Additionally, it is important to remember that a permission might have been
            // rejected without asking the img_user for permission (device policy or "Never ask
            // again" prompts). Therefore, a img_user interface affordance is typically implemented
            // when permissions are denied. Otherwise, your app could appear unresponsive to
            // touches or interactions which have required permissions.
            showSnackbar(R.string.permissionDenied,
                R.string.settings, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Build intent that displays the App settings screen.
                        Intent intent = new Intent();
                        intent.setAction(
                                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package",
                                BuildConfig.APPLICATION_ID, null);
                        intent.setData(uri);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
        }
    }
}

@Override
public void onDestroy() {

    //Stop location sharing service to app server.........

    stopService(new Intent(this, LocationServicesForLocationUpdates.class));
    mAlreadyStartedService = false;
    //Ends................................................

    super.onDestroy();
}

}

Feel free to ask any queries in case you don't understand my problem and tell me the correct approach to solve my problem . I am new to android app development.

Body:
You can do like that :

public class MapsMarkerActivity extends AppCompatActivity
    implements OnMapReadyCallback {
   // Include the OnCreate() method here too, as described above.
   @Override
   public void onMapReady(GoogleMap googleMap) {
       // Add a marker in Sydney, Australia,
       // and move the map's camera to the same location.
       LatLng sydney = new LatLng(-33.852, 151.211);
       googleMap.addMarker(new MarkerOptions().position(sydney)
            .title("Marker in Sydney"));
       googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
   }
}

The code is from the Google documentation page