问:
I want to display multiple vtkUnstructuredGrids in paraview
I've just started to learn VTK to get .vtu format files. I am doing WriteVTU which is one example of VTK.
I modified the code slightly so that two tetrahedrons are displayed in ParaView, but only one tetrahedron is displayed in ParaView.

Obviously I'm missing something, but I can't figure where. I'd be grateful for any hints.

This is the code.

```<code>#include <vtkVersion.h>
#include <vtkSmartPointer.h>
#include <vtkTetra.h>
#include <vtkCellArray.h>
#include <vtkXMLUnstructuredGridReader.h>
#include <vtkDataSetMapper.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkXMLUnstructuredGridWriter.h>
#include <vtkUnstructuredGrid.h>
#include <vtkPointData.h>
#include <vtkVertexGlyphFilter.h>

int main(int argc, char *argv[])
{
  // Parse command line arguments
  if(argc != 2)
  {
    std::cout << "Required arguments: OutputFilename" << std::endl;
    return EXIT_FAILURE;
  }

  std::string filename = argv[1];

  vtkSmartPointer<vtkPoints> points =
    vtkSmartPointer<vtkPoints>::New();
  points->InsertNextPoint(0, 0, 0);
  points->InsertNextPoint(1, 0, 0);
  points->InsertNextPoint(1, 1, 0);
  points->InsertNextPoint(0, 1, 1);

  points->InsertNextPoint(-1, 0, 0);
  points->InsertNextPoint(-1, -1, 0);
  points->InsertNextPoint(0, -1, -1);

 vtkSmartPointer<vtkTetra> tetra =
  vtkSmartPointer<vtkTetra>::New();

  tetra->GetPointIds()->SetId(0, 0);
  tetra->GetPointIds()->SetId(1, 1);
  tetra->GetPointIds()->SetId(2, 2);
  tetra->GetPointIds()->SetId(3, 3);

 vtkSmartPointer<vtkTetra> tetra2 =
  vtkSmartPointer<vtkTetra>::New();

  tetra->GetPointIds()->SetId(0, 0);
  tetra->GetPointIds()->SetId(1, 4);
  tetra->GetPointIds()->SetId(2, 5);
  tetra->GetPointIds()->SetId(3, 6);

  vtkSmartPointer<vtkCellArray> cellArray =
    vtkSmartPointer<vtkCellArray>::New();
  cellArray->InsertNextCell(tetra);
  cellArray->InsertNextCell(tetra2);

  vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid =
    vtkSmartPointer<vtkUnstructuredGrid>::New();
  unstructuredGrid->SetPoints(points);
  unstructuredGrid->SetCells(VTK_TETRA, cellArray);

  // Write file
  vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
    vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
  writer->SetFileName(filename.c_str());
#if VTK_MAJOR_VERSION <= 5
  writer->SetInput(unstructuredGrid);
#else
  writer->SetInputData(unstructuredGrid);
#endif
  writer->Write();

  return EXIT_SUCCESS;
}
</code>```

This is the .vtu file.

```<code><?xml version="1.0"?>
<VTKFile type="UnstructuredGrid" version="0.1" byte_order="LittleEndian" header_type="UInt32" compressor="vtkZLibDataCompressor">
  <UnstructuredGrid>
    <Piece NumberOfPoints="7"                    NumberOfCells="2"                   >
      <PointData>
      </PointData>
      <CellData>
      </CellData>
      <Points>
        <DataArray type="Float32" Name="Points" NumberOfComponents="3" format="appended" RangeMin="0"                    RangeMax="1.4142135624"         offset="0"                   />
      </Points>
      <Cells>
        <DataArray type="Int64" Name="connectivity" format="appended" RangeMin=""                     RangeMax=""                     offset="56"                  />
        <DataArray type="Int64" Name="offsets" format="appended" RangeMin=""                     RangeMax=""                     offset="108"                 />
        <DataArray type="UInt8" Name="types" format="appended" RangeMin=""                     RangeMax=""                     offset="152"                 />
      </Cells>
    </Piece>
  </UnstructuredGrid>
  <AppendedData encoding="base64">
   _AQAAAACAAABUAAAAGAAAAA==eJxjYEAGDfaobGz8hv1IYvux8QElFQn3AQAAAACAAABAAAAAFAAAAA==eJxjYIAAFijNCqXZGIgDAAMAABA=AQAAAACAAAAQAAAADgAAAA==eJxjYYAADigNAACQAA0=AQAAAACAAAACAAAACgAAAA==eJzj4gIAACAAFQ==
  </AppendedData>
</VTKFile>
</code>```

答:
I'm sorry. It's just a typo.</p>

```<code> vtkSmartPointer<vtkTetra> tetra2 =
  vtkSmartPointer<vtkTetra>::New();

  tetra2->GetPointIds()->SetId(0, 0);
  tetra2->GetPointIds()->SetId(1, 4);
  tetra2->GetPointIds()->SetId(2, 5);
  tetra2->GetPointIds()->SetId(3, 6);
</code>```

Body:
I've just started to learn VTK to get .vtu format files. I am doing WriteVTU which is one example of VTK.
I modified the code slightly so that two tetrahedrons are displayed in ParaView, but only one tetrahedron is displayed in ParaView.

Obviously I'm missing something, but I can't figure where. I'd be grateful for any hints.

This is the code.

#include <vtkVersion.h>
#include <vtkSmartPointer.h>
#include <vtkTetra.h>
#include <vtkCellArray.h>
#include <vtkXMLUnstructuredGridReader.h>
#include <vtkDataSetMapper.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkXMLUnstructuredGridWriter.h>
#include <vtkUnstructuredGrid.h>
#include <vtkPointData.h>
#include <vtkVertexGlyphFilter.h>

int main(int argc, char *argv[])
{
  // Parse command line arguments
  if(argc != 2)
  {
    std::cout << "Required arguments: OutputFilename" << std::endl;
    return EXIT_FAILURE;
  }

  std::string filename = argv[1];

  vtkSmartPointer<vtkPoints> points =
    vtkSmartPointer<vtkPoints>::New();
  points->InsertNextPoint(0, 0, 0);
  points->InsertNextPoint(1, 0, 0);
  points->InsertNextPoint(1, 1, 0);
  points->InsertNextPoint(0, 1, 1);

  points->InsertNextPoint(-1, 0, 0);
  points->InsertNextPoint(-1, -1, 0);
  points->InsertNextPoint(0, -1, -1);

 vtkSmartPointer<vtkTetra> tetra =
  vtkSmartPointer<vtkTetra>::New();

  tetra->GetPointIds()->SetId(0, 0);
  tetra->GetPointIds()->SetId(1, 1);
  tetra->GetPointIds()->SetId(2, 2);
  tetra->GetPointIds()->SetId(3, 3);

 vtkSmartPointer<vtkTetra> tetra2 =
  vtkSmartPointer<vtkTetra>::New();

  tetra->GetPointIds()->SetId(0, 0);
  tetra->GetPointIds()->SetId(1, 4);
  tetra->GetPointIds()->SetId(2, 5);
  tetra->GetPointIds()->SetId(3, 6);

  vtkSmartPointer<vtkCellArray> cellArray =
    vtkSmartPointer<vtkCellArray>::New();
  cellArray->InsertNextCell(tetra);
  cellArray->InsertNextCell(tetra2);

  vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid =
    vtkSmartPointer<vtkUnstructuredGrid>::New();
  unstructuredGrid->SetPoints(points);
  unstructuredGrid->SetCells(VTK_TETRA, cellArray);

  // Write file
  vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
    vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
  writer->SetFileName(filename.c_str());
#if VTK_MAJOR_VERSION <= 5
  writer->SetInput(unstructuredGrid);
#else
  writer->SetInputData(unstructuredGrid);
#endif
  writer->Write();

  return EXIT_SUCCESS;
}

This is the .vtu file.

<?xml version="1.0"?>
<VTKFile type="UnstructuredGrid" version="0.1" byte_order="LittleEndian" header_type="UInt32" compressor="vtkZLibDataCompressor">
  <UnstructuredGrid>
    <Piece NumberOfPoints="7"                    NumberOfCells="2"                   >
      <PointData>
      </PointData>
      <CellData>
      </CellData>
      <Points>
        <DataArray type="Float32" Name="Points" NumberOfComponents="3" format="appended" RangeMin="0"                    RangeMax="1.4142135624"         offset="0"                   />
      </Points>
      <Cells>
        <DataArray type="Int64" Name="connectivity" format="appended" RangeMin=""                     RangeMax=""                     offset="56"                  />
        <DataArray type="Int64" Name="offsets" format="appended" RangeMin=""                     RangeMax=""                     offset="108"                 />
        <DataArray type="UInt8" Name="types" format="appended" RangeMin=""                     RangeMax=""                     offset="152"                 />
      </Cells>
    </Piece>
  </UnstructuredGrid>
  <AppendedData encoding="base64">
   _AQAAAACAAABUAAAAGAAAAA==eJxjYEAGDfaobGz8hv1IYvux8QElFQn3AQAAAACAAABAAAAAFAAAAA==eJxjYIAAFijNCqXZGIgDAAMAABA=AQAAAACAAAAQAAAADgAAAA==eJxjYYAADigNAACQAA0=AQAAAACAAAACAAAACgAAAA==eJzj4gIAACAAFQ==
  </AppendedData>
</VTKFile>

Body:
I'm sorry. It's just a typo.

 vtkSmartPointer<vtkTetra> tetra2 =
  vtkSmartPointer<vtkTetra>::New();

  tetra2->GetPointIds()->SetId(0, 0);
  tetra2->GetPointIds()->SetId(1, 4);
  tetra2->GetPointIds()->SetId(2, 5);
  tetra2->GetPointIds()->SetId(3, 6);


来源: stackexchange

问:
Custom checkbox bootstrap toggle switch with text
I'm trying to achieve like below image but not get any result yet. I need a switch button with different text like Yes/No, Automatic/Custom, Check/Uncheck. I tried but not get same as below image.

View Demo Code :  http://discountwicedeals.com/toggle.html

答:
You can do this with jQuery.

Some awesome plugins can be found (example and download) here: https://simontabor.com/labs/toggles/.

If you like to search something else, search 'jQuery toggle buttons' on Google. I recommend to have a source with HTML and jQuery code. Otherwise you need to modify the code, which could be pain.

Related to the first link I gave you: https://simontabor.com/labs/toggles/, see this link: https://www.npmjs.com/package/jquery-toggles. At step 3 you can customize your toggle button.

Look at this:

```<code>// With options (defaults shown below)
$('.toggle').toggles({
  drag: true, // allow dragging the toggle between positions
  click: true, // allow clicking on the toggle
  text: {
    on: 'ON', // text for the ON position
    off: 'OFF' // and off
  },
  on: true, // is the toggle ON on init
  animate: 250, // animation time (ms)
  easing: 'swing', // animation transition easing function
  checkbox: null, // the checkbox to toggle (for use in forms)
  clicker: null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
  width: 50, // width used if not set in css
  height: 20, // height if not set in css
  type: 'compact' // if this is set to 'select' then the select style toggle will be used
});
</code>```

The piece of code which is called text: means you can set text for toggle ON and OFF. That's exactly what you need.

At last:

If you really, really want to have the same design as your link: you can get the same design by copy the script, try to make a total different page in your home directory and copy paste the html and javascript by pressing F12. You'll see you'll get the same design. From there on you can try to implement the design with the needed scripts to get the same design.

ContentLicense: CC BY-SA 3.0

Body:
You can do this with jQuery.

Some awesome plugins can be found (example and download) here: https://simontabor.com/labs/toggles/.

If you like to search something else, search 'jQuery toggle buttons' on Google. I recommend to have a source with HTML and jQuery code. Otherwise you need to modify the code, which could be pain.

Related to the first link I gave you: https://simontabor.com/labs/toggles/, see this link: https://www.npmjs.com/package/jquery-toggles. At step 3 you can customize your toggle button.

Look at this:

// With options (defaults shown below)
$('.toggle').toggles({
  drag: true, // allow dragging the toggle between positions
  click: true, // allow clicking on the toggle
  text: {
    on: 'ON', // text for the ON position
    off: 'OFF' // and off
  },
  on: true, // is the toggle ON on init
  animate: 250, // animation time (ms)
  easing: 'swing', // animation transition easing function
  checkbox: null, // the checkbox to toggle (for use in forms)
  clicker: null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
  width: 50, // width used if not set in css
  height: 20, // height if not set in css
  type: 'compact' // if this is set to 'select' then the select style toggle will be used
});

The piece of code which is called text: means you can set text for toggle ON and OFF. That's exactly what you need.

At last:

If you really, really want to have the same design as your link: you can get the same design by copy the script, try to make a total different page in your home directory and copy paste the html and javascript by pressing F12. You'll see you'll get the same design. From there on you can try to implement the design with the needed scripts to get the same design.


问:
Symfony (Doctrine) 2: Entity ManyToMany Relationship with itself
I have an entity "Product". A Product can be a "package" (boolean) which then consists of Products. A Product can be a part of many packages. As such, I need to map a ManyToMany relationship in Product with itself, so that I have $packageProducts in a mapping table with "package_id" and "product_id".

How do I define the ManyToMany relationship inside the "Product" entity to map to itself? I know you need to define your join table and you mappedColumn and inverseColumn, but I do not know exactly how to do this.

Current Product Entity (ManyToMany mapping not yet included):

```<code><?php

namespace LittleGiant\PortalBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation as Ser;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Product
 *
 * @ORM\Entity
 * @ORM\Table(name="products")
 * @Ser\ExclusionPolicy("all")
 */
class Product
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Ser\Expose
     */
    protected $id;

    /**
     * @var boolean
     *
     * @ORM\Column(name="package", type="boolean")
     * @Ser\Expose
     */
    protected $package;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active", type="boolean")
     * @Ser\Expose
     */
    protected $active;

    /**
     * @var string
     *
     * @ORM\Column(name="product_range", type="string", length=32)
     * @Ser\Expose
     */
    protected $range;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=128)
     * @Ser\Expose
     */
    protected $name;

    /**
     * @var text
     *
     * @ORM\Column(name="description", type="text")
     * @Ser\Expose
     */
    protected $description;

    /**
     * @var File
     *
     * @ORM\OneToOne(targetEntity="LittleGiant\PortalBundle\Entity\File", cascade={"remove","persist"})
     * @Ser\Expose
     **/
    protected $displayImage;

    /**
     * @var float
     *
     * @ORM\Column(name="price", type="float")
     * @Ser\Expose
     */
    protected $price;

    /**
     * @var Deliverable[]
     *
     * @ORM\OneToMany(targetEntity="LittleGiant\PortalBundle\Entity\Deliverable", mappedBy="product", cascade={"remove"})
     **/
    protected $deliverables;
}
</code>```

EDIT: When I add the following to my Product Entity

```<code>/**
 * @var Product[]
 *
 * @ORM\ManyToMany(targetEntity="LittleGiant\PortalBundle\Entity\Product", mappedBy="packageProducts")
 **/
protected $packages;

/**
 * @var Product[]
 *
 * @ORM\ManyToMany(targetEntity="LittleGiant\PortalBundle\Entity\Product", inversedBy="packages")
 **/
protected $packageProducts;
</code>```

I get a mapping table "product_product" with a single field "product_id". I need this to be "package_products" with fields "product_id", "package_id". How do I define this in the ORM?

答:
In reference to the docs (see http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-self-referencing):
I had to edit the "getFriendsWithMe" method to get friends for ALL users (the original user where the friends are added and vice versa: The "new" friends of the user should also display the original user as their friend):</p>

```<code>public function getFriendsWithMe()
{
    return new ArrayCollection(
        array_merge(array_merge($this->friendsWithMe->toArray(), $this->myFriends->toArray()))
    );
}
</code>```

Body:
I have an entity "Product". A Product can be a "package" (boolean) which then consists of Products. A Product can be a part of many packages. As such, I need to map a ManyToMany relationship in Product with itself, so that I have $packageProducts in a mapping table with "package_id" and "product_id".

How do I define the ManyToMany relationship inside the "Product" entity to map to itself? I know you need to define your join table and you mappedColumn and inverseColumn, but I do not know exactly how to do this.

Current Product Entity (ManyToMany mapping not yet included):

<?php

namespace LittleGiant\PortalBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation as Ser;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Product
 *
 * @ORM\Entity
 * @ORM\Table(name="products")
 * @Ser\ExclusionPolicy("all")
 */
class Product
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Ser\Expose
     */
    protected $id;

    /**
     * @var boolean
     *
     * @ORM\Column(name="package", type="boolean")
     * @Ser\Expose
     */
    protected $package;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active", type="boolean")
     * @Ser\Expose
     */
    protected $active;

    /**
     * @var string
     *
     * @ORM\Column(name="product_range", type="string", length=32)
     * @Ser\Expose
     */
    protected $range;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=128)
     * @Ser\Expose
     */
    protected $name;

    /**
     * @var text
     *
     * @ORM\Column(name="description", type="text")
     * @Ser\Expose
     */
    protected $description;

    /**
     * @var File
     *
     * @ORM\OneToOne(targetEntity="LittleGiant\PortalBundle\Entity\File", cascade={"remove","persist"})
     * @Ser\Expose
     **/
    protected $displayImage;

    /**
     * @var float
     *
     * @ORM\Column(name="price", type="float")
     * @Ser\Expose
     */
    protected $price;

    /**
     * @var Deliverable[]
     *
     * @ORM\OneToMany(targetEntity="LittleGiant\PortalBundle\Entity\Deliverable", mappedBy="product", cascade={"remove"})
     **/
    protected $deliverables;
}

EDIT: When I add the following to my Product Entity

/**
 * @var Product[]
 *
 * @ORM\ManyToMany(targetEntity="LittleGiant\PortalBundle\Entity\Product", mappedBy="packageProducts")
 **/
protected $packages;

/**
 * @var Product[]
 *
 * @ORM\ManyToMany(targetEntity="LittleGiant\PortalBundle\Entity\Product", inversedBy="packages")
 **/
protected $packageProducts;

I get a mapping table "product_product" with a single field "product_id". I need this to be "package_products" with fields "product_id", "package_id". How do I define this in the ORM?

Body:
In reference to the docs (see http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-self-referencing):
I had to edit the "getFriendsWithMe" method to get friends for ALL users (the original user where the friends are added and vice versa: The "new" friends of the user should also display the original user as their friend):

public function getFriendsWithMe()
{
    return new ArrayCollection(
        array_merge(array_merge($this->friendsWithMe->toArray(), $this->myFriends->toArray()))
    );
}


问:
Data not inserting in database when submitted
I've set up a form to insert data into a database. It's connected to it fine and can display records with no issues. However, when I want to insert data I click the submit button it removes it from the form but doesn't insert it into the db. I've tried rewriting it about 3 times now using 2 different databases but just can't figure out where I'm going on.</p>

```<code><html>
<head>
</head>

<body>
<form action="input.php" meathod="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>

<?php
if( isset($_POST['submit'])){

//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);

if($conn){
        echo 'connected';
    }
    else {
        die('failed to connect');
    }

$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";

mysql_query($sql,$conn);

mysqli_close($conn);
};
?>
</body>
</html>
</code>```

答:
you have written "meathod=post" instead of "method=post"
also I have changed

```<code>$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";
</code>```

to

```<code>$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
</code>```

this style much more better

```<code><html>
<head>
</head>

<body>
<form action="lol.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>

<?php
if( isset($_POST['submit'])){

//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);

if($conn){
        echo 'connected';
    }
    else {
        die('failed to connect');
    }

$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";

mysql_query($sql,$conn);

mysqli_close($conn);
};
?>
</body>
</html>
</code>```

Body:
I've set up a form to insert data into a database. It's connected to it fine and can display records with no issues. However, when I want to insert data I click the submit button it removes it from the form but doesn't insert it into the db. I've tried rewriting it about 3 times now using 2 different databases but just can't figure out where I'm going on.

<form action="input.php" meathod="post">
Username: <input type="text" name="username">

Password: <input type="text" name="password">

<input type="submit" name="submit">
</form>

<?php
if( isset($_POST['submit'])){

//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);

if($conn){
        echo 'connected';
    }
    else {
        die('failed to connect');
    }

$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";

mysql_query($sql,$conn);

mysqli_close($conn);
};
?>

Body:
you have written "meathod=post" instead of "method=post"
also I have changed

$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";

to

$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";

this style much more better

<html>
<head>
</head>

<body>
<form action="lol.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>

<?php
if( isset($_POST['submit'])){

//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);

if($conn){
        echo 'connected';
    }
    else {
        die('failed to connect');
    }

$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";

mysql_query($sql,$conn);

mysqli_close($conn);
};
?>
</body>
</html>


问:
Will the ternary operator be executed on every digest?
If I use the ternary operator in my Angular.js view will it be executed on every digest(like functions) or only if the variables necessary for the decision are changed?

Example:

```<code><div>{{ui.isTrue ? "foo" : "bar"}}</div>
</code>```

or:

```<code><div ng-bind="ui.isTrue ? 'foo' : 'bar'"></div>
</code>```

Would it be executed on every digest or only when is ui.IsTrue changed?

答:
I made a fiddle to test this myself.

http://jsfiddle.net/xuvzzay8/4/

HTML:

```<code><div ng-controller="MyCtrl">
    {{bool ? ternaryTrue() : ternaryFalse() }}<br/>

    {{bool}}<br/>
    <button ng-click="bool = !bool">Toggle Bool</button>
    {{a}}
    <div style="background-color:red" ng-mouseover="hover()">
        Hover here to trigger digest
    </div>
</div>
</code>```

JS:

```<code>var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.bool = true;
    $scope.a = 0;
    $scope.ternaryTrue = function(){
        console.log("ternary executed on true");
    }
    $scope.ternaryFalse = function(){
        $scope.a++; //creates an infinite digest loop
        console.log("ternary executed on false");
    }
    $scope.hover = function(){
        console.log("Hover");
    }
}
</code>```

The result is that the ternary operator is executed on EVERY digest.

Edit:
An infinite digest loop can easily be created with this. As soon as something in the $scope will be changed during the function which is called by the ternary operator another digest will be started wich executes the function of the  ternary operator again etc.

Body:
If I use the ternary operator in my Angular.js view will it be executed on every digest(like functions) or only if the variables necessary for the decision are changed?

Example:

{{ui.isTrue ? "foo" : "bar"}}

or:

Would it be executed on every digest or only when is ui.IsTrue changed?

Body:
I made a fiddle to test this myself.

http://jsfiddle.net/xuvzzay8/4/

HTML:

<div ng-controller="MyCtrl">
    {{bool ? ternaryTrue() : ternaryFalse() }}<br/>

    {{bool}}<br/>
    <button ng-click="bool = !bool">Toggle Bool</button>
    {{a}}
    <div style="background-color:red" ng-mouseover="hover()">
        Hover here to trigger digest
    </div>
</div>

JS:

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.bool = true;
    $scope.a = 0;
    $scope.ternaryTrue = function(){
        console.log("ternary executed on true");
    }
    $scope.ternaryFalse = function(){
        $scope.a++; //creates an infinite digest loop
        console.log("ternary executed on false");
    }
    $scope.hover = function(){
        console.log("Hover");
    }
}

The result is that the ternary operator is executed on EVERY digest.

Edit:
An infinite digest loop can easily be created with this. As soon as something in the $scope will be changed during the function which is called by the ternary operator another digest will be started wich executes the function of the  ternary operator again etc.


问:
Create a JSON document, elasticsearch
I will quote part of the documentation of 'www.elastic.co' concerning the creation of a JSON document:

index a simple customer document into the customer index, "external" type, with an ID of 1 as follows :
  Our JSON document: { "name": "John Doe" }

```<code>curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '{"name": "John Doe"}'
</code>```

I removed the quotes from the url,

curl -XPUT localhost:9200/customer/external/1?pretty -d '{"name": "John Doe"}'

the result is an error

{ "error" : "Content-Type header [application/x-www-formurlencoded] is not supported", "status" : 406}

答:
Content type is missing in the curl query.</p>

```<code>curl -XPUT -H "Content-Type: application/json" 'localhost:9200/customer/external/1?pretty' -d '{"name": "John Doe"}'
</code>```

Title: Create a JSON document, elasticsearch

Body:
I will quote part of the documentation of 'www.elastic.co' concerning the creation of a JSON document:

index a simple customer document into the customer index, "external" type, with an ID of 1 as follows :
  Our JSON document: { "name": "John Doe" }

curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '{"name": "John Doe"}'

I removed the quotes from the url,

curl -XPUT localhost:9200/customer/external/1?pretty -d '{"name": "John Doe"}'

the result is an error

{ "error" : "Content-Type header [application/x-www-formurlencoded] is not supported", "status" : 406}

Body:
Content type is missing in the curl query.

curl -XPUT -H "Content-Type: application/json" 'localhost:9200/customer/external/1?pretty' -d '{"name": "John Doe"}'


问:
custom button always too big
I am trying to create a custom button with its shape being as similar as possible to the one of the Android default button. The problem is, no matter how much I reduce the height, it doesn't go below a certain value:

image of custom and default button

The text size of both buttons is 14sp. Here the xlm-code for my custom button:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <padding
        android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp" />
    <solid
        android:color="@color/colorBtnActive" />

    <corners android:radius="2dp" />

    <size
        android:height="16dp"/>

</shape>
</code>```

So even if I write <size android:height="50dp"/>, the button looks the same.

Here part of the xlm-file of the activity:

```<code><Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_selector_selected"
    android:text="custom"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:text="default"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.501" />
</code>```

What am I doing wrong? Thank you!

EDIT:
So upon your suggestions I removed the size-tag.Sadly, the button still looks the same. However, I noticed that the buttoms have the same size, the default button just looks smaller: screenshot

How can I achieve this effect?

答:
when you set any Background to A Button its hight will increase check below test cases

when you set both button background the button size are same

Try this you also need to set android:background to your default button like this

```<code>    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:background="@drawable/demo"
        android:text="custom"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:background="@color/colorAccent"
        android:text="default"
         />
</LinearLayout>
</code>```

OUTPUT

without setting custom background to your custom button

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:text="custom"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:background="@color/colorAccent"
        android:text="default"
         />
</LinearLayout>
</code>```

Output

EDIT Android Button has default padding.

check the default Size of button

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:background="@drawable/demo"
        android:text="custom"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:text="default"
         />
</LinearLayout>
</code>```

OUTPUT

Title: custom button always too big

Body:
I am trying to create a custom button with its shape being as similar as possible to the one of the Android default button. The problem is, no matter how much I reduce the height, it doesn't go below a certain value:

image of custom and default button

The text size of both buttons is 14sp. Here the xlm-code for my custom button:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <padding
        android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp" />
    <solid
        android:color="@color/colorBtnActive" />

    <corners android:radius="2dp" />

    <size
        android:height="16dp"/>

</shape>

So even if I write <size android:height="50dp"/>, the button looks the same.

Here part of the xlm-file of the activity:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_selector_selected"
    android:text="custom"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:text="default"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.501" />

What am I doing wrong? Thank you!

EDIT:
So upon your suggestions I removed the size-tag.Sadly, the button still looks the same. However, I noticed that the buttoms have the same size, the default button just looks smaller: screenshot

How can I achieve this effect?

Body:
when you set any Background to A Button its hight will increase check below test cases

when you set both button background the button size are same

Try this you also need to set android:background to your default button like this

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:background="@drawable/demo"
        android:text="custom"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:background="@color/colorAccent"
        android:text="default"
         />
</LinearLayout>

OUTPUT

without setting custom background to your custom button

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:text="custom"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:background="@color/colorAccent"
        android:text="default"
         />
</LinearLayout>

Output

EDIT Android Button has default padding.

check the default Size of button

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:background="@drawable/demo"
        android:text="custom"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:text="default"
         />
</LinearLayout>

OUTPUT


问:
How to add the local Library to product flavour in gradle latest version 4.1
I have a library in libs folder.I need to add that library to specific product flavour. previously we have Compile but latest version it is deprecated and added "API"

Previously:

```<code>dependencies {
....
market1Compile project(path: ':lib', configuration: 'market1Release')
market2Compile project(path: ':lib', configuration: 'market2Release')
</code>```

}

Now:

```<code>api files('libs/AF-Android-SDK-v2.3.1.17.jar')
</code>```

How add that to particular flavor. any one help me!!

答:
Put your local library inside the dependencies.
Like this:</p>

```<code>dependencies {
   compile files('your_library.jar')
}
</code>```

Body:
I have a library in libs folder.I need to add that library to specific product flavour. previously we have Compile but latest version it is deprecated and added "API"

Previously:

dependencies {
....
market1Compile project(path: ':lib', configuration: 'market1Release')
market2Compile project(path: ':lib', configuration: 'market2Release')

}

Now:

api files('libs/AF-Android-SDK-v2.3.1.17.jar')

How add that to particular flavor. any one help me!!

Body:
Put your local library inside the dependencies.
Like this:

dependencies {
   compile files('your_library.jar')
}


问:
Onclick javascript function doesn't work on first click
I've wrote a code to hide/show a div by clicking on a "p" element, but at first click nothing happens.

Only from 2nd click the code works as expected.
I've read some similar questions and I've understood that it's probably a style problem.

So I've tried to change style (without really knowing what I was doing) but I wasn't lucky.

I've also another problem: the "p" element sometimes covers an input and I've not understood how to have it on the bottom right of the div but below every other element.

```<code><!DOCTYPE html>
<html>
    <head>
        <style>
        .Class1 {
            position:relative;
            display: inline-block;
            width: 48%;
            margin: 3px;
            border: 3px solid #CCC;
        }
        .Class2 {
            position:absolute;
            bottom:0;
            right:0;
            border: 1px solid #CCC;
            margin:1px;
            background: #FFC;
        }
        .Fields {
            clear: both;
            border: 1px solid #CCC;
            display: inline-block;
            margin:3px;
        }
        .H_p {
            border: 1px solid #CCC;
            display: inline-block;
        }
        .Opt {
            border: 1px solid #CCC;
            display: none;
        }
        </style>
    </head>
    <body>
        <h2>My test</h2>
            <?php
            $Divs = array('Div1'=>'Class1',
                'Div2'=>'Class1',
                'Div3'=>'Class1',
                'Div4'=>'Class1',
                'Div5'=>'Class1');
            $AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
            foreach ($Divs as $Name=>$Class){
                echo '
                <div class="'.$Class.'">';
                echo $Name.'<br/>';
                foreach ($AskToShow as $I_Name=>$Id){
                    echo '
                        <label>'.$I_Name.'</label>
                            <input type="text" id="'.$Id.'" class="Fields"/>';
                }
                echo '
                    <p id="Btn_Opt'.$Name.'" class="Class2" >Mostra campi opzionali</p>';
                echo '
                        <div id=Opt'.$Name.' name="Opt'.$Name.'" class="Opt" >';
                foreach ($AskToShow as $H_Name=>$Id){
                    echo'
                            <p id="H_'.$Id.'" class="H_p">'.$H_Name.'</p>';
                }
                echo '
                        </div>';
                echo '
                </div>';
            }
            ?>
        <script>
    var MyClass = document.getElementsByClassName("Class2");

    var myFunction = function() {
        var SenderId = this.id;
        var SubId = SenderId.substring(SenderId.indexOf('_')+1)
        var SubSH = document.getElementById(SubId);
        if (SubSH.style.display == 'none'){
            SubSH.style.display = 'inline-block';
        }else{
            SubSH.style.display = 'none';
        }
    };
    for (var i = 0; i < MyClass.length; i++) {
        MyClass[i].addEventListener('click', myFunction, false);
    }
        </script>
    </body>
</html>
</code>```

答:
Please find the working code below</p>

```<code><!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
    position:relative;
    display: inline-block;
    width: 48%;
    margin: 3px;
    border: 3px solid #CCC;
}
.Class2 {
    position:relative;
    bottom:0;
    right:0;
    border: 1px solid #CCC;
    margin:1px;
    background: #FFC;
    display: inline-block;
    float:right;
}
.Fields {
    clear: both;
    border: 1px solid #CCC;
    display: inline-block;
    margin:3px;
}
.H_p {
    border: 1px solid #CCC;
    display: inline-block;
}
.Opt {
    border: 1px solid #CCC;
    display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs      = array(
    'Div1' => 'Class1',
    'Div2' => 'Class1',
    'Div3' => 'Class1',
    'Div4' => 'Class1',
    'Div5' => 'Class1'
);
$AskToShow = array(
    "Field1" => "1.1.1",
    "Field2" => "1.2.1",
    "Field3" => "1.3.1"
);
foreach ($Divs as $Name => $Class) {
    echo '
    <div class="' . $Class . '">';
    echo $Name . '<br/>';
    foreach ($AskToShow as $I_Name => $Id) {
        echo '
            <label>' . $I_Name . '</label>
                <input type="text" id="' . $Id . '" class="Fields"/>';
    }

    echo '
            <div id=Opt' . $Name . ' name="Opt' . $Name . '" class="Opt" >';
    foreach ($AskToShow as $H_Name => $Id) {
        echo '
                <p id="H_' . $Id . '" class="H_p">' . $H_Name . '</p>';
    }
    echo '
            </div>';
    echo '
        <div style="clear:both;"></div>';
    echo '
        <p id="Btn_Opt' . $Name . '" class="Class2" >Mostra campi opzionali</p>';
    echo '
    </div>';
}
?>
<script>
    var MyClass = document.getElementsByClassName("Class2");

    var myFunction = function() {
        var SenderId = this.id;
        var SubId = SenderId.substring(SenderId.indexOf('_')+1)
        var SubSH = document.getElementById(SubId);
        if (window.getComputedStyle(SubSH, null).display == 'none'){
                SubSH.style.display = 'inline-block';
        } else {
                SubSH.style.display = 'none';
        }
    };
    for (var i = 0; i < MyClass.length; i++) {
        MyClass[i].addEventListener('click', myFunction, false);
    }
</script>
</body>
</html>
</code>```

Body:
I've wrote a code to hide/show a div by clicking on a "p" element, but at first click nothing happens.

Only from 2nd click the code works as expected.
I've read some similar questions and I've understood that it's probably a style problem.

So I've tried to change style (without really knowing what I was doing) but I wasn't lucky.

I've also another problem: the "p" element sometimes covers an input and I've not understood how to have it on the bottom right of the div but below every other element.

<!DOCTYPE html>

My test

            <?php
            $Divs = array('Div1'=>'Class1',
                'Div2'=>'Class1',
                'Div3'=>'Class1',
                'Div4'=>'Class1',
                'Div5'=>'Class1');
            $AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
            foreach ($Divs as $Name=>$Class){
                echo '

';
                echo $Name.'
';
                foreach ($AskToShow as $I_Name=>$Id){
                    echo '
                        '.$I_Name.'
                            <input type="text" id="'.$Id.'" class="Fields"/>';
                }
                echo '

Mostra campi opzionali
';
                echo '

';
                foreach ($AskToShow as $H_Name=>$Id){
                    echo'

'.$H_Name.'
';
                }
                echo '

';
                echo '

';
            }
            ?>

Body:
Please find the working code below

<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
    position:relative;
    display: inline-block;
    width: 48%;
    margin: 3px;
    border: 3px solid #CCC;
}
.Class2 {
    position:relative;
    bottom:0;
    right:0;
    border: 1px solid #CCC;
    margin:1px;
    background: #FFC;
    display: inline-block;
    float:right;
}
.Fields {
    clear: both;
    border: 1px solid #CCC;
    display: inline-block;
    margin:3px;
}
.H_p {
    border: 1px solid #CCC;
    display: inline-block;
}
.Opt {
    border: 1px solid #CCC;
    display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs      = array(
    'Div1' => 'Class1',
    'Div2' => 'Class1',
    'Div3' => 'Class1',
    'Div4' => 'Class1',
    'Div5' => 'Class1'
);
$AskToShow = array(
    "Field1" => "1.1.1",
    "Field2" => "1.2.1",
    "Field3" => "1.3.1"
);
foreach ($Divs as $Name => $Class) {
    echo '
    <div class="' . $Class . '">';
    echo $Name . '<br/>';
    foreach ($AskToShow as $I_Name => $Id) {
        echo '
            <label>' . $I_Name . '</label>
                <input type="text" id="' . $Id . '" class="Fields"/>';
    }

    echo '
            <div id=Opt' . $Name . ' name="Opt' . $Name . '" class="Opt" >';
    foreach ($AskToShow as $H_Name => $Id) {
        echo '
                <p id="H_' . $Id . '" class="H_p">' . $H_Name . '</p>';
    }
    echo '
            </div>';
    echo '
        <div style="clear:both;"></div>';
    echo '
        <p id="Btn_Opt' . $Name . '" class="Class2" >Mostra campi opzionali</p>';
    echo '
    </div>';
}
?>
<script>
    var MyClass = document.getElementsByClassName("Class2");

    var myFunction = function() {
        var SenderId = this.id;
        var SubId = SenderId.substring(SenderId.indexOf('_')+1)
        var SubSH = document.getElementById(SubId);
        if (window.getComputedStyle(SubSH, null).display == 'none'){
                SubSH.style.display = 'inline-block';
        } else {
                SubSH.style.display = 'none';
        }
    };
    for (var i = 0; i < MyClass.length; i++) {
        MyClass[i].addEventListener('click', myFunction, false);
    }
</script>
</body>
</html>


答:
The thing is that when you do SubSH.style.display you are checking only inline style so something which is inn <your-tag style='...'/> but you have it in your stylesheet so it is not accessible by this method. try to change your function a bit - for example

```<code>var myFunction = function() {
    var SenderId = this.id;
    var SubId = SenderId.substring(SenderId.indexOf('_')+1)
    var SubSH = document.getElementById(SubId);
    var style = window.getComputedStyle(SubSH);
    if (style.display == 'none'){
        SubSH.style.display = 'inline-block';
    }else{
        SubSH.style.display = 'none';
    }
};
</code>```

by using window.getComputedStyle(SubSH); you are checking style which is aware of all your classes and csses

Title: Onclick javascript function doesn't work on first click

Body:
The thing is that when you do SubSH.style.display you are checking only inline style so something which is inn <your-tag style='...'/> but you have it in your stylesheet so it is not accessible by this method. try to change your function a bit - for example

var myFunction = function() {
    var SenderId = this.id;
    var SubId = SenderId.substring(SenderId.indexOf('_')+1)
    var SubSH = document.getElementById(SubId);
    var style = window.getComputedStyle(SubSH);
    if (style.display == 'none'){
        SubSH.style.display = 'inline-block';
    }else{
        SubSH.style.display = 'none';
    }
};

by using window.getComputedStyle(SubSH); you are checking style which is aware of all your classes and csses


问:
Is there a simple way to get a object by _id in Kotlin?
I'm a beginner of Kotlin, I hope to get a object by _id in the following data structure, so I write the fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long)... which is a traditional method.

But I think the fun is too complex, is there a simple way do that? such as use Lambda expression.

```<code>class UIMain : AppCompatActivity() {

    data class BluetoothDef(val Status:Boolean=false)
    data class WiFiDef(val Name:String, val Status:Boolean=false)

    data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
    )

    data class MDetailsList(val mListMetail: MutableList<MDetail>)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)

        var aMDetailsList=MDetailsList(mListMetail)

        var c=getMDetailByID(aMDetailsList,5L)

    }

    fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long):MDetail?{
        var aMDetail: MDetail?=null

        var a=aMDetailsList.mListMetail

        for (b in a){
            if (b._id==_id){
                aMDetail=b
            }
        }

        return aMDetail

    }

}
</code>```

答:
There is a simpler way using lambdas, indeed. You could replace your function code by:

```<code>fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long): MDetail? {
    return aMDetailsList.mListMetail.filter { it._id == _id }.lastOrNull()
}
</code>```

It will, like your implementation did, return the last matching element or null if there is none.

Body:
I'm a beginner of Kotlin, I hope to get a object by _id in the following data structure, so I write the fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long)... which is a traditional method.

But I think the fun is too complex, is there a simple way do that? such as use Lambda expression.

class UIMain : AppCompatActivity() {

    data class BluetoothDef(val Status:Boolean=false)
    data class WiFiDef(val Name:String, val Status:Boolean=false)

    data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
    )

    data class MDetailsList(val mListMetail: MutableList<MDetail>)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)

        var aMDetailsList=MDetailsList(mListMetail)

        var c=getMDetailByID(aMDetailsList,5L)

    }

    fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long):MDetail?{
        var aMDetail: MDetail?=null

        var a=aMDetailsList.mListMetail

        for (b in a){
            if (b._id==_id){
                aMDetail=b
            }
        }

        return aMDetail

    }

}

Body:
There is a simpler way using lambdas, indeed. You could replace your function code by:

fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long): MDetail? {
    return aMDetailsList.mListMetail.filter { it._id == _id }.lastOrNull()
}

It will, like your implementation did, return the last matching element or null if there is none.


问:
Getting NodaTime.Serialization.JsonNet to work with a custom date format
I'm trying to deserialize a JSON, which contains dates in the format 2017-10-26 13:32:11 Etc/GMT. NodaTime seems to support this when combined with Json.NET and NodaTime.Serialization.JsonNet. I found some info here on StackOverflow that made me get this working, using only NodaTime:

```<code>var date = "2017-10-26 13:32:11 Etc/GMT";

var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
    "yyyy'-'MM'-'dd HH':'mm':'ss z",
    DateTimeZoneProviders.Tzdb
);

var result = pattern.Parse(date);
</code>```

However when extending this example into deserializing a JSON using the other two packages, I can't get it to work. From reading documentation and other resources, I believe this is supposed to work:

```<code>public class DateObj
{
    public ZonedDateTime Date { get; set; }
}

void Main()
{
    var date = "2017-10-26 13:32:11 Etc/GMT";
    var json = $"{{\"Date\": \"{date}\"}}";

    var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
        "yyyy-MM-dd HH:mm:ss z",
        DateTimeZoneProviders.Serialization
    );

    var settings = new JsonSerializerSettings();
    settings.ConfigureForNodaTime(pattern.ZoneProvider);
    var dateObj = JsonConvert.DeserializeObject<DateObj>(json, settings);
}
</code>```

But it throws an exception on the last line saying The value string does not match a quoted string in the pattern. Value being parsed: '2017-10-26^ 13:32:11 Etc/GMT'. (^ indicates error position.). What am I doing wrong?

答:
Currently, you're creating a specific ZonedDateTime pattern - but you're not actually telling Json.NET about that pattern anywhere.

If this is the only Noda Time type that you need to use, I'd advise that you don't call ConfigureForNodaTime at all - because that will configure a ZonedDateTime converter with the wrong pattern. We have code internal to NodaTime.Serialization.JsonNet to replace a converter, but that's not exposed at the moment. (Maybe we should do that...)

It's simple to just create a single converter though, and configure the settings for that:

```<code>var settings = new JsonSerializerSettings
{
    DateParseHandling = DateParseHandling.None,
    Converters = { new NodaPatternConverter<ZonedDateTime>(pattern) }
};
</code>```

Here's what that looks like in the context of a full program. Note that I'm explicitly using DateTimeZoneProviders.Tzdb here, rather than DateTimeZoneProviders.Serialization, given that you definitely have TZDB identifiers:

```<code>using Newtonsoft.Json;
using NodaTime;
using NodaTime.Serialization.JsonNet;
using NodaTime.Text;
using System;

public class DateObj
{
    public ZonedDateTime Date { get; set; }
}

class Program
{
    static void Main()
    {
        var date = "2017-10-26 13:32:11 Etc/GMT";
        var json = $"{{\"Date\": \"{date}\"}}";

        var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
            "yyyy-MM-dd HH:mm:ss z",
            DateTimeZoneProviders.Tzdb
        );

        var settings = new JsonSerializerSettings
        {
            DateParseHandling = DateParseHandling.None,
            Converters = { new NodaPatternConverter<ZonedDateTime>(pattern) }
        };
        var dateObj = JsonConvert.DeserializeObject<DateObj>(json, settings);
        Console.WriteLine(dateObj.Date);
    }
}
</code>```

Body:
I'm trying to deserialize a JSON, which contains dates in the format 2017-10-26 13:32:11 Etc/GMT. NodaTime seems to support this when combined with Json.NET and NodaTime.Serialization.JsonNet. I found some info here on StackOverflow that made me get this working, using only NodaTime:

var date = "2017-10-26 13:32:11 Etc/GMT";

var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
    "yyyy'-'MM'-'dd HH':'mm':'ss z",
    DateTimeZoneProviders.Tzdb
);

var result = pattern.Parse(date);

However when extending this example into deserializing a JSON using the other two packages, I can't get it to work. From reading documentation and other resources, I believe this is supposed to work:

public class DateObj
{
    public ZonedDateTime Date { get; set; }
}

void Main()
{
    var date = "2017-10-26 13:32:11 Etc/GMT";
    var json = $"{{\"Date\": \"{date}\"}}";

    var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
        "yyyy-MM-dd HH:mm:ss z",
        DateTimeZoneProviders.Serialization
    );

    var settings = new JsonSerializerSettings();
    settings.ConfigureForNodaTime(pattern.ZoneProvider);
    var dateObj = JsonConvert.DeserializeObject<DateObj>(json, settings);
}

But it throws an exception on the last line saying The value string does not match a quoted string in the pattern. Value being parsed: '2017-10-26^ 13:32:11 Etc/GMT'. (^ indicates error position.). What am I doing wrong?

Body:
Currently, you're creating a specific ZonedDateTime pattern - but you're not actually telling Json.NET about that pattern anywhere.

If this is the only Noda Time type that you need to use, I'd advise that you don't call ConfigureForNodaTime at all - because that will configure a ZonedDateTime converter with the wrong pattern. We have code internal to NodaTime.Serialization.JsonNet to replace a converter, but that's not exposed at the moment. (Maybe we should do that...)

It's simple to just create a single converter though, and configure the settings for that:

var settings = new JsonSerializerSettings
{
    DateParseHandling = DateParseHandling.None,
    Converters = { new NodaPatternConverter<ZonedDateTime>(pattern) }
};

Here's what that looks like in the context of a full program. Note that I'm explicitly using DateTimeZoneProviders.Tzdb here, rather than DateTimeZoneProviders.Serialization, given that you definitely have TZDB identifiers:

using Newtonsoft.Json;
using NodaTime;
using NodaTime.Serialization.JsonNet;
using NodaTime.Text;
using System;

public class DateObj
{
    public ZonedDateTime Date { get; set; }
}

class Program
{
    static void Main()
    {
        var date = "2017-10-26 13:32:11 Etc/GMT";
        var json = $"{{\"Date\": \"{date}\"}}";

        var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
            "yyyy-MM-dd HH:mm:ss z",
            DateTimeZoneProviders.Tzdb
        );

        var settings = new JsonSerializerSettings
        {
            DateParseHandling = DateParseHandling.None,
            Converters = { new NodaPatternConverter<ZonedDateTime>(pattern) }
        };
        var dateObj = JsonConvert.DeserializeObject<DateObj>(json, settings);
        Console.WriteLine(dateObj.Date);
    }
}


问:
EXCEL/VBA: converting boolean text to checks
I've exported data from access to excel.

Some columns where boolean values, and excel displays them as "true" or "false".

Not very readable, so I want to change the false values to blank, and the true values to "x".

Here is the VBA code I wrote:

```<code>Sub BoolToCheck()
Dim myRow As Integer
Dim myCol As Integer

For myCol = 7 To 38
    For myRow = 2 To 458

    Select Case Cells(myRow, myCol)
        Case "TRUE"
         Cells(myRow, myCol) = "x"
        Case "FALSE"
         Cells(myRow, myCol) = ""
    End Select

    DoEvents
    Next myRow
Next myCol
End Sub
</code>```

but it doesn't work; when I'm running it step by step, neither case happens.

tried switching from "true" and "false" to true and false, but it didn't change anything.

Anyone knows why this isn't working ?  I don't get it...

答:
changed from

```<code>Select Case Cells(myRow, myCol)
</code>```

to

```<code>Select Case Cells(myRow, myCol).text
</code>```

works now.

ContentLicense: CC BY-SA 2.5

Body:
I've exported data from access to excel.

Some columns where boolean values, and excel displays them as "true" or "false".

Not very readable, so I want to change the false values to blank, and the true values to "x".

Here is the VBA code I wrote:

Sub BoolToCheck()
Dim myRow As Integer
Dim myCol As Integer

For myCol = 7 To 38
    For myRow = 2 To 458

    Select Case Cells(myRow, myCol)
        Case "TRUE"
         Cells(myRow, myCol) = "x"
        Case "FALSE"
         Cells(myRow, myCol) = ""
    End Select

    DoEvents
    Next myRow
Next myCol
End Sub

but it doesn't work; when I'm running it step by step, neither case happens.

tried switching from "true" and "false" to true and false, but it didn't change anything.

Anyone knows why this isn't working ?  I don't get it...

Body:
changed from

Select Case Cells(myRow, myCol)

to

Select Case Cells(myRow, myCol).text

works now.


问:
Can I change the default return type int in C?
Is there have any way that I can change the bit width of int in 64bit machine?

On a 64bit machine, int is 32bit and long is 64bit.

The next program will core, because the getenv function default returns int. But the char* is 64bit. I want to change the int bit width, or change the default return type to long:

```<code>#include <stdio.h>

int main(){
    printf(getenv("HOME"));
}
</code>```

答:
because the getenv function default returns int

It does not. This is a C standard lib function defined as (C11 7.22.4.6):

```<code>#include <stdlib.h>
char *getenv(const char *name);
</code>```

However, if you compile your code with an old, obsolete C compiler and fail to include stdlib.h, the return type will default to int. This was a design mistake of the C language which was fixed 18 years ago.

So the only reason why you would get getenv to return int would be if you have a bug in your program as you failed to include the relevant header stdlib.h and you are using an old, outdated compiler.

Fix this by adding #include <stdlib.h> and then also ensure that you are using a modern compiler1).

1) gcc versions older than 5.x do for example default to the old, obsolete non-standard -std=gnu90. If you are using an old version of gcc, you must compile with one of the following options: -std=c11 (preferred if supported) or -std=c99.

Body:
Is there have any way that I can change the bit width of int in 64bit machine?

On a 64bit machine, int is 32bit and long is 64bit.

The next program will core, because the getenv function default returns int. But the char* is 64bit. I want to change the int bit width, or change the default return type to long:

#include <stdio.h>

int main(){
    printf(getenv("HOME"));
}

Body:
because the getenv function default returns int

It does not. This is a C standard lib function defined as (C11 7.22.4.6):

#include <stdlib.h>
char *getenv(const char *name);

However, if you compile your code with an old, obsolete C compiler and fail to include stdlib.h, the return type will default to int. This was a design mistake of the C language which was fixed 18 years ago.

So the only reason why you would get getenv to return int would be if you have a bug in your program as you failed to include the relevant header stdlib.h and you are using an old, outdated compiler.

Fix this by adding #include <stdlib.h> and then also ensure that you are using a modern compiler1).

1) gcc versions older than 5.x do for example default to the old, obsolete non-standard -std=gnu90. If you are using an old version of gcc, you must compile with one of the following options: -std=c11 (preferred if supported) or -std=c99.


问:
Get access to $item->getNumberOfDownloadsUsed() function on Download.php
I need to get the number of downloads bought and used, that's two methods that are available on $item object. But I can't instance $item on the file that I'm working:

app/code/core/Mage/Downloadable/Helper/Download.php

On this file, I need to retrieve the number of boughts and used of the download purchased.

I'm also trying to get the order ID or at least the link hash to identify that number of boughts/used downloads with the unique id of the purchase.

For example, I try this:

```<code>Mage::getModel('downloadable/link_purchased_item')
            ->load($this->getOrderItem()->getOrder()->getId(), 'order_id');
</code>```

But $this->getOrderItem() is not available on Download.php file. I was trying this:

```<code>Mage::getModel('downloadable/link_purchased_item')->getCollection()
            ->addFieldToFilter('order_item_id', $this->getOrderItem()->getId());
</code>```

But obviously getOrderItem() is unavailable.

Fatal error: Call to undefined method Mage_Downloadable_Helper_Download::getOrderItem() in /[...]/app/code/core/Mage/Downloadable/Helper/Download.php on line 135

But I'm able to use the customer singleton to retrieve client data like this:

```<code>$cliente = Mage::getSingleton('customer/session')->getCustomer();
</code>```

So on this file I'm able to access others methods, but I'm unable to get the following details:

Number of downloads bought

Number of downloads used

Order ID or Link hash ID.

So please, I'm requesting how to get the current order instance and / or the current link instance, on the Download.php related with the file downloading.

Thank you!

答:
You are doing it wrong, you can not get any object like this $this->getOrderItem() without set/declaring them. As you are trying to get order_id and item_id in the helper, which you are using on a custom page redirected from customer downloadable products. Here is what you have to do

Step - 1

From customer My Downloadable products, in the redirect url you have to pass that products order_id and item_id as parameter. You can get them from below code

```<code>$orderId = $_item->getPurchased()->getOrderId();
$itemId = $_item->getId();
</code>```

Step -2

Now in your template file while using your helper function pass this order_id and item_id to method parameter.  Like below code

```<code>$orderId = $this->getRequest()->getParam('order_param');
$itemId = $this->getRequest()->getParam('item_param');

//Your helper function
Mage::helper('your_helper')->yourMethod($orderId, $itemId);
</code>```

Step - 3

In your helper file you can use below code

```<code>public function yourMethod($orderId, $itemId)
{
    $linkPurchasedItem = Mage::getModel('downloadable/link_purchased_item')
            ->load($orderItem, 'order_id');

    $LinkPurchaseOrderItemId = Mage::getModel('downloadable/link_purchased_item')->getCollection()
            ->addFieldToFilter('order_item_id', $itemId);
}
</code>```

Note: Do not make any changes in core files, instead override them

Body:
I need to get the number of downloads bought and used, that's two methods that are available on $item object. But I can't instance $item on the file that I'm working:

app/code/core/Mage/Downloadable/Helper/Download.php

On this file, I need to retrieve the number of boughts and used of the download purchased.

I'm also trying to get the order ID or at least the link hash to identify that number of boughts/used downloads with the unique id of the purchase.

For example, I try this:

Mage::getModel('downloadable/link_purchased_item')
            ->load($this->getOrderItem()->getOrder()->getId(), 'order_id');

But $this->getOrderItem() is not available on Download.php file. I was trying this:

Mage::getModel('downloadable/link_purchased_item')->getCollection()
            ->addFieldToFilter('order_item_id', $this->getOrderItem()->getId());

But obviously getOrderItem() is unavailable.

Fatal error: Call to undefined method Mage_Downloadable_Helper_Download::getOrderItem() in /[...]/app/code/core/Mage/Downloadable/Helper/Download.php on line 135

But I'm able to use the customer singleton to retrieve client data like this:

$cliente = Mage::getSingleton('customer/session')->getCustomer();

So on this file I'm able to access others methods, but I'm unable to get the following details:

Number of downloads bought

Number of downloads used

Order ID or Link hash ID.

So please, I'm requesting how to get the current order instance and / or the current link instance, on the Download.php related with the file downloading.

Thank you!

Body:
You are doing it wrong, you can not get any object like this $this->getOrderItem() without set/declaring them. As you are trying to get order_id and item_id in the helper, which you are using on a custom page redirected from customer downloadable products. Here is what you have to do

Step - 1

From customer My Downloadable products, in the redirect url you have to pass that products order_id and item_id as parameter. You can get them from below code

$orderId = $_item->getPurchased()->getOrderId();
$itemId = $_item->getId();

Step -2

Now in your template file while using your helper function pass this order_id and item_id to method parameter.  Like below code

$orderId = $this->getRequest()->getParam('order_param');
$itemId = $this->getRequest()->getParam('item_param');

//Your helper function
Mage::helper('your_helper')->yourMethod($orderId, $itemId);

Step - 3

In your helper file you can use below code

public function yourMethod($orderId, $itemId)
{
    $linkPurchasedItem = Mage::getModel('downloadable/link_purchased_item')
            ->load($orderItem, 'order_id');

    $LinkPurchaseOrderItemId = Mage::getModel('downloadable/link_purchased_item')->getCollection()
            ->addFieldToFilter('order_item_id', $itemId);
}

Note: Do not make any changes in core files, instead override them


问:
Wordpress Internal server 500
I have a wordpress site in my local environment, then I transferred it on clients server then I encountered internal server error, when I changed language using q-translate plugin but in my local environment it is working.

I have tried:

wp-config - add memory

php.ini - put in root directory with
memoey_limit 2048M

答: double check .htaccess file, something wrong with ur htaccess. I had this kind of problem so normally i checked and replace .htaccess from local env to new one.</p>

Title: Wordpress Internal server 500


问:
WatchOS: Panning and zooming image
In my little watch app (targeting watchOS3+) I need to show an image which will be fetched from a server (it is not big, let's say 600x600).
The image will be displayed alone in a modal page (only the Close button is on the top left corner)
Similar with the Photos app, I would like to be able to offer the user the possibility to pan and zoom the image.
Zooming will be done by using the Digital Crown (the events are wired up already).

Any idea how to deal with panning and zooming? Did anyone implement something like this already?

Thank you in advance!

答:
I have solved the problem by implementing a small trick (see attached image).
Basically the zooming (Digital Crown) happens "in background" on a cached UIImage and a viewport (sized exactly as the display size) crops an area from the UIImage and shows it via the WKInterfaceImage.
Panning is done by simply moving the viewport around, following the TapGestureRecognizer data.

I think I will encapsulate this in a custom control and put it on GitHub.

Title: WatchOS: Panning and zooming image


问:
XSLT transform to search and delete
The <P1> tags appear under <web-app> and under <servlet> tags in the XML file.
I want to search <servlet> tag with <servlet-name> as DUMMY and then delete <P1> tags under it when its sub-tag <p1-name> is equal to B2 OR B3. We DO NOT WANT TO ALTER THE <P1> tags directly uder <web-app>

I have got familiar with identity template and searching but struggling to delete. Any solutions so that i can tackle similar problems in future?

Input XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true">

<P1>IGNORE1</P1>
<P1>IGNORE2</P1>

<servlet>
    <servlet-name>TEST</servlet-name>
        <servlet-class>com.mm.bb.servlet.TEST</servlet-class>
        <P1>
            <p1-name>A1</p1-name>
            <p1-value>A11111</p1-value>
        </P1>
        <P1>
            <p1-name>A2</p1-name>
            <p1-value>A22222</p1-value>
        </P1>
        <P1>
            <p1-name>A3</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>A4</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>A5</p1-name>
                <p1-value/>
        </P1>

      <junk>1</junk>
  </servlet>

<servlet>
    <servlet-name>DUMMY</servlet-name>
        <servlet-class>com.mm.bb.servlet.DUMMY</servlet-class>
        <P1>
            <p1-name>B1</p1-name>
            <p1-value>B11111</p1-value>
        </P1>
        <P1>
            <p1-name>B2</p1-name>
            <p1-value>A22222</p1-value>
        </P1>
        <P1>
            <p1-name>B3</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>B4</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>B5</p1-name>
                <p1-value/>
        </P1>

      <junk>1333</junk>
  </servlet>

<servlet>
    <servlet-name>SAMMY</servlet-name>
        <servlet-class>com.mm.bb.servlet.SAMMY</servlet-class>
        <P1>
            <p1-name>C1</p1-name>
            <p1-value>B11111</p1-value>
        </P1>
        <P1>
            <p1-name>C2</p1-name>
            <p1-value>A22222</p1-value>
        </P1>
        <P1>
            <p1-name>C3</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>C4</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>C5</p1-name>
                <p1-value/>
        </P1>

      <junk>12313</junk>
  </servlet>

<D>
        <D1>
            <D11>admin</D11>
        </D1>
        <D2>
            <D21>XX</D21>
        </D2>
</D>

<E>
     <E1>Yo</E1>
     <E2>Hello</E2>
</E>

</web-app>
</code>```

The O/P XML should look like this where <P1> tag under <servlet> with <servlet-name> as DUMMY are removed because <p1-name> was either B2 OR B3.

```<code> <?xml version="1.0" encoding="UTF-8"?>
  <web-app metadata-complete="true">
  <P1>IGNORE1</P1>
  <P1>IGNORE2</P1>

        <servlet>
        <servlet-name>TEST</servlet-name>
            <servlet-class>com.mm.bb.servlet.TEST</servlet-class>
            <P1>
                <p1-name>A1</p1-name>
                <p1-value>A11111</p1-value>
            </P1>
            <P1>
                <p1-name>A2</p1-name>
                <p1-value>A22222</p1-value>
            </P1>
            <P1>
                <p1-name>A3</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>A4</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>A5</p1-name>
                    <p1-value/>
            </P1>

          <junk>1</junk>
      </servlet>

    <servlet>
        <servlet-name>DUMMY</servlet-name>
            <servlet-class>com.mm.bb.servlet.DUMMY</servlet-class>
            <P1>
                <p1-name>B1</p1-name>
                <p1-value>B11111</p1-value>
            </P1>

            <P1>
                <p1-name>B4</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>B5</p1-name>
                    <p1-value/>
            </P1>

          <junk>1333</junk>
      </servlet>

    <servlet>
        <servlet-name>SAMMY</servlet-name>
            <servlet-class>com.mm.bb.servlet.SAMMY</servlet-class>
            <P1>
                <p1-name>C1</p1-name>
                <p1-value>B11111</p1-value>
            </P1>
            <P1>
                <p1-name>C2</p1-name>
                <p1-value>A22222</p1-value>
            </P1>
            <P1>
                <p1-name>C3</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>C4</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>C5</p1-name>
                    <p1-value/>
            </P1>

          <junk>12313</junk>
      </servlet>

    <D>
            <D1>
                <D11>admin</D11>
            </D1>
            <D2>
                <D21>XX</D21>
            </D2>
    </D>

    <E>
         <E1>Yo</E1>
         <E2>Hello</E2>
    </E>

</web-app>
</code>```

答:
Use the identity transformation and an empty template for the elements you want to remove:

```<code><xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="servlet[servlet-name = 'DUMMY']/P1[p1-name = ('B2', 'B3')]"/>
</code>```

At http://xsltransform.hikmatu.com/nbUY4ki I get the output

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true">
   <P1>IGNORE1</P1>
   <P1>IGNORE2</P1>
   <servlet>
      <servlet-name>TEST</servlet-name>
      <servlet-class>com.mm.bb.servlet.TEST</servlet-class>
      <P1>
         <p1-name>A1</p1-name>
         <p1-value>A11111</p1-value>
      </P1>
      <P1>
         <p1-name>A2</p1-name>
         <p1-value>A22222</p1-value>
      </P1>
      <P1>
         <p1-name>A3</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>A4</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>A5</p1-name>
         <p1-value/>
      </P1>
      <junk>1</junk>
   </servlet>
   <servlet>
      <servlet-name>DUMMY</servlet-name>
      <servlet-class>com.mm.bb.servlet.DUMMY</servlet-class>
      <P1>
         <p1-name>B1</p1-name>
         <p1-value>B11111</p1-value>
      </P1>
      <P1>
         <p1-name>B4</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>B5</p1-name>
         <p1-value/>
      </P1>
      <junk>1333</junk>
   </servlet>
   <servlet>
      <servlet-name>SAMMY</servlet-name>
      <servlet-class>com.mm.bb.servlet.SAMMY</servlet-class>
      <P1>
         <p1-name>C1</p1-name>
         <p1-value>B11111</p1-value>
      </P1>
      <P1>
         <p1-name>C2</p1-name>
         <p1-value>A22222</p1-value>
      </P1>
      <P1>
         <p1-name>C3</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>C4</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>C5</p1-name>
         <p1-value/>
      </P1>
      <junk>12313</junk>
   </servlet>
   <D>
      <D1>
         <D11>admin</D11>
      </D1>
      <D2>
         <D21>XX</D21>
      </D2>
   </D>
   <E>
      <E1>Yo</E1>
      <E2>Hello</E2>
   </E>
</web-app>
</code>```

Title: XSLT transform to search and delete

Body:
The <P1> tags appear under <web-app> and under <servlet> tags in the XML file.
I want to search <servlet> tag with <servlet-name> as DUMMY and then delete <P1> tags under it when its sub-tag <p1-name> is equal to B2 OR B3. We DO NOT WANT TO ALTER THE <P1> tags directly uder <web-app>

I have got familiar with identity template and searching but struggling to delete. Any solutions so that i can tackle similar problems in future?

Input XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true">

<P1>IGNORE1</P1>
<P1>IGNORE2</P1>

<servlet>
    <servlet-name>TEST</servlet-name>
        <servlet-class>com.mm.bb.servlet.TEST</servlet-class>
        <P1>
            <p1-name>A1</p1-name>
            <p1-value>A11111</p1-value>
        </P1>
        <P1>
            <p1-name>A2</p1-name>
            <p1-value>A22222</p1-value>
        </P1>
        <P1>
            <p1-name>A3</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>A4</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>A5</p1-name>
                <p1-value/>
        </P1>

      <junk>1</junk>
  </servlet>

<servlet>
    <servlet-name>DUMMY</servlet-name>
        <servlet-class>com.mm.bb.servlet.DUMMY</servlet-class>
        <P1>
            <p1-name>B1</p1-name>
            <p1-value>B11111</p1-value>
        </P1>
        <P1>
            <p1-name>B2</p1-name>
            <p1-value>A22222</p1-value>
        </P1>
        <P1>
            <p1-name>B3</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>B4</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>B5</p1-name>
                <p1-value/>
        </P1>

      <junk>1333</junk>
  </servlet>

<servlet>
    <servlet-name>SAMMY</servlet-name>
        <servlet-class>com.mm.bb.servlet.SAMMY</servlet-class>
        <P1>
            <p1-name>C1</p1-name>
            <p1-value>B11111</p1-value>
        </P1>
        <P1>
            <p1-name>C2</p1-name>
            <p1-value>A22222</p1-value>
        </P1>
        <P1>
            <p1-name>C3</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>C4</p1-name>
                <p1-value/>
        </P1>
        <P1>
            <p1-name>C5</p1-name>
                <p1-value/>
        </P1>

      <junk>12313</junk>
  </servlet>

<D>
        <D1>
            <D11>admin</D11>
        </D1>
        <D2>
            <D21>XX</D21>
        </D2>
</D>

<E>
     <E1>Yo</E1>
     <E2>Hello</E2>
</E>

</web-app>

The O/P XML should look like this where <P1> tag under <servlet> with <servlet-name> as DUMMY are removed because <p1-name> was either B2 OR B3.

 <?xml version="1.0" encoding="UTF-8"?>
  <web-app metadata-complete="true">
  <P1>IGNORE1</P1>
  <P1>IGNORE2</P1>

        <servlet>
        <servlet-name>TEST</servlet-name>
            <servlet-class>com.mm.bb.servlet.TEST</servlet-class>
            <P1>
                <p1-name>A1</p1-name>
                <p1-value>A11111</p1-value>
            </P1>
            <P1>
                <p1-name>A2</p1-name>
                <p1-value>A22222</p1-value>
            </P1>
            <P1>
                <p1-name>A3</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>A4</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>A5</p1-name>
                    <p1-value/>
            </P1>

          <junk>1</junk>
      </servlet>

    <servlet>
        <servlet-name>DUMMY</servlet-name>
            <servlet-class>com.mm.bb.servlet.DUMMY</servlet-class>
            <P1>
                <p1-name>B1</p1-name>
                <p1-value>B11111</p1-value>
            </P1>

            <P1>
                <p1-name>B4</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>B5</p1-name>
                    <p1-value/>
            </P1>

          <junk>1333</junk>
      </servlet>

    <servlet>
        <servlet-name>SAMMY</servlet-name>
            <servlet-class>com.mm.bb.servlet.SAMMY</servlet-class>
            <P1>
                <p1-name>C1</p1-name>
                <p1-value>B11111</p1-value>
            </P1>
            <P1>
                <p1-name>C2</p1-name>
                <p1-value>A22222</p1-value>
            </P1>
            <P1>
                <p1-name>C3</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>C4</p1-name>
                    <p1-value/>
            </P1>
            <P1>
                <p1-name>C5</p1-name>
                    <p1-value/>
            </P1>

          <junk>12313</junk>
      </servlet>

    <D>
            <D1>
                <D11>admin</D11>
            </D1>
            <D2>
                <D21>XX</D21>
            </D2>
    </D>

    <E>
         <E1>Yo</E1>
         <E2>Hello</E2>
    </E>

</web-app>

Body:
Use the identity transformation and an empty template for the elements you want to remove:

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="servlet[servlet-name = 'DUMMY']/P1[p1-name = ('B2', 'B3')]"/>

At http://xsltransform.hikmatu.com/nbUY4ki I get the output

<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true">
   <P1>IGNORE1</P1>
   <P1>IGNORE2</P1>
   <servlet>
      <servlet-name>TEST</servlet-name>
      <servlet-class>com.mm.bb.servlet.TEST</servlet-class>
      <P1>
         <p1-name>A1</p1-name>
         <p1-value>A11111</p1-value>
      </P1>
      <P1>
         <p1-name>A2</p1-name>
         <p1-value>A22222</p1-value>
      </P1>
      <P1>
         <p1-name>A3</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>A4</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>A5</p1-name>
         <p1-value/>
      </P1>
      <junk>1</junk>
   </servlet>
   <servlet>
      <servlet-name>DUMMY</servlet-name>
      <servlet-class>com.mm.bb.servlet.DUMMY</servlet-class>
      <P1>
         <p1-name>B1</p1-name>
         <p1-value>B11111</p1-value>
      </P1>
      <P1>
         <p1-name>B4</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>B5</p1-name>
         <p1-value/>
      </P1>
      <junk>1333</junk>
   </servlet>
   <servlet>
      <servlet-name>SAMMY</servlet-name>
      <servlet-class>com.mm.bb.servlet.SAMMY</servlet-class>
      <P1>
         <p1-name>C1</p1-name>
         <p1-value>B11111</p1-value>
      </P1>
      <P1>
         <p1-name>C2</p1-name>
         <p1-value>A22222</p1-value>
      </P1>
      <P1>
         <p1-name>C3</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>C4</p1-name>
         <p1-value/>
      </P1>
      <P1>
         <p1-name>C5</p1-name>
         <p1-value/>
      </P1>
      <junk>12313</junk>
   </servlet>
   <D>
      <D1>
         <D11>admin</D11>
      </D1>
      <D2>
         <D21>XX</D21>
      </D2>
   </D>
   <E>
      <E1>Yo</E1>
      <E2>Hello</E2>
   </E>
</web-app>


问:
React-Router - componentDidMount not called when navigating to URL
I'm a little stumped on this one. I defined a route called classes/:id. When navigating to that route in the app, the componentDidMount() is called. However, when reloading the page or copying and pasting the URL the page completely loads, but the componentDidMount() method is not called at all.

From what I have read, the reason is because the same component mounted even though the page is being reloaded which is why the lifecycle method does ever get fired off.

What are some ways to handle this? Your help is greatly appreciated. Thanks!

答: the componentWillReceiveProps,componentDidUpdate lifecycle will receive the new props and then setState to change state to trigger render method.</p>


问:
Trouble importing local package
I've decided to try breaking my project into a MVC type view, so to start I wanted to put all my routing into a controller folder and I put my database connection into another folder titled db.

I can't figure out how to make the database connection work smoothly. Back when all of the files were in my package main I just called InitDb() in main and in all of my other files in the main package I had access to the db variable. Now that I made db it's down package and imported it, nothing is recognized.

I also don't know where to call InitDb() and defer db.Close() anymore since it's not all in main.

db/db.go

```<code>package database

import (
    "fmt"
    "database/sql"
)

var db *sql.DB

const (
    dbhost = "localhost"
    dbuser = "root"
    dbpass = "password"
    dbname = "user"
)

func InitDb() {
    var err error

    connectionString := fmt.Sprintf("%s:%s@/%s", dbuser, dbpass, dbname)

    db, err = sql.Open("mysql", connectionString)

    if err != nil {
        panic(err)
    }

    err = db.Ping()

    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected!")
}
</code>```

controllers/index.go

```<code>package controllers

import (
    "net/http"
    "fmt"
    "db"
    "github.com/gorilla/mux"

)

func TestHandler(r *mux.Router)
    r.HandleFunc("/index", test).Methods("GET")
}

func test(w http.ResponseWriter, r *http.Request) {
    // database undefined
    err := database.QueryRow("some sql statement")

    CheckErr(err)
}
</code>```

main.go

```<code>package main

import (
    "net/http"
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    controllers.TestHandler(r)

    log.Fatal(http.ListenAndServe("localhost:8000", r))
}
</code>```

答:
While not required it is a good idea to have the package name be the same as the folder in which it lives, so either do:

db/db.go

```<code>package db

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

Or do:

database/db.go

```<code>package database

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

I would not recommend mixing the two.

You can have your database package export a Close function and have main call it when it's done.

database/db.go

```<code>package database

import (
    "fmt"
    "database/sql"
)

var db *sql.DB

func Close() {
    db.Close()
}

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

main.go

```<code>package main

import "database"

func main() {
    defer database.Close()

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

Or just don't close it in this case. When main exits the *sql.DB does not stay alive outside your program, it will not take up connection slots if the program is not running. Closing makes sense only if you're using multiple instances of *sql.DB and there is danger that they will start blocking while waiting for a connection. If you have only one that's shared by the whole program then you should be ok not calling defer close.

Title: Trouble importing local package

Body:
I've decided to try breaking my project into a MVC type view, so to start I wanted to put all my routing into a controller folder and I put my database connection into another folder titled db.

I can't figure out how to make the database connection work smoothly. Back when all of the files were in my package main I just called InitDb() in main and in all of my other files in the main package I had access to the db variable. Now that I made db it's down package and imported it, nothing is recognized.

I also don't know where to call InitDb() and defer db.Close() anymore since it's not all in main.

db/db.go

package database

import (
    "fmt"
    "database/sql"
)

var db *sql.DB

const (
    dbhost = "localhost"
    dbuser = "root"
    dbpass = "password"
    dbname = "user"
)

func InitDb() {
    var err error

    connectionString := fmt.Sprintf("%s:%s@/%s", dbuser, dbpass, dbname)

    db, err = sql.Open("mysql", connectionString)

    if err != nil {
        panic(err)
    }

    err = db.Ping()

    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected!")
}

controllers/index.go

package controllers

import (
    "net/http"
    "fmt"
    "db"
    "github.com/gorilla/mux"

)

func TestHandler(r *mux.Router)
    r.HandleFunc("/index", test).Methods("GET")
}

func test(w http.ResponseWriter, r *http.Request) {
    // database undefined
    err := database.QueryRow("some sql statement")

    CheckErr(err)
}

main.go

package main

import (
    "net/http"
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    controllers.TestHandler(r)

    log.Fatal(http.ListenAndServe("localhost:8000", r))
}

Body:
While not required it is a good idea to have the package name be the same as the folder in which it lives, so either do:

db/db.go

package db

// ...

Or do:

database/db.go

package database

// ...

I would not recommend mixing the two.

You can have your database package export a Close function and have main call it when it's done.

database/db.go

package database

import (
    "fmt"
    "database/sql"
)

var db *sql.DB

func Close() {
    db.Close()
}

// ...

main.go

package main

import "database"

func main() {
    defer database.Close()

    // ...
}

Or just don't close it in this case. When main exits the *sql.DB does not stay alive outside your program, it will not take up connection slots if the program is not running. Closing makes sense only if you're using multiple instances of *sql.DB and there is danger that they will start blocking while waiting for a connection. If you have only one that's shared by the whole program then you should be ok not calling defer close.


问:
c# linq to xml
I have an xml string that I wish to traverse using LINQ to XML (I have never used this, so wish to learn).  However when I try to use

```<code>XDocument xDoc = XDocument.Load(adminUsersXML);
        var users = from result in xDoc.Descendants("Result")
                    select new
                    {
                        test = result.Element("USER_ID").Value
                    };
</code>```

I get an error message saying illegal characters in path.  reading up on it, it's because I cannot pass a standard string in this way.  Is there a way to use XML LINQ qith a standard string?

Thanks.

答: I think adminUserXML is not a file but a string containing xml, which should be parsed to convert to XDocument with XDocument.Parse(adminUserXML)

Title: c# linq to xml

Body:
I have an xml string that I wish to traverse using LINQ to XML (I have never used this, so wish to learn).  However when I try to use

XDocument xDoc = XDocument.Load(adminUsersXML);
        var users = from result in xDoc.Descendants("Result")
                    select new
                    {
                        test = result.Element("USER_ID").Value
                    };

I get an error message saying illegal characters in path.  reading up on it, it's because I cannot pass a standard string in this way.  Is there a way to use XML LINQ qith a standard string?

Thanks.


问:
AWS Auditor Role - AWSCloudTrailFullAccess Or AWSCloudTrailReadOnlyAccess
For AWS Auditor role, do we need to provide AWSCloudTrailFullAccess or its enough to provide AWSCloudTrailReadOnlyAccess?</p>

答:
AWS has an Amazon Managed Policy for Security Auditor named "SecurityAudit". This policy does not include most of the APIs in AWSCloudTrailReadOnlyAccess.

I recommend either using this policy as is, or basing your Auditor Role upon this policy. Document each API that you grant or deny access to that differs from this policy.

```<code>arn:aws:iam::aws:policy/SecurityAudit
</code>```

Body:
AWS has an Amazon Managed Policy for Security Auditor named "SecurityAudit". This policy does not include most of the APIs in AWSCloudTrailReadOnlyAccess.

I recommend either using this policy as is, or basing your Auditor Role upon this policy. Document each API that you grant or deny access to that differs from this policy.

arn:aws:iam::aws:policy/SecurityAudit