问:
Extract data from a ggplot
I have made a plot using  ggplot2 geom_histogram from a data frame. See sample below and link to the ggplot histogram Need to label each geom_vline with the factors using a nested ddply function and facet wrap

I now need to make a data frame that contains the summarized data used to generate the ggplot above.

```<code>Sector2 Family  Year    Length
BUN Acroporidae 2010    332.1300496
BUN Poritidae   2011    141.1467966
BUN Acroporidae 2012    127.479
BUN Acroporidae 2013    142.5940556
MUR Faviidae    2010    304.0405
MUR Faviidae    2011    423.152
MUR Pocilloporidae  2012    576.0295
MUR Poritidae   2013    123.8936667
NTH Faviidae    2010    60.494
NTH Faviidae    2011    27.427
NTH Pocilloporidae  2012    270.475
NTH Poritidae   2013    363.4635
</code>```

答:
layer_data is designed precisely for this :

```<code>layer_data(p, 1)
</code>```

It will give you the data of the first layer, same as ggplot_build(p)$data[[1]].

Its source code is indeed precisely:

```<code>function (plot, i = 1L) ggplot_build(plot)$data[[i]]
</code>```

Title: Extract data from a ggplot

Body:
I have made a plot using  ggplot2 geom_histogram from a data frame. See sample below and link to the ggplot histogram Need to label each geom_vline with the factors using a nested ddply function and facet wrap

I now need to make a data frame that contains the summarized data used to generate the ggplot above.

Sector2 Family  Year    Length
BUN Acroporidae 2010    332.1300496
BUN Poritidae   2011    141.1467966
BUN Acroporidae 2012    127.479
BUN Acroporidae 2013    142.5940556
MUR Faviidae    2010    304.0405
MUR Faviidae    2011    423.152
MUR Pocilloporidae  2012    576.0295
MUR Poritidae   2013    123.8936667
NTH Faviidae    2010    60.494
NTH Faviidae    2011    27.427
NTH Pocilloporidae  2012    270.475
NTH Poritidae   2013    363.4635

Body:
layer_data is designed precisely for this :

layer_data(p, 1)

It will give you the data of the first layer, same as ggplot_build(p)$data[[1]].

Its source code is indeed precisely:

function (plot, i = 1L) ggplot_build(plot)$data[[i]]


来源: stackexchange

问:
Left align images with fewer images than 'slidesToShow'
In the code below there are two .wrapper divs, creating two carousels with slick.js. In the upper carousel there are two images, in the second carousel four images. In the initialisation of slick slidesToShow is set to 4.

The two images on the first carousel are centered horizontally, but I need them to be left aligned. How to left-align the carousel images? Images should be the same size for both carousels.

Code html head:

```<code><link rel="stylesheet" type="text/css" href="slick/slick.css"/>
<link rel="stylesheet" type="text/css" href="slick/slick-theme.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</code>```

CSS:

```<code>.wrapper div {
  padding: 10px;
}
.wrapper img {
  width: 100%;
  height: auto;
}
</code>```

JS:

```<code>$(document).ready(function(){
  $('.wrapper').slick({
    infinite: true,
    slidesToShow: 4,
    slidesToScroll: 4,
    responsive: [
      {
        breakpoint: 1000,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2
        }
      },
      {
        breakpoint: 650,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1
        }
      },
    ]
  });
});
</code>```

HTML body:

```<code><div class="wrapper">
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
</div>
<div class="wrapper">
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
</div>

<script type="text/javascript" src="slick/slick.min.js"></script>
</code>```

I tried the following, which works, but I prefer not to change slick.js generated code for maintenance reasons:

```<code>.slick-track {
  margin-left: 0;
  margin-right: 0;
}
</code>```

Is there a more appropriate way to left align the images?

答:
Slick documentation does not have an option to align left yet. So overriding css class is one way to go.

If you only want the first carousel to be left aligned, add following segment to one of custom override css files (any css file loads after slick.css)

```<code>.left-align-slick > .slick-list > .slick-track {
    margin-left:0;
}
</code>```

Add left-align-slick class to the container div of the carousel you want to be left aligned.

```<code><div class="wrapper left-align-slick">
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In the code below there are two .wrapper divs, creating two carousels with slick.js. In the upper carousel there are two images, in the second carousel four images. In the initialisation of slick slidesToShow is set to 4.

The two images on the first carousel are centered horizontally, but I need them to be left aligned. How to left-align the carousel images? Images should be the same size for both carousels.

Code html head:

<link rel="stylesheet" type="text/css" href="slick/slick.css"/>
<link rel="stylesheet" type="text/css" href="slick/slick-theme.css"/>

CSS:

.wrapper div {
  padding: 10px;
}
.wrapper img {
  width: 100%;
  height: auto;
}

JS:

$(document).ready(function(){
  $('.wrapper').slick({
    infinite: true,
    slidesToShow: 4,
    slidesToScroll: 4,
    responsive: [
      {
        breakpoint: 1000,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2
        }
      },
      {
        breakpoint: 650,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1
        }
      },
    ]
  });
});

HTML body:

title

title

title

title

title

title

I tried the following, which works, but I prefer not to change slick.js generated code for maintenance reasons:

.slick-track {
  margin-left: 0;
  margin-right: 0;
}

Is there a more appropriate way to left align the images?

Body:
Slick documentation does not have an option to align left yet. So overriding css class is one way to go.

If you only want the first carousel to be left aligned, add following segment to one of custom override css files (any css file loads after slick.css)

.left-align-slick > .slick-list > .slick-track {
    margin-left:0;
}

Add left-align-slick class to the container div of the carousel you want to be left aligned.

<div class="wrapper left-align-slick">
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
  <div>
    <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" />
    <p>title</p>
  </div>
</div>


问:
C# static vs instance methods
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

```<code>public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}
</code>```

Instead of this:

```<code>public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}
</code>```

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!

答:
In addition to Guffa's answer:

Methods only exist once in memory,
  regardless if they are static or not,
  so there is no difference at all in
  memory usage.

The instance method has a class instance passed to it as an invisible(which can be explicitly accessed through this) parameter, essentially making the newName of void Rename(string newName) a second parameter passed to your instance method; thus the resulting burned instructions for static void RenamePet(Pet pet, string newName) and void Rename(string newName) look essentially the same, so they has no differences on performance or whatsoever

ContentLicense: CC BY-SA 2.5

Title: C# static vs instance methods

Body:
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}

Instead of this:

public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!


问:
Finding perfect numbers (optimization)
I coded up a program in C# to find perfect numbers within a certain range as part of a programming challenge . However, I realized it is very slow when calculating perfect numbers upwards of 10000. Are there any methods of optimization that exist for finding perfect numbers? My code is as follows:</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleTest
{
 class Program
 {
  public static List<int> FindDivisors(int inputNo)
  {
   List<int> Divisors = new List<int>();
   for (int i = 1; i<inputNo; i++)
   {
    if (inputNo%i==0)
     Divisors.Add(i);
   }
   return Divisors;
  }

  public static void Main(string[] args)
  {
   const int limit = 100000;

   List<int> PerfectNumbers = new List<int>();
   List<int> Divisors=new List<int>();
   for (int i=1; i<limit; i++)
   {
    Divisors = FindDivisors(i);
    if (i==Divisors.Sum())
     PerfectNumbers.Add(i);
   }

   Console.Write("Output =");

   for (int i=0; i<PerfectNumbers.Count; i++)
   {
    Console.Write(" {0} ",PerfectNumbers[i]);
   }

   Console.Write("\n\n\nPress any key to continue . . . ");
   Console.ReadKey(true);
  }
 }
}
</code>```

答:
To continue from Charles Gargent's answer there is a very quick way to check if a Mersenne Number a.k.a. 2^n - 1 is prime. It is called the Lucas-Lehmer test
The basic pseudocode though (taken from the Wikipedia page) is:</p>

```<code>// Determine if Mp = 2p − 1 is prime for p > 2
Lucas–Lehmer(p)
    var s = 4
    var M = 2p − 1
    repeat p − 2 times:
        s = ((s × s) − 2) mod M
    if s == 0 return PRIME else return COMPOSITE
</code>```

Title: Finding perfect numbers (optimization)

Body:
I coded up a program in C# to find perfect numbers within a certain range as part of a programming challenge . However, I realized it is very slow when calculating perfect numbers upwards of 10000. Are there any methods of optimization that exist for finding perfect numbers? My code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleTest
{
 class Program
 {
  public static List<int> FindDivisors(int inputNo)
  {
   List<int> Divisors = new List<int>();
   for (int i = 1; i<inputNo; i++)
   {
    if (inputNo%i==0)
     Divisors.Add(i);
   }
   return Divisors;
  }

  public static void Main(string[] args)
  {
   const int limit = 100000;

   List<int> PerfectNumbers = new List<int>();
   List<int> Divisors=new List<int>();
   for (int i=1; i<limit; i++)
   {
    Divisors = FindDivisors(i);
    if (i==Divisors.Sum())
     PerfectNumbers.Add(i);
   }

   Console.Write("Output =");

   for (int i=0; i<PerfectNumbers.Count; i++)
   {
    Console.Write(" {0} ",PerfectNumbers[i]);
   }

   Console.Write("\n\n\nPress any key to continue . . . ");
   Console.ReadKey(true);
  }
 }
}

Body:
To continue from Charles Gargent's answer there is a very quick way to check if a Mersenne Number a.k.a. 2^n - 1 is prime. It is called the Lucas-Lehmer test
The basic pseudocode though (taken from the Wikipedia page) is:

// Determine if Mp = 2p − 1 is prime for p > 2
Lucas–Lehmer(p)
    var s = 4
    var M = 2p − 1
    repeat p − 2 times:
        s = ((s × s) − 2) mod M
    if s == 0 return PRIME else return COMPOSITE


问:
reading an xml file line by line with c# gives a reverse output
My code is below. The xml file I used is here.

```<code>using System;
using System.Text;
using System.Xml;

namespace ReadingAnXMLFile
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlReader xmlReader = XmlReader.Create("D:/C#/GameAssets/Images/alienExplode/images/alienExplode.xml");
            while (xmlReader.Read())
            {
                Console.Write(xmlReader.Name);
                while (xmlReader.MoveToNextAttribute()) // Read the attributes.
                    Console.Write(" " + xmlReader.Name + " = '" + xmlReader.Value + "' ");
                Console.WriteLine(" ");
            }
            Console.ReadKey(); // wait for keyboard input to exit
        }
    }
}
</code>```

The output of this program is in the reverse order from the data in the xml file. For example The xml file line shows

```<code><SubTexture height="25" width="24" y="474" x="180" name="explosion0000.png"/>
</code>```

whereas my console output is

```<code>SubTexture name = 'explosion0000.png'  x = '180'  y = '474'  width = '24'  height = '25'
</code>```

Any idear why this happens?

答:
The actual implementation of MoveToNextAttribute() is recursive, which returns the last (deepest) element first.
The nature of XML Attributes is that they are order-independent, so you should design without that expectation in mind.

From MSDN:

```<code>public override bool MoveToNextAttribute() {
            if ( !IsInReadingStates() || nodeType == XmlNodeType.EndElement )
                return false;
            readerNav.LogMove( curDepth );
            readerNav.ResetToAttribute( ref curDepth );
            if ( readerNav.MoveToNextAttribute( ref curDepth ) ) {
                nodeType = readerNav.NodeType;
                if ( bInReadBinary ) {
                    FinishReadBinary();
                }
                return true;
            }
            readerNav.RollBackMove( ref curDepth );
            return false;
        }
</code>```

Body:
My code is below. The xml file I used is here.

using System;
using System.Text;
using System.Xml;

namespace ReadingAnXMLFile
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlReader xmlReader = XmlReader.Create("D:/C#/GameAssets/Images/alienExplode/images/alienExplode.xml");
            while (xmlReader.Read())
            {
                Console.Write(xmlReader.Name);
                while (xmlReader.MoveToNextAttribute()) // Read the attributes.
                    Console.Write(" " + xmlReader.Name + " = '" + xmlReader.Value + "' ");
                Console.WriteLine(" ");
            }
            Console.ReadKey(); // wait for keyboard input to exit
        }
    }
}

The output of this program is in the reverse order from the data in the xml file. For example The xml file line shows

<SubTexture height="25" width="24" y="474" x="180" name="explosion0000.png"/>

whereas my console output is

SubTexture name = 'explosion0000.png'  x = '180'  y = '474'  width = '24'  height = '25'

Any idear why this happens?

Body:
The actual implementation of MoveToNextAttribute() is recursive, which returns the last (deepest) element first.
The nature of XML Attributes is that they are order-independent, so you should design without that expectation in mind.

From MSDN:

public override bool MoveToNextAttribute() {
            if ( !IsInReadingStates() || nodeType == XmlNodeType.EndElement )
                return false;
            readerNav.LogMove( curDepth );
            readerNav.ResetToAttribute( ref curDepth );
            if ( readerNav.MoveToNextAttribute( ref curDepth ) ) {
                nodeType = readerNav.NodeType;
                if ( bInReadBinary ) {
                    FinishReadBinary();
                }
                return true;
            }
            readerNav.RollBackMove( ref curDepth );
            return false;
        }


问:
Translate a text with parameters
I am making a multilingual react app. I am using redux to store an object that contains all my translations.

en.json

```<code>{
 "loginMessage": "Welcome to my app",
 "loginButton": "Log in",
 "summary": "Viewing {p1} items totalling {p2}"
}
</code>```

es.json

```<code>{
 "loginMessage": "Bienvenido",
 "loginButton": "Iniciar sesion",
 "summary": "Viendo {p1} elementos totalizando {p2}"
}
</code>```

Some of the text in my app are dynamic, it means it includes number or html tags. For example

Viewing 15 items totalling $300.00.

So I need to include some html tags between the strings. I came up with a partial solution which is using a function that replace the parameters for variables that I provided in. With this approach I have to provide the html tag as part of the variable something like this.

```<code>replaceAll(translation.summary, {
 "{p1}": `<strong> ${expenses.count} </strong>`,
 "{p2}": `<strong> ${expenses.total} </strong>`
})
</code>```

I also need to put this function in a react parameter called dangerouslySetInnerHTML otherwise the html tags are treated as strings.

This is getting the work done but I would like to know if there is any better approach. Using a feature that I am not aware of.

答:
you can use i18n-react i used that before is so useful.
https://www.npmjs.com/package/i18n-react</p>

Title: Translate a text with parameters

Body:
I am making a multilingual react app. I am using redux to store an object that contains all my translations.

en.json

{
 "loginMessage": "Welcome to my app",
 "loginButton": "Log in",
 "summary": "Viewing {p1} items totalling {p2}"
}

es.json

{
 "loginMessage": "Bienvenido",
 "loginButton": "Iniciar sesion",
 "summary": "Viendo {p1} elementos totalizando {p2}"
}

Some of the text in my app are dynamic, it means it includes number or html tags. For example

Viewing 15 items totalling $300.00.

So I need to include some html tags between the strings. I came up with a partial solution which is using a function that replace the parameters for variables that I provided in. With this approach I have to provide the html tag as part of the variable something like this.

replaceAll(translation.summary, {
 "{p1}": `<strong> ${expenses.count} </strong>`,
 "{p2}": `<strong> ${expenses.total} </strong>`
})

I also need to put this function in a react parameter called dangerouslySetInnerHTML otherwise the html tags are treated as strings.

This is getting the work done but I would like to know if there is any better approach. Using a feature that I am not aware of.


问:
Angular natural sort array of objects
I'm fairly new to Angular so maybe I'm just searching for the wrong thing, but I can't seem to find an easy answer to this anywhere.

Let's say I have an array of objects:

```<code>[
  {Label: "UDP 128B Flood", ...},
  {Label: "UDP 512B Flood", ...},
  {Label: "UPD 1514B Flood",...},
  {Label: "HTTP Excessive GET",...}
]
</code>```

This is array is being displayed as the options in a dropdown:

```<code><option *ngFor="let profile of Profiles" [value]="profile.Label">{{profile.Label}}</option>
</code>```

I want to sort these objects to make sure they show up in alphanumeric order.

答:
Use the array.prototype.sort function

let sorted = [
  {Label: "UDP 128B Flood"},
  {Label: "UDP 512B Flood"},
  {Label: "UDP 1514B Flood"},
  {Label: "HTTP Excessive GET"}
].sort((a, b) => a.Label.localeCompare(b.Label));

console.log(sorted);```

Title: Angular natural sort array of objects

Body:
I'm fairly new to Angular so maybe I'm just searching for the wrong thing, but I can't seem to find an easy answer to this anywhere.

Let's say I have an array of objects:

[
  {Label: "UDP 128B Flood", ...},
  {Label: "UDP 512B Flood", ...},
  {Label: "UPD 1514B Flood",...},
  {Label: "HTTP Excessive GET",...}
]

This is array is being displayed as the options in a dropdown:

<option *ngFor="let profile of Profiles" [value]="profile.Label">{{profile.Label}}</option>

I want to sort these objects to make sure they show up in alphanumeric order.


问:
Saving information in controller symfony relation ManyToMany HELPPPPP
Hi I need to save information in my db, what I mean is, how to persist when the relationship is manytomany, I am doing like this but it doesn't work!...I will put some code of entity Menu.

```<code>     /** Agrega nuevo menù
         *
         * @Route("/save", name="admin_menu_save")
         * @Method({"GET", "POST"})
         * @param Request $request
         * @return Response
         */
        public function saveAction(Request $request)
        {
            $em = $this->getDoctrine()->getManager();
            $fecha_menu = $request->get('fecha');
            $fecha_comprar = $request->get('fechacomprado');
            $fecha_vencimiento = $request->get('fechavencimiento');
            $alimentos = $request->get('select_alimentos');
            $a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
            $menu = new Menu();
            $menu->setFecha(new \DateTime($fecha_menu));
            $menu->setFechacomprar(new \DateTime($fecha_comprar));
            $menu->setFechavence(new \DateTime($fecha_vencimiento));
            $menu->setPrecio(6);
            $menu->addAlimento($a);
            $em->persist($menu);
            $em->flush();
            return new Response('Guardado OK');
        }
 //Menu Entity Definition (Just the necessary code):

       /**
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return ArrayCollection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }

}
</code>```

I have not experience working with manytomany relations, I hope to solve this problem, that´s show very good, but I don´t know how to save,edit or remove in that manytomany table!....

答:
I just realized what was...This was my solution:

```<code>foreach ($alimentos as $item) {
            $a = $em->getRepository('AdminBundle:Alimento')->find($item);
            $menu->addAlimento($a);
        }
</code>```

And of course later I persist menu.

Body:
Hi I need to save information in my db, what I mean is, how to persist when the relationship is manytomany, I am doing like this but it doesn't work!...I will put some code of entity Menu.

     /** Agrega nuevo menù
         *
         * @Route("/save", name="admin_menu_save")
         * @Method({"GET", "POST"})
         * @param Request $request
         * @return Response
         */
        public function saveAction(Request $request)
        {
            $em = $this->getDoctrine()->getManager();
            $fecha_menu = $request->get('fecha');
            $fecha_comprar = $request->get('fechacomprado');
            $fecha_vencimiento = $request->get('fechavencimiento');
            $alimentos = $request->get('select_alimentos');
            $a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
            $menu = new Menu();
            $menu->setFecha(new \DateTime($fecha_menu));
            $menu->setFechacomprar(new \DateTime($fecha_comprar));
            $menu->setFechavence(new \DateTime($fecha_vencimiento));
            $menu->setPrecio(6);
            $menu->addAlimento($a);
            $em->persist($menu);
            $em->flush();
            return new Response('Guardado OK');
        }
 //Menu Entity Definition (Just the necessary code):

       /**
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return ArrayCollection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }

}

I have not experience working with manytomany relations, I hope to solve this problem, that´s show very good, but I don´t know how to save,edit or remove in that manytomany table!....

Body:
I just realized what was...This was my solution:

foreach ($alimentos as $item) {
            $a = $em->getRepository('AdminBundle:Alimento')->find($item);
            $menu->addAlimento($a);
        }

And of course later I persist menu.


问:
Print Method in Java with an attached pic
The picture I attached is of the output screen. I’d like the first line to be 30 USD. What to do? Here is my code:

```<code>    Scanner scanner = new Scanner (System.in);

    System.out.print("USD");
    double sum = Double.parseDouble (scanner.nextLine ());

    double UsdBgn = sum * 1.7954;
    double UsdEur = sum / (1.95583/1.79549);
    double UsdGbp = sum / (2.53405/1.79549);

    System.out.printf("%.2f BGN\n", UsdBgn);
    System.out.printf("%.2f EUR\n", UsdEur);
    System.out.printf("%.2f GBP\n", UsdGbp);
</code>```

Output Screen:

答:
You can use string concatenation using '+' operator to join strings together, by concating a double you implicity call double.ToString function so it should print out fine.

So inserting:
    System.out.println(sum+" USD"); after the input statement will printout to the console the value that user inputted.

So it will look something like this:

```<code>double sum = Double.parseDouble (scanner.nextLine ());
System.out.println(sum+" USD");
</code>```

Sidenote -
You don't have to cast String to Double when using scanner

```<code>double sum = Double.parseDouble (scanner.nextLine ());
</code>```

can be transformed to :

```<code>double sum = scanner.nextDouble();
</code>```

Body:
The picture I attached is of the output screen. I’d like the first line to be 30 USD. What to do? Here is my code:

    Scanner scanner = new Scanner (System.in);

    System.out.print("USD");
    double sum = Double.parseDouble (scanner.nextLine ());

    double UsdBgn = sum * 1.7954;
    double UsdEur = sum / (1.95583/1.79549);
    double UsdGbp = sum / (2.53405/1.79549);

    System.out.printf("%.2f BGN\n", UsdBgn);
    System.out.printf("%.2f EUR\n", UsdEur);
    System.out.printf("%.2f GBP\n", UsdGbp);

Output Screen:

Body:
You can use string concatenation using '+' operator to join strings together, by concating a double you implicity call double.ToString function so it should print out fine.

So inserting:
    System.out.println(sum+" USD"); after the input statement will printout to the console the value that user inputted.

So it will look something like this:

double sum = Double.parseDouble (scanner.nextLine ());
System.out.println(sum+" USD");

Sidenote -
You don't have to cast String to Double when using scanner

double sum = Double.parseDouble (scanner.nextLine ());

can be transformed to :

double sum = scanner.nextDouble();


问:
What alternative do I have to a Left Join in this query?
I have this query that is used in a SSRS report that someone else created. The left join is the cause of the problem. If I change it to an inner join I get results (not the correct results) in about 15 seconds. With the Left Join I end up canceling the query after 20 minutes.  I added an index to both Budgets.Professionals and Transactions.Professionals with no change in performance. Is there a way to rewrite the query and not use the Left Join?</p>

```<code>SELECT
profs.ProfName as orig
,profs.Initials
,DATEPART(year, TransDate) as [Year]
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0.0
    ELSE Units * (aph.assignedpercent/100) * isnull(B.rate, 0.0)
    END) AS ctp
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0
    ELSE Units
    END * (aph.assignedpercent/100)) AS worked_hours
,SUM(Value * (aph.assignedpercent/100)) AS worked_value
, 0 AS billed_hours
,0 AS billed_value
,0 AS billed_netamt
, 0.0 as paid
, 0.0 as wo
FROM Transactions Trans
INNER JOIN Matters Matts ON Trans.matters  = Matts.matters
INNER JOIN MatterTypes MT ON Matts.mattertype  = MT.mattertypesdesc
and MT.Admin <> 'Y'
INNER JOIN Components Comps ON Comps.components  = Trans.components
and Comps.CompType = 'F'
INNER JOIN AssignedProfsHistory APH on APH.Matters = Trans.Matters
and APH.AssignedType = 'Originating'
and Trans.TransDate between APH.EffectiveDate and
ISNULL(EndDate,'12/31/2099')
INNER JOIN  Professionals profs on profs.Professionals  = APH.Professionals
    and profs.ProfType = 'Member'
    and profs.IsActive = 'Y'
    and profs.IsBillable = 'Y'
**LEFT join** (SELECT Budgets.Professionals as timekeeper, Budgets.Amount as
rate, Budgets.PeriodDate
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters  = Budgets.matters
    and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
    AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID  = '99999-99.003') as B
    *on B.timekeeper = Trans.Professionals*
    and YEAR(B.PeriodDate) = DATEPART(year, TransDate)
WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
'2017-12-31')) and '2017-12-31'
GROUP BY profs.ProfName, profs.Initials, DATEPART(year, TransDate)
</code>```

答:
Thanks everyone who responded. I took your suggestions and I was able to come up with a solution. The query that I had to kill after running for 2 hrs now finishes in about 14 seconds.

I ended up creating a cte at the beginning of the script.

```<code> ;with cte as
 (SELECT Transactions FROM Transactions t
 WHERE cast(t.TransDate as DATE) between dateadd(day, 1, DATEADD(year, -3,
 @EndDate)) and @EndDate)
</code>```

Then I linked the CTE to Transactions.

```<code>FROM Transactions Trans
INNER JOIN cte ON cte.Transactions = Trans.Transactions
</code>```

I then was able to remove the 'where' clause that was causing the issue.

```<code>WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
@EndDate)) and @EndDate
</code>```

Body:
I have this query that is used in a SSRS report that someone else created. The left join is the cause of the problem. If I change it to an inner join I get results (not the correct results) in about 15 seconds. With the Left Join I end up canceling the query after 20 minutes.  I added an index to both Budgets.Professionals and Transactions.Professionals with no change in performance. Is there a way to rewrite the query and not use the Left Join?

SELECT
profs.ProfName as orig
,profs.Initials
,DATEPART(year, TransDate) as [Year]
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0.0
    ELSE Units * (aph.assignedpercent/100) * isnull(B.rate, 0.0)
    END) AS ctp
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0
    ELSE Units
    END * (aph.assignedpercent/100)) AS worked_hours
,SUM(Value * (aph.assignedpercent/100)) AS worked_value
, 0 AS billed_hours
,0 AS billed_value
,0 AS billed_netamt
, 0.0 as paid
, 0.0 as wo
FROM Transactions Trans
INNER JOIN Matters Matts ON Trans.matters  = Matts.matters
INNER JOIN MatterTypes MT ON Matts.mattertype  = MT.mattertypesdesc
and MT.Admin <> 'Y'
INNER JOIN Components Comps ON Comps.components  = Trans.components
and Comps.CompType = 'F'
INNER JOIN AssignedProfsHistory APH on APH.Matters = Trans.Matters
and APH.AssignedType = 'Originating'
and Trans.TransDate between APH.EffectiveDate and
ISNULL(EndDate,'12/31/2099')
INNER JOIN  Professionals profs on profs.Professionals  = APH.Professionals
    and profs.ProfType = 'Member'
    and profs.IsActive = 'Y'
    and profs.IsBillable = 'Y'
**LEFT join** (SELECT Budgets.Professionals as timekeeper, Budgets.Amount as
rate, Budgets.PeriodDate
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters  = Budgets.matters
    and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
    AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID  = '99999-99.003') as B
    *on B.timekeeper = Trans.Professionals*
    and YEAR(B.PeriodDate) = DATEPART(year, TransDate)
WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
'2017-12-31')) and '2017-12-31'
GROUP BY profs.ProfName, profs.Initials, DATEPART(year, TransDate)

Body:
Thanks everyone who responded. I took your suggestions and I was able to come up with a solution. The query that I had to kill after running for 2 hrs now finishes in about 14 seconds.

I ended up creating a cte at the beginning of the script.

 ;with cte as
 (SELECT Transactions FROM Transactions t
 WHERE cast(t.TransDate as DATE) between dateadd(day, 1, DATEADD(year, -3,
 @EndDate)) and @EndDate)

Then I linked the CTE to Transactions.

FROM Transactions Trans
INNER JOIN cte ON cte.Transactions = Trans.Transactions

I then was able to remove the 'where' clause that was causing the issue.

WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
@EndDate)) and @EndDate


问:
Argument passed to function must be callable, array given
I'm trying to run a method on each element inside a collection. It's an object method residing in the same class:

```<code>protected function doSomething()
{
    $discoveries = $this->findSomething();
    $discoveries->each([$this, 'doSomethingElse']);
}

protected function doSomethingElse($element)
{
    $element->bar();
    // And some more
}
</code>```

If I precede the call on Collection::each with the check is_callable([$this, 'doSomethingElse']) it returns true, so apparently it is callable. The call itself however throws an exception:

Type error: Argument 1 passed to Illuminate\Support\Collection::each() must
     be callable, array given, called in ---.php on line 46

The method trying to be called can be found here.

I'm bypassing this by just passing a closure that itself simply calls that function, but this would definitely a much cleaner solution and I can't find out why it throws the error.

答:
PHP >= 5.4

I wasn't able to reproduce your error, but my guess is that you should use $discoveries instead of $this in the callback array, like so:

```<code>$discoveries->each([$discoveries, 'doSomethingElse']);
</code>```

Even though $discoveries and $this are of the same class, and therefore can access each other's protected and private methods, the type-hinting functionality may not check that the object in the callback array is the same class as the current class. However, the is_callable() method will check for this, which may explain why it returns true when you call it from inside the each() method.

PHP < 5.4

There is no type named callable, so when you use it as a type hint, it is referring to a class named callable. See this answer.

Body:
I'm trying to run a method on each element inside a collection. It's an object method residing in the same class:

protected function doSomething()
{
    $discoveries = $this->findSomething();
    $discoveries->each([$this, 'doSomethingElse']);
}

protected function doSomethingElse($element)
{
    $element->bar();
    // And some more
}

If I precede the call on Collection::each with the check is_callable([$this, 'doSomethingElse']) it returns true, so apparently it is callable. The call itself however throws an exception:

Type error: Argument 1 passed to Illuminate\Support\Collection::each() must
     be callable, array given, called in ---.php on line 46

The method trying to be called can be found here.

I'm bypassing this by just passing a closure that itself simply calls that function, but this would definitely a much cleaner solution and I can't find out why it throws the error.

Body:
PHP >= 5.4

I wasn't able to reproduce your error, but my guess is that you should use $discoveries instead of $this in the callback array, like so:

$discoveries->each([$discoveries, 'doSomethingElse']);

Even though $discoveries and $this are of the same class, and therefore can access each other's protected and private methods, the type-hinting functionality may not check that the object in the callback array is the same class as the current class. However, the is_callable() method will check for this, which may explain why it returns true when you call it from inside the each() method.

PHP < 5.4

There is no type named callable, so when you use it as a type hint, it is referring to a class named callable. See this answer.


问:
Angular 5 Server Side Rendering with TransferState Module doesn't seem to be working properly
I am using TransferState Module to cached http response on server side but it doesn't seem to work.

What I did was, added ServerTransferStateModule to AppServerModule and BrowserTransferStateModule to AppModule as suggested here https://next.angular.io/api/platform-browser/TransferState

Then I added below interceptor, which intercepts each http request and:

when on server, executes request and stores response in cache.

when on client, check the cache if cached response exists, it returns it otherwise executes request.

```<code>import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { of } from "rxjs/observable/of";
import { catchError, tap } from 'rxjs/operators';

const CACHE_KEY = makeStateKey('httpCacheKey');

@Injectable()
export class MyInterceptor implements HttpInterceptor {

  private isServer = isPlatformServer(this.platformId);

  constructor(
    @Inject(PLATFORM_ID) private platformId,
    private transferState: TransferState,
    @Inject('BASE_URL') private baseUrl: string) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let modifiedRequest: any;

    let isLocalRequest: boolean = !req.url.startsWith('http');

    if (isLocalRequest) {

      //skip cache check if the request method isn't GET.
      if (req.method == 'GET') {
        // check and serve cached response, if it exists
        const cachedResponse = this.transferState.get(CACHE_KEY, null as any);

        if (cachedResponse) {
          let modifiedResponse = new HttpResponse<any>({ headers: cachedResponse.headers, body: cachedResponse.body, status: cachedResponse.status, statusText: cachedResponse.statusText, url: cachedResponse.url });
          return of(modifiedResponse);
        }
      }

      // Clone the request to add the new header.
      modifiedRequest = req.clone({ headers: req.headers, url: this.baseUrl + req.url, body: req.body });
    }

    return next.handle(isLocalRequest ? modifiedRequest : req)
      .pipe(tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          if (this.isServer && isLocalRequest) {
            this.transferState.set(CACHE_KEY, event as any);
          }
        }
      }));
  }
}
</code>```

I do see the response being cached and transferred to client, I see below script tag in the markup returned from server:

```<code><script id="ng-cli-universal-state" type="application/json">{&q;httpCacheKey&q;:{&q;headers&q;:{&q;normalizedNames&q;:{},&q;lazyUpdate&q;:null},&q;status&q;:200,&q;statusText&q;:&q;OK&q;,&q;url&q;:&q;http://localhost:49805/api/SampleData/WeatherForecasts&q;,&q;ok&q;:true,&q;type&q;:4,&q;body&q;:[{&q;dateFormatted&q;:&q;11/28/2017&q;,&q;temperatureC&q;:28,&q;summary&q;:&q;Mild&q;,&q;temperatureF&q;:82},{&q;dateFormatted&q;:&q;11/29/2017&q;,&q;temperatureC&q;:-15,&q;summary&q;:&q;Balmy&q;,&q;temperatureF&q;:6},{&q;dateFormatted&q;:&q;11/30/2017&q;,&q;temperatureC&q;:51,&q;summary&q;:&q;Freezing&q;,&q;temperatureF&q;:123},{&q;dateFormatted&q;:&q;12/1/2017&q;,&q;temperatureC&q;:45,&q;summary&q;:&q;Mild&q;,&q;temperatureF&q;:112},{&q;dateFormatted&q;:&q;12/2/2017&q;,&q;temperatureC&q;:1,&q;summary&q;:&q;Mild&q;,&q;temperatureF&q;:33}]}}</script>
</code>```

But the http requests are executed twice, once on server and again in browser.

答:
I experienced the same problem. Found the solution at the end of this tutorial. You need to make sure you are bootstrapping your App Module after the DOMContentLoaded event fires.

main.ts:

```<code>import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

// Listen for the event before bootstrapping:
document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.log(err));
});
</code>```

Body:
I am using TransferState Module to cached http response on server side but it doesn't seem to work.

What I did was, added ServerTransferStateModule to AppServerModule and BrowserTransferStateModule to AppModule as suggested here https://next.angular.io/api/platform-browser/TransferState

Then I added below interceptor, which intercepts each http request and:

when on server, executes request and stores response in cache.

when on client, check the cache if cached response exists, it returns it otherwise executes request.

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { of } from "rxjs/observable/of";
import { catchError, tap } from 'rxjs/operators';

const CACHE_KEY = makeStateKey('httpCacheKey');

@Injectable()
export class MyInterceptor implements HttpInterceptor {

  private isServer = isPlatformServer(this.platformId);

  constructor(
    @Inject(PLATFORM_ID) private platformId,
    private transferState: TransferState,
    @Inject('BASE_URL') private baseUrl: string) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let modifiedRequest: any;

    let isLocalRequest: boolean = !req.url.startsWith('http');

    if (isLocalRequest) {

      //skip cache check if the request method isn't GET.
      if (req.method == 'GET') {
        // check and serve cached response, if it exists
        const cachedResponse = this.transferState.get(CACHE_KEY, null as any);

        if (cachedResponse) {
          let modifiedResponse = new HttpResponse<any>({ headers: cachedResponse.headers, body: cachedResponse.body, status: cachedResponse.status, statusText: cachedResponse.statusText, url: cachedResponse.url });
          return of(modifiedResponse);
        }
      }

      // Clone the request to add the new header.
      modifiedRequest = req.clone({ headers: req.headers, url: this.baseUrl + req.url, body: req.body });
    }

    return next.handle(isLocalRequest ? modifiedRequest : req)
      .pipe(tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          if (this.isServer && isLocalRequest) {
            this.transferState.set(CACHE_KEY, event as any);
          }
        }
      }));
  }
}

I do see the response being cached and transferred to client, I see below script tag in the markup returned from server:

But the http requests are executed twice, once on server and again in browser.

Body:
I experienced the same problem. Found the solution at the end of this tutorial. You need to make sure you are bootstrapping your App Module after the DOMContentLoaded event fires.

main.ts:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

// Listen for the event before bootstrapping:
document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.log(err));
});


问:
Springboot executable jar can not access index page
I created an application with springboot, restapi and angularjs. I will turn this project as executable jar. but when i do java -jar patchinit.jar, it does not reload index page. it gives

Whitelabel Error Page (There was an unexpected error (type=Not Found,
  status=404 No message available)

Trying to http://localhost:8080/

Am i missing something? I almost tried everything desperately..

POM.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ama.ist</groupId>
    <artifactId>patchinit</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1</version>
    <name>patchinit Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!-- <scope>provided</scope> -->
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
<!--            <scope>provided</scope> -->
        </dependency>

        <dependency>
            <groupId>org.tmatesoft.svnkit</groupId>
            <artifactId>svnkit</artifactId>
            <version>1.7.8</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>patchinit</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>
</project>
</code>```

Webapplication.java

```<code>package com.ama.ist;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApplication.class, args);
    }

}
</code>```

HelloController.java

```<code>package com.ama.ist.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @RequestMapping("/")
    String index() {
        return "index";
    }

}
</code>```

index.html

```<code><!DOCTYPE html>
<html ng-app="MyApp">
<head>

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.5/angular-material.min.css">

</head>
<body>

    <div class="container">

        <div class="row">

            <div class="col-md-4 jumbotron">
                <div class="col-md-12 dialog-demo-content">
                    <div ui-view="newPatch"></div>
                </div>
            </div>

            <div class="col-md-8 ">

                <div ui-view="svntab"></div>

            </div>

        </div>
    </div>

    <!--    <div class="container" class="md-padding" ng-cloak> -->
    <!--        <div class="row"> -->
    <!--            <div class="col-md-3 dialog-demo-content"> -->
    <!--                <div ui-view="newPatch"></div> -->
    <!--            </div> -->

    <!--            <div class="col-md-2"></div> -->

    <!--            <div class="col-md-3"> -->
    <!--                <div ui-view="svntab"></div> -->
    <!--            </div> -->
    <!--        </div> -->
    <!--    </div> -->

    <!-- *************************   SCRIPTS  ********************************** -->
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>

    <script
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script
        src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">

    </script>
    <script
        src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
    <script
        src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
    <script
        src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
    <script
        src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>

    <script src="js/app.js"></script>
    <script src="js/patch.controller.js"></script>
    <script src="js/svn.controller.js"></script>

</body>

</html>
</code>```

This is the output of springboot

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.5.RELEASE)

2017-12-05 19:54:09.019  INFO 480 --- [           main] com.ama.ist.WebApplication               : Starting WebApplication on ISTL55310 with PID 480 (C:\Erkan\eclipse-workspace-new\patchinit\target\classes started by erkan.erkisi in C:\Erkan\eclipse-workspace-new\patchinit)
2017-12-05 19:54:09.022  INFO 480 --- [           main] com.ama.ist.WebApplication               : No active profile set, falling back to default profiles: default
2017-12-05 19:54:09.063  INFO 480 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1ce2a846: startup date [Tue Dec 05 19:54:09 EET 2017]; root of context hierarchy
2017-12-05 19:54:10.335  INFO 480 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-12-05 19:54:10.345  INFO 480 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-12-05 19:54:10.347  INFO 480 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.33
2017-12-05 19:54:10.987  INFO 480 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2017-12-05 19:54:10.994  INFO 480 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-12-05 19:54:10.994  INFO 480 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1933 ms
2017-12-05 19:54:11.468  INFO 480 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2017-12-05 19:54:11.639  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1ce2a846: startup date [Tue Dec 05 19:54:09 EET 2017]; root of context hierarchy
2017-12-05 19:54:11.697  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.ama.ist.controller.HelloController.index()
2017-12-05 19:54:11.698  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/resource]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.ama.ist.controller.PatchController.home()
2017-12-05 19:54:11.698  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/mk],methods=[POST]}" onto public org.springframework.http.ResponseEntity<?> com.ama.ist.controller.PatchController.createFolder(com.ama.ist.model.Patch)
2017-12-05 19:54:11.701  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/localfolders],methods=[GET]}" onto public org.springframework.http.ResponseEntity<java.util.List<com.ama.ist.model.Folder>> com.ama.ist.controller.SvnController.getlocalFolders(com.ama.ist.model.User)
2017-12-05 19:54:11.702  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/svnfolders],methods=[GET]}" onto public org.springframework.http.ResponseEntity<java.util.List<com.ama.ist.model.Folder>> com.ama.ist.controller.SvnController.getFolders(com.ama.ist.model.User)
2017-12-05 19:54:11.703  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-12-05 19:54:11.704  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-12-05 19:54:11.716  INFO 480 --- [           main] o.s.w.s.c.a.WebMvcConfigurerAdapter      : Adding welcome page: ServletContext resource [/index.html]
2017-12-05 19:54:11.736  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Root mapping to handler of type [class org.springframework.web.servlet.mvc.ParameterizableViewController]
2017-12-05 19:54:11.745  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-05 19:54:11.745  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-05 19:54:11.778  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-05 19:54:11.878  INFO 480 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-12-05 19:54:11.945  INFO 480 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-05 19:54:11.949  INFO 480 --- [           main] com.ama.ist.WebApplication               : Started WebApplication in 3.254 seconds (JVM running for 3.827)
</code>```

Project Structure as an image

答:
Finally I got a solution. I was able to resolve this issue by adding thymeleaf dependency in pom

```<code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</code>```

What is Thymeleaf?

Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine that is able to apply a set of transformations to template files in order to display data and/or text produced by your applications.

There is one correction required in your html file:

```<code><link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.5/angular-material.min.css">
</code>```

make sure to close this tag <link> with end tag </link>. Otherwise you will get below error

There was an unexpected error (type=Internal Server Error,
  status=500). Exception parsing document: template="index", line 12 -
  column 3

Project structure

Body:
I created an application with springboot, restapi and angularjs. I will turn this project as executable jar. but when i do java -jar patchinit.jar, it does not reload index page. it gives

Whitelabel Error Page (There was an unexpected error (type=Not Found,
  status=404 No message available)

Trying to http://localhost:8080/

Am i missing something? I almost tried everything desperately..

POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ama.ist</groupId>
    <artifactId>patchinit</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1</version>
    <name>patchinit Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>

        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>

        </dependency>

        <dependency>
            <groupId>org.tmatesoft.svnkit</groupId>
            <artifactId>svnkit</artifactId>
            <version>1.7.8</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>patchinit</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>
</project>

Webapplication.java

package com.ama.ist;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApplication.class, args);
    }

}

HelloController.java

package com.ama.ist.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @RequestMapping("/")
    String index() {
        return "index";
    }

}

index.html

<!DOCTYPE html>

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.5/angular-material.min.css">

This is the output of springboot

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.5.RELEASE)

2017-12-05 19:54:09.019  INFO 480 --- [           main] com.ama.ist.WebApplication               : Starting WebApplication on ISTL55310 with PID 480 (C:\Erkan\eclipse-workspace-new\patchinit\target\classes started by erkan.erkisi in C:\Erkan\eclipse-workspace-new\patchinit)
2017-12-05 19:54:09.022  INFO 480 --- [           main] com.ama.ist.WebApplication               : No active profile set, falling back to default profiles: default
2017-12-05 19:54:09.063  INFO 480 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1ce2a846: startup date [Tue Dec 05 19:54:09 EET 2017]; root of context hierarchy
2017-12-05 19:54:10.335  INFO 480 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-12-05 19:54:10.345  INFO 480 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-12-05 19:54:10.347  INFO 480 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.33
2017-12-05 19:54:10.987  INFO 480 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2017-12-05 19:54:10.994  INFO 480 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-12-05 19:54:10.994  INFO 480 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1933 ms
2017-12-05 19:54:11.468  INFO 480 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-12-05 19:54:11.471  INFO 480 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2017-12-05 19:54:11.639  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1ce2a846: startup date [Tue Dec 05 19:54:09 EET 2017]; root of context hierarchy
2017-12-05 19:54:11.697  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.ama.ist.controller.HelloController.index()
2017-12-05 19:54:11.698  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/resource]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.ama.ist.controller.PatchController.home()
2017-12-05 19:54:11.698  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/mk],methods=[POST]}" onto public org.springframework.http.ResponseEntity<?> com.ama.ist.controller.PatchController.createFolder(com.ama.ist.model.Patch)
2017-12-05 19:54:11.701  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/localfolders],methods=[GET]}" onto public org.springframework.http.ResponseEntity<java.util.List<com.ama.ist.model.Folder>> com.ama.ist.controller.SvnController.getlocalFolders(com.ama.ist.model.User)
2017-12-05 19:54:11.702  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/svnfolders],methods=[GET]}" onto public org.springframework.http.ResponseEntity<java.util.List<com.ama.ist.model.Folder>> com.ama.ist.controller.SvnController.getFolders(com.ama.ist.model.User)
2017-12-05 19:54:11.703  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-12-05 19:54:11.704  INFO 480 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-12-05 19:54:11.716  INFO 480 --- [           main] o.s.w.s.c.a.WebMvcConfigurerAdapter      : Adding welcome page: ServletContext resource [/index.html]
2017-12-05 19:54:11.736  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Root mapping to handler of type [class org.springframework.web.servlet.mvc.ParameterizableViewController]
2017-12-05 19:54:11.745  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-05 19:54:11.745  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-05 19:54:11.778  INFO 480 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-05 19:54:11.878  INFO 480 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-12-05 19:54:11.945  INFO 480 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-05 19:54:11.949  INFO 480 --- [           main] com.ama.ist.WebApplication               : Started WebApplication in 3.254 seconds (JVM running for 3.827)

Project Structure as an image

Body:
Finally I got a solution. I was able to resolve this issue by adding thymeleaf dependency in pom

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

What is Thymeleaf?

Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine that is able to apply a set of transformations to template files in order to display data and/or text produced by your applications.

There is one correction required in your html file:

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.5/angular-material.min.css">

make sure to close this tag <link> with end tag </link>. Otherwise you will get below error

There was an unexpected error (type=Internal Server Error,
  status=500). Exception parsing document: template="index", line 12 -
  column 3

Project structure


问:
I want to configure the subscription endpoint located in my account page of woocommerce?
What i want is to edit a subscription in my account page of woocommerce. i have shared a picture below, of what exactly I want to edit.

This is the link of picture, what i want to edit is highlighted with red pen:

I want to edit the things which are highlighted with red pen. but i am unable to locate the exact page of this where i can edit things.
actually i want to change the link of update button in subscription table.
the URL of the page is like :

https://www.example.com/my-account/subscriptions/
There is no subscription page in pages menu of wordpress.

I am also unable to see this in endpoint of woocommerce.

Is there any way to do it ?

答:
First have a look to that: Template structure & Overriding templates via a theme… It explains how to override correctly woocommerce templates via your active theme.

The templates that you will override have to be located in woocommerce folder inside your theme folder…

Now in the woocommerce-subscriptions plugin folder, you have also a template folder, and you can pick the necessary templates that you need to change, copying them into that woocommerce folder located in your theme, taking care to keep path (subfolder hierarchy)…

So you will copy from: wp-content/plugins/woocommerce-subscriptions/templates/myaccount(5 files inside)… to wp-content/themes/your-theme/woocommerce/myaccount (where your-theme is the folder name of your theme)…

Now you can edit templates just like the woocommerce ones…

The subscription end point is not listed in woocommerce as it's not a default end point

To rename the menu label for "Subscriptions", you can use this:

```<code>add_filter( 'woocommerce_account_menu_items', 'rename_my_account_menu_items', 0, 15 );
function rename_my_account_menu_items( $items ) {

    // HERE set your new label name for subscriptions
    $items['subscriptions'] = __( 'Custom label', 'woocommerce' );

    return $items;
}
</code>```

The code goes on function.php file of your active child theme (or theme) or in any plugin file.

Tested and working

Body:
First have a look to that: Template structure & Overriding templates via a theme… It explains how to override correctly woocommerce templates via your active theme.

The templates that you will override have to be located in woocommerce folder inside your theme folder…

Now in the woocommerce-subscriptions plugin folder, you have also a template folder, and you can pick the necessary templates that you need to change, copying them into that woocommerce folder located in your theme, taking care to keep path (subfolder hierarchy)…

So you will copy from: wp-content/plugins/woocommerce-subscriptions/templates/myaccount(5 files inside)… to wp-content/themes/your-theme/woocommerce/myaccount (where your-theme is the folder name of your theme)…

Now you can edit templates just like the woocommerce ones…

The subscription end point is not listed in woocommerce as it's not a default end point

To rename the menu label for "Subscriptions", you can use this:

add_filter( 'woocommerce_account_menu_items', 'rename_my_account_menu_items', 0, 15 );
function rename_my_account_menu_items( $items ) {

    // HERE set your new label name for subscriptions
    $items['subscriptions'] = __( 'Custom label', 'woocommerce' );

    return $items;
}

The code goes on function.php file of your active child theme (or theme) or in any plugin file.

Tested and working


问:
Pass table as parameter to SQLCLR TV-UDF
We have a third-party DLL that can operate on a DataTable of source information and generate some useful values, and we're trying to hook it up through SQLCLR to be callable as a table-valued UDF in SQL Server 2008.

Taking the concept here one step further, I would like to program a CLR Table-Valued Function that operates on a table of source data from the DB.

I'm pretty sure I understand what needs to happen on the T-SQL side of things; but, what should the method signature look like in the .NET (C#) code? What would be the parameter datatype for "table data from SQL Server?"

e.g.

```<code>/* Setup */
CREATE TYPE InTableType
AS TABLE (LocationName VARCHAR(50), Lat FLOAT, Lon FLOAT)
GO

CREATE TYPE OutTableType
AS TABLE (LocationName VARCHAR(50), NeighborName VARCHAR(50), Distance FLOAT)
GO

CREATE ASSEMBLY myCLRAssembly
FROM 'D:\assemblies\myCLR_UDFs.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO
CREATE FUNCTION GetDistances(@locations InTableType)
RETURNS OutTableType
AS
EXTERNAL NAME myCLRAssembly.GeoDistance.SQLCLRInitMethod
GO

/* Execution */

DECLARE @myTable InTableType
INSERT INTO @myTable(LocationName, Lat, Lon) VALUES('aaa', -50.0, -20.0)
INSERT INTO @myTable(LocationName, Lat, Lon) VALUES('bbb', -20.0, -50.0)
SELECT * FROM @myTable

DECLARE @myResult OutTableType
INSERT INTO @myResult
GetDistances @myTable /* SQLCLR Call: GeoDistance.SQLCLRInitMethod(@myTable) */
</code>```

The lat/lon -> distance thing is a silly example that should of course be better handled entirely in SQL; but I hope it illustrates the general intent of table-in -> table-out through a table-valued UDF tied to a SQLCLR assembly.

I am not certain this is possible; what would the SQLCLRInitMethod method signature look like in the C#?

```<code>public class GeoDistance
{
    [SqlFunction(FillRowMethodName = "FillRow")]
    public static IEnumerable SQLCLRInitMethod(<appropriateType> myInputData)
    {
      //...
    }

    public static void FillRow(...)
    {
      //...
    }
}
</code>```

If it's not possible, I know I can use a "context connection=true" SQL connection within the C# code to have the CLR component query for the necessary data given the relevant keys; but that's sensitive to changes in the DB schema. So I hope to just have SQL bundle up all the source data and pass it to the function.

Bonus question - assuming this works at all, would it also work with more than one input table?

答:
This question seems to be (mostly) a duplicate of:

CLR Table-valued function with array argument

As a quick note, in that question I recommended: delimited list, XML, or CLR UDT.

There is also the option of filling a table and loading the DataTable from it in the function. Using a real Table is likely not recommended as it would require extra effort to make it "thread safe" (to not cross data with other SPIDs) and would require an additional clean-up process since the Function would not be able to do a DML statement to clean it up once it was done with the data. In certain situations maybe this is preferred but probably not for this particular case. Fortunately, Temporary Tables are accessible within SQLCLR Functions (as read-only, but they are not accessible at all in T-SQL functions). Using Temp Tables would have the same advantages as using permanent Tables but not the disadvantages of collisions with other SPIDs or needing to be cleaned up separately. The only requirement is that you use the Context Connection as that is the only way to access session-based objects (i.e. Temp Tables).

So for this particular case, I would recommend trying either the Temp Table or XML options.

Body:
We have a third-party DLL that can operate on a DataTable of source information and generate some useful values, and we're trying to hook it up through SQLCLR to be callable as a table-valued UDF in SQL Server 2008.

Taking the concept here one step further, I would like to program a CLR Table-Valued Function that operates on a table of source data from the DB.

I'm pretty sure I understand what needs to happen on the T-SQL side of things; but, what should the method signature look like in the .NET (C#) code? What would be the parameter datatype for "table data from SQL Server?"

e.g.

/* Setup */
CREATE TYPE InTableType
AS TABLE (LocationName VARCHAR(50), Lat FLOAT, Lon FLOAT)
GO

CREATE TYPE OutTableType
AS TABLE (LocationName VARCHAR(50), NeighborName VARCHAR(50), Distance FLOAT)
GO

CREATE ASSEMBLY myCLRAssembly
FROM 'D:\assemblies\myCLR_UDFs.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO
CREATE FUNCTION GetDistances(@locations InTableType)
RETURNS OutTableType
AS
EXTERNAL NAME myCLRAssembly.GeoDistance.SQLCLRInitMethod
GO

/* Execution */

DECLARE @myTable InTableType
INSERT INTO @myTable(LocationName, Lat, Lon) VALUES('aaa', -50.0, -20.0)
INSERT INTO @myTable(LocationName, Lat, Lon) VALUES('bbb', -20.0, -50.0)
SELECT * FROM @myTable

DECLARE @myResult OutTableType
INSERT INTO @myResult
GetDistances @myTable /* SQLCLR Call: GeoDistance.SQLCLRInitMethod(@myTable) */

The lat/lon -> distance thing is a silly example that should of course be better handled entirely in SQL; but I hope it illustrates the general intent of table-in -> table-out through a table-valued UDF tied to a SQLCLR assembly.

I am not certain this is possible; what would the SQLCLRInitMethod method signature look like in the C#?

public class GeoDistance
{
    [SqlFunction(FillRowMethodName = "FillRow")]
    public static IEnumerable SQLCLRInitMethod(<appropriateType> myInputData)
    {
      //...
    }

    public static void FillRow(...)
    {
      //...
    }
}

If it's not possible, I know I can use a "context connection=true" SQL connection within the C# code to have the CLR component query for the necessary data given the relevant keys; but that's sensitive to changes in the DB schema. So I hope to just have SQL bundle up all the source data and pass it to the function.

Bonus question - assuming this works at all, would it also work with more than one input table?


问:
Find consecutive Nans in pandas dataframe
I would like to find consecutive nans in my dataframe columns, something like

```<code>>>> df = pd.DataFrame([[np.nan, 2, np.nan],
...                    [3, 4, np.nan],
...                    [np.nan, np.nan, np.nan],
...                    [np.nan, 3, np.nan]],
...                    columns=list('ABC'))
>>> df
     A    B   C
0  NaN  2.0 NaN
1  3.0  4.0 NaN
2  NaN  NaN NaN
3  NaN  3.0 NaN
</code>```

would give

```<code>>>> df
     A    B   C
0  1.0  NaN 4.0
1  NaN  NaN 4.0
2  2.0  1.0 4.0
3  2.0  NaN 4.0
</code>```

答:
Not sure if that's too elegant but that's how I made it:

```<code>def f(ds):
    ds = ds.isnull()
    splits = np.split(ds, np.where(ds == False)[0])
    counts = [np.sum(v) for v in splits]
    return pd.concat([pd.Series(split).replace({False: np.nan, True: count})
                      for split, count in zip(splits, counts)])

df.apply(lambda x: f(x))
</code>```

Explanation:

```<code># Binarize the array
ds = ds.isnull()

# Split the array where we have False (former nan values)
splits = np.split(ds, np.where(ds == False)[0])

# Now just count the number of True values
counts = [np.sum(v) for v in splits]

# Concatenate series that contains the requested values
pd.concat([pd.Series(split).replace({False: np.nan, True: count})
           for split, count in zip(splits, counts)])
</code>```

Body:
I would like to find consecutive nans in my dataframe columns, something like

>>> df = pd.DataFrame([[np.nan, 2, np.nan],
...                    [3, 4, np.nan],
...                    [np.nan, np.nan, np.nan],
...                    [np.nan, 3, np.nan]],
...                    columns=list('ABC'))
>>> df
     A    B   C
0  NaN  2.0 NaN
1  3.0  4.0 NaN
2  NaN  NaN NaN
3  NaN  3.0 NaN

would give

>>> df
     A    B   C
0  1.0  NaN 4.0
1  NaN  NaN 4.0
2  2.0  1.0 4.0
3  2.0  NaN 4.0

Body:
Not sure if that's too elegant but that's how I made it:

def f(ds):
    ds = ds.isnull()
    splits = np.split(ds, np.where(ds == False)[0])
    counts = [np.sum(v) for v in splits]
    return pd.concat([pd.Series(split).replace({False: np.nan, True: count})
                      for split, count in zip(splits, counts)])

df.apply(lambda x: f(x))

Explanation:

# Binarize the array
ds = ds.isnull()

# Split the array where we have False (former nan values)
splits = np.split(ds, np.where(ds == False)[0])

# Now just count the number of True values
counts = [np.sum(v) for v in splits]

# Concatenate series that contains the requested values
pd.concat([pd.Series(split).replace({False: np.nan, True: count})
           for split, count in zip(splits, counts)])


问:
How to move requestId and caller to the HTTP headers?
We're trying to encrypt our payload and move anything that shouldn't be encrypted.

So far, these are the attributes that we identified not to be encrypted.

-- event.requestContext.requestId

-- event.requestContext.requestId.identity.caller

So, how can I move these items to the HTTP header?

答:
Hi if i understand correctly and this is a nodejs question you can use:

```<code>request.setHeader(KEY,VALUE);
</code>```

This way you can put the request.callerId in the value and create new Key for this header entry, like CALLER_ID.
Usually the key syntax is in capital letters.

Update:

Ok, so if you use aws-lambda you need to create custom request with curl that contain wrapper for the lambda payload, follow this manual:

https://aws.amazon.com/premiumsupport/knowledge-center/custom-headers-api-gateway-lambda/

Body:
Hi if i understand correctly and this is a nodejs question you can use:

request.setHeader(KEY,VALUE);

This way you can put the request.callerId in the value and create new Key for this header entry, like CALLER_ID.
Usually the key syntax is in capital letters.

Update:

Ok, so if you use aws-lambda you need to create custom request with curl that contain wrapper for the lambda payload, follow this manual:

https://aws.amazon.com/premiumsupport/knowledge-center/custom-headers-api-gateway-lambda/


问:
How to return top 3 rows if last row is tied
Suppose my table contains data like that

```<code>  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80
</code>```

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.

答:
You would want to select the rows in the moviesdb table where the Rating is in the DISTINCT Top 3 Ratings Ordered BY Ratings in Desc Order:</p>

```<code>SELECT *
  FROM moviesdb
 WHERE Rating IN (SELECT DISTINCT TOP 3 Rating
                    FROM moviesdb
                   ORDER BY Rating Desc)
</code>```

Body:
Suppose my table contains data like that

  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.

Body:
You would want to select the rows in the moviesdb table where the Rating is in the DISTINCT Top 3 Ratings Ordered BY Ratings in Desc Order:

SELECT *
  FROM moviesdb
 WHERE Rating IN (SELECT DISTINCT TOP 3 Rating
                    FROM moviesdb
                   ORDER BY Rating Desc)


问:
Saving a List to the database as multiple rows
I have a list that is derived from check box selections defined as the following:

```<code>checkedlist = request.GET.getlist('report_id')
</code>```

This list gets POSTed to a submitted view.

```<code>def submitted(request):

    owner = User.objects.get (formattedusername=request.user.formattedusername)
    requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
                                      ,report_id = request.POST.getlist('report_id'))

    requestsave.save()
</code>```

The problem is that when it tries to save to the database my field is defined as an int which is correct.  I want my report_id for the list to be stored on multiple lines in my database like the following:

```<code>user information report_id
user1234         1
user1234         2
user1234         3
user1234         4
</code>```

In the current save it's trying to post the list to the report_id how would I break it into multiple rows as shown above? I get the following error:

```<code>TypeError at /account/submitted/
int() argument must be a string, a bytes-like object or a number, not 'list'
</code>```

答:
how about</p>

```<code>my_list = request.POST.getlist('report_id')
for i in my_list
    requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title, report_id = i)
    requestsave.save()
</code>```

Body:
I have a list that is derived from check box selections defined as the following:

checkedlist = request.GET.getlist('report_id')

This list gets POSTed to a submitted view.

def submitted(request):

    owner = User.objects.get (formattedusername=request.user.formattedusername)
    requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
                                      ,report_id = request.POST.getlist('report_id'))

    requestsave.save()

The problem is that when it tries to save to the database my field is defined as an int which is correct.  I want my report_id for the list to be stored on multiple lines in my database like the following:

user information report_id
user1234         1
user1234         2
user1234         3
user1234         4

In the current save it's trying to post the list to the report_id how would I break it into multiple rows as shown above? I get the following error:

TypeError at /account/submitted/
int() argument must be a string, a bytes-like object or a number, not 'list'

Body:
how about

my_list = request.POST.getlist('report_id')
for i in my_list
    requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title, report_id = i)
    requestsave.save()


问:
404 Not Found aspx file but it is there
I´m using Plesk and in Web scripting and statistics I have Microsoft ASP support in ON.

I uploaded a application (which works correctly in my PC) to a directory and it can be shown but when I go to the aspx file it shows me the 404 error (The path is the correct).

I noticed that some files in "shtml" extension are neither shown by the server.

This is my very first time with ASP.NET, ISS8 and Plesk. I don´t know what to do. I will thank you for your help

答:
You have to set the HTTP Handler Extension. If you have no access to IIS directly, you could do on the web.config:

Open the Web.config file for the application, locate the httpHandlers element of the system.web section and add an entry for the file-name extension

Example:

```<code>  <system.webServer>
    <handlers>
      <add name="SampleHandler" verb="*"
        path="SampleHandler.new"
        type="SampleHandler, SampleHandlerAssembly"
        resourceType="Unspecified" />
    </handlers>
  </system.webServer>
</code>```

For more configuration options please refer to:
https://msdn.microsoft.com/en-us/library/bb515343.aspx
and
https://msdn.microsoft.com/en-us/library/46c5ddfy(v=vs.100).aspx

Check also the Custom Handler Policy of Plesk that should not be enabled:
https://docs.plesk.com/en-US/onyx/administrator-guide/plesk-administration/securing-plesk/custom-handlers-policy.76787/

Here I've found also another interesting document:
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/handlers/

Scroll down and you'll find a piece of code to add the handlers programmatically, even if I suggest you to add them in your web.config

Title: 404 Not Found aspx file but it is there

Body:
You have to set the HTTP Handler Extension. If you have no access to IIS directly, you could do on the web.config:

Open the Web.config file for the application, locate the httpHandlers element of the system.web section and add an entry for the file-name extension

Example:

  <system.webServer>
    <handlers>
      <add name="SampleHandler" verb="*"
        path="SampleHandler.new"
        type="SampleHandler, SampleHandlerAssembly"
        resourceType="Unspecified" />
    </handlers>
  </system.webServer>

For more configuration options please refer to:
https://msdn.microsoft.com/en-us/library/bb515343.aspx
and
https://msdn.microsoft.com/en-us/library/46c5ddfy(v=vs.100).aspx

Check also the Custom Handler Policy of Plesk that should not be enabled:
https://docs.plesk.com/en-US/onyx/administrator-guide/plesk-administration/securing-plesk/custom-handlers-policy.76787/

Here I've found also another interesting document:
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/handlers/

Scroll down and you'll find a piece of code to add the handlers programmatically, even if I suggest you to add them in your web.config


问:
How can I parse csv to array?
I want to parse csv file to array. But I have a problem. I get csv file name,but when I do parse this parth return me this error.
'The provided file test.csv doesn't exists or inaccessible'
How can I resolve this problem?</p>

```<code>const csv = require('csv-array');

router.post('/upload', function(req,res){
   let test = req.files.test.name //this return me uploaded file name
   csv.parseCSV(test, (data) => {
      console.log(data); //this parth return me 'The provided file
                                     //test.csv doesn't exists or inaccessible'
   })
})
</code>```

答:
Your csv-array package's parseCSV method expects the first argument to be a filename. You should tell us what the console.log(req.files.test.name) is.

Assuming it is exactly "test.csv", your error is obvious, as you mentioned:

```<code>The provided file test.csv doesn't exists or inaccessible
</code>```

(1) Make sure that file actually exists wherever your script is running from

(2) If that does indeed exist (and you are pointing to the right location), verify its permissions. You might need to grant read permission for whoever is executing the application.

Title: How can I parse csv to array?

Body:
I want to parse csv file to array. But I have a problem. I get csv file name,but when I do parse this parth return me this error.
'The provided file test.csv doesn't exists or inaccessible'
How can I resolve this problem?

const csv = require('csv-array');

router.post('/upload', function(req,res){
   let test = req.files.test.name //this return me uploaded file name
   csv.parseCSV(test, (data) => {
      console.log(data); //this parth return me 'The provided file
                                     //test.csv doesn't exists or inaccessible'
   })
})

Body:
Your csv-array package's parseCSV method expects the first argument to be a filename. You should tell us what the console.log(req.files.test.name) is.

Assuming it is exactly "test.csv", your error is obvious, as you mentioned:

The provided file test.csv doesn't exists or inaccessible

(1) Make sure that file actually exists wherever your script is running from

(2) If that does indeed exist (and you are pointing to the right location), verify its permissions. You might need to grant read permission for whoever is executing the application.


问:
How to send an image from a database via mail
I am getting an image inforamtion as string from a database and by using that string I create a bitmap image.

Now my question is how am I sending this image and matter also via mail. This image is not stored on the sdcard or anywhere else.

答:
Store that bitmap on your filesystem

Then use following code to attach that file to your email:

```<code>File F = new File("/path/to/your/file.png");
Uri U = Uri.fromFile(F);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/png");
i.putExtra(Intent.EXTRA_STREAM, U);
startActivity(Intent.createChooser(i,"Email:"));
</code>```

Body:
Store that bitmap on your filesystem

Then use following code to attach that file to your email:

File F = new File("/path/to/your/file.png");
Uri U = Uri.fromFile(F);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/png");
i.putExtra(Intent.EXTRA_STREAM, U);
startActivity(Intent.createChooser(i,"Email:"));