问:
WooCommerce shortcode to ajaxify message that display: "You need to spend to get free shipping"
I modified this script to make a shortcode that shows how much the customer need to spend to get free shipping.

 /**
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.9
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_shortcode ('woo_freeshipping_target', 'woo_freeship_target' );

function woo_freeship_target() {
  ob_start();

   $min_amount = 279; //change this to your free shipping threshold

   $current = WC()->cart->subtotal;

   if ( $current < $min_amount ) {
      $added_text = wc_price( $min_amount - $current );
      $notice = sprintf( $added_text );
      echo ' You need to add '.$notice.'';
   }

     else if ( $current >= $min_amount ) {
      echo 'Free Shipping!';
   }

    return ob_get_clean();

}
```

But I cannot figure out how can I make it to auto update when the items quantity is modified. Any idea?

答:
To ajaxify your message so it updates when the subtotal change (via ajax) use the woocommerce_add_to_cart_fragments filter hook

So you get:

function custom_message() {
    // Initialize
    $message = __( 'Default message', 'woocommerce' );

    // True
    if ( WC()->cart ) {
        // Change this to your free shipping threshold
        $min_amount = 279;

        // Get cart subtotal
        $subtotal = WC()->cart->get_subtotal();

        if ( $subtotal < $min_amount ) {
            $message = sprintf( __( 'You need to add %s to get free shipping', 'woocommerce' ), wc_price( $min_amount - $subtotal ) );
        } else {
            $message = __( 'Free shipping', 'woocommerce' );
        }
    }

    return $message;
}

// Refreshing on cart ajax events
function filter_woocommerce_add_to_cart_fragments( $fragments ) {
    $fragments['div.display-message'] = '
' . custom_message() . '
';

    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1 );

// Shortcode
function display_my_message() {
    return '
' . custom_message() . '
';
}
// Register shortcode
add_shortcode( 'display_message', 'display_my_message' );
```

SHORTCODE USAGE

In an existing page:

[display_message]

Or in PHP:

echo do_shortcode("[display_message]");

Related: WooCommerce shortcode to ajaxify message that display: "Buy X more products to get a discount"

Body:
I modified this script to make a shortcode that shows how much the customer need to spend to get free shipping.

 /**
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.9
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_shortcode ('woo_freeshipping_target', 'woo_freeship_target' );

function woo_freeship_target() {
  ob_start();

   $min_amount = 279; //change this to your free shipping threshold

   $current = WC()->cart->subtotal;

   if ( $current < $min_amount ) {
      $added_text = wc_price( $min_amount - $current );
      $notice = sprintf( $added_text );
      echo ' You need to add '.$notice.'';
   }

     else if ( $current >= $min_amount ) {
      echo 'Free Shipping!';
   }

    return ob_get_clean();

}

But I cannot figure out how can I make it to auto update when the items quantity is modified. Any idea?

Body:
To ajaxify your message so it updates when the subtotal change (via ajax) use the woocommerce_add_to_cart_fragments filter hook

So you get:

function custom_message() {
    // Initialize
    $message = __( 'Default message', 'woocommerce' );

    // True
    if ( WC()->cart ) {
        // Change this to your free shipping threshold
        $min_amount = 279;

        // Get cart subtotal
        $subtotal = WC()->cart->get_subtotal();

        if ( $subtotal < $min_amount ) {
            $message = sprintf( __( 'You need to add %s to get free shipping', 'woocommerce' ), wc_price( $min_amount - $subtotal ) );
        } else {
            $message = __( 'Free shipping', 'woocommerce' );
        }
    }

    return $message;
}

// Refreshing on cart ajax events
function filter_woocommerce_add_to_cart_fragments( $fragments ) {
    $fragments['div.display-message'] = '<div class="display-message">' . custom_message() . '</div>';

    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1 );

// Shortcode
function display_my_message() {
    return '<div class="display-message">' . custom_message() . '</div>';
}
// Register shortcode
add_shortcode( 'display_message', 'display_my_message' );

SHORTCODE USAGE

In an existing page:

[display_message]

Or in PHP:

echo do_shortcode("[display_message]");

Related: WooCommerce shortcode to ajaxify message that display: "Buy X more products to get a discount"


来源: stackexchange

问:
Unable to iterate xml and create a dictionary with desired attribute in python
I am pretty new in python and xml. Actually, I am trying to extract two attributes (vehicle-brand, car-definition) values and create a dictionary. I am able to iterate over only one attribute at a time, but my goal is to iterate two attributes together so that I can create a dictionary.

My desired output is {"BMW":"C1","FORD":"C2","TOYOTA":"k1"}

import xml.etree.ElementTree as ET

def cars():
    str1='''\
<?xml version="1.0" encoding="UTF-8"?>
<vehicles xmlns:xsi="https://cars.com" >
  <vehicle>
        <vehicle-brand>BMW</vehicle-brand>
    <cars>
        <car>
            <car-type>MID</car-type>
            <car-definition>C1</car-definition>
        </car>
    </cars>
  </vehicle>
 <vehicle>
    <vehicle-brand>FORD</vehicle-brand>
    <cars>
        <car>
            <car-type>LARGE</car-type>
            <car-definition>C2</car-definition>
        </car>
    </cars>
    </vehicle>
    <vehicle>
            <vehicle-brand>TOYOTA</vehicle-brand>
            <cars>
                <car>
                    <car-type>SMALL</car-type>
                    <car-definition>K1</car-definition>
                </car>
            </cars>
    </vehicle>
</vehicles>'''

    try:
        e = ET.ElementTree(ET.fromstring(str1))
        for elt in e.iter('car-definition'):
        print(elt.tag, elt.text)

    except Exception as e:
       print("error")
       raise e
```

答:
Consider a dict comprehension that iterates across each <car> descendant under each <vehicle>, retrieving element text for key-value pair of dictionary:

xml_dict = {
    veh.find("vehicle-brand").text: car.find("car-definition").text
    for veh in doc.iterfind("vehicle")
    for car in veh.iterfind("cars/car")
}

xml_dict
{'BMW': 'C1', 'FORD': 'C2', 'TOYOTA': 'K1'}
```
<p>Since <code><cars></code> can expand to many multiple per <code><vehicle></code>, nest lists of cars for each distinct vehicle:</p>
<pre class="lang-py prettyprint-override"><code>xml_dict = {
    veh.find("vehicle-brand").text:
        [car.find("car-definition").text
         for car in veh.iterfind("cars/car")]
    for veh in doc.iterfind("vehicle")
}

xml_dict
{'BMW': ['C1'], 'FORD': ['C2'], 'TOYOTA': ['K1']}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider a dict comprehension that iterates across each <car> descendant under each <vehicle>, retrieving element text for key-value pair of dictionary:

xml_dict = {
    veh.find("vehicle-brand").text: car.find("car-definition").text
    for veh in doc.iterfind("vehicle")
    for car in veh.iterfind("cars/car")
}

xml_dict
{'BMW': 'C1', 'FORD': 'C2', 'TOYOTA': 'K1'}

Since <cars> can expand to many multiple per <vehicle>, nest lists of cars for each distinct vehicle:

xml_dict = {
    veh.find("vehicle-brand").text:
        [car.find("car-definition").text
         for car in veh.iterfind("cars/car")]
    for veh in doc.iterfind("vehicle")
}

xml_dict
{'BMW': ['C1'], 'FORD': ['C2'], 'TOYOTA': ['K1']}


问:
How to hide button when another button is clicked in React?
I have 2 buttons displayed on the page Display and Hide. When the Hide button is clicked I want to hide the Display button.

I am using useState. To some extent, I am able to hide Display more text present on the button, but not the whole button

Initial state- https://ibb.co/jMdH3tq

When the Hide button is clicked, Display text disappear but the button stays- https://ibb.co/Jm5FPNy

```<code>const [show, setShow] = useState(false);

const hideButton = () => {
  setShow(true);
};
</code>```

Hide button code:

```<code><div>
  <button
    style={{ marginLeft: '190px' }}
    className="button button1"
    onClick={() => {
      clearBooks();
      hideButton();
    }}
  >
    Hide
  </button>
</div>;
</code>```

Show button code:

```<code><button
  className="button button1"
  style={{ marginLeft: '190px', width: '124px', height: '50px' }}
  onClick={fetchBooks}
>
  {!show && 'Display more'}
</button>;
</code>```

答:
A tidier way of doing this would be to use the ternary operator with your state. Every time your buttons are clicked, they invert the state which changes which button is rendered in the DOM.</p>
```<code>import { useState } from "react";

export default function App() {
  const [show, setShow] = useState(true);

  function changeState() {
    setShow(!show);
  }

  return (
    <div className="App">
      {show ? (
        <button onClick={changeState}> Display </button>
      ) : (
        <button onClick={changeState}> Hide </button>
      )}
    </div>
  );
}
</code>```

Body:
I have 2 buttons displayed on the page Display and Hide. When the Hide button is clicked I want to hide the Display button.

I am using useState. To some extent, I am able to hide Display more text present on the button, but not the whole button

Initial state- https://ibb.co/jMdH3tq

When the Hide button is clicked, Display text disappear but the button stays- https://ibb.co/Jm5FPNy

const [show, setShow] = useState(false);

const hideButton = () => {
  setShow(true);
};

Hide button code:

  <button
    style={{ marginLeft: '190px' }}
    className="button button1"
    onClick={() => {
      clearBooks();
      hideButton();
    }}
  >
    Hide
  </button>

;

Show button code:

<button
  className="button button1"
  style={{ marginLeft: '190px', width: '124px', height: '50px' }}
  onClick={fetchBooks}
>
  {!show && 'Display more'}
</button>;

Body:
A tidier way of doing this would be to use the ternary operator with your state. Every time your buttons are clicked, they invert the state which changes which button is rendered in the DOM.

import { useState } from "react";

export default function App() {
  const [show, setShow] = useState(true);

  function changeState() {
    setShow(!show);
  }

  return (
    <div className="App">
      {show ? (
        <button onClick={changeState}> Display </button>
      ) : (
        <button onClick={changeState}> Hide </button>
      )}
    </div>
  );
}


问:
Flutter: How to make dropdownbutton resize according to what was selected
I'm trying to make a dropdown button resize its width according to either what item was selected in the dropdown or the width of the "hint" text. How can I do this I'm totally lost. The dropdown button is being placed inside of a ListView that is horizontally scrollable.</p>
```<code>class FilterDropdown extends StatelessWidget {
  final Text? hint;
  final String? value;
  final List<DropdownMenuItem<String>>? items;
  final Function(String?)? onChanged;
  final Key? key;
  final IconData? iconData;

  FilterDropdown(
      {this.key,
      this.hint,
      this.value,
      this.items,
      this.onChanged,
      this.iconData});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.white),
          borderRadius: BorderRadius.circular(8.0),
          color: const Color(0xff161F25),
        ),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(21, 0, 21, 0),
          child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
            selectedItemBuilder: (BuildContext context) {
              return items!.map<Widget>((DropdownMenuItem<String> item) {
                Text innerWidget = item.child as Text;
                return Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      innerWidget.data!,
                      style: TextStyle(color: Colors.white),
                    )
                    // style: const TextStyle(color: Colors.white)),
                    );
              }).toList();
            },
            style: const TextStyle(
              color: Colors.black,
              fontSize: 16,
            ),
            key: key,
            hint: Align(
              alignment: Alignment.centerLeft,
              child: hint,
            ),
            value: value,
            icon: const Icon(Icons.arrow_drop_down),
            items: items,
            onChanged: onChanged,
          )),
        ));
  }
}
</code>```

答:
```<code>Expanded(
    child: new Column(
    children: <Widget>[
        new DropdownButton(
            items: [
                new DropdownMenuItem(child: new Text("Abc")),
                new DropdownMenuItem(child: new Text("Xyz")),
            ],
            hint: new Text("Select City"),
            onChanged: null
          )
       ]
    ),
    flex: 1,
)
</code>```

Use Column

Body:
I'm trying to make a dropdown button resize its width according to either what item was selected in the dropdown or the width of the "hint" text. How can I do this I'm totally lost. The dropdown button is being placed inside of a ListView that is horizontally scrollable.

class FilterDropdown extends StatelessWidget {
  final Text? hint;
  final String? value;
  final List<DropdownMenuItem<String>>? items;
  final Function(String?)? onChanged;
  final Key? key;
  final IconData? iconData;

  FilterDropdown(
      {this.key,
      this.hint,
      this.value,
      this.items,
      this.onChanged,
      this.iconData});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.white),
          borderRadius: BorderRadius.circular(8.0),
          color: const Color(0xff161F25),
        ),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(21, 0, 21, 0),
          child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
            selectedItemBuilder: (BuildContext context) {
              return items!.map<Widget>((DropdownMenuItem<String> item) {
                Text innerWidget = item.child as Text;
                return Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      innerWidget.data!,
                      style: TextStyle(color: Colors.white),
                    )
                    // style: const TextStyle(color: Colors.white)),
                    );
              }).toList();
            },
            style: const TextStyle(
              color: Colors.black,
              fontSize: 16,
            ),
            key: key,
            hint: Align(
              alignment: Alignment.centerLeft,
              child: hint,
            ),
            value: value,
            icon: const Icon(Icons.arrow_drop_down),
            items: items,
            onChanged: onChanged,
          )),
        ));
  }
}

Body:
Expanded(
    child: new Column(
    children: <Widget>[
        new DropdownButton(
            items: [
                new DropdownMenuItem(child: new Text("Abc")),
                new DropdownMenuItem(child: new Text("Xyz")),
            ],
            hint: new Text("Select City"),
            onChanged: null
          )
       ]
    ),
    flex: 1,
)

Use Column


问:
R plotly: using scaleanchor and constraintoward leaves white space between plotted data and title
I created a kind of interactive calendar heatmap using the following code. It is quite long but should be reproducible.

```<code>library(plotly)
library(data.table)
library(tidyr)
library(htmlwidgets)
library(widgetframe)

df <- data.frame(dom = sequence(31,1,1),
             Januar= sample(50:500, 31),
             Februar = sample(50:500, 31),
             März =sample(50:500, 31),
             April = sample(50:500, 31),
             Mai = sample(50:500, 31))

df <- as.data.table(df)
df<- melt(df, id.vars= "dom",variable.name="month",value.name="value", na.rm=T)
df<- as.data.frame(df)
df <- df %>% mutate(month= factor(month,levels=as.character(c("Januar","Februar","März","April","Mai")),labels=c("Jan","Feb","Mär","Apr","Mai"),ordered=TRUE))
df$dommapped <- ordered(df$dom, levels = 31:1)
df <- df%>% mutate(group=ceiling(value/(max(value)/5)))
df$group_1<- ifelse(df$group==1,df$group,NA)
df$group_2<- ifelse(df$group==2,df$group,NA)
df$group_3<- ifelse(df$group==3,df$group,NA)
df$group_4<- ifelse(df$group==4,df$group,NA)
df$group_5<- ifelse(df$group==5,df$group,NA)

colorScale1 <- data.frame(z=c(0,1),col=c("#FFE27a","#FFE27a"))
colorScale1$col <- as.character(colorScale1$col)
colorScale2 <- data.frame(z=c(0,1),col=c("#FFCD0e","#FFCD0e"))
colorScale2$col <- as.character(colorScale2$col)
colorScale3 <- data.frame(z=c(0,1),col=c("#A1C863","#A1C863"))
colorScale3$col <- as.character(colorScale3$col)
colorScale4 <- data.frame(z=c(0,1),col=c("#76B82b","#76B82b"))
colorScale4$col <- as.character(colorScale4$col)
colorScale5 <- data.frame(z=c(0,1),col=c("#4A731c","#4A731c"))
colorScale5$col <- as.character(colorScale5$col)

f1=list(family = "Arial, sans-serif",
      size = 12,
      color = "#000000")
f2 <- list(family = "Arial, sans-serif",
      size = 14,
      color = "#000000")

plot<-df%>%
  plot_ly(.,y = ~month, x = ~dommapped, z=~group_1, text=~value,name="group1", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
          hoverongaps=FALSE,colorscale=colorScale1,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_2, text=~value,name="group2", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale2,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_3, text=~value,name="group3", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale3,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_4, text=~value,name="group4",type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale4,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_5, text=~value,name="group5", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale5,showlegend=TRUE, showscale=FALSE)
plot<-plot %>%
  layout(title =list(text= "Very long title about content of graph",
                     xref = "paper",
                     x = 0,
                     font = f2),
         hoverlabel=list(bgcolor="#ffffff",
                         bordercolor ="#ffffff",
                         font=f2),
         showlegend = TRUE,
         separators = ', ',
         plot_bgcolor='#ffffff',
         legend=list(itemclick="toggleothers",
                     orientation="h",
                     title=list(font=f1,
                                text="title"),
                     yanchor="top",
                     y=-0.25),
         modebar = list(color = "#a3a3a3",
                        activecolor = "#000000"),
         xaxis = list(title = "Day of month",
                      zeroline = FALSE,
                      gridcolor = 'ffff',
                      autorange = "reversed",
                      constraintoward="left"),
         yaxis = list(title="month",zeroline = FALSE,gridcolor = 'ffff',autorange = "reversed",
                      scaleanchor="x", constraintoward = "bottom"))

    plot<- plot %>% config(modeBarButtonsToRemove = list('autoScale2d'))
    plot<- plot %>% config(locale='de')
    plot<- plot %>% config(toImageButtonOptions = list(format = "png",filename = "",width = 760,height = 600))
    plot<- plot %>% onRender("function(el, x) {Plotly.d3.select('.cursor-crosshair').style('cursor', 'default')}")
    plot$sizingPolicy$browser$padding <- 0
    htmlwidgets::saveWidget(title = "plot", frameableWidget(plot), "directory/plot_1.html")
</code>```

The scaleanchor and constraintoward commands help to get the design I need. Otherwise the boxes wouldn't be square format.
But it leads - depending on the browser window size - a big white space between graph and title.
Setting the range for the yaxis does not work.
Setting the margin also didn't work so far.

I thought I have to find a solution without scaleanchor and constraintoward to get the needed aspect ratio. So I tried to change the layout by using aspectratio and aspectmode.

```<code>layout(title =list(text= "Very long title about content of graph",
                     xref = "paper",
                     x = 0,
                     font = f2),
         hoverlabel=list(bgcolor="#ffffff",
                         bordercolor ="#ffffff",
                         font=f2),
         showlegend = TRUE,
         separators = ', ',
         plot_bgcolor='#ffffff',
         legend=list(itemclick="toggleothers",
                     orientation="h",
                     title=list(font=f1,
                                text="title"),
                     yanchor="top",
                     y=-0.25),
         modebar = list(color = "#a3a3a3",
                        activecolor = "#000000"),
         xaxis = list(title = "Day of month",
                      zeroline = FALSE,
                      gridcolor = 'ffff',
                      autorange = "reversed"),
         yaxis = list(title="month",zeroline = FALSE,gridcolor = 'ffff',autorange = "reversed"),
         scene=list(aspectmode="manual",
                    aspectratio=list(x=3,
                                     y=1)))

</code>```

But this also didn't work.
I would be happy, if someone has an other idea or solution for this problem.

答:
There isn't intentional whitespace between the plot and title. What is happening is that plotly has anchored the title at the top, and then it uses the available space for everything else.

If you look at it in RStudio, just adjusting the viewer pane will change it to the appearance you are looking for.

View One

View Two

This version uses the exact same code, just a different viewer pane size.

(I added a border so that the whitespace was more evident.)

If you're planning to save the plot, control the size when saving. If you're using R Markdown, control the size with knitr options.

So you are aware:

In your question, you used colorScale multiple times, but that object doesn't exist. I improvised.

You also used objects f1 and f2, but these objects weren't provided, so I commented them out.

Lastly, I added a buffer above the title, so that it wasn't touching the top of the viewer pane using the following code:

```<code>  layout(margin = list(l = 50, r = 50,
                       b = 50, t = 50,
                       pad = 20))
</code>```

To put that into perspective--the margin before I changed it:

```<code>  "layout": {
    "margin": {
      "b": 40,
      "l": 60,
      "t": 25,
      "r": 10
    }
</code>```

If you'd like to explore things like these settings that you never chose, take a look at plotly_json(plot).

Body:
I created a kind of interactive calendar heatmap using the following code. It is quite long but should be reproducible.

library(plotly)
library(data.table)
library(tidyr)
library(htmlwidgets)
library(widgetframe)

df <- data.frame(dom = sequence(31,1,1),
             Januar= sample(50:500, 31),
             Februar = sample(50:500, 31),
             März =sample(50:500, 31),
             April = sample(50:500, 31),
             Mai = sample(50:500, 31))

df <- as.data.table(df)
df<- melt(df, id.vars= "dom",variable.name="month",value.name="value", na.rm=T)
df<- as.data.frame(df)
df <- df %>% mutate(month= factor(month,levels=as.character(c("Januar","Februar","März","April","Mai")),labels=c("Jan","Feb","Mär","Apr","Mai"),ordered=TRUE))
df$dommapped <- ordered(df$dom, levels = 31:1)
df <- df%>% mutate(group=ceiling(value/(max(value)/5)))
df$group_1<- ifelse(df$group==1,df$group,NA)
df$group_2<- ifelse(df$group==2,df$group,NA)
df$group_3<- ifelse(df$group==3,df$group,NA)
df$group_4<- ifelse(df$group==4,df$group,NA)
df$group_5<- ifelse(df$group==5,df$group,NA)

colorScale1 <- data.frame(z=c(0,1),col=c("#FFE27a","#FFE27a"))
colorScale1$col <- as.character(colorScale1$col)
colorScale2 <- data.frame(z=c(0,1),col=c("#FFCD0e","#FFCD0e"))
colorScale2$col <- as.character(colorScale2$col)
colorScale3 <- data.frame(z=c(0,1),col=c("#A1C863","#A1C863"))
colorScale3$col <- as.character(colorScale3$col)
colorScale4 <- data.frame(z=c(0,1),col=c("#76B82b","#76B82b"))
colorScale4$col <- as.character(colorScale4$col)
colorScale5 <- data.frame(z=c(0,1),col=c("#4A731c","#4A731c"))
colorScale5$col <- as.character(colorScale5$col)

f1=list(family = "Arial, sans-serif",
      size = 12,
      color = "#000000")
f2 <- list(family = "Arial, sans-serif",
      size = 14,
      color = "#000000")

plot<-df%>%
  plot_ly(.,y = ~month, x = ~dommapped, z=~group_1, text=~value,name="group1", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
          hoverongaps=FALSE,colorscale=colorScale1,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_2, text=~value,name="group2", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale2,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_3, text=~value,name="group3", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale3,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_4, text=~value,name="group4",type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale4,showlegend=TRUE, showscale=FALSE) %>%
  add_trace(.,y = ~month, x = ~dommapped, z=~group_5, text=~value,name="group5", type="heatmap", xgap=2, ygap=2,hovertemplate=" <extra>%{y}. %{x}: Ø %{text} cases</extra>",
            hoverongaps=FALSE,colorscale=colorScale5,showlegend=TRUE, showscale=FALSE)
plot<-plot %>%
  layout(title =list(text= "Very long title about content of graph",
                     xref = "paper",
                     x = 0,
                     font = f2),
         hoverlabel=list(bgcolor="#ffffff",
                         bordercolor ="#ffffff",
                         font=f2),
         showlegend = TRUE,
         separators = ', ',
         plot_bgcolor='#ffffff',
         legend=list(itemclick="toggleothers",
                     orientation="h",
                     title=list(font=f1,
                                text="title"),
                     yanchor="top",
                     y=-0.25),
         modebar = list(color = "#a3a3a3",
                        activecolor = "#000000"),
         xaxis = list(title = "Day of month",
                      zeroline = FALSE,
                      gridcolor = 'ffff',
                      autorange = "reversed",
                      constraintoward="left"),
         yaxis = list(title="month",zeroline = FALSE,gridcolor = 'ffff',autorange = "reversed",
                      scaleanchor="x", constraintoward = "bottom"))

    plot<- plot %>% config(modeBarButtonsToRemove = list('autoScale2d'))
    plot<- plot %>% config(locale='de')
    plot<- plot %>% config(toImageButtonOptions = list(format = "png",filename = "",width = 760,height = 600))
    plot<- plot %>% onRender("function(el, x) {Plotly.d3.select('.cursor-crosshair').style('cursor', 'default')}")
    plot$sizingPolicy$browser$padding <- 0
    htmlwidgets::saveWidget(title = "plot", frameableWidget(plot), "directory/plot_1.html")

The scaleanchor and constraintoward commands help to get the design I need. Otherwise the boxes wouldn't be square format.
But it leads - depending on the browser window size - a big white space between graph and title.
Setting the range for the yaxis does not work.
Setting the margin also didn't work so far.

I thought I have to find a solution without scaleanchor and constraintoward to get the needed aspect ratio. So I tried to change the layout by using aspectratio and aspectmode.

layout(title =list(text= "Very long title about content of graph",
                     xref = "paper",
                     x = 0,
                     font = f2),
         hoverlabel=list(bgcolor="#ffffff",
                         bordercolor ="#ffffff",
                         font=f2),
         showlegend = TRUE,
         separators = ', ',
         plot_bgcolor='#ffffff',
         legend=list(itemclick="toggleothers",
                     orientation="h",
                     title=list(font=f1,
                                text="title"),
                     yanchor="top",
                     y=-0.25),
         modebar = list(color = "#a3a3a3",
                        activecolor = "#000000"),
         xaxis = list(title = "Day of month",
                      zeroline = FALSE,
                      gridcolor = 'ffff',
                      autorange = "reversed"),
         yaxis = list(title="month",zeroline = FALSE,gridcolor = 'ffff',autorange = "reversed"),
         scene=list(aspectmode="manual",
                    aspectratio=list(x=3,
                                     y=1)))

But this also didn't work.
I would be happy, if someone has an other idea or solution for this problem.

Body:
There isn't intentional whitespace between the plot and title. What is happening is that plotly has anchored the title at the top, and then it uses the available space for everything else.

If you look at it in RStudio, just adjusting the viewer pane will change it to the appearance you are looking for.

View One

View Two

This version uses the exact same code, just a different viewer pane size.

(I added a border so that the whitespace was more evident.)

If you're planning to save the plot, control the size when saving. If you're using R Markdown, control the size with knitr options.

So you are aware:

In your question, you used colorScale multiple times, but that object doesn't exist. I improvised.

You also used objects f1 and f2, but these objects weren't provided, so I commented them out.

Lastly, I added a buffer above the title, so that it wasn't touching the top of the viewer pane using the following code:

  layout(margin = list(l = 50, r = 50,
                       b = 50, t = 50,
                       pad = 20))

To put that into perspective--the margin before I changed it:

  "layout": {
    "margin": {
      "b": 40,
      "l": 60,
      "t": 25,
      "r": 10
    }

If you'd like to explore things like these settings that you never chose, take a look at plotly_json(plot).


问:
How to create nested JSON using first entry from from flat JSON as parent in javascript
I've tried various answers to this (same/similar) question here, and none have given the desired result.
I have a flat Json file that I need to convert to nested.
The first item in each chunk is the item that the data needs grouping on when converted to nested data.
The example data just shows two "types" but there are several more in the data, and a few more other elements along with colour and size as well - I kept it short for posting here.

Example data input:

```<code>[
  {
    "type": "Background",
    "colour": "Blue",
    "size": "5"
  },
  {
    "type": "Background",
    "colour": "Grey",
    "size": "3"
  },
  {
    "type": "Foreground",
    "colour": "Red",
    "size": "5"
  },
  {
    "type": "Foreground",
    "colour": "White",
    "size": "10"
  }
]
</code>```

Desired Output:

```<code>[
  {
    "type": "Background",
    "elements": [
      {
        "colour": "Blue",
        "size": "5"
      },
      {
        "colour": "Grey",
        "size": "3"
      }
    ]
  }
  {
    "type": "Foreground",
    "elements": [
      {
        "colour": "Red",
        "size": "5"
      },
      {
        "colour": "White",
        "size": "10"
      }
    ]
  }
]
</code>```

The closest I came to an answer for this was here:
Create nested json from flattened JSON in javascript

But the output I received from that (in VSCode) was this:

```<code>{
  type: { elements: [ [Object], [Object] ] }
}
</code>```

While I am trying to follow the code, it is beyond my javascript knowledge currently, so I don't know what's going wrong, or why I get [object] and not the actual elements?

Can anyone help me get this sorted out so my output looks like my above "Desired output"?

Cheers!

答:
try this</p>
```<code>var output = [];

var newObj = { type: input[0].type, elements: [] };
var prevType = input[0].type;

input.forEach((element) => {
  if (element.type != prevType) {
    output.push(newObj);
    newObj = { type: element.type, elements: [] };
    prevType = element.type;
  }
  newObj.elements.push({ colour: element.colour, size: element.size });
});
output.push(newObj);
</code>```

Body:
I've tried various answers to this (same/similar) question here, and none have given the desired result.
I have a flat Json file that I need to convert to nested.
The first item in each chunk is the item that the data needs grouping on when converted to nested data.
The example data just shows two "types" but there are several more in the data, and a few more other elements along with colour and size as well - I kept it short for posting here.

Example data input:

[
  {
    "type": "Background",
    "colour": "Blue",
    "size": "5"
  },
  {
    "type": "Background",
    "colour": "Grey",
    "size": "3"
  },
  {
    "type": "Foreground",
    "colour": "Red",
    "size": "5"
  },
  {
    "type": "Foreground",
    "colour": "White",
    "size": "10"
  }
]

Desired Output:

[
  {
    "type": "Background",
    "elements": [
      {
        "colour": "Blue",
        "size": "5"
      },
      {
        "colour": "Grey",
        "size": "3"
      }
    ]
  }
  {
    "type": "Foreground",
    "elements": [
      {
        "colour": "Red",
        "size": "5"
      },
      {
        "colour": "White",
        "size": "10"
      }
    ]
  }
]

The closest I came to an answer for this was here:
Create nested json from flattened JSON in javascript

But the output I received from that (in VSCode) was this:

{
  type: { elements: [ [Object], [Object] ] }
}

While I am trying to follow the code, it is beyond my javascript knowledge currently, so I don't know what's going wrong, or why I get [object] and not the actual elements?

Can anyone help me get this sorted out so my output looks like my above "Desired output"?

Cheers!

Body:
try this

var output = [];

var newObj = { type: input[0].type, elements: [] };
var prevType = input[0].type;

input.forEach((element) => {
  if (element.type != prevType) {
    output.push(newObj);
    newObj = { type: element.type, elements: [] };
    prevType = element.type;
  }
  newObj.elements.push({ colour: element.colour, size: element.size });
});
output.push(newObj);


问:
How to pass struct array arguments to a function the right way?
Source Code:

```<code>#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}
</code>```

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

答:
You are reading data into a pointer to the first element of the array. To read into n-th element your code should be using indexing, like cin >> employee[i].name;.

However...

"Naked" arrays are a source of many errors, subtle bugs, and generally unsafe code. Consider using std::array instead - this will eliminate the need for code like int sizeOfEmployee = sizeof(... and will nicely encapsulate that array as a parameter to a function:

```<code>#include <array>

int main() {

   std::array<Employee, 3> employee;

   for(int i = 0; i < employee.size(); i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee[i].name;
   // the rest of that for loop...
   }
// and the second loop becomes:
   for(const auto& e: employee) {
       displayData(e);
}
</code>```

Body:
Source Code:

#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

Body:
You are reading data into a pointer to the first element of the array. To read into n-th element your code should be using indexing, like cin >> employee[i].name;.

However...

"Naked" arrays are a source of many errors, subtle bugs, and generally unsafe code. Consider using std::array instead - this will eliminate the need for code like int sizeOfEmployee = sizeof(... and will nicely encapsulate that array as a parameter to a function:

#include <array>

int main() {

   std::array<Employee, 3> employee;

   for(int i = 0; i < employee.size(); i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee[i].name;
   // the rest of that for loop...
   }
// and the second loop becomes:
   for(const auto& e: employee) {
       displayData(e);
}


问:
Convert upper case into sentence case
How do we convert Upper case text like this:

WITHIN THE FIELD OF LITERARY CRITICISM, "TEXT" ALSO REFERS TO THE
  ORIGINAL INFORMATION CONTENT OF A PARTICULAR PIECE OF WRITING; THAT
  IS, THE "TEXT" OF A WORK IS THAT PRIMAL SYMBOLIC ARRANGEMENT OF
  LETTERS AS ORIGINALLY COMPOSED, APART FROM LATER ALTERATIONS,
  DETERIORATION, COMMENTARY, TRANSLATIONS, PARATEXT, ETC. THEREFORE,
  WHEN LITERARY CRITICISM IS CONCERNED WITH THE DETERMINATION OF A
  "TEXT," IT IS CONCERNED WITH THE DISTINGUISHING OF THE ORIGINAL
  INFORMATION CONTENT FROM WHATEVER HAS BEEN ADDED TO OR SUBTRACTED FROM
  THAT CONTENT AS IT APPEARS IN A GIVEN TEXTUAL DOCUMENT (THAT IS, A
  PHYSICAL REPRESENTATION OF TEXT).

Into usual sentence case like this:

Within the field of literary criticism, "text" also refers to the
  original information content of a particular piece of writing; that
  is, the "text" of a work is that primal symbolic arrangement of
  letters as originally composed, apart from later alterations,
  deterioration, commentary, translations, paratext, etc. Therefore,
  when literary criticism is concerned with the determination of a
  "text," it is concerned with the distinguishing of the original
  information content from whatever has been added to or subtracted from
  that content as it appears in a given textual document (that is, a
  physical representation of text).

答:
The base answer is just to use the LOWER() function.

It's easy enough to separate the sentences by CHARINDEX()ing for the period (and then using UPPER() on the first letter of each sentence...).

But even then, you'll end-up leaving proper names, acronyms, etc. in lower-case.

Distinguishing proper names, etc. from the rest is beyond anything that can be done in TSQL.  I've seen people attempt it in code using the dictionary from MS Word, etc...but even then, Word doesn't always get it right either.

ContentLicense: CC BY-SA 3.0

Title: Convert upper case into sentence case


问:
Java String.indexOf and empty Strings
I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string.

The Javadocs only say this method returns the index in this string of the specified string, -1 if the string isn't found.

To me this behavior seems highly unexpected, I would have expected a -1.  Any ideas why this unexpected behavior is going on?  I would at the least think this is worth a note in the method's Javadocs...

```<code>System.out.println("FOO".indexOf("")); // outputs 0 wtf!!!
System.out.println("FOO".indexOf("bar")); // outputs -1 as expected
System.out.println("FOO".indexOf("F")); // outputs 0 as expected
System.out.println("".indexOf("")); // outputs 0 as expected, I think
</code>```

答:
if we look inside of String implementation for a method "foo".indexOf(""), we arrive at this method:

```<code>public int indexOf(String str) {
    byte coder = coder();
    if (coder == str.coder()) {
        return isLatin1() ? StringLatin1.indexOf(value, str.value)
                          : StringUTF16.indexOf(value, str.value);
    }
    if (coder == LATIN1) {  // str.coder == UTF16
        return -1;
    }
    return StringUTF16.indexOfLatin1(value, str.value);
}
</code>```

If we look inside of any of the called indexOf(value, str.value) methods we find a condition that says:

if the second parameter (string we are searching for) length is 0 return 0:

```<code> public static int indexOf(byte[] value, byte[] str) {
    if (str.length == 0) {
        return 0;
    }
    ...
</code>```

This is just defensive coding for an edge case, and it is necessary because in the next method that is called to do actual searching by comparing bytes of the string (string is a byte array) it would otherwise have resulted in an ArrayIndexOutOfBounds exception:

```<code>public static int indexOf(byte[] value, int valueCount, byte[] str, int strCount, int fromIndex) {
        byte first = str[0];
...
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java String.indexOf and empty Strings

Body:
I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string.

The Javadocs only say this method returns the index in this string of the specified string, -1 if the string isn't found.

To me this behavior seems highly unexpected, I would have expected a -1.  Any ideas why this unexpected behavior is going on?  I would at the least think this is worth a note in the method's Javadocs...

System.out.println("FOO".indexOf("")); // outputs 0 wtf!!!
System.out.println("FOO".indexOf("bar")); // outputs -1 as expected
System.out.println("FOO".indexOf("F")); // outputs 0 as expected
System.out.println("".indexOf("")); // outputs 0 as expected, I think

Body:
if we look inside of String implementation for a method "foo".indexOf(""), we arrive at this method:

public int indexOf(String str) {
    byte coder = coder();
    if (coder == str.coder()) {
        return isLatin1() ? StringLatin1.indexOf(value, str.value)
                          : StringUTF16.indexOf(value, str.value);
    }
    if (coder == LATIN1) {  // str.coder == UTF16
        return -1;
    }
    return StringUTF16.indexOfLatin1(value, str.value);
}

If we look inside of any of the called indexOf(value, str.value) methods we find a condition that says:

if the second parameter (string we are searching for) length is 0 return 0:

 public static int indexOf(byte[] value, byte[] str) {
    if (str.length == 0) {
        return 0;
    }
    ...

This is just defensive coding for an edge case, and it is necessary because in the next method that is called to do actual searching by comparing bytes of the string (string is a byte array) it would otherwise have resulted in an ArrayIndexOutOfBounds exception:

public static int indexOf(byte[] value, int valueCount, byte[] str, int strCount, int fromIndex) {
        byte first = str[0];
...


问:
Writing to a Local json file dart flutter
I am creating an app that allows user to save small data. I have a json file in my assets folder and I would like to create an app that can write more json data to it. Path: assets/vault.json

vault.json

```<code>[
  {
    "name":"Ash",
    "age":"22",
    "hobby" : "golf"
  },
  {
    "name":"philip",
    "age":"17",
    "hobby" : "fishing"
  },
  {
    "name":"charles",
    "age":"32",
    "hobby" : "drawing"
  }

]
</code>```

However I am stuck at adding more list to the json file.

In my main.dart, I created 3 textfield for input and a button onPress to trigger writeToFile(arg1,arg2,arg3).

Here is what I have tried:

```<code>void writeToFile(String hobbyy, String agee, String namee) {
  print("Writing to file!");

  Map<String, dynamic> content = new Map();
  content1 = {name: namee};
  content2 = {age: agee};
  content3 = {hobby: hobbyy};

  content.addAll(content1);
  content.addAll(content2);
  content.addAll(content3);

  print(content);  //working fine
}

Future<String> _loadAVaultAsset() async {
  return await rootBundle.loadString('assets/vault.json');
}

Future loadVault() async {
  String jsonString = await _loadAVaultAsset();
  final jsonResponse = json.decode(jsonString);
  var add = jsonResponse.toString();

  add = add.replaceFirst(new RegExp(r'}]'), "},"+content.toString()+"]");

  print(add); //shows the full json string that I want.

//How to add/replace (add) into the json file?
}
</code>```

although I am getting the json string that I want, I am unable to reflect it in the json file.

Here is my vault_model.dart (incase if there is any use):

```<code>class UsersList{
  final List<Users> user;

  UsersList({
    this.user,
  });

  factory UsersList.fromJson(List<dynamic> parsedJson){

    List<Users> entireList = new List<Users>();

    entireList = parsedJson.map((i)=>Users.fromJson(i)).toList();

    return UsersList(
      user: entireList,
    );
  }
}

class Users{
  final String name;
  final String age;
  final String hobby;

  Users({
    this.name,
    this.age,
    this.hobby
});

  factory Users.fromJson(Map<String, dynamic> json){
    return new Users(
      name: json['name'],
      age: json['age'],
      hobby: json['hobby'],
    );
  }

}
</code>```

Please teach me how to replace the old json string with the new string (add) in the assets/vault.json path.

答:
Since you cannot write to a file in assets during runtime, as mentioned before, store it somewhere else in your local machine. The following code can read from a json file and write to it --

```<code>import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
    print("hello world");
    final File file = File('D:/Sadi/../vault.json'); //load the json file
    await readPlayerData(file); //read data from json file

    Player newPlayer = Player(  //add a new item to data list
      'Samy Brook',
      '31',
      'cooking'
      );

  players.add(newPlayer);

  print(players.length);

  players  //convert list data  to json
      .map(
        (player) => player.toJson(),
      )
      .toList();

    file.writeAsStringSync(json.encode(players));  //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async {

    String contents = await file.readAsString();
    var jsonResponse = jsonDecode(contents);

    for(var p in jsonResponse){

        Player player = Player(p['name'],p['age'],p['hobby']);
        players.add(player);
    }

}

class Player {
  late String name;
  late String age;
  late String hobby;

  Player(
     this.name,
     this.age,
    this.hobby,

  );

  Player.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
    hobby = json['hobby'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    data['hobby'] = this.hobby;

    return data;
  }

}
</code>```

Body:
I am creating an app that allows user to save small data. I have a json file in my assets folder and I would like to create an app that can write more json data to it. Path: assets/vault.json

vault.json

[
  {
    "name":"Ash",
    "age":"22",
    "hobby" : "golf"
  },
  {
    "name":"philip",
    "age":"17",
    "hobby" : "fishing"
  },
  {
    "name":"charles",
    "age":"32",
    "hobby" : "drawing"
  }

]

However I am stuck at adding more list to the json file.

In my main.dart, I created 3 textfield for input and a button onPress to trigger writeToFile(arg1,arg2,arg3).

Here is what I have tried:

void writeToFile(String hobbyy, String agee, String namee) {
  print("Writing to file!");

  Map<String, dynamic> content = new Map();
  content1 = {name: namee};
  content2 = {age: agee};
  content3 = {hobby: hobbyy};

  content.addAll(content1);
  content.addAll(content2);
  content.addAll(content3);

  print(content);  //working fine
}

Future<String> _loadAVaultAsset() async {
  return await rootBundle.loadString('assets/vault.json');
}

Future loadVault() async {
  String jsonString = await _loadAVaultAsset();
  final jsonResponse = json.decode(jsonString);
  var add = jsonResponse.toString();

  add = add.replaceFirst(new RegExp(r'}]'), "},"+content.toString()+"]");

  print(add); //shows the full json string that I want.

//How to add/replace (add) into the json file?
}

although I am getting the json string that I want, I am unable to reflect it in the json file.

Here is my vault_model.dart (incase if there is any use):

class UsersList{
  final List<Users> user;

  UsersList({
    this.user,
  });

  factory UsersList.fromJson(List<dynamic> parsedJson){

    List<Users> entireList = new List<Users>();

    entireList = parsedJson.map((i)=>Users.fromJson(i)).toList();

    return UsersList(
      user: entireList,
    );
  }
}

class Users{
  final String name;
  final String age;
  final String hobby;

  Users({
    this.name,
    this.age,
    this.hobby
});

  factory Users.fromJson(Map<String, dynamic> json){
    return new Users(
      name: json['name'],
      age: json['age'],
      hobby: json['hobby'],
    );
  }

}

Please teach me how to replace the old json string with the new string (add) in the assets/vault.json path.

Body:
Since you cannot write to a file in assets during runtime, as mentioned before, store it somewhere else in your local machine. The following code can read from a json file and write to it --

import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
    print("hello world");
    final File file = File('D:/Sadi/../vault.json'); //load the json file
    await readPlayerData(file); //read data from json file

    Player newPlayer = Player(  //add a new item to data list
      'Samy Brook',
      '31',
      'cooking'
      );

  players.add(newPlayer);

  print(players.length);

  players  //convert list data  to json
      .map(
        (player) => player.toJson(),
      )
      .toList();

    file.writeAsStringSync(json.encode(players));  //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async {

    String contents = await file.readAsString();
    var jsonResponse = jsonDecode(contents);

    for(var p in jsonResponse){

        Player player = Player(p['name'],p['age'],p['hobby']);
        players.add(player);
    }

}

class Player {
  late String name;
  late String age;
  late String hobby;

  Player(
     this.name,
     this.age,
    this.hobby,

  );

  Player.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
    hobby = json['hobby'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    data['hobby'] = this.hobby;

    return data;
  }

}


问:
Discord.js DiscordAPIError: Two factor is require for this operation
I've been using this sudo command in my test server and it works well but when I tried to use it in another server, I keep getting the DiscordAPIError: Two factors are required for this operation error.

Any way on how to fix this?

```<code>const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');

module.exports = {
  name: 'sudo',
  description: 'sudo webhook',
  userpermissions: ['MANAGE_WEBHOOKS'],

  async run(client, message, args) {
    if (!args[1])
      return message.reply(
        'Please provide a message to send \n ```\n usages: sudo [mention] [text]```'
      );
    const member = message.mentions.members.first();
    if (!member) return message.reply('Please tag a user');
    message.channel
      .createWebhook(member.user.username, {
        avatar: member.user.displayAvatarURL({ dynamic: true }),
      })
      .then((webhook) => {
        webhook.send(args.slice(1).join(' '));
        setTimeout(() => {
          webhook.delete();
        }, 3000);
      });
  },
};
</code>```

答: You probably have 2FA enabled on the guild/account and it is asking since you're creating a webhook.</p>

Body:
I've been using this sudo command in my test server and it works well but when I tried to use it in another server, I keep getting the DiscordAPIError: Two factors are required for this operation error.

Any way on how to fix this?

const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');

module.exports = {
  name: 'sudo',
  description: 'sudo webhook',
  userpermissions: ['MANAGE_WEBHOOKS'],

  async run(client, message, args) {
    if (!args[1])
      return message.reply(
        'Please provide a message to send \n ```\n usages: sudo [mention] [text]```'
      );
    const member = message.mentions.members.first();
    if (!member) return message.reply('Please tag a user');
    message.channel
      .createWebhook(member.user.username, {
        avatar: member.user.displayAvatarURL({ dynamic: true }),
      })
      .then((webhook) => {
        webhook.send(args.slice(1).join(' '));
        setTimeout(() => {
          webhook.delete();
        }, 3000);
      });
  },
};


问:
what should I add in the OnPressed in flutter to do the google OAuth sign in?
this is the code, I've already done everything, but I'm stuck on the OnPressed and don't know what to do.
please help,

SignInButton(Buttons.Google, onPressed:  .... )

I'm trying to do google sign in on a mobile application for a class project, but I'm unable to figure it out, I've done the facebook one but google is just a pain.. lol,
please help

答:
```<code>dependencies:
  google_sign_in: ^5.2.3
</code>```

Example:

```<code>import 'dart:async';
import 'dart:convert' show json;

import "package:http/http.dart" as http;
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

GoogleSignIn _googleSignIn = GoogleSignIn(
  // Optional clientId
  // clientId: '479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com',
  scopes: <String>[
    'email',
    'https://www.googleapis.com/auth/contacts.readonly',
  ],
);

void main() {
  runApp(
    MaterialApp(
      title: 'Google Sign In',
      home: SignInDemo(),
    ),
  );
}

class SignInDemo extends StatefulWidget {
  @override
  State createState() => SignInDemoState();
}

class SignInDemoState extends State<SignInDemo> {
  GoogleSignInAccount? _currentUser;
  String _contactText = '';

  @override
  void initState() {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account) {
      setState(() {
        _currentUser = account;
      });
      if (_currentUser != null) {
        _handleGetContact(_currentUser!);
      }
    });
    _googleSignIn.signInSilently();
  }

  Future<void> _handleGetContact(GoogleSignInAccount user) async {
    setState(() {
      _contactText = "Loading contact info...";
    });
    final http.Response response = await http.get(
      Uri.parse('https://people.googleapis.com/v1/people/me/connections'
          '?requestMask.includeField=person.names'),
      headers: await user.authHeaders,
    );
    if (response.statusCode != 200) {
      setState(() {
        _contactText = "People API gave a ${response.statusCode} "
            "response. Check logs for details.";
      });
      print('People API ${response.statusCode} response: ${response.body}');
      return;
    }
    final Map<String, dynamic> data = json.decode(response.body);
    final String? namedContact = _pickFirstNamedContact(data);
    setState(() {
      if (namedContact != null) {
        _contactText = "I see you know $namedContact!";
      } else {
        _contactText = "No contacts to display.";
      }
    });
  }

  String? _pickFirstNamedContact(Map<String, dynamic> data) {
    final List<dynamic>? connections = data['connections'];
    final Map<String, dynamic>? contact = connections?.firstWhere(
      (dynamic contact) => contact['names'] != null,
      orElse: () => null,
    );
    if (contact != null) {
      final Map<String, dynamic>? name = contact['names'].firstWhere(
        (dynamic name) => name['displayName'] != null,
        orElse: () => null,
      );
      if (name != null) {
        return name['displayName'];
      }
    }
    return null;
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print(error);
    }
  }

  Future<void> _handleSignOut() => _googleSignIn.disconnect();

  Widget _buildBody() {
    GoogleSignInAccount? user = _currentUser;
    if (user != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            leading: GoogleUserCircleAvatar(
              identity: user,
            ),
            title: Text(user.displayName ?? ''),
            subtitle: Text(user.email),
          ),
          const Text("Signed in successfully."),
          Text(_contactText),
          ElevatedButton(
            child: const Text('SIGN OUT'),
            onPressed: _handleSignOut,
          ),
          ElevatedButton(
            child: const Text('REFRESH'),
            onPressed: () => _handleGetContact(user),
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text("You are not currently signed in."),
          ElevatedButton(
            child: const Text('SIGN IN'),
            onPressed: _handleSignIn,
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Google Sign In'),
        ),
        body: ConstrainedBox(
          constraints: const BoxConstraints.expand(),
          child: _buildBody(),
        ));
  }
}
</code>```

Body:
dependencies:
  google_sign_in: ^5.2.3

Example:

import 'dart:async';
import 'dart:convert' show json;

import "package:http/http.dart" as http;
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

GoogleSignIn _googleSignIn = GoogleSignIn(
  // Optional clientId
  // clientId: '479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com',
  scopes: <String>[
    'email',
    'https://www.googleapis.com/auth/contacts.readonly',
  ],
);

void main() {
  runApp(
    MaterialApp(
      title: 'Google Sign In',
      home: SignInDemo(),
    ),
  );
}

class SignInDemo extends StatefulWidget {
  @override
  State createState() => SignInDemoState();
}

class SignInDemoState extends State<SignInDemo> {
  GoogleSignInAccount? _currentUser;
  String _contactText = '';

  @override
  void initState() {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account) {
      setState(() {
        _currentUser = account;
      });
      if (_currentUser != null) {
        _handleGetContact(_currentUser!);
      }
    });
    _googleSignIn.signInSilently();
  }

  Future<void> _handleGetContact(GoogleSignInAccount user) async {
    setState(() {
      _contactText = "Loading contact info...";
    });
    final http.Response response = await http.get(
      Uri.parse('https://people.googleapis.com/v1/people/me/connections'
          '?requestMask.includeField=person.names'),
      headers: await user.authHeaders,
    );
    if (response.statusCode != 200) {
      setState(() {
        _contactText = "People API gave a ${response.statusCode} "
            "response. Check logs for details.";
      });
      print('People API ${response.statusCode} response: ${response.body}');
      return;
    }
    final Map<String, dynamic> data = json.decode(response.body);
    final String? namedContact = _pickFirstNamedContact(data);
    setState(() {
      if (namedContact != null) {
        _contactText = "I see you know $namedContact!";
      } else {
        _contactText = "No contacts to display.";
      }
    });
  }

  String? _pickFirstNamedContact(Map<String, dynamic> data) {
    final List<dynamic>? connections = data['connections'];
    final Map<String, dynamic>? contact = connections?.firstWhere(
      (dynamic contact) => contact['names'] != null,
      orElse: () => null,
    );
    if (contact != null) {
      final Map<String, dynamic>? name = contact['names'].firstWhere(
        (dynamic name) => name['displayName'] != null,
        orElse: () => null,
      );
      if (name != null) {
        return name['displayName'];
      }
    }
    return null;
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print(error);
    }
  }

  Future<void> _handleSignOut() => _googleSignIn.disconnect();

  Widget _buildBody() {
    GoogleSignInAccount? user = _currentUser;
    if (user != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            leading: GoogleUserCircleAvatar(
              identity: user,
            ),
            title: Text(user.displayName ?? ''),
            subtitle: Text(user.email),
          ),
          const Text("Signed in successfully."),
          Text(_contactText),
          ElevatedButton(
            child: const Text('SIGN OUT'),
            onPressed: _handleSignOut,
          ),
          ElevatedButton(
            child: const Text('REFRESH'),
            onPressed: () => _handleGetContact(user),
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text("You are not currently signed in."),
          ElevatedButton(
            child: const Text('SIGN IN'),
            onPressed: _handleSignIn,
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Google Sign In'),
        ),
        body: ConstrainedBox(
          constraints: const BoxConstraints.expand(),
          child: _buildBody(),
        ));
  }
}


问:
How to display user inputted line breaks from a textarea value?
I am creating a program with two pages: one for inputting text via textarea into a database as a form, and the other to fetch said data and display it on a textarea. However, submitting text that has indentation in it (as a product of the user hitting the enter button), the page to fetch and display info breaks, and I know why but not how to fix it.

Page to submit form:

      <form action="/spaceData" method="POST">

               <textarea value="" id="textbox" name="usertext" maxlength="100" placeholder="Write your fortune:" onchange="handleChange(this)"></textarea>

            <button type="submit" id="submit" onclick="return handleChange()">Contribute Wisdom</button>

      </form>

```
<p>The page to display data is an ejs file which retrieves the text value of a submission as so:</p>
<pre class="lang-js prettyprint-override"><code>let text = "<%= text %>";
</code>```

But, for strings with indentation, the variable breaks. For example, say a user inputs the string:

```<code>hello
world
!
</code>```

The ejs file would display the variable as:

let text = "hello
world
!";
```

This causes the program to break. How do I allow the text variable to detect line breaks?

I thought perhaps I could have the string be iterated over prior to submission and if an indentation is detected it can be replaced with a \n, but I'm unsure how to implement this or if it would even fix the problem.

Thanks for any advice.

答:
this is cause html and js break lines are working different.

any the case. text area send this breaklines when you input them
and if you want you enable these linebreaks in you frontend just add this css in the area where you want to render these textarea info
for example: into a "p" tag

in < style> or .css file:

```<code>p {
  white-space: pre-wrap;
}
</code>```

or in the html:

```<code><p style="white-space: pre-wrap"> {textarea} </p>
</code>```

textarea can register all these breaklines. but when it sendit to a database there is no form in js you can see that breaklines. idk how to explain it but are hidding these
 lines

Body:
I am creating a program with two pages: one for inputting text via textarea into a database as a form, and the other to fetch said data and display it on a textarea. However, submitting text that has indentation in it (as a product of the user hitting the enter button), the page to fetch and display info breaks, and I know why but not how to fix it.

Page to submit form:

      <form action="/spaceData" method="POST">

               <textarea value="" id="textbox" name="usertext" maxlength="100" placeholder="Write your fortune:" onchange="handleChange(this)"></textarea>

            <button type="submit" id="submit" onclick="return handleChange()">Contribute Wisdom</button>

      </form>

The page to display data is an ejs file which retrieves the text value of a submission as so:

let text = "<%= text %>";

But, for strings with indentation, the variable breaks. For example, say a user inputs the string:

hello
world
!

The ejs file would display the variable as:

let text = "hello
world
!";

This causes the program to break. How do I allow the text variable to detect line breaks?

I thought perhaps I could have the string be iterated over prior to submission and if an indentation is detected it can be replaced with a \n, but I'm unsure how to implement this or if it would even fix the problem.

Thanks for any advice.

Body:
this is cause html and js break lines are working different.

any the case. text area send this breaklines when you input them
and if you want you enable these linebreaks in you frontend just add this css in the area where you want to render these textarea info
for example: into a "p" tag

in < style> or .css file:

p {
  white-space: pre-wrap;
}

or in the html:

<p style="white-space: pre-wrap"> {textarea} </p>

textarea can register all these breaklines. but when it sendit to a database there is no form in js you can see that breaklines. idk how to explain it but are hidding these
 lines


问:
C# I can't inherit from another project not recognizing namespace - error could not find namespace
If anyone could point me in the right direction not understanding why I see both namespaces in one project and not the other?

答:
In the Solution Explorer in Visual Studio, shown right in your image, right-click on the Dependencies node right inside and first in the FABackEnd node. In the popup-menu, click on Add Project Reference... Then in the Projects list, check FADTO if it isn't checked already.

In the source shown there are several using statements at the top. Below these, add another using statement that looks like this.

```<code>using FADTO;
</code>```

Body:
In the Solution Explorer in Visual Studio, shown right in your image, right-click on the Dependencies node right inside and first in the FABackEnd node. In the popup-menu, click on Add Project Reference... Then in the Projects list, check FADTO if it isn't checked already.

In the source shown there are several using statements at the top. Below these, add another using statement that looks like this.

using FADTO;


问:
SPA Routing Issues
I have a post that I made over on Reddit that pretty much details my issue:

https://www.reddit.com/r/learnjavascript/comments/sljr6r/spa_refreshpopstate_function_help/

If you are still wanting me to lay it out here, then allow me to explain.

I have a website that I help run, and I am in the process of developing an SPA. I have sample data setup in a table and I currently have it functioning to remove the table and populate the selected Pokemon's name in a new  tag. My issue is that if a user is to ever click the "Back/Forward/Refresh" buttons, either nothing happens or it then loads the default 404 for our site. To my knowledge, I am unable to access the server that SquareSpace works off of, and I'm not able to assign routes to specific html files due to us working out of SS. Below is the link to the page I'm working on. If I need to provide more information I can.

答:
SPAs have conflicts with server distributed pages. As the front-end can edit the URL (/pages), once refreshed, the server takes that URL and ends up not finding the page in the server.

Usually, you'd redirect everything from the server URL to your index.html to handle the URL, but since you can't acces the back-end, I'd say the best option here is to use a hash-router for your SPA

More here, full detailed explanation about the BrowserRouter and HashRouter difference:
https://itnext.io/why-using-hash-based-urls-in-your-react-spa-will-save-you-more-time-than-you-think-a21e2c560879

Title: SPA Routing Issues


问:
Limited number of clients used in federated learning
I just started studying federated learning and want to apply it to a certain dataset, and there are some questions that have risen up.

My data is containing records of 3 categories, each of which is having 3 departments. I am planning to have 3 different federated learning models for each category and treat the three department of this category as the distributed clients.

Is this possible? or building federated learning models requires having thousands of clients?

Thanks

答: Difficult to say by what you have provided in your question. Usually, when building a federated learning system, you are extending your centralized approach to one with data split/partitioned between segregated clients. Again, depending on the type of data you have, the type of task you are trying to solve and also the amount of data required to solve the task in a centralized approach, these factors along with other ones will depend how many clients you can use and how much data is required at each client. Additionally, the aggregation method that you wish to use combine the parameters from different clients will affect this. I suggest experimenting with different client numbers and partitioning methods and seeing what suits your needs.</p>


问:
media query with jquery
I would like to check if it’s possible to add media query.

For example,
if the window size is between 700px to 1000px, then change certain text of hyperlink (with class name : ‘samplebutton’ from ‘ABC’ to ‘DEF’.

I got something like this… but it throws an error.. not sure what went wrong..

```<code><script>
    jQuery(document).ready(function() {
        if($(window.width()) >= 700) {
        jQuery('a.samplebutton').text("DEF");
    }
});

</script>
</code>```

I am not well-verse in programming but if you could show some sample lines of code, I will be able to take it from there… Can you please help?

Thank you

答:
If you want to change the content of any element when the screen size changes, you need to use an event listener.

jQuery(document).ready(function() {
  /* Prints the current mode and screen width. */
  function log(width, mode) {
    console.clear();
    console.log(`Mode: ${mode} Width: ${width}px`);
  }

  /* This method is called when the resize event is triggered. */
  function update(object) {
    let width = object.width();
    let mode;

    $('#result').text(`${width}px`);

    /* Dekstop Mode */
    if(width >= 1024) {
      mode = 'Desktop';
      $('#engine').text('Google');
    }
    /* Tablet Mode */
    else if(width < 1024 && width > 768) {
      mode = 'Tablet';
      $('#engine').text('Google');
    }
    /* Mobile Mode */
    else if(width <= 768) {
      $('#engine').text('Yahoo');
      mode = 'Mobile';
    }

    log(width, mode);
  }

  /* The resize event fires when the page width changes. */
  $(window).on('resize', function(){
    update($(this));
  });

  update($(this));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  display: inline;
}
.samplebutton {
  background-color: #4CAF50;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}</code>```

Page Width:

Google```

Title: media query with jquery

Body:
I would like to check if it’s possible to add media query.

For example,
if the window size is between 700px to 1000px, then change certain text of hyperlink (with class name : ‘samplebutton’ from ‘ABC’ to ‘DEF’.

I got something like this… but it throws an error.. not sure what went wrong..

I am not well-verse in programming but if you could show some sample lines of code, I will be able to take it from there… Can you please help?

Thank you

Body:
If you want to change the content of any element when the screen size changes, you need to use an event listener.

jQuery(document).ready(function() {
  /* Prints the current mode and screen width. */
  function log(width, mode) {
    console.clear();
    console.log(`Mode: ${mode} Width: ${width}px`);
  }

  /* This method is called when the resize event is triggered. */
  function update(object) {
    let width = object.width();
    let mode;

    $('#result').text(`${width}px`);

    /* Dekstop Mode */
    if(width >= 1024) {
      mode = 'Desktop';
      $('#engine').text('Google');
    }
    /* Tablet Mode */
    else if(width < 1024 && width > 768) {
      mode = 'Tablet';
      $('#engine').text('Google');
    }
    /* Mobile Mode */
    else if(width <= 768) {
      $('#engine').text('Yahoo');
      mode = 'Mobile';
    }

    log(width, mode);
  }

  /* The resize event fires when the page width changes. */
  $(window).on('resize', function(){
    update($(this));
  });

  update($(this));
});

p {
  display: inline;
}
.samplebutton {
  background-color: #4CAF50;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span>Page Width: </span>
<p id="result"></p><hr>

<a id="engine" class="samplebutton" href="https://www.google.com">Google</a>


问:
How to bind border background to tabitem header background in WPF?
My TabItem styling is something like

```<code>    <!-- TabItem Style -->
    <Style
        TargetType="TabItem">
        <Setter
            Property="BorderThickness"
            Value="0" />
        <Setter
            Property="BorderBrush"
            Value="Transparent" />
        <Setter
            Property="Background"
            Value="Transparent" />
        <Setter
            Property="VerticalContentAlignment"
            Value="Center" />
        <Setter
            Property="HorizontalContentAlignment"
            Value="Center" />
        <Setter
            Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type TabItem}">
                    <Border>
                        <Grid>
                            <Grid Name="TabPanel">
                                <Border
                                    CornerRadius="3,3,0,0"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}" />
                            </Grid>
                            <Border
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}">
                                <ContentPresenter
                                    ContentSource="Header"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </Grid>
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <!--<Setter TargetName="TabPanel" Property="Background" Value="LightGreen" />-->
                            <Setter Property="FontWeight" Value="Bold" />
                        </Trigger>
                        <Trigger Property="IsSelected" Value="False">
                            <Setter Property="FontWeight" Value="Normal" />
                        </Trigger>
                    </ControlTemplate.Triggers>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

and my TabControl code

```<code><TabControl>
            <TabItem
                Header="Dash"
                Name="tabItem1"
            ...>
                <Border
                    Background="#002e00"
                    ...>
                ...
                </Border>
            </TabItem>
            <TabItem
                Header="Hash"
                Name="tabItem2"
            ...>
                <Border
                    Background="#00a800"
                    ...>
                ...
                </Border>
            </TabItem>
            <TabItem
                Header="Bash"
                Name="tabItem3"
            ...>
                <Border
                    Background="#ffde24"
                    ...>
                ...
                </Border>
            </TabItem>
</TabControl>
</code>```

I want to make the Background colors of TabItem Headers i.e. Header="Dash", "Hash" & "Bash" to be exact of its TabItem Border Backgrounds i.e. "#002e00", "#00a800" & "#ffde24" respectively when it is selected using Trigger in ControlTemplate.Triggers?

答:
You can add styling as key based on your base styling (something like)

```<code>    <SolidColorBrush
        x:Key="Blueish"
        Color="#5252ff" />
    <SolidColorBrush
        x:Key="Greenish"
        Color="#005757" />
    <SolidColorBrush
        x:Key="Blackish"
        Color="#2e2e00" />

    <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}" x:Key="blue">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type TabItem}">
                    <Border>
                        <Grid>
                            <Grid Name="TabPanel">
                                <Border
                                    CornerRadius="3,3,0,0"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}" />
                            </Grid>
                            <Border
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}">
                                <ContentPresenter
                                    ContentSource="Header"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="TabPanel" Property="Background" Value="{DynamicResource Blueish}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}" x:Key="green">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type TabItem}">
                    <Border>
                        <Grid>
                            <Grid Name="TabPanel">
                                <Border
                                    CornerRadius="3,3,0,0"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}" />
                            </Grid>
                            <Border
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}">
                                <ContentPresenter
                                    ContentSource="Header"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="TabPanel" Property="Background" Value="{DynamicResource Greenish}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}" x:Key="black">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type TabItem}">
                    <Border>
                        <Grid>
                            <Grid Name="TabPanel">
                                <Border
                                    CornerRadius="3,3,0,0"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}" />
                            </Grid>
                            <Border
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}">
                                <ContentPresenter
                                    ContentSource="Header"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="TabPanel" Property="Background" Value="{DynamicResource Blackish}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Use it like:

```<code><TabItem Style="{StaticResource blue}" ...>
  <Border Background="{DynamicResource Blueish}" ...</Border>...
<TabItem Style="{StaticResource green}" .../>
  <Border Background="{DynamicResource Greenish}" ...</Border>...
<TabItem Style="{StaticResource black}" .../>
  <Border Background="{DynamicResource Blackish}" ...</Border>...
</code>```

Now, I'm not sure whether this code can be further shortened (possibly) but nonetheless this should do the job.

Body:
My TabItem styling is something like

and my TabControl code

<TabControl>
            <TabItem
                Header="Dash"
                Name="tabItem1"
            ...>
                <Border
                    Background="#002e00"
                    ...>
                ...
                </Border>
            </TabItem>
            <TabItem
                Header="Hash"
                Name="tabItem2"
            ...>
                <Border
                    Background="#00a800"
                    ...>
                ...
                </Border>
            </TabItem>
            <TabItem
                Header="Bash"
                Name="tabItem3"
            ...>
                <Border
                    Background="#ffde24"
                    ...>
                ...
                </Border>
            </TabItem>
</TabControl>

I want to make the Background colors of TabItem Headers i.e. Header="Dash", "Hash" & "Bash" to be exact of its TabItem Border Backgrounds i.e. "#002e00", "#00a800" & "#ffde24" respectively when it is selected using Trigger in ControlTemplate.Triggers?

Body:
You can add styling as key based on your base styling (something like)

    <SolidColorBrush
        x:Key="Blueish"
        Color="#5252ff" />
    <SolidColorBrush
        x:Key="Greenish"
        Color="#005757" />
    <SolidColorBrush
        x:Key="Blackish"
        Color="#2e2e00" />

    <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}" x:Key="blue">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type TabItem}">
                    <Border>
                        <Grid>
                            <Grid Name="TabPanel">
                                <Border
                                    CornerRadius="3,3,0,0"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}" />
                            </Grid>
                            <Border
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}">
                                <ContentPresenter
                                    ContentSource="Header"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="TabPanel" Property="Background" Value="{DynamicResource Blueish}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}" x:Key="green">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type TabItem}">
                    <Border>
                        <Grid>
                            <Grid Name="TabPanel">
                                <Border
                                    CornerRadius="3,3,0,0"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}" />
                            </Grid>
                            <Border
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}">
                                <ContentPresenter
                                    ContentSource="Header"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="TabPanel" Property="Background" Value="{DynamicResource Greenish}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}" x:Key="black">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type TabItem}">
                    <Border>
                        <Grid>
                            <Grid Name="TabPanel">
                                <Border
                                    CornerRadius="3,3,0,0"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}" />
                            </Grid>
                            <Border
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}">
                                <ContentPresenter
                                    ContentSource="Header"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="TabPanel" Property="Background" Value="{DynamicResource Blackish}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Use it like:

<TabItem Style="{StaticResource blue}" ...>
  <Border Background="{DynamicResource Blueish}" ...</Border>...
<TabItem Style="{StaticResource green}" .../>
  <Border Background="{DynamicResource Greenish}" ...</Border>...
<TabItem Style="{StaticResource black}" .../>
  <Border Background="{DynamicResource Blackish}" ...</Border>...

Now, I'm not sure whether this code can be further shortened (possibly) but nonetheless this should do the job.


问:
Finding the last occurrence of x in the array
I want to find the last occurrence of x(13) in the array which is 6, but my code only finds the first occurrences which is 4, is there a way I can solve this?</p>
```<code>/* Application Program */
int[] arr = {9, 12, 2, 8, 13, -8, 13, 9};
int index = lastIndexOf(arr, 13);

if(index != -1)
    System.out.println(index);
else
    System.out.println("not found");

/* Method */
public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}
</code>```

答:
you want to find the last occurrence of 13 but you are returning the index in very first match itself.

```<code>public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}
</code>```

In order to return the last occurrence you can modify the code and return the most recent index.

```<code>public static int lastIndexOf(int[] arr, int x){
int lastIndex = -1
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            lastIndex = i;
        }
    }
    return lastIndex;
}
</code>```

Body:
I want to find the last occurrence of x(13) in the array which is 6, but my code only finds the first occurrences which is 4, is there a way I can solve this?

/* Application Program */
int[] arr = {9, 12, 2, 8, 13, -8, 13, 9};
int index = lastIndexOf(arr, 13);

if(index != -1)
    System.out.println(index);
else
    System.out.println("not found");

/* Method */
public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}

Body:
you want to find the last occurrence of 13 but you are returning the index in very first match itself.

public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}

In order to return the last occurrence you can modify the code and return the most recent index.

public static int lastIndexOf(int[] arr, int x){
int lastIndex = -1
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            lastIndex = i;
        }
    }
    return lastIndex;
}


问:
Apache with Angular2 - 404 Not Found
I have deployed an Angular2 application on an AWS server with Bitnami image.
The application is served by Apache (configured with a virtual host on port 8080) and works fine as long as I start from index.html. If I want to access a different page (which has been configured in the RouteConfig)  I get a 404 not found error.
Here is the configuration of the virtual server:

```<code>Listen 8080
<VirtualHost _default_:8080>
  DocumentRoot "/opt/bitnami/apps/MyApp"
<Directory  "/opt/bitnami/apps/MyApp">
Options All
Require all granted
</Directory>
</VirtualHost>
</code>```

答:
This is what worked for me (thanks to @Ankur Loriya and many others to get me there)...

Go to the directory with your index.html file.

```<code>sudo nano .htaccess
</code>```

Add this to the file:

```<code>RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
</code>```

Exit Nano (Control+X) and save your changes (Y).

```<code>cd /etc/apache2
sudo nano apache2.conf
</code>```

At the bottom of the file, there's a series of <Directory> tags.  Find the one that reads:

```<code><Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>
</code>```

...and change AllowOverride None to AllowOverride All

Exit Nano (Control+X) and save your changes (Y).

I'm not sure if the following command is needed, but I did it:

```<code>sudo a2enmod rewrite
</code>```

Finally, restart Apache:

```<code>sudo service apache2 restart
</code>```

And that did it.

Title: Apache with Angular2 - 404 Not Found

Body:
I have deployed an Angular2 application on an AWS server with Bitnami image.
The application is served by Apache (configured with a virtual host on port 8080) and works fine as long as I start from index.html. If I want to access a different page (which has been configured in the RouteConfig)  I get a 404 not found error.
Here is the configuration of the virtual server:

Listen 8080
<VirtualHost _default_:8080>
  DocumentRoot "/opt/bitnami/apps/MyApp"
<Directory  "/opt/bitnami/apps/MyApp">
Options All
Require all granted
</Directory>
</VirtualHost>

Body:
This is what worked for me (thanks to @Ankur Loriya and many others to get me there)...

Go to the directory with your index.html file.

sudo nano .htaccess

Add this to the file:

RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

Exit Nano (Control+X) and save your changes (Y).

cd /etc/apache2
sudo nano apache2.conf

At the bottom of the file, there's a series of <Directory> tags.  Find the one that reads:

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

...and change AllowOverride None to AllowOverride All

Exit Nano (Control+X) and save your changes (Y).

I'm not sure if the following command is needed, but I did it:

sudo a2enmod rewrite

Finally, restart Apache:

sudo service apache2 restart

And that did it.