问:
How To fix Values of Second Y scale Using ggplot in R?
I'm trying to get a graph with 2 y scales using 2 different dataframes. The first dataframe bargraph_dets_temp looks like this

```<code>bargraph_dets_temp = structure(list(Zone = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
                                                                             "2", "3", "4"), class = "factor"), month = structure(c(8L, 8L,
                                                                                8L, 8L, 8L, 8L), .Label = c("Jan", "Feb", "Mar", "Apr", "May",
                                                                                "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2016, 2016, 2016, 2016, 2016, 2017), location = c("HFX001",
                                                                                "HFX002", "HFX003", "KETCH HARBOUR, NS", "NSTR001", "Gill Cove"
                                                                                ), num_unique_tags = c(5, 4, 2, 5, 5, 6), total_res_time_in_seconds = c(10666,
                                                                                14645, 6799, 0, 58959, 0), latitude = c(44.47846, 44.47222, 44.46643,
                                                                                44.48427, 44.48422, 44.48467), longitude = c(-63.53341, -63.52704,
                                                                                -63.51983, -63.53338, -63.53246, -63.53316), geometry = structure(list(
                                                                                structure(c(-63.53341, 44.47846), class = c("XY", "POINT",
                                                                                "sfg")), structure(c(-63.52704, 44.47222), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.51983, 44.46643), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53338, 44.48427), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53246, 44.48422), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53316, 44.48467), class = c("XY",
                                                                                "POINT", "sfg"))), class = c("sfc_POINT", "sfc"), precision = 0, bbox = structure(c(xmin = -63.53341,
                                                                                ymin = 44.46643, xmax = -63.51983, ymax = 44.48467), class = "bbox"), crs = structure(list(
                                                                                epsg = 4326L, proj4string = "+proj=longlat +datum=WGS84 +no_defs"), class = "crs"), n_empty = 0L),
                      distances = c(27.3573801954343, 26.4992220821035, 25.6385699365414,
                                    27.8643036652756, 27.8152639871898, 27.8888441811952), ave_temp = c(6.417815,
                                                                                6.417815, 6.417815, 6.417815, 6.417815, 5.786351)), row.names = c(NA,
                                                                                -6L), groups = structure(list(month = structure(c(8L, 8L), .Label = c("Jan",
                                                                                "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
                                                                                "Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
                                                                                2017), .rows = list(1:5, 6L)), row.names = c(NA, -2L), class = c("tbl_df",
                                                                                "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
                                                                                "tbl_df", "tbl", "data.frame"))
</code>```

from this dataframe I need the month, year, num_unique_tags, and Zone. My next dataframe mapoc_temp looks like this:

```<code>mapoc_temp = structure(list(month = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
2017, 2018, 2016, 2017, 2018), ave = c(6.52922242976571, 5.72051368352674,
5.78635119450037, 6.43544457584707, 5.81728212255571, 5.79052889374
)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), groups = structure(list(month = structure(1:2, .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), .rows = list(
    1:3, 4:6)), row.names = c(NA, -2L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE))
</code>```

from this dataframe I need the ave_temp

To graph the values from both dataframes I am using this code

```<code>#putting 2 y scales on one graph

ggplot(bargraph_dets_temp,
       aes(x = month, y = num_unique_tags)) +
  geom_col(position = position_dodge(),
           aes(fill = as.factor(Zone))) +
  geom_line(inherit.aes = FALSE, data = mapoc_temp,
            aes(x = month, y = ave, group = 2),
            color = "forestgreen", size = 1.5) +
  scale_x_discrete(limits = c("Jan","Feb","Mar","Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) +
  scale_y_continuous(limits = c(0,11), name = "Total Unique Detections",
                     sec.axis = sec_axis(~ . , name = "Average Temp (Celsius)")) +
  scale_fill_manual(name = "Zone",values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
  xlab("Month") +
  facet_wrap(~ year, scales = "free", nrow = 3, strip.position = "top") +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        panel.border = element_blank(),

        axis.line = element_line(),

        axis.line.y.right = element_line(color = "forestgreen"),
        axis.ticks.y.right = element_line(color = "forestgreen"),
        axis.text.y.right = element_text(color = "forestgreen"),
        axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 30)),
        axis.title.y.left = element_text(margin = margin(t = 0, r = 30, b = 0, l = 0)),
        axis.title.x = element_text(margin = margin(t = 40, r = 0, b = 0, l = 0)),

        strip.background =  element_rect(fill = NA, colour = NA),
        strip.text = element_text(size = 25),
        text = element_text(size = 24))
</code>```

This is the image I get

As you can see the temperature data goes straight across. But I want to show the temperature line increasing and decreasing, so I need the second y scale to be finer to show the change in temperature. Is there a way to fix the values of the second y scale so they go from 5-7 instead of 0-9?

答:
The main issue when using sec.axis is to find the appropriate ratio to convert your second dataset and get a nice looking second y axis.

Here, I recreate your dataframe (because they were not enough descriptive for all months and years):

library(lubridate)
Month <- month(seq(ymd("2020-01-01"),ymd("2020-12-31"), by = "month"), label = TRUE)
bargraph <- data.frame(Month = rep(Month,3),
                       year = rep(c(2016,2017,2018),each = 12),
                       tags = sample(1:9,36,replace = TRUE),
                       zone = sample(1:4,36, replace = TRUE))

mapoc <- data.frame(Month = rep(Month,3),
                    year = rep(c(2016,2017,2018),each = 12),
                    ave = rnorm(36, mean = 6, sd = 0.5))
```

<p>Basically, it seems that your bargraph dataset contains values ranging from 0 to 11 (it's your first scale you passed in the <code>scale_y_continuous</code>). Your temperature dataset has values that seems to have  a mean around 6 and a standard deviation of 0.5 (based on the example you provided). So, basically you want your second y-axis to be ranging from 4 to 7 ich. </p>

<p>Here, a good ratio that I found was *3-11 (multiply by the interval of the second axis 7-4 and substract the interval of the first axis 11-0):</p>

<pre class="lang-r prettyprint-override"><code>library(ggplot2)
ggplot(bargraph, aes(x = Month, y = tags))+
  geom_col(position = position_dodge(), aes(fill = as.factor(zone)))+
  geom_line(inherit.aes = FALSE, data = mapoc,
            aes(x = Month, y = ave*3-11, group = 2),
            color = "forestgreen", size = 1.5) +
  facet_wrap(~ year, scales = "free", nrow = 3, strip.position = "top")+
  scale_y_continuous(limits = c(0,11), name = "Total Unique Detections",
                     sec.axis = sec_axis(~(.+11)/3 , name = "Average Temp (Celsius)"))
</code>```

And you get:

So, it is not perfect but it allow you to have a better representation of your second y axis.

Does it answer your question ?

NB: In your question, you can't obtain the graph you are showing with the code you are posting because you used nrow = 3 in your facet_wrap, so you should have obtained a similar graph to the one I'm posting.

Body:
I'm trying to get a graph with 2 y scales using 2 different dataframes. The first dataframe bargraph_dets_temp looks like this

bargraph_dets_temp = structure(list(Zone = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
                                                                             "2", "3", "4"), class = "factor"), month = structure(c(8L, 8L,
                                                                                8L, 8L, 8L, 8L), .Label = c("Jan", "Feb", "Mar", "Apr", "May",
                                                                                "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2016, 2016, 2016, 2016, 2016, 2017), location = c("HFX001",
                                                                                "HFX002", "HFX003", "KETCH HARBOUR, NS", "NSTR001", "Gill Cove"
                                                                                ), num_unique_tags = c(5, 4, 2, 5, 5, 6), total_res_time_in_seconds = c(10666,
                                                                                14645, 6799, 0, 58959, 0), latitude = c(44.47846, 44.47222, 44.46643,
                                                                                44.48427, 44.48422, 44.48467), longitude = c(-63.53341, -63.52704,
                                                                                -63.51983, -63.53338, -63.53246, -63.53316), geometry = structure(list(
                                                                                structure(c(-63.53341, 44.47846), class = c("XY", "POINT",
                                                                                "sfg")), structure(c(-63.52704, 44.47222), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.51983, 44.46643), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53338, 44.48427), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53246, 44.48422), class = c("XY",
                                                                                "POINT", "sfg")), structure(c(-63.53316, 44.48467), class = c("XY",
                                                                                "POINT", "sfg"))), class = c("sfc_POINT", "sfc"), precision = 0, bbox = structure(c(xmin = -63.53341,
                                                                                ymin = 44.46643, xmax = -63.51983, ymax = 44.48467), class = "bbox"), crs = structure(list(
                                                                                epsg = 4326L, proj4string = "+proj=longlat +datum=WGS84 +no_defs"), class = "crs"), n_empty = 0L),
                      distances = c(27.3573801954343, 26.4992220821035, 25.6385699365414,
                                    27.8643036652756, 27.8152639871898, 27.8888441811952), ave_temp = c(6.417815,
                                                                                6.417815, 6.417815, 6.417815, 6.417815, 5.786351)), row.names = c(NA,
                                                                                -6L), groups = structure(list(month = structure(c(8L, 8L), .Label = c("Jan",
                                                                                "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
                                                                                "Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
                                                                                2017), .rows = list(1:5, 6L)), row.names = c(NA, -2L), class = c("tbl_df",
                                                                                "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
                                                                                "tbl_df", "tbl", "data.frame"))

from this dataframe I need the month, year, num_unique_tags, and Zone. My next dataframe mapoc_temp looks like this:

mapoc_temp = structure(list(month = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), year = c(2016,
2017, 2018, 2016, 2017, 2018), ave = c(6.52922242976571, 5.72051368352674,
5.78635119450037, 6.43544457584707, 5.81728212255571, 5.79052889374
)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), groups = structure(list(month = structure(1:2, .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"), class = c("ordered", "factor")), .rows = list(
    1:3, 4:6)), row.names = c(NA, -2L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE))

from this dataframe I need the ave_temp

To graph the values from both dataframes I am using this code

#putting 2 y scales on one graph

ggplot(bargraph_dets_temp,
       aes(x = month, y = num_unique_tags)) +
  geom_col(position = position_dodge(),
           aes(fill = as.factor(Zone))) +
  geom_line(inherit.aes = FALSE, data = mapoc_temp,
            aes(x = month, y = ave, group = 2),
            color = "forestgreen", size = 1.5) +
  scale_x_discrete(limits = c("Jan","Feb","Mar","Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) +
  scale_y_continuous(limits = c(0,11), name = "Total Unique Detections",
                     sec.axis = sec_axis(~ . , name = "Average Temp (Celsius)")) +
  scale_fill_manual(name = "Zone",values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
  xlab("Month") +
  facet_wrap(~ year, scales = "free", nrow = 3, strip.position = "top") +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        panel.border = element_blank(),

        axis.line = element_line(),

        axis.line.y.right = element_line(color = "forestgreen"),
        axis.ticks.y.right = element_line(color = "forestgreen"),
        axis.text.y.right = element_text(color = "forestgreen"),
        axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 30)),
        axis.title.y.left = element_text(margin = margin(t = 0, r = 30, b = 0, l = 0)),
        axis.title.x = element_text(margin = margin(t = 40, r = 0, b = 0, l = 0)),

        strip.background =  element_rect(fill = NA, colour = NA),
        strip.text = element_text(size = 25),
        text = element_text(size = 24))

This is the image I get

As you can see the temperature data goes straight across. But I want to show the temperature line increasing and decreasing, so I need the second y scale to be finer to show the change in temperature. Is there a way to fix the values of the second y scale so they go from 5-7 instead of 0-9?

Body:
The main issue when using sec.axis is to find the appropriate ratio to convert your second dataset and get a nice looking second y axis.

Here, I recreate your dataframe (because they were not enough descriptive for all months and years):

library(lubridate)
Month <- month(seq(ymd("2020-01-01"),ymd("2020-12-31"), by = "month"), label = TRUE)
bargraph <- data.frame(Month = rep(Month,3),
                       year = rep(c(2016,2017,2018),each = 12),
                       tags = sample(1:9,36,replace = TRUE),
                       zone = sample(1:4,36, replace = TRUE))

mapoc <- data.frame(Month = rep(Month,3),
                    year = rep(c(2016,2017,2018),each = 12),
                    ave = rnorm(36, mean = 6, sd = 0.5))

Basically, it seems that your bargraph dataset contains values ranging from 0 to 11 (it's your first scale you passed in the scale_y_continuous). Your temperature dataset has values that seems to have  a mean around 6 and a standard deviation of 0.5 (based on the example you provided). So, basically you want your second y-axis to be ranging from 4 to 7 ich.

Here, a good ratio that I found was *3-11 (multiply by the interval of the second axis 7-4 and substract the interval of the first axis 11-0):

library(ggplot2)
ggplot(bargraph, aes(x = Month, y = tags))+
  geom_col(position = position_dodge(), aes(fill = as.factor(zone)))+
  geom_line(inherit.aes = FALSE, data = mapoc,
            aes(x = Month, y = ave*3-11, group = 2),
            color = "forestgreen", size = 1.5) +
  facet_wrap(~ year, scales = "free", nrow = 3, strip.position = "top")+
  scale_y_continuous(limits = c(0,11), name = "Total Unique Detections",
                     sec.axis = sec_axis(~(.+11)/3 , name = "Average Temp (Celsius)"))

And you get:

So, it is not perfect but it allow you to have a better representation of your second y axis.

Does it answer your question ?

NB: In your question, you can't obtain the graph you are showing with the code you are posting because you used nrow = 3 in your facet_wrap, so you should have obtained a similar graph to the one I'm posting.


来源: stackexchange

问:
Display elements on second level relationship in Nova Laravel using indexQuery
I've 3 models

User has a hasmany relation (domains()) with Domain and this hasMany relation (mailboxes) with Mailbox

User.php

```<code>public function domains()
{
    return $this->hasMany(Domain::class);
}
</code>```

Domain.php

```<code>public function user()
{
    return $this->belongsTo(User::class);
}

public function mailboxes()
{
    return $this->hasMany(Mailbox::class, 'domain', 'domain');
}
</code>```

Mailbox.php

```<code>public function domains()
{
    return $this->belongsTo('App\Domain', 'domain', 'domain');
}
</code>```

Code below work fine for get only mailboxes owned but if put in policies not work.

```<code>public function view(User $user, Mailbox $mailbox)
{
    $domains = Domain::where('user_id', $user->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

}
</code>```

I tried overrinding indexQuery on my Nova/Mailbox model, but not work. Retunr all mailboxes on database

```<code>public static function indexQuery(NovaRequest $request, $query)
{

    $domains = Domain::where('user_id', $request->user()->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

    if ($request->user()->is_super_admin) {
        return $query;
    } else {
        return User::with([
            'domains.mailboxes' => function ($builder) use ($domains) {
                $builder->where('domain',$domains);
            }
        ])->find($user);
    }
}
</code>```

答:
I would add a hasManyThrough (documentation) relationship between User and Mailbox so you can pluck the mailboxes directly from the User model:

# Inside User model class
public function mailboxes()
{
    return $this->hasManyThrough(Mailbox::class, Domain::class, 'user_id', 'domain', 'id', 'domain');
}
```

<p>Then in your indexQuery you could return the user with all its mailboxes:</p>

<pre class="lang-php prettyprint-override"><code>public static function indexQuery(NovaRequest $request, $query)
{
    return $query->when(! $request->user()->is_super_admin, function ($builder) use ($request) {
        // Or use the request() method helper instead of use
        return $request->user()->with('mailboxes');
    });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've 3 models

User has a hasmany relation (domains()) with Domain and this hasMany relation (mailboxes) with Mailbox

User.php

public function domains()
{
    return $this->hasMany(Domain::class);
}

Domain.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function mailboxes()
{
    return $this->hasMany(Mailbox::class, 'domain', 'domain');
}

Mailbox.php

public function domains()
{
    return $this->belongsTo('App\Domain', 'domain', 'domain');
}

Code below work fine for get only mailboxes owned but if put in policies not work.

public function view(User $user, Mailbox $mailbox)
{
    $domains = Domain::where('user_id', $user->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

}

I tried overrinding indexQuery on my Nova/Mailbox model, but not work. Retunr all mailboxes on database

public static function indexQuery(NovaRequest $request, $query)
{

    $domains = Domain::where('user_id', $request->user()->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

    if ($request->user()->is_super_admin) {
        return $query;
    } else {
        return User::with([
            'domains.mailboxes' => function ($builder) use ($domains) {
                $builder->where('domain',$domains);
            }
        ])->find($user);
    }
}

Body:
I would add a hasManyThrough (documentation) relationship between User and Mailbox so you can pluck the mailboxes directly from the User model:

# Inside User model class
public function mailboxes()
{
    return $this->hasManyThrough(Mailbox::class, Domain::class, 'user_id', 'domain', 'id', 'domain');
}

Then in your indexQuery you could return the user with all its mailboxes:

public static function indexQuery(NovaRequest $request, $query)
{
    return $query->when(! $request->user()->is_super_admin, function ($builder) use ($request) {
        // Or use the request() method helper instead of use
        return $request->user()->with('mailboxes');
    });
}


问:
how to convert numbers to million in javascript
As in image. for some values converting correctly but some of values not converting... you can see in image

I want to convert numbers to million.I am using Money format function to convert numbers but i am unable to convert numbers.

This is controller part.for some numbers it is converting to millions and for some numbers it is not converting.. Please someone help.

```<code> $scope.MoneyFormat = function (labelValue)
                    {
                          // Nine Zeroes for Billions
                          return Math.abs(Number(labelValue)) >= 1.0e+9

                               ? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
                               // Six Zeroes for Millions
                               : Math.abs(Number(labelValue)) >= 1.0e+6

                               ? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
                               // Three Zeroes for Thousands
                               : Math.abs(Number(labelValue)) >= 1.0e+3

                               ? Math.abs(Number(labelValue)) / 1.0e+3 + "K"

                               : Math.abs(Number(labelValue));
                   }
</code>```

Here I am converting numbers by using Moneyformat. This is controller part where I am converting numbers

```<code>            $scope.rep.won = $scope.MoneyFormat($scope.rep.won);
            $scope.outlook.rem = $scope.MoneyFormat($scope.outlook.rem);
            $scope.rep.expectedAmount = $scope.MoneyFormat($scope.rep.expectedAmount);
            $scope.rep.potential = $scope.MoneyFormat($scope.rep.potential);
            $scope.rep.quota = $scope.MoneyFormat($scope.rep.quota);
</code>```

答:
Because of how far javascript number goes they can only go up to 1e301
This function shows the number in a 3 digit along with a letter, for example 30000000000000000 would be 30,0 Quadrillion and 1000000 would be 1,00 Million.

function simpleNumber(costOfIt, visualOfIt) {
    var visualOfIt = costOfIt.toString();

    var visualLeng = 6;
    var maxLeng = 4;
    var letterArrayIndex = 0;

    var letterArray = [" Thousand", " Million", " Billion", " Trillion", " Quadrillion", " Quintillion", " Sextillion", " Septillion", " Octillion", " Nonillion", " Decillion", " Undecillion", " Duodecillion", " Tredecillion", " Quatuordecillion", " Quindecillion", " Sexdecillion", " Septendecillion", " Octodecillion", " Novemdecillion", " Vigintillion", " Unvigintillion", " Duovigintillion", " Tresvigintillion", " Quatuorvigintillion", " Quinquavigintillion", " Sesvigintillion", " Septemvigintillion", " Octovigintillion", " Novemvigintillion", " Trigintillion", " Untrigintillion", " Duotrigintillion", " Trestrigintillion", " Quatuortrigintillion", " Quinquatrigintillion", " Sestrigintillion", " Septentrigintillion", " Octotrigintillion", " Novemtrigintillion", " Quadragintillion", " Unquadragintillion", " Duoquadragintillion", " Tresquadragintillion", " Quatuorquadragintillion", " Quinquaquadragintillion", " Sesquadragintillion", " Septemquadragintillion", " Octoquadragintillion", " Novemquadragintillion", " Quinquagintillion", " Unquinquagintillion", " Duoquinquagintillion", " Tresquinquagintillion", " Quatuorquinquagintillion", " Quinquaquinquagintillion", " Sesquinquagintillion", " Septenquinquagintillion", " Octoquinquagintillion", " Novemquinquagintillion", " Sexagintillion", " Unsexagintillion", " Duosexagintillion", " Tressexagintillion", " Quatuorsexagintillion", " Quinquasexagintillion", " Sexasexagintillion", " Septemsexagintillion", " Octosexagintillion", " Novemsexagintillion", " Septuagintillion", " Unseptuagintillion", " Duoseptuagintillion", " Tresseptuagintillion", " Quatuorseptuagintillion", " Quinquaseptuagintillion", " Sexaseptuagintillion", " Septenseptuagintillion", " Octoseptuagintillion", " Novemseptuagintillion", " Octogintillion", " Unoctogintillion", " Duooctogintillion", " Tresoctogintillion", " Quatuoroctogintillion", " Quinquaoctogintillion", " Sesoctogintillion", " Septemoctogintillion", " Octooctogintillion", " Novemoctogintillion", " Nonagintillion", " Unnonagintillion", " Duononagintillion", " Tresnonagintillion", " Quatuornonagintillion", " Quinquanonagintillion", " Sesnonagintillion", " Septemnonagintillion", " Octononagintillion", " Novemnonagintillion", " Centillion", " Uncentillion"];

    var leng = 4;
    var slic = 1;

    for (var g = 0; g < visualOfIt.length; g++) {
        if (visualOfIt.length <= visualLeng) {
            if (leng < maxLeng) {
                leng = maxLeng;
            }

            if (visualOfIt.length === leng) {
                if (slic > 2) {
                    visualOfIt = costOfIt.toString().slice(0, slic) + letterArray[letterArrayIndex];
                    break;
                } else {
                    visualOfIt = costOfIt.toString().slice(0, slic) + "," + costOfIt.toString().slice(slic, 3) + letterArray[letterArrayIndex];
                    break;
                }
            } else {
                leng++;
                slic++;
            }
        } else {
            maxLeng += 3;
            visualLeng += 3;
            letterArrayIndex++;
        }
    }

    return visualOfIt;
}
```

Just use console.log(simpleNumber(1435345, 0)) outside of the function then it would return 1,43 Million

ContentLicense: CC BY-SA 3.0

Body:
As in image. for some values converting correctly but some of values not converting... you can see in image

I want to convert numbers to million.I am using Money format function to convert numbers but i am unable to convert numbers.

This is controller part.for some numbers it is converting to millions and for some numbers it is not converting.. Please someone help.

 $scope.MoneyFormat = function (labelValue)
                    {
                          // Nine Zeroes for Billions
                          return Math.abs(Number(labelValue)) >= 1.0e+9

                               ? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
                               // Six Zeroes for Millions
                               : Math.abs(Number(labelValue)) >= 1.0e+6

                               ? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
                               // Three Zeroes for Thousands
                               : Math.abs(Number(labelValue)) >= 1.0e+3

                               ? Math.abs(Number(labelValue)) / 1.0e+3 + "K"

                               : Math.abs(Number(labelValue));
                   }

Here I am converting numbers by using Moneyformat. This is controller part where I am converting numbers

            $scope.rep.won = $scope.MoneyFormat($scope.rep.won);
            $scope.outlook.rem = $scope.MoneyFormat($scope.outlook.rem);
            $scope.rep.expectedAmount = $scope.MoneyFormat($scope.rep.expectedAmount);
            $scope.rep.potential = $scope.MoneyFormat($scope.rep.potential);
            $scope.rep.quota = $scope.MoneyFormat($scope.rep.quota);

Body:
Because of how far javascript number goes they can only go up to 1e301
This function shows the number in a 3 digit along with a letter, for example 30000000000000000 would be 30,0 Quadrillion and 1000000 would be 1,00 Million.

function simpleNumber(costOfIt, visualOfIt) {
    var visualOfIt = costOfIt.toString();

    var visualLeng = 6;
    var maxLeng = 4;
    var letterArrayIndex = 0;

    var letterArray = [" Thousand", " Million", " Billion", " Trillion", " Quadrillion", " Quintillion", " Sextillion", " Septillion", " Octillion", " Nonillion", " Decillion", " Undecillion", " Duodecillion", " Tredecillion", " Quatuordecillion", " Quindecillion", " Sexdecillion", " Septendecillion", " Octodecillion", " Novemdecillion", " Vigintillion", " Unvigintillion", " Duovigintillion", " Tresvigintillion", " Quatuorvigintillion", " Quinquavigintillion", " Sesvigintillion", " Septemvigintillion", " Octovigintillion", " Novemvigintillion", " Trigintillion", " Untrigintillion", " Duotrigintillion", " Trestrigintillion", " Quatuortrigintillion", " Quinquatrigintillion", " Sestrigintillion", " Septentrigintillion", " Octotrigintillion", " Novemtrigintillion", " Quadragintillion", " Unquadragintillion", " Duoquadragintillion", " Tresquadragintillion", " Quatuorquadragintillion", " Quinquaquadragintillion", " Sesquadragintillion", " Septemquadragintillion", " Octoquadragintillion", " Novemquadragintillion", " Quinquagintillion", " Unquinquagintillion", " Duoquinquagintillion", " Tresquinquagintillion", " Quatuorquinquagintillion", " Quinquaquinquagintillion", " Sesquinquagintillion", " Septenquinquagintillion", " Octoquinquagintillion", " Novemquinquagintillion", " Sexagintillion", " Unsexagintillion", " Duosexagintillion", " Tressexagintillion", " Quatuorsexagintillion", " Quinquasexagintillion", " Sexasexagintillion", " Septemsexagintillion", " Octosexagintillion", " Novemsexagintillion", " Septuagintillion", " Unseptuagintillion", " Duoseptuagintillion", " Tresseptuagintillion", " Quatuorseptuagintillion", " Quinquaseptuagintillion", " Sexaseptuagintillion", " Septenseptuagintillion", " Octoseptuagintillion", " Novemseptuagintillion", " Octogintillion", " Unoctogintillion", " Duooctogintillion", " Tresoctogintillion", " Quatuoroctogintillion", " Quinquaoctogintillion", " Sesoctogintillion", " Septemoctogintillion", " Octooctogintillion", " Novemoctogintillion", " Nonagintillion", " Unnonagintillion", " Duononagintillion", " Tresnonagintillion", " Quatuornonagintillion", " Quinquanonagintillion", " Sesnonagintillion", " Septemnonagintillion", " Octononagintillion", " Novemnonagintillion", " Centillion", " Uncentillion"];

    var leng = 4;
    var slic = 1;

    for (var g = 0; g < visualOfIt.length; g++) {
        if (visualOfIt.length <= visualLeng) {
            if (leng < maxLeng) {
                leng = maxLeng;
            }

            if (visualOfIt.length === leng) {
                if (slic > 2) {
                    visualOfIt = costOfIt.toString().slice(0, slic) + letterArray[letterArrayIndex];
                    break;
                } else {
                    visualOfIt = costOfIt.toString().slice(0, slic) + "," + costOfIt.toString().slice(slic, 3) + letterArray[letterArrayIndex];
                    break;
                }
            } else {
                leng++;
                slic++;
            }
        } else {
            maxLeng += 3;
            visualLeng += 3;
            letterArrayIndex++;
        }
    }

    return visualOfIt;
}

Just use console.log(simpleNumber(1435345, 0)) outside of the function then it would return 1,43 Million


问:
PowerShell analysing variables and objects
I found that I do .GetType() and | Get-Member a lot, and sometimes I forget that it's .GetType and I try .Get-Type duh! error!), so I've been writing a function to try and gather that info quickly. This has proven to be quite useful when working on the console (I make sure to put the core command before each output so that I never forget the connection to real commands, so more of a techy summary to keep me connected to the language).

I'm curious if there are additional compound commands to extract useful generic information that we could use to report on the structure of a given object (things that we can quickly obtain in a nicely compact summary format even though more complex commands are required for some useful insight about given objects)?

• $a = @(1,2,"x") ; obj $a. This returns 71 Methods (System.String and System.Int32) Types, so I've removed duplicates down to 50 (good to quickly see what is usable but maybe good to somehow also mention the different Types that are contained in that array?).

• Some input will break the function of course, but even a ScriptBlock example like this also works fine obj {$a; $x}. You can even do things like obj "".GetType() to see the Methods and properties in there.

• The use of .Module in the GetType() might be redundant as usually outputs CommonLanguageRuntimeLibrary, but maybe other useful information from these members (everything is useful at different times of course, but I'm curious for generic summary output)?

• In general any improvements or other compound commands that you use or could be useful to crack open object information in a quick summary view would be great to know? :-)

Updated with -Force that @Clint suggested:

```<code>function obj ($cmd) {
    if ($cmd -eq $null) { Write-Host "Object is `$null" ; return }
    Write-Host "Contents:" -F Cyan
    $cmd
    ""
    Write-Host "(`$object).GetType()" -F Cyan -NoNewline ; Write-Host " :: [BaseType|Name|IsPublic|IsSerial|Module]"
    ($cmd).GetType() | % { "$($_.BaseType), $($_.Name), $($_.IsPublic), $($_.IsSerializable), $($_.Module)" }
    ""
    Write-Host "`$object | Get-Member -Force" -F Cyan
    $m = "" ; $p = "" ; $pp = "" ; $np = "" ; $sp = ""
    $msum = 0 ; $psum = 0 ; $ppsum = 0 ; $npsum = 0 ; $spsum = 0
    $($cmd | Get-Member -Force) | % {
        if ($_.MemberType -eq "Method") { if(!($m -like "*$($_.Name),*")) { $m += "$($_.Name), " ; $msum++ } }
        if ($_.MemberType -eq "Property") { if(!($p -like "*$($_.Name),*")) { $p += "$($_.Name), " ; $psum++ } }
        if ($_.MemberType -eq "ParameterizedProperty") { if(!($pp -like "*$($_.Name),*")) { $pp += "$($_.Name), " ; $ppsum++} }
        if ($_.MemberType -eq "NoteProperty") { if(!($np -like "*$($_.Name),*")) { $np += "$($_.Name), " ; $npsum++ } }
        if ($_.MemberType -eq "ScriptProperty") { if(!($sp -like "*$($_.Name),*")) { $sp += "$($_.Name), " ; $npsum++ } }
    }
    if($msum -ne 0) { Write-Host ":: Method [$msum] => $($m.TrimEnd(", "))" }
    if($psum -ne 0) { Write-Host ":: Property [$psum] => $($p.TrimEnd(", "))" }
    if($ppsum -ne 0) { Write-Host ":: ParameterizedProperty [$ppsum] => $($pp.TrimEnd(", "))" }
    if($npsum -ne 0) { Write-Host ":: NoteProperty [$npsum] => $($np.TrimEnd(", "))" }
    if($spsum -ne 0) { Write-Host ":: ScriptProperty [$spsum] => $($sp.TrimEnd(", "))" }
    ""
}
</code>```

An example of output:

```<code>C:\> $a = @(123,"x")
C:\> def $a
Contents:
123
x

($object).GetType() :: [BaseType|Name|IsPublic|IsSerial|Module]
array, Object[], True, True, CommonLanguageRuntimeLibrary

$object | Get-Member -Force
:: Method [50] => CompareTo, Equals, GetHashCode, GetType, GetTypeCode, ToBoolean, ToByte, ToChar, ToDateTime, ToDecimal, ToDouble, ToInt16,
ToInt32, ToInt64, ToSByte, ToSingle, ToString, ToType, ToUInt16, ToUInt32, ToUInt64, Clone, Contains, CopyTo, EndsWith, GetEnumerator,
get_Chars, get_Length, IndexOf, IndexOfAny, Insert, IsNormalized, LastIndexOf, LastIndexOfAny, Normalize, PadLeft, PadRight, Remove, Replace,
Split, StartsWith, Substring, ToCharArray, ToLower, ToLowerInvariant, ToUpper, ToUpperInvariant, Trim, TrimEnd, TrimStart
:: Property [1] => Length
:: ParameterizedProperty [1] => Chars
</code>```

答:
Knowing that PowerShell isn't very clear in displaying an object (as e.g.: '', $Null, @() and @{$Null) all result in an empty line, or nothing at all), I think you need start with the first paragraph of you question and visualize the types and the structure of your objects in question and later concern with the methods which might differ on every
level in the object structure.

*note: you might also reveal the types by using .PSTypeNames, which doesn't error on a $Null (presuming that strict mode isn't switch on).

Taken a little bit more advanced example: $a = @($Null, 1, '2', @(3))

Write-Host

The Write-Host cmdlet (used by your function) doesn't reveal much where is concerns types and the structure of the object:
(Besides you should try to avoid Write-Host as it is Host specific)

```<code>PS C:\> $a
1
2
3

PS C:\> Write-Host $a
 1 2 3
</code>```

To better understand such an object, you might want to serializes it.
Quote from WikiPedia:

In computer science, in the context of data storage, serialization (or
  serialisation) is the process of translating data structures or object
  state into a format that can be stored (for example, in a file or
  memory buffer) or transmitted (for example, across a network
  connection link) and reconstructed later (possibly in a different
  computer environment)

This means that the string representation of the object basically contains all the information to rebuild (and to understand) the object (or at least to a certain level).

There are a few serializers that might come at hand here:

ConvertTo-Json

The ConvertTo-Json cmdlet converts any object to a string in JavaScript Object Notation (JSON) format a therefore might be handy to get an idea of the structure but not for the PowerShell types:

```<code>PS C:\> ConvertTo-Json $a
[
  null,
  1,
  "2",
  [
    3
  ]
]
</code>```

ConvertTo-Xml

The ConvertTo-Xml cmdlet creates an XML-based representation of an object which is pretty verbose:

```<code>PS C:\> ConvertTo-Xml $a -as String
<?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object Type="System.Object[]">
    <Property />
    <Property Type="System.Int32">1</Property>
    <Property Type="System.String">2</Property>
    <Property Type="System.Object[]">
      <Property Type="System.Int32">3</Property>
    </Property>
  </Object>
</Objects>**strong text**
</code>```

PSSerializer

This (.Net) class provides public functionality for serializing a PSObject and is internally used by PowerShell:

```<code>PS C:\> [System.Management.Automation.PSSerializer]::Serialize($a)
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Object[]</T>
      <T>System.Array</T>
      <T>System.Object</T>
    </TN>
    <LST>
      <Nil />
      <Obj RefId="1">
        <I32>1</I32>
      </Obj>
      <S>2</S>
      <Obj RefId="2">
        <TNRef RefId="0" />
        <LST>
          <I32>3</I32>
        </LST>
      </Obj>
    </LST>
  </Obj>
</Objs>
</code>```

ConvertTo-Expression

The ConvertTo-Expression cmdlet originated from the question: Save hash table in PowerShell object notation (PSON) and gives you a PowerShell representation of the object:

Implicit:

```<code>PS C:\> ConvertTo-Expression $a
$Null,
1,
'2',
(,3)
</code>```

Explicit:

```<code>PS C:\> ConvertTo-Expression $a -Strong
[array](
        $Null,
        [int]1,
        [string]'2',
        [array][int]3
)
</code>```

To explorer .Net classes that are not native to PowerShell:

*note that you might not reconstruct from -Explore expressions

```<code>PS C:\> Get-Service | Select -First 1 | ConvertTo-Expression -Strong -Explore
[System.ServiceProcess.ServiceController]@{
        'UserName' = [string]''
        'Description' = [string]'Runtime for activating conversational agent applications'
        'DelayedAutoStart' = [bool]$False
        'BinaryPathName' = [string]'C:\WINDOWS\system32\svchost.exe -k AarSvcGroup -p'
        'StartupType' = [Microsoft.PowerShell.Commands.ServiceStartupType]3
        'CanPauseAndContinue' = [bool]$False
        'CanShutdown' = [bool]$False
        'CanStop' = [bool]$False
        'DisplayName' = [string]'Agent Activation Runtime_131b90'
        'DependentServices' = [System.ServiceProcess.ServiceController[]]@()
        'MachineName' = [string]'.'
        'ServiceName' = [string]'AarSvc_131b90'
        'ServicesDependedOn' = [System.ServiceProcess.ServiceController[]]@()
        'StartType' = [System.ServiceProcess.ServiceStartMode]3
        'ServiceHandle' = $Null
        'Status' = [System.ServiceProcess.ServiceControllerStatus]1
        'ServiceType' = [System.ServiceProcess.ServiceType]224
        'Site' = $Null
        'Container' = $Null
}
</code>```

To drill down in known (accelerated) PowerShell types:

```<code>PS C:\>Get-Date | Select-Object -Property * | ConvertTo-Expression
Date        : 1963-10-07 12:00:00 AM
DateTime    : Monday, October 7, 1963 10:47:00 PM
Day         : 7
DayOfWeek   : Monday
DayOfYear   : 280
DisplayHint : DateTime
Hour        : 22
Kind        : Local
Millisecond : 0
Minute      : 22
Month       : 1
Second      : 0
Ticks       : 619388596200000000
TimeOfDay   : 22:47:00
Year        : 1963
</code>```

Body:
I found that I do .GetType() and | Get-Member a lot, and sometimes I forget that it's .GetType and I try .Get-Type duh! error!), so I've been writing a function to try and gather that info quickly. This has proven to be quite useful when working on the console (I make sure to put the core command before each output so that I never forget the connection to real commands, so more of a techy summary to keep me connected to the language).

I'm curious if there are additional compound commands to extract useful generic information that we could use to report on the structure of a given object (things that we can quickly obtain in a nicely compact summary format even though more complex commands are required for some useful insight about given objects)?

• $a = @(1,2,"x") ; obj $a. This returns 71 Methods (System.String and System.Int32) Types, so I've removed duplicates down to 50 (good to quickly see what is usable but maybe good to somehow also mention the different Types that are contained in that array?).

• Some input will break the function of course, but even a ScriptBlock example like this also works fine obj {$a; $x}. You can even do things like obj "".GetType() to see the Methods and properties in there.

• The use of .Module in the GetType() might be redundant as usually outputs CommonLanguageRuntimeLibrary, but maybe other useful information from these members (everything is useful at different times of course, but I'm curious for generic summary output)?

• In general any improvements or other compound commands that you use or could be useful to crack open object information in a quick summary view would be great to know? :-)

Updated with -Force that @Clint suggested:

function obj ($cmd) {
    if ($cmd -eq $null) { Write-Host "Object is `$null" ; return }
    Write-Host "Contents:" -F Cyan
    $cmd
    ""
    Write-Host "(`$object).GetType()" -F Cyan -NoNewline ; Write-Host " :: [BaseType|Name|IsPublic|IsSerial|Module]"
    ($cmd).GetType() | % { "$($_.BaseType), $($_.Name), $($_.IsPublic), $($_.IsSerializable), $($_.Module)" }
    ""
    Write-Host "`$object | Get-Member -Force" -F Cyan
    $m = "" ; $p = "" ; $pp = "" ; $np = "" ; $sp = ""
    $msum = 0 ; $psum = 0 ; $ppsum = 0 ; $npsum = 0 ; $spsum = 0
    $($cmd | Get-Member -Force) | % {
        if ($_.MemberType -eq "Method") { if(!($m -like "*$($_.Name),*")) { $m += "$($_.Name), " ; $msum++ } }
        if ($_.MemberType -eq "Property") { if(!($p -like "*$($_.Name),*")) { $p += "$($_.Name), " ; $psum++ } }
        if ($_.MemberType -eq "ParameterizedProperty") { if(!($pp -like "*$($_.Name),*")) { $pp += "$($_.Name), " ; $ppsum++} }
        if ($_.MemberType -eq "NoteProperty") { if(!($np -like "*$($_.Name),*")) { $np += "$($_.Name), " ; $npsum++ } }
        if ($_.MemberType -eq "ScriptProperty") { if(!($sp -like "*$($_.Name),*")) { $sp += "$($_.Name), " ; $npsum++ } }
    }
    if($msum -ne 0) { Write-Host ":: Method [$msum] => $($m.TrimEnd(", "))" }
    if($psum -ne 0) { Write-Host ":: Property [$psum] => $($p.TrimEnd(", "))" }
    if($ppsum -ne 0) { Write-Host ":: ParameterizedProperty [$ppsum] => $($pp.TrimEnd(", "))" }
    if($npsum -ne 0) { Write-Host ":: NoteProperty [$npsum] => $($np.TrimEnd(", "))" }
    if($spsum -ne 0) { Write-Host ":: ScriptProperty [$spsum] => $($sp.TrimEnd(", "))" }
    ""
}

An example of output:

C:\> $a = @(123,"x")
C:\> def $a
Contents:
123
x

($object).GetType() :: [BaseType|Name|IsPublic|IsSerial|Module]
array, Object[], True, True, CommonLanguageRuntimeLibrary

$object | Get-Member -Force
:: Method [50] => CompareTo, Equals, GetHashCode, GetType, GetTypeCode, ToBoolean, ToByte, ToChar, ToDateTime, ToDecimal, ToDouble, ToInt16,
ToInt32, ToInt64, ToSByte, ToSingle, ToString, ToType, ToUInt16, ToUInt32, ToUInt64, Clone, Contains, CopyTo, EndsWith, GetEnumerator,
get_Chars, get_Length, IndexOf, IndexOfAny, Insert, IsNormalized, LastIndexOf, LastIndexOfAny, Normalize, PadLeft, PadRight, Remove, Replace,
Split, StartsWith, Substring, ToCharArray, ToLower, ToLowerInvariant, ToUpper, ToUpperInvariant, Trim, TrimEnd, TrimStart
:: Property [1] => Length
:: ParameterizedProperty [1] => Chars

Body:
Knowing that PowerShell isn't very clear in displaying an object (as e.g.: '', $Null, @() and @{$Null) all result in an empty line, or nothing at all), I think you need start with the first paragraph of you question and visualize the types and the structure of your objects in question and later concern with the methods which might differ on every
level in the object structure.

*note: you might also reveal the types by using .PSTypeNames, which doesn't error on a $Null (presuming that strict mode isn't switch on).

Taken a little bit more advanced example: $a = @($Null, 1, '2', @(3))

Write-Host

The Write-Host cmdlet (used by your function) doesn't reveal much where is concerns types and the structure of the object:
(Besides you should try to avoid Write-Host as it is Host specific)

PS C:\> $a
1
2
3

PS C:\> Write-Host $a
 1 2 3

To better understand such an object, you might want to serializes it.
Quote from WikiPedia:

In computer science, in the context of data storage, serialization (or
  serialisation) is the process of translating data structures or object
  state into a format that can be stored (for example, in a file or
  memory buffer) or transmitted (for example, across a network
  connection link) and reconstructed later (possibly in a different
  computer environment)

This means that the string representation of the object basically contains all the information to rebuild (and to understand) the object (or at least to a certain level).

There are a few serializers that might come at hand here:

ConvertTo-Json

The ConvertTo-Json cmdlet converts any object to a string in JavaScript Object Notation (JSON) format a therefore might be handy to get an idea of the structure but not for the PowerShell types:

PS C:\> ConvertTo-Json $a
[
  null,
  1,
  "2",
  [
    3
  ]
]

ConvertTo-Xml

The ConvertTo-Xml cmdlet creates an XML-based representation of an object which is pretty verbose:

PS C:\> ConvertTo-Xml $a -as String
<?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object Type="System.Object[]">
    <Property />
    <Property Type="System.Int32">1</Property>
    <Property Type="System.String">2</Property>
    <Property Type="System.Object[]">
      <Property Type="System.Int32">3</Property>
    </Property>
  </Object>
</Objects>**strong text**

PSSerializer

This (.Net) class provides public functionality for serializing a PSObject and is internally used by PowerShell:

PS C:\> [System.Management.Automation.PSSerializer]::Serialize($a)
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Object[]</T>
      <T>System.Array</T>
      <T>System.Object</T>
    </TN>
    <LST>
      <Nil />
      <Obj RefId="1">
        <I32>1</I32>
      </Obj>
      <S>2</S>
      <Obj RefId="2">
        <TNRef RefId="0" />
        <LST>
          <I32>3</I32>
        </LST>
      </Obj>
    </LST>
  </Obj>
</Objs>

ConvertTo-Expression

The ConvertTo-Expression cmdlet originated from the question: Save hash table in PowerShell object notation (PSON) and gives you a PowerShell representation of the object:

Implicit:

PS C:\> ConvertTo-Expression $a
$Null,
1,
'2',
(,3)

Explicit:

PS C:\> ConvertTo-Expression $a -Strong
[array](
        $Null,
        [int]1,
        [string]'2',
        [array][int]3
)

To explorer .Net classes that are not native to PowerShell:

*note that you might not reconstruct from -Explore expressions

PS C:\> Get-Service | Select -First 1 | ConvertTo-Expression -Strong -Explore
[System.ServiceProcess.ServiceController]@{
        'UserName' = [string]''
        'Description' = [string]'Runtime for activating conversational agent applications'
        'DelayedAutoStart' = [bool]$False
        'BinaryPathName' = [string]'C:\WINDOWS\system32\svchost.exe -k AarSvcGroup -p'
        'StartupType' = [Microsoft.PowerShell.Commands.ServiceStartupType]3
        'CanPauseAndContinue' = [bool]$False
        'CanShutdown' = [bool]$False
        'CanStop' = [bool]$False
        'DisplayName' = [string]'Agent Activation Runtime_131b90'
        'DependentServices' = [System.ServiceProcess.ServiceController[]]@()
        'MachineName' = [string]'.'
        'ServiceName' = [string]'AarSvc_131b90'
        'ServicesDependedOn' = [System.ServiceProcess.ServiceController[]]@()
        'StartType' = [System.ServiceProcess.ServiceStartMode]3
        'ServiceHandle' = $Null
        'Status' = [System.ServiceProcess.ServiceControllerStatus]1
        'ServiceType' = [System.ServiceProcess.ServiceType]224
        'Site' = $Null
        'Container' = $Null
}

To drill down in known (accelerated) PowerShell types:

PS C:\>Get-Date | Select-Object -Property * | ConvertTo-Expression
Date        : 1963-10-07 12:00:00 AM
DateTime    : Monday, October 7, 1963 10:47:00 PM
Day         : 7
DayOfWeek   : Monday
DayOfYear   : 280
DisplayHint : DateTime
Hour        : 22
Kind        : Local
Millisecond : 0
Minute      : 22
Month       : 1
Second      : 0
Ticks       : 619388596200000000
TimeOfDay   : 22:47:00
Year        : 1963


问:
TypeError: Cannot set property 'Id' of "Null"
When I run the code it does work in browser but the error keeps appearing.
Here is my code:

```<code><div id="dashboardJob">
  <script>
     var i = 0;
     do {
        document.getElementById("dashboardJob").id = "dashboardJob" + i;
        i++;
     }
     while (i < 40)
  </script>
</div>
</code>```

Is anyone able to point out what i'm missing here?

Cheers

答:
You need to put
```

The reason it is not working is, that once browser sees an opening script tag, it starts to execute the code, but at that time, the DIV has yet not been closed, this why you get error .

EDIT

Your code will not work. I am not sure, what are you trying to accomplish, but if the loop runs for the first time, you change it's ID attribute, then the second iteration will fail, since there will not be DIV with ID id="dashboardJob", but with id="dashboardJob-1"

Body:
When I run the code it does work in browser but the error keeps appearing.
Here is my code:

Is anyone able to point out what i'm missing here?

Cheers

Body:
You need to put <script> tag below the DIV

<div id="dashboardJob">

</div>
<script>
     var i = 0;
     do {
        document.getElementById("dashboardJob").id = "dashboardJob" + i;
        i++;
     }
     while (i < 40)
 </script>

The reason it is not working is, that once browser sees an opening script tag, it starts to execute the code, but at that time, the DIV has yet not been closed, this why you get error .

EDIT

Your code will not work. I am not sure, what are you trying to accomplish, but if the loop runs for the first time, you change it's ID attribute, then the second iteration will fail, since there will not be DIV with ID id="dashboardJob", but with id="dashboardJob-1"


问:
regex to match content not containing multiple sentences including line breaks
I'm trying to match content that does not include three separate sentences including line breaks.

```<code>one sentence
another one
last one
</code>```

I tried this:

^((?!this sentence|another one|last one).)*$

which works but only along a single line, how can I make it match across multiple line breaks? It should match something like this:

```<code>None of the sentences
are included in this
paragraph, so it should
match the whole content
</code>```

答:
You could match all the lines that do not start with any of the options using a negative lookahead.

```<code>^(?:(?!this sentence|another one|last one).*\r?\n)*(?!this sentence|another one|last one).*
</code>```

^ Start of string

(?: Non capture group

(?!this sentence|another one|last one) Assert non of the options

.*\r?\n

)* Close group and match 0+ times

(?!this sentence|another one|last one) Assert non of the options

.* Match any char 0+ times

regex demo

Body:
I'm trying to match content that does not include three separate sentences including line breaks.

one sentence
another one
last one

I tried this:

^((?!this sentence|another one|last one).)*$

which works but only along a single line, how can I make it match across multiple line breaks? It should match something like this:

None of the sentences
are included in this
paragraph, so it should
match the whole content

Body:
You could match all the lines that do not start with any of the options using a negative lookahead.

^(?:(?!this sentence|another one|last one).*\r?\n)*(?!this sentence|another one|last one).*

^ Start of string

(?: Non capture group

(?!this sentence|another one|last one) Assert non of the options

.*\r?\n

)* Close group and match 0+ times

(?!this sentence|another one|last one) Assert non of the options

.* Match any char 0+ times

regex demo


问:
Capture opening but not the closing tag
I want to segment a parent block, while capturing nested tags along each segment's text:

```<code>(?<tag>.)(?: href="(?<url>.+?)")?>(?<text>.+?)<
</code>```

it works, but I want the "tag" to be empty in segments that aren't wrapped in a tag, however with the current reg., these capture the preceding segment's closing tag...:(

Live sample: https://regex101.com/r/UEZAaw/3/

The result set I would like to obtain, note that item 2 and 4 should have null for the tag:

```<code>{
   "0":{
      match: "p>The <",
      tag: "p",
      url: null,
      text: "The "
   },
   "1":[
      match: "a href=\"https://www.legislation.gov.uk/ukpga/2010/23/contents\">UK Bribery Act<",
      tag: "a",
      url: "https://www.legislation.gov.uk/ukpga/2010/23/contents",
      text: "UK Bribery Act"
   ],
   "2":[
      match: "/a> (“the Act”) received Royal Assent in April 2010 and came into ... <",
      tag: null
      url: null,
      text: " (“the Act”) received Royal Assent in April 2010 and came into ... "
   ],
   "3":[
      match: "a href=\"http://www.oecd.org/daf/anti-bribery/ConvCombatBribery_ENG.pdf\">OECD anti-bribery Convention<",
      tag: "a",
      url: "http://www.oecd.org/daf/anti-bribery/ConvCombatBribery_ENG.pdf",
      text: "OECD anti-bribery Convention"
   ],
   "4":[
      match: "/a>. The Act outlined four prime offences, including the introduction ... <",
      tag: null,
      url: null,
      text: ". The Act outlined four prime offences, including the introduction ... "
   ],
   "5":[
      match: "b>rest is history<",
      tag: "b",
      url: null,
      text: "rest is history"
   ]
   ...
}
</code>```

Spent a few good hours, haven't figured it out, would really appreciate your suggestions.

答:
I think this works, based on what I see in the MATCH INFORMATION box on regex101:

```<code>/(?:(?<tag>(?<!\/).)|(?:\/.))(?: href="(?<url>.+?)")?>(?<text>.+?)</gm
</code>```

Title: Capture opening but not the closing tag

Body:
I want to segment a parent block, while capturing nested tags along each segment's text:

(?<tag>.)(?: href="(?<url>.+?)")?>(?<text>.+?)<

it works, but I want the "tag" to be empty in segments that aren't wrapped in a tag, however with the current reg., these capture the preceding segment's closing tag...:(

Live sample: https://regex101.com/r/UEZAaw/3/

The result set I would like to obtain, note that item 2 and 4 should have null for the tag:

{
   "0":{
      match: "p>The <",
      tag: "p",
      url: null,
      text: "The "
   },
   "1":[
      match: "a href=\"https://www.legislation.gov.uk/ukpga/2010/23/contents\">UK Bribery Act<",
      tag: "a",
      url: "https://www.legislation.gov.uk/ukpga/2010/23/contents",
      text: "UK Bribery Act"
   ],
   "2":[
      match: "/a> (“the Act”) received Royal Assent in April 2010 and came into ... <",
      tag: null
      url: null,
      text: " (“the Act”) received Royal Assent in April 2010 and came into ... "
   ],
   "3":[
      match: "a href=\"http://www.oecd.org/daf/anti-bribery/ConvCombatBribery_ENG.pdf\">OECD anti-bribery Convention<",
      tag: "a",
      url: "http://www.oecd.org/daf/anti-bribery/ConvCombatBribery_ENG.pdf",
      text: "OECD anti-bribery Convention"
   ],
   "4":[
      match: "/a>. The Act outlined four prime offences, including the introduction ... <",
      tag: null,
      url: null,
      text: ". The Act outlined four prime offences, including the introduction ... "
   ],
   "5":[
      match: "b>rest is history<",
      tag: "b",
      url: null,
      text: "rest is history"
   ]
   ...
}

Spent a few good hours, haven't figured it out, would really appreciate your suggestions.

Body:
I think this works, based on what I see in the MATCH INFORMATION box on regex101:

/(?:(?<tag>(?<!\/).)|(?:\/.))(?: href="(?<url>.+?)")?>(?<text>.+?)</gm


问:
Prolog, building list with conditional clauses
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

```<code>goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).
</code>```

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

答:
you can use the if structure:

```<code><condition> -> (do_something) ; (do_something else)
</code>```

in this case:

```<code>goal(Stuff):-
  do_something(X),
  if_something(Y)-> do_this(Y) ; true,
  always_do_this(Z).
</code>```

or you simply write two clauses like:

```<code>goal(Stuff):-
  do_something(X),
  conditional_stuff(Y),
  always_do_this(Z).

conditional_stuff(Y):-
  condition(Y),
  do_this(Y).

conditional_stuff(_).
</code>```

Body:
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

Body:
you can use the if structure:

<condition> -> (do_something) ; (do_something else)

in this case:

goal(Stuff):-
  do_something(X),
  if_something(Y)-> do_this(Y) ; true,
  always_do_this(Z).

or you simply write two clauses like:

goal(Stuff):-
  do_something(X),
  conditional_stuff(Y),
  always_do_this(Z).

conditional_stuff(Y):-
  condition(Y),
  do_this(Y).

conditional_stuff(_).


问:
How to fetch count from distant relationship in laravel way?
I am trying to fetch all the attributes with product count that is associated with products in the given category.

table structure

attributes table:

```<code>| id  | name | value | filterable |
</code>```

products table:

```<code>| id  | name |
</code>```

categories table:

```<code>| id  | name |
</code>```

attribute_product pivot table:

```<code>| id  | attribute_id | product_id
</code>```

category_product pivot table:

```<code>| id  | category_id | product_id
</code>```

Below is how my models look like.

Attribute

public function products(){
        return $this->belongsToMany('App\Models\Product');
    }
```

<p>Product</p>

<pre class="lang-php prettyprint-override"><code>public function attributes(){
        return $this->belongsToMany('App\Models\Attribute');
    }

public function categories(){
        return $this->belongsToMany('App\Models\Category');
    }
</code>```

Category

public function products(){
        return $this->belongsToMany('App\Models\Product');
    }
```

<p>I can get all the attributes associated with a product in the given category with the below query.</p>

<pre class="lang-php prettyprint-override"><code>
Attribute::where('filterable', '=', 1)
->whereHas('products.categories', function (Builder $query) use ($category) {

$query->where('category_product.category_id', '=', $category->id);

})->get();
</code>```

However, I cannot figure out how I should get product counts.

I started testing query builder to achieve this but condition on where pivot seems to be binding attribute_product.attribute_id as a string value instead of the column value.

$data = DB::table('attributes')->where('filterable', '=', true)
->whereExists(function ($query) {
$query->select('*')->from('products')
->join('attribute_product', function ($join){
    $join->on('products.id', '=', 'attribute_product.product_id');
})->where('attributes.id', '=', 'attribute_product.attribute_id');

})->get();
```

<p>Below is more or less the final SQL query I need to send to the database</p>

<pre class="lang-sql prettyprint-override"><code>select `attributes`.*,
(SELECT
count(*) from `products`
inner join `attribute_product` on `products`.`id` = `attribute_product`.`product_id`
where `attributes`.`id` = `attribute_product`.`attribute_id`) as `products_count`
from `attributes` where `filterable` = 1
and EXISTS
(select * from `products` inner join `attribute_product` on `products`.`id` = `attribute_product`.`product_id`
where `attributes`.`id` = `attribute_product`.`attribute_id`
and EXISTS
(select * from `categories` inner join `category_product` on `categories`.`id` = `category_product`.`category_id`
where `products`.`id` = `category_product`.`product_id` and `category_product`.`category_id` = 9))
</code>```

Please, someone, assist me in getting attributes with associated product count in the laravel way.

答:
I managed to get all my results in a single request with the below query. Thanks! @athul for showing the direction.

Attribute::where('filterable', '=', 1)->whereHas('products.categories', function (Builder $query) use($category) {
                    $query->where('categories.id', '=', $category->id);
                })
                ->withCount(['products' => function ($query) use($category) {
                    $query->whereHas('categories', function (Builder $query) use ($category) {
                        $query->where('categories.id', '=', $category->id);
                  });
           }])->get();
```

Body:
I am trying to fetch all the attributes with product count that is associated with products in the given category.

table structure

attributes table:

| id  | name | value | filterable |

products table:

| id  | name |

categories table:

| id  | name |

attribute_product pivot table:

| id  | attribute_id | product_id

category_product pivot table:

| id  | category_id | product_id

Below is how my models look like.

Attribute

public function products(){
        return $this->belongsToMany('App\Models\Product');
    }

Product

public function attributes(){
        return $this->belongsToMany('App\Models\Attribute');
    }

public function categories(){
        return $this->belongsToMany('App\Models\Category');
    }

Category

public function products(){
        return $this->belongsToMany('App\Models\Product');
    }

I can get all the attributes associated with a product in the given category with the below query.

Attribute::where('filterable', '=', 1)
->whereHas('products.categories', function (Builder $query) use ($category) {

$query->where('category_product.category_id', '=', $category->id);

})->get();

However, I cannot figure out how I should get product counts.

I started testing query builder to achieve this but condition on where pivot seems to be binding attribute_product.attribute_id as a string value instead of the column value.

$data = DB::table('attributes')->where('filterable', '=', true)
->whereExists(function ($query) {
$query->select('*')->from('products')
->join('attribute_product', function ($join){
    $join->on('products.id', '=', 'attribute_product.product_id');
})->where('attributes.id', '=', 'attribute_product.attribute_id');

})->get();

Below is more or less the final SQL query I need to send to the database

select `attributes`.*,
(SELECT
count(*) from `products`
inner join `attribute_product` on `products`.`id` = `attribute_product`.`product_id`
where `attributes`.`id` = `attribute_product`.`attribute_id`) as `products_count`
from `attributes` where `filterable` = 1
and EXISTS
(select * from `products` inner join `attribute_product` on `products`.`id` = `attribute_product`.`product_id`
where `attributes`.`id` = `attribute_product`.`attribute_id`
and EXISTS
(select * from `categories` inner join `category_product` on `categories`.`id` = `category_product`.`category_id`
where `products`.`id` = `category_product`.`product_id` and `category_product`.`category_id` = 9))

Please, someone, assist me in getting attributes with associated product count in the laravel way.


问:
Angular 6 Search bar and Result two different non-related components
I have two components
1. Header Component
2. Result Component
In the header, I have a search bar with a button on click of that I want the result to populate on the result page.

Second problem is once I am the result page if I enter the search value in the header component search it should not reload the page

Both header and result components are not related so I can use @input or output correct me if there a way for me to pass value?

main.component.html

```<code>  <app-header *ngIf="auth.isLoggednIn()"></app-header>
  <router-outlet></router-outlet>
  <app-footer></app-footer>
</div>
</code>```

Header.component.html

```<code>    <div class="container">
      <ul>
        <li routerLinkActive="active"><a routerLink="/statupdate">Status Update</a></li>
        <li routerLinkActive="active"><a routerLink="/add">Add New</a></li>
        <li routerLinkActive="active"><a routerLink="/projects">Opportunity</a></li>
      </ul>
      <form class="form-inline" [formGroup]="searchForm" (ngSubmit)="onSubmit()">
        <input class="form-control mr-sm-2" type="search" placeholder="ClientName" aria-label="Search"
          formControlName="searchText">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
      </form>
    </div>
  </div>
</code>```

Header.component.ts

```<code>    this.router.navigate(['search'], {
      queryParams: {
        search: this.searchForm.value.searchText,
      }
    });
  }
</code>```

I have all my result from the search box to display on the result page so i am using router to navigate.
Result component.ts

```<code>constructor(private route: ActivatedRoute,public projectService: ProjectService) { }

    ngOnInit() {

        this.projectService.list(this.route.snapshot.queryParamMap.get('search')).subscribe(
          (resp) => {
            this.list = resp;
          },(err) => {
            console.log(err);
          }
        )
    }
</code>```

Is it possible to populate to data without reloading the page? I am not able to find an example of this

Update I have written the BehaviorSubject service to resolve this issue

```<code>private messageSource = new BehaviorSubject(<any>[]);
  currentMessage = this.messageSource.asObservable();

  constructor(public httpClient: HttpService) { }

  changeMessage(message) {

    this.httpClient.get('project?clientName=' + message)
      .subscribe(
        (resp) => {
          this.messageSource.next(resp);
        }
      )
  }
</code>```

but wanted to known if i can improve this coding somewhat like this if possible

```<code>changeMessage(message) {

    let temp = this.httpClient.get('project?clientName=' + message)
     this.messageSource.next(temp);
  }
</code>```

my Result.component.ts

```<code>ngOnInit() {
    this.searchService.currentMessage.subscribe(
      (message) => { console.log(message); this.message = message }, (err) => { console.log(err) })
  }
</code>```

答:
Unrelated Components: Sharing Data with a Service

When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should you a shared service. When you have data that should aways been in sync, I find the RxJS BehaviorSubject very useful in this situation.

You can also use a regular RxJS Subject for sharing data via the service, but here’s why I prefer a BehaviorSubject.

It will always return the current value on subscription - there is no need to
call onnext

It has a getValue() function to extract the last value as raw data.

It ensures that the component always receives the most recent data.

In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable handle this data stream as an observable that will be used by the components. Lastly, we create function that calls next on the BehaviorSubject to change its value.

The parent, child, and sibling components all receive the same treatment. We inject the DataService in the constructor, then subscribe to the currentMessage observable and set its value equal to the message variable.

Now if we create a function in any one of these components that changes the value of the message. when this function is executed the new data it’s automatically broadcast to all other components.

data.service.ts
------------------------

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

one.component.ts
-----------------------------

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `,
  styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

two.component.ts
--------------------------------------------
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("Hello from Sibling")
  }

}```

Body:
I have two components
1. Header Component
2. Result Component
In the header, I have a search bar with a button on click of that I want the result to populate on the result page.

Second problem is once I am the result page if I enter the search value in the header component search it should not reload the page

Both header and result components are not related so I can use @input or output correct me if there a way for me to pass value?

main.component.html

  <app-header *ngIf="auth.isLoggednIn()"></app-header>
  <router-outlet></router-outlet>
  <app-footer></app-footer>

Header.component.html

Status Update

Add New

Opportunity

      <form class="form-inline" [formGroup]="searchForm" (ngSubmit)="onSubmit()">
        <input class="form-control mr-sm-2" type="search" placeholder="ClientName" aria-label="Search"
          formControlName="searchText">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
      </form>

Header.component.ts

    this.router.navigate(['search'], {
      queryParams: {
        search: this.searchForm.value.searchText,
      }
    });
  }

I have all my result from the search box to display on the result page so i am using router to navigate.
Result component.ts

constructor(private route: ActivatedRoute,public projectService: ProjectService) { }

    ngOnInit() {

        this.projectService.list(this.route.snapshot.queryParamMap.get('search')).subscribe(
          (resp) => {
            this.list = resp;
          },(err) => {
            console.log(err);
          }
        )
    }

Is it possible to populate to data without reloading the page? I am not able to find an example of this

Update I have written the BehaviorSubject service to resolve this issue

private messageSource = new BehaviorSubject(<any>[]);
  currentMessage = this.messageSource.asObservable();

  constructor(public httpClient: HttpService) { }

  changeMessage(message) {

    this.httpClient.get('project?clientName=' + message)
      .subscribe(
        (resp) => {
          this.messageSource.next(resp);
        }
      )
  }

but wanted to known if i can improve this coding somewhat like this if possible

changeMessage(message) {

    let temp = this.httpClient.get('project?clientName=' + message)
     this.messageSource.next(temp);
  }

my Result.component.ts

ngOnInit() {
    this.searchService.currentMessage.subscribe(
      (message) => { console.log(message); this.message = message }, (err) => { console.log(err) })
  }


问:
Create a distinct List<String>
I have three lists of List<String> type, named as list1, list2, and list3.

I add some items into list1 then copy them to a new list which is list2. Then I create the list3 to add some more items then copy them again to list2. However, I need list2 to contain distinct items, so how would I exclude the duplicate items and avoid adding them into list2?

This is what I have tried out:

List<String> list2 = new ArrayList<>();
List<String> list1 = new ArrayList<>();

                list1.add("String1");
                list1.add("String2");

                list2.addAll(list1);

List<String> list3 = new ArrayList<>();

list3.add("String1");
list3.add("String3");

list2.addAll(list3);
```

答:
Below I show an example of what you are expecting. Before adding list3 elements to list2, we will filter out all the elements from list2 that are also present in list3.

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

public class Main {
    public static void main(String args[]) {
        ArrayList<String> list1 = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        ArrayList<String> list3 = new ArrayList<>();

        list1.add("string1");
        list1.add("string2");
        list1.add("string4");

        list2.addAll(list1);

        System.out.println("\nPrinting List2 Elements");
        for(String element : list2){
            System.out.println(element);
        }

        list3.add("string3");
        //these will be the duplicates that we will find in list2,
        //before adding list3, we will remove them from list 2
        list3.add("string2");
        list3.add("string1");

        //filtering out list3 elements from list2
        System.out.println("\nPrinting List3 Elements");

        for(String element : list3){
            System.out.println(element);
            int indexOfElement = list2.indexOf(element);
            if(indexOfElement != -1) //means it has found the element in the list
            {
                list2.remove(indexOfElement);
            }
        }

        //Now list2 doesn't contain any element that exists in list3
        System.out.println("\nPrinting List2 Elements after filtering");
        for(String element : list2){
            System.out.println(element);
        }

        list2.addAll(list3);

        System.out.println("\nPrinting List2 Elements");
        for(String element : list2){
            System.out.println(element);
        }
    }
}
</code>```

Here is an example of the output with the source code link

Title: Create a distinct List<String>

Body:
Below I show an example of what you are expecting. Before adding list3 elements to list2, we will filter out all the elements from list2 that are also present in list3.

import java.util.*;

public class Main {
    public static void main(String args[]) {
        ArrayList<String> list1 = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        ArrayList<String> list3 = new ArrayList<>();

        list1.add("string1");
        list1.add("string2");
        list1.add("string4");

        list2.addAll(list1);

        System.out.println("\nPrinting List2 Elements");
        for(String element : list2){
            System.out.println(element);
        }

        list3.add("string3");
        //these will be the duplicates that we will find in list2,
        //before adding list3, we will remove them from list 2
        list3.add("string2");
        list3.add("string1");

        //filtering out list3 elements from list2
        System.out.println("\nPrinting List3 Elements");

        for(String element : list3){
            System.out.println(element);
            int indexOfElement = list2.indexOf(element);
            if(indexOfElement != -1) //means it has found the element in the list
            {
                list2.remove(indexOfElement);
            }
        }

        //Now list2 doesn't contain any element that exists in list3
        System.out.println("\nPrinting List2 Elements after filtering");
        for(String element : list2){
            System.out.println(element);
        }

        list2.addAll(list3);

        System.out.println("\nPrinting List2 Elements");
        for(String element : list2){
            System.out.println(element);
        }
    }
}

Here is an example of the output with the source code link


问:
Move position of text in ggplot
Hopefully a pretty simply problem to solve - I have produced the boxplot pictured using the following code

```<code>ggplot(minanalysis, aes(x=MinAnaType, y=Calcium)) +
  geom_boxplot() +
  geom_point(aes(colour=Ploidy)) +
  stat_summary(fun.y=mean, colour="black", geom="point", size=2,show.legend = FALSE) +
  geom_text(data = means, vjust = -0.25, hjust=-0.3, size = 3, aes(label = round(Calcium, 2),
                                                   y = Calcium + 0.08)) +
  #add a sample size n =
  geom_text(data = minanalysis %>% group_by(MinAnaType) %>%
          summarize(Count = n(),
          Calcium=max(Calcium) + 0.05 * diff(range(minanalysis$Calcium))),
          aes(label = paste0("n = ", Count)),
          position = position_dodge(0.85), size=3, show.legend = FALSE) +
  # Add pairwise comparisons p-value and global p-value
  stat_compare_means(comparisons = my_comparisons, label = "p.signif", label.y = 9500, size = 4) +
  stat_compare_means(label.y = 10500, size = 4)
</code>```

What I want is for the "n=290" and n=50" to be located underneath x axis labels 'Eviscerated' and 'WholeBody'. Having them above the boxplots themselves is too messy. Could somebody help with the code for this, I'm new to R studio.

Thanks

答:
The easiest is probably to add a linebreak to your x labels. You can then add your count, either hardcoded, or programmatically.
(This would be within scale_x_...(labels = ...))

E.g.

library(tidyverse)

ggplot(filter(iris, Species %in% c('setosa','virginica')), aes(Species, Sepal.Length)) +
  geom_boxplot() +
  scale_x_discrete(labels = c(setosa = paste('setosa', '\nn = 30'),
                              virginica = paste('virginica', '\nn = 30')))
```

Title: Move position of text in ggplot

Body:
Hopefully a pretty simply problem to solve - I have produced the boxplot pictured using the following code

ggplot(minanalysis, aes(x=MinAnaType, y=Calcium)) +
  geom_boxplot() +
  geom_point(aes(colour=Ploidy)) +
  stat_summary(fun.y=mean, colour="black", geom="point", size=2,show.legend = FALSE) +
  geom_text(data = means, vjust = -0.25, hjust=-0.3, size = 3, aes(label = round(Calcium, 2),
                                                   y = Calcium + 0.08)) +
  #add a sample size n =
  geom_text(data = minanalysis %>% group_by(MinAnaType) %>%
          summarize(Count = n(),
          Calcium=max(Calcium) + 0.05 * diff(range(minanalysis$Calcium))),
          aes(label = paste0("n = ", Count)),
          position = position_dodge(0.85), size=3, show.legend = FALSE) +
  # Add pairwise comparisons p-value and global p-value
  stat_compare_means(comparisons = my_comparisons, label = "p.signif", label.y = 9500, size = 4) +
  stat_compare_means(label.y = 10500, size = 4)

What I want is for the "n=290" and n=50" to be located underneath x axis labels 'Eviscerated' and 'WholeBody'. Having them above the boxplots themselves is too messy. Could somebody help with the code for this, I'm new to R studio.

Thanks


问:
Flutter Screen from routes is loading before Localization
I'm adding flutter to an existing app.

I localized my app, as described here, and as I will display any flutter screen from legacy code, I decided to use named routes, as described here, but after using it, I realized that localization was loaded after I tried to render screen, so the _localizedValues was null.

When using hot reload (so localization was already loaded), it would display correctly, but when using hot restart, it gives the error because localizations was not loaded yet.

Any solution for this?

Thanks!

答:
NVM, it seems the way I was doing was not working, but I discovered another way that works.</p>

```<code>Intent intent = new Intent(context, FlutterMainActivity.class).putExtra("route", "/your-route");
startActivity(intent);
</code>```

Body:
NVM, it seems the way I was doing was not working, but I discovered another way that works.

Intent intent = new Intent(context, FlutterMainActivity.class).putExtra("route", "/your-route");
startActivity(intent);


问:
Naming convention for Web Apps added via the Add to Home Screen on iOS or Android?
I am developing a Web App with Rails which I am then adding via the Add to Home Screen option (and testing in Simulator via Xcode).

What we call such apps in my workplace is (Home Screen App Mode) 'HSAM' (in what we see as the absence of any naming convention for this particular scenario).

What I essentially want to know is, is there a naming convention to describe Web Apps built to such an end?

Possibilities I have found include:

- 'Shortcut'

 - 'Non-native'

 - 'Homescreen'

 - 'Add to Home Screen'

None of the above keywords seem to pinpoint results of what I am looking for when I am attempting to debug issues specific to this format.

Is there a naming convention? If so, what is the accepted term for these specific apps?

答:
According to MDN, A2HS (which at the time of writing only gives 94 results on StackOverflow

Add to Home screen (or A2HS for short)

It is referred to as A2HS for the rest of the linked page.


问:
Python "split" function on repeated characters
I have gone through many threads on Stackoverflow about using Split function on strings, but still am unclear about the following output:

```<code>"aaaaa".split("a")
output: ['', '', '', '', '', '']

"baaaaa".split("a")
output: ['b', '', '', '', '', '']
</code>```

Can someone please explain how repeated characters are treated by "split" function?

答:
The empty strings are not due to the fact that you have repeated characters but that in your string you have only the delimiter (the string by which you are splitting the target string). The output of str.split doesn't include the delimiter.

From the docs:

```<code>str.split(sep=None, maxsplit=-1)
</code>```

[...]

If sep is given, consecutive delimiters are not grouped together and
  are deemed to delimit empty strings (for example, '1,,2'.split(',')
  returns ['1', '', '2']). The sep argument may consist of multiple
  characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns
  [''].

Other way to see it:

Separate your string by the delimiter; you will get:

```<code>"aaaaa" --> ['a', 'a', 'a', 'a', 'a']
</code>```

Exclude the delimiter from your strings and you will get:

```<code>['', '', '', '', '']
</code>```

In this manner, you will get your output similar to your second string.

Body:
I have gone through many threads on Stackoverflow about using Split function on strings, but still am unclear about the following output:

"aaaaa".split("a")
output: ['', '', '', '', '', '']

"baaaaa".split("a")
output: ['b', '', '', '', '', '']

Can someone please explain how repeated characters are treated by "split" function?

Body:
The empty strings are not due to the fact that you have repeated characters but that in your string you have only the delimiter (the string by which you are splitting the target string). The output of str.split doesn't include the delimiter.

From the docs:

str.split(sep=None, maxsplit=-1)

[...]

If sep is given, consecutive delimiters are not grouped together and
  are deemed to delimit empty strings (for example, '1,,2'.split(',')
  returns ['1', '', '2']). The sep argument may consist of multiple
  characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns
  [''].

Other way to see it:

Separate your string by the delimiter; you will get:

"aaaaa" --> ['a', 'a', 'a', 'a', 'a']

Exclude the delimiter from your strings and you will get:

['', '', '', '', '']

In this manner, you will get your output similar to your second string.


问:
push hash onto array in perl, result defies understanding
Why does this..

```<code>my @menu;

my %el1 = ("element1" => "hello");
push @menu, \%el1;

my %el2 = ("element2" => "world");
push @menu, \%el2;

print to_json({"menu", @menu});
</code>```

produce this..

```<code>{
    "menu": {
        "element1": "hello"
    },
    "HASH(0x18e2280)": null
}
</code>```

and not this..

```<code>{
    "menu": {
        "element1": "hello",
        "element2": "world"
    }
}
</code>```

答:
If you pass a reference to the array, the results are cleaner:

```<code>print to_json({"menu", \@menu});
</code>```

Body:
Why does this..

my @menu;

my %el1 = ("element1" => "hello");
push @menu, \%el1;

my %el2 = ("element2" => "world");
push @menu, \%el2;

print to_json({"menu", @menu});

produce this..

{
    "menu": {
        "element1": "hello"
    },
    "HASH(0x18e2280)": null
}

and not this..

{
    "menu": {
        "element1": "hello",
        "element2": "world"
    }
}

Body:
If you pass a reference to the array, the results are cleaner:

print to_json({"menu", \@menu});


问:
DriverManager cant be found, underlines red and prompts me to create class DriverManager
```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
    //define the fields
    String username = "root";
    String password = "Otiwah0771";
    String jdbcURL = "jdbc:mysql://localhost:3306/employeedirectory";
    String driver = "com.mysql.jdbc.Driver";

    try
    {

    //Get the Print Writer object
    PrintWriter out = response.getWriter();
    out.println("Connecting to databace"+jdbcURL);

    //load the Driver
    Class.forName(driver);

    //Get the connection
    Connection connection = DriverManager.getConnection(jdbcURL,username,password);

    //Close the connection
    connection.close();
    }catch(Exception e)
    {
        e.printStackTrace();
    }
}
</code>```

** Using Netbeans 11.2 **

I have added mysql connector jar and yet the issue persists (DriverManager symbol cant be found)

答:
The issue is jdbc-api-1.4.jar is not part of the libraries and therefore cannot import java.sql.Driver.class. download jdbc-api-1.4.jar fromjdbc api
- add it to the libraries and it works</p>

Body:
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
    //define the fields
    String username = "root";
    String password = "Otiwah0771";
    String jdbcURL = "jdbc:mysql://localhost:3306/employeedirectory";
    String driver = "com.mysql.jdbc.Driver";

    try
    {

    //Get the Print Writer object
    PrintWriter out = response.getWriter();
    out.println("Connecting to databace"+jdbcURL);

    //load the Driver
    Class.forName(driver);

    //Get the connection
    Connection connection = DriverManager.getConnection(jdbcURL,username,password);

    //Close the connection
    connection.close();
    }catch(Exception e)
    {
        e.printStackTrace();
    }
}

** Using Netbeans 11.2 **

I have added mysql connector jar and yet the issue persists (DriverManager symbol cant be found)


问:
SQL join return results if where clause does not match
I’m trying to return values from a join where the where clause might  not have a matches.

Here’s my database schema

```<code>strings
-------
id: INT
name: VARCHAR
value: VARCHAR
fileId: INT FOREIGN KEY files(id)

languages
---------
id: INT
code: CHAR
name: VARCHAR

translations
------------
id: INT
string_id: INT, FOREIGN KEY strings(id)
language_id: INT, FOREIGN KEY languages(id)
translation: VARCHAR
</code>```

I’m trying to select all the strings, and all the translations in a given language. The translations may or may not exist for a given language, but I want to return the strings any way.

I’m using a query similar to:

```<code>SELECT s.id, s.name, s.value, t.translation
FROM strings s LEFT OUTER JOIN translations t ON s.id = t.string_id
WHERE s.file_id = $1 AND t.language_id = $2
</code>```

I want to return strings regardless of whether matches are found in the translations table. If translations don’t exist for a given language, that field would of course be null. I think the problem is with the WHERE clause having the t.language_id = ..., since language_id doesn't exist in this particular case. But not sure the best way to fix this.

Database Postgresql

答:
Conditions on the second table need to go in the ON clause:

```<code>SELECT s.id, s.name, s.value, t.translation
FROM strings s LEFT OUTER JOIN
     translations t
     ON s.id = t.string_id AND t.language_id = $2
WHERE s.file_id = $1;
</code>```

Otherwise, t.language_id is NULL and that fails the comparison in the WHERE clause.

Body:
I’m trying to return values from a join where the where clause might  not have a matches.

Here’s my database schema

strings
-------
id: INT
name: VARCHAR
value: VARCHAR
fileId: INT FOREIGN KEY files(id)

languages
---------
id: INT
code: CHAR
name: VARCHAR

translations
------------
id: INT
string_id: INT, FOREIGN KEY strings(id)
language_id: INT, FOREIGN KEY languages(id)
translation: VARCHAR

I’m trying to select all the strings, and all the translations in a given language. The translations may or may not exist for a given language, but I want to return the strings any way.

I’m using a query similar to:

SELECT s.id, s.name, s.value, t.translation
FROM strings s LEFT OUTER JOIN translations t ON s.id = t.string_id
WHERE s.file_id = $1 AND t.language_id = $2

I want to return strings regardless of whether matches are found in the translations table. If translations don’t exist for a given language, that field would of course be null. I think the problem is with the WHERE clause having the t.language_id = ..., since language_id doesn't exist in this particular case. But not sure the best way to fix this.

Database Postgresql

Body:
Conditions on the second table need to go in the ON clause:

SELECT s.id, s.name, s.value, t.translation
FROM strings s LEFT OUTER JOIN
     translations t
     ON s.id = t.string_id AND t.language_id = $2
WHERE s.file_id = $1;

Otherwise, t.language_id is NULL and that fails the comparison in the WHERE clause.


问:
Reference 'django.contrib.auth.urls' to custom specific templates
I wrote specific templates to deal with password reset and change,

the file tree structures as:

```<code>In [3]: !tree /Users/me/desktop/Django/forum/user/templates
/Users/me/desktop/Django/forum/user/templates
├── registration
│   ├── logged_out.html
│   ├── login.html
│   ├── password_change_done.html
│   ├── password_reset_complete.html
│   ├── password_reset_confirm.html
│   ├── password_reset_done.html
│   └── password_reset_form.html
└── user
    ├── activate.html
    ├── failure.html
    ├── register.html
    ├── success.html
    └── validate.html
</code>```

The project urls is configured as:

```<code># Project url
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r"^$", views.index, name="index"),
    url(r'^article/', include('article.urls',namespace='article')),
    url(r'^user/', include('user.urls',namespace='user')),
    url(r'^user/', include('django.contrib.auth.urls')),
]
</code>```

Unfortunately, when I try to issue request as http://127.0.0.1:8001/user/password_reset/,

the browser redirect to its default admin site

I am working on Django 1.11

How reference 'django.contrib.auth.urls' to my own templates?

答:
To ref to your template, in case it doesn't work just use template name:

```<code>urlpatterns = [
    path(
        'change-password/',
        auth_views.PasswordChangeView.as_view(template_name='change-password.html'),
    ),
]
</code>```

OR:

Even skip django.contrib.auth.urls if you want to use another directory template not in registration, in this case I point to template /basic_app/

```<code>from django.contrib.auth import views as auth_views
</code>```

AND

```<code>re_path(r'^login/$',auth_views.LoginView.as_view(template_name='basic_app/login.html'),name='login')
</code>```

Body:
I wrote specific templates to deal with password reset and change,

the file tree structures as:

In [3]: !tree /Users/me/desktop/Django/forum/user/templates
/Users/me/desktop/Django/forum/user/templates
├── registration
│   ├── logged_out.html
│   ├── login.html
│   ├── password_change_done.html
│   ├── password_reset_complete.html
│   ├── password_reset_confirm.html
│   ├── password_reset_done.html
│   └── password_reset_form.html
└── user
    ├── activate.html
    ├── failure.html
    ├── register.html
    ├── success.html
    └── validate.html

The project urls is configured as:

# Project url
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r"^$", views.index, name="index"),
    url(r'^article/', include('article.urls',namespace='article')),
    url(r'^user/', include('user.urls',namespace='user')),
    url(r'^user/', include('django.contrib.auth.urls')),
]

Unfortunately, when I try to issue request as http://127.0.0.1:8001/user/password_reset/,

the browser redirect to its default admin site

I am working on Django 1.11

How reference 'django.contrib.auth.urls' to my own templates?

Body:
To ref to your template, in case it doesn't work just use template name:

urlpatterns = [
    path(
        'change-password/',
        auth_views.PasswordChangeView.as_view(template_name='change-password.html'),
    ),
]

OR:

Even skip django.contrib.auth.urls if you want to use another directory template not in registration, in this case I point to template /basic_app/

from django.contrib.auth import views as auth_views

AND

re_path(r'^login/$',auth_views.LoginView.as_view(template_name='basic_app/login.html'),name='login')