问:
Best Practices: What's the Best Way for Constructing Headers and Footers?
What's the best way for constructing headers, and footers?  Should you call it all from the controller, or include it from the view file? I'm using CodeIgniter, and I'm wanting to know what's the best practice for this. Loading all the included view files from the controller, like this?

```<code>class Page extends Controller {

   function index()
   {
      $data['page_title'] = 'Your title';
      $this->load->view('header');
      $this->load->view('menu');
      $this->load->view('content', $data);
      $this->load->view('footer');
   }

}
</code>```

or calling the single view file, and calling the header and footer views from there:

```<code>//controller file
class Page extends Controller {

   function index()
   {
      $data['page_title'] = 'Your title';
      $this->load->view('content', $data);

   }

}

//view file

<?php $this->load->view('header'); ?>

<p>The data from the controller</p>

<?php $this->load->view('footer'); ?>
</code>```

I've seen it done both ways, but want to choose now before I go too far down a path.

答:
Actually, after researching this quite a bit myself, I came to the conclusion that the best practice for including headers and footers in MVC is a third option - namely extending a base controller. That will give you a little more flexibility than the text's suggestion, particularly if you're building a very modular layout (not just header and footer, also sidebar panels, non-static menus, etc.).

First, define a Base_controller class, in which you create methods that append your page elements (header, footer, etc.) to an output string:

```<code>class Base_controller extends Controller
{
    var $_output = '';

    function _standard_header($data=null)
    {
        if (empty($data))
            $data = ...; // set default data for standard header here

        $this->_output .= $this->load->view('header', $data, true);
    }

    function _admin_header($data=null)
    {
        if (empty($data))
            $data = ...; // set default data for expanded header here

        $this->_output .= $this->load->view('admin_header', $data, true);
    }

    function _standard_page($data)
    {
        $this->_standard_header();
        $this->_output .=
            $this->load->view('standard_content', $data, true);
        echo $this->_output; // note: place the echo statement in a
                             // separate function for added flexibility
    }

    function _page_with_admin_header($data)
    {
        $this->_admin_header($data);
        $this->_output .=
            $this->load->view('standard_content', $data, true);
        echo $this->_output;
    }
}
</code>```

Then, in your page controllers, simply extend the base class and call your functions to build the page.

```<code>class Page_controller extends Base_controller
{
    function index()
    {
        $data = ...; // Set content data here
        $this->_standard_page($data);
    }

    function admin()
    {
        $data = ...; // Set content and header data here
        $this->_page_with_admin_header($data);
    }
}
</code>```

Using a base controller, you can achieve very clean code in your individual page controllers AND have separate views for elements on the page (allowing code reuse in both views and controllers). All you need to do is define your common page 'sections' (what you might be tempted to call 'fragments') as functions in your base controller.

And if the base controller should start to grow uncontrollably (which can happen on large sites), you can rearrange some of its less-general functions by placing them in subclasses and letting the corresponding page controllers extend those instead of the original base controller.

Enjoy!

OwnerDisplayName: jmccartie

Body:
What's the best way for constructing headers, and footers?  Should you call it all from the controller, or include it from the view file? I'm using CodeIgniter, and I'm wanting to know what's the best practice for this. Loading all the included view files from the controller, like this?

class Page extends Controller {

   function index()
   {
      $data['page_title'] = 'Your title';
      $this->load->view('header');
      $this->load->view('menu');
      $this->load->view('content', $data);
      $this->load->view('footer');
   }

}

or calling the single view file, and calling the header and footer views from there:

//controller file
class Page extends Controller {

   function index()
   {
      $data['page_title'] = 'Your title';
      $this->load->view('content', $data);

   }

}

//view file

<?php $this->load->view('header'); ?>

The data from the controller

<?php $this->load->view('footer'); ?>

I've seen it done both ways, but want to choose now before I go too far down a path.

Body:
Actually, after researching this quite a bit myself, I came to the conclusion that the best practice for including headers and footers in MVC is a third option - namely extending a base controller. That will give you a little more flexibility than the text's suggestion, particularly if you're building a very modular layout (not just header and footer, also sidebar panels, non-static menus, etc.).

First, define a Base_controller class, in which you create methods that append your page elements (header, footer, etc.) to an output string:

class Base_controller extends Controller
{
    var $_output = '';

    function _standard_header($data=null)
    {
        if (empty($data))
            $data = ...; // set default data for standard header here

        $this->_output .= $this->load->view('header', $data, true);
    }

    function _admin_header($data=null)
    {
        if (empty($data))
            $data = ...; // set default data for expanded header here

        $this->_output .= $this->load->view('admin_header', $data, true);
    }

    function _standard_page($data)
    {
        $this->_standard_header();
        $this->_output .=
            $this->load->view('standard_content', $data, true);
        echo $this->_output; // note: place the echo statement in a
                             // separate function for added flexibility
    }

    function _page_with_admin_header($data)
    {
        $this->_admin_header($data);
        $this->_output .=
            $this->load->view('standard_content', $data, true);
        echo $this->_output;
    }
}

Then, in your page controllers, simply extend the base class and call your functions to build the page.

class Page_controller extends Base_controller
{
    function index()
    {
        $data = ...; // Set content data here
        $this->_standard_page($data);
    }

    function admin()
    {
        $data = ...; // Set content and header data here
        $this->_page_with_admin_header($data);
    }
}

Using a base controller, you can achieve very clean code in your individual page controllers AND have separate views for elements on the page (allowing code reuse in both views and controllers). All you need to do is define your common page 'sections' (what you might be tempted to call 'fragments') as functions in your base controller.

And if the base controller should start to grow uncontrollably (which can happen on large sites), you can rearrange some of its less-general functions by placing them in subclasses and letting the corresponding page controllers extend those instead of the original base controller.

Enjoy!

OwnerDisplayName: Scarpia

LastEditorDisplayName: Jens Roland


来源: stackexchange

问:
Get an element id inside a p:dialog
I need get an id of a inputText that is inside a p:dialog.
I tried this way but nothing happened.
Can anyone helpe me?

```<code><h:form id="form">
<p:dialog header="Telefones" widgetVar="telefoneDialog" modal="true" showEffect="explode" hideEffect="explode" resizable="false">
    <p:outputPanel id="empresaTelefoneDialog">
            <p:panelGrid columns="3">
                <p:outputLabel for="tipoTelefones" value="Tipo "/>
                   <p:selectOneMenu id="tipoTelefones" value="#{empresaBean.telefone.tipo}">
                            <f:selectItem itemLabel="Fone 2" itemValue="Fone 2"/>
                            <f:selectItem itemLabel="Celular 2" itemValue="Celular 2"/>
                        </p:selectOneMenu>
                        <p:inputMask id="telefoneMask" mask='99-9999-99-99' value="#{empresaBean.telefone.telefone}"/>
                        <h:commandButton value="Add" action="#{empresaBean.addTelefone()}"/>
            </p:panelGrid>
    </p:outputPanel>
</p:dialog>
</code>```

```<code>$(document).ready(function(){

  $('#form\\:telefoneMask').click(function(){

  console.log("TESTE");
 });
</code>```

});

答:
Try with this

```<code>$(document).ready(function(){
    $("#form input[id*='telefoneMask']").click(function(){
    console.log("TESTE");
});
</code>```

This should return an input element, containing "telefoneMask" as part of the id attribute.

ContentLicense: CC BY-SA 3.0

Title: Get an element id inside a p:dialog

Body:
I need get an id of a inputText that is inside a p:dialog.
I tried this way but nothing happened.
Can anyone helpe me?

<h:form id="form">

                            <f:selectItem itemLabel="Fone 2" itemValue="Fone 2"/>
                            <f:selectItem itemLabel="Celular 2" itemValue="Celular 2"/>

                        <h:commandButton value="Add" action="#{empresaBean.addTelefone()}"/>

$(document).ready(function(){

  $('#form\\:telefoneMask').click(function(){

  console.log("TESTE");
 });

});

Body:
Try with this

$(document).ready(function(){
    $("#form input[id*='telefoneMask']").click(function(){
    console.log("TESTE");
});

This should return an input element, containing "telefoneMask" as part of the id attribute.


问:
SQL SERVER DATA TOOLS WITH TFS INTEGRATION
I want to use ssdt with tfs but there is no team explorer menu in ssdt.Most of people suggest to use visual studio community edition to do it.
I want to use SSDT without Visual Studio but use with TFS ,is there any way to do that?</p>

答:
Quick answer: no.

You would need to install at least Team Explorer (ie. TFS Client Tools) to use TFS, but that does include the VS shell.

The other option would be to use TFS to host git repositories and thus avoid the need for a TFSVC client. You would need a git client (eg. https://git-for-windows.github.io/), but that can be from the command line.


问:
Stop flex child from growing when text contents are too long
I have a flex layout which looks like this:

That's fine but when the product description is very long, I want to hide the overflow and show an ellipsis.

There is a flex container with the class info-container which has 2 flex children - left (30%) and right (70%). The right div is itself a flex container. The problem is this div expands when the text is too long:

The HTML is:

```<code><div class="info-container top">
  <div class="left">
    <div class="item-image-container">
      <div class="item-image" >
        <img height="75" width="75" src="https://static.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg" />
      </div>
    </div>
  </div>
  <div class="right">
    <h2>
     header
    </h2>

    <div class="product-description">
      product desc stuff product desc stuff stuff product desc stuff stuff
    </div>
  </div>
</div>
</code>```

And the CSS is:

```<code>.info-container {
      margin-left: 300px;
      display: flex;
      flex: 0 0 100%;
      flex-direction: row;
      justify-content: center;
      padding-bottom: 20px;
      width: 400px;
      border: 1px red solid;
      padding: 3px;
}

.left {
  font-size: 2.5rem;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex: 30%;
}

.right {
  flex: 70%;
}

h2 {
  font-weight: bold;
  min-width:0;
}

.product-description {
  min-width:0;
  font-sixe: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

h2 {
  margin: 0;
}
</code>```

The jsfiddle is here.

How can I ensure the right div does not expand if the text is too long, and instead an ellipsis is shown?

答:
While I'm a big proponent of flex box, your usage of it here doesn't seem appropriate.

You have a lot of fixed width elements (img: 75px, .info-container: 400px)

You have flex parent properties assigned to children (justify-content, align-items)

You can simplify this a lot with just a floated container for your image if using so many fixed widths is a criteria of this situation.

Simple float example:

.info-container {
  max-width: 400px;
  border: 1px red solid;
  padding: 3px;
  background: #ddd;
  min-height: 75px;
}

.left {
  float: left;
}

h2 {
  font-weight: bold;
  min-width:0;
  margin: 0;
}

.product-description {
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="info-container top">
  <div class="left">
  <img height="75" width="75" src="https://static.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg" />
  </div>
  <div class="right">
    <h2>header</h2>
    <div class="product-description">
      Product desc stuff product desc stuff stuff product desc stuff stuff product desc stuff stuff
    </div>
</div></code>```

Flex box is meant to be fluid.  A more appropriate use of it might look like the following, where we allow the containers and the content to flex and fill their space appropriately.

Flex Box example:

.info-container {
  display: flex;
  border: 1px red solid;
  padding: 3px;
  background: #ddd;
  min-height: 75px;
}

.left {
  flex: 30%;
}

.right {
  flex-basis: 70%;
  min-width: 0;
}

.left img {
  max-width: 100%;
}

h2 {
  font-weight: bold;
  min-width:0;
  margin: 0;
}

.product-description {
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="info-container top">
  <div class="left">
  <img src="https://static.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg" />
  </div>
  <div class="right">
    <h2>header</h2>
    <div class="product-description">
      Product desc stuff product desc stuff stuff product desc stuff stuff product desc stuff stuff
    </div>
</div></code>```

Notice the min-width: 0 on the .right flex child. This is used to ensure the overflow works correctly (see reference here), and that any fixed widths both in the CSS and the markup are removed.

Body:
I have a flex layout which looks like this:

That's fine but when the product description is very long, I want to hide the overflow and show an ellipsis.

There is a flex container with the class info-container which has 2 flex children - left (30%) and right (70%). The right div is itself a flex container. The problem is this div expands when the text is too long:

The HTML is:

     header

      product desc stuff product desc stuff stuff product desc stuff stuff

And the CSS is:

.info-container {
      margin-left: 300px;
      display: flex;
      flex: 0 0 100%;
      flex-direction: row;
      justify-content: center;
      padding-bottom: 20px;
      width: 400px;
      border: 1px red solid;
      padding: 3px;
}

.left {
  font-size: 2.5rem;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex: 30%;
}

.right {
  flex: 70%;
}

h2 {
  font-weight: bold;
  min-width:0;
}

.product-description {
  min-width:0;
  font-sixe: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

h2 {
  margin: 0;
}

The jsfiddle is here.

How can I ensure the right div does not expand if the text is too long, and instead an ellipsis is shown?

Body:
While I'm a big proponent of flex box, your usage of it here doesn't seem appropriate.

You have a lot of fixed width elements (img: 75px, .info-container: 400px)

You have flex parent properties assigned to children (justify-content, align-items)

You can simplify this a lot with just a floated container for your image if using so many fixed widths is a criteria of this situation.

Simple float example:

.info-container {
  max-width: 400px;
  border: 1px red solid;
  padding: 3px;
  background: #ddd;
  min-height: 75px;
}

.left {
  float: left;
}

h2 {
  font-weight: bold;
  min-width:0;
  margin: 0;
}

.product-description {
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<div class="info-container top">
  <div class="left">
  <img height="75" width="75" src="https://static.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg" />
  </div>
  <div class="right">
    <h2>header</h2>
    <div class="product-description">
      Product desc stuff product desc stuff stuff product desc stuff stuff product desc stuff stuff
    </div>
</div>

Flex box is meant to be fluid.  A more appropriate use of it might look like the following, where we allow the containers and the content to flex and fill their space appropriately.

Flex Box example:

.info-container {
  display: flex;
  border: 1px red solid;
  padding: 3px;
  background: #ddd;
  min-height: 75px;
}

.left {
  flex: 30%;
}

.right {
  flex-basis: 70%;
  min-width: 0;
}

.left img {
  max-width: 100%;
}

h2 {
  font-weight: bold;
  min-width:0;
  margin: 0;
}

.product-description {
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<div class="info-container top">
  <div class="left">
  <img src="https://static.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg" />
  </div>
  <div class="right">
    <h2>header</h2>
    <div class="product-description">
      Product desc stuff product desc stuff stuff product desc stuff stuff product desc stuff stuff
    </div>
</div>

Notice the min-width: 0 on the .right flex child. This is used to ensure the overflow works correctly (see reference here), and that any fixed widths both in the CSS and the markup are removed.


问:
Declaring a variable as final for Firebase function. Checking if username and email exist
I am trying to make a register page. Before registering that user I will try to validate the username and email do not exist in the database. But I somehow cannot set the variable to be false when the username/email already exist so it will end up still registering the user.

How can I do this? Please guide me on this.

Checking if username and email already exist before register user:

```<code>            if (!checkIfUsernameExists(userName) && !checkIfEmailExists(userEmail)){
            registerUser();
        }
</code>```

Method for checking if the username exists or not:

```<code>    public boolean checkIfUsernameExists(String userName){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userName").equalTo(userName).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextUserNameRegister.setError("Username already exists");
                editTextUserNameRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}
</code>```

Method for checking if the email already exists or not:

```<code>    public boolean checkIfEmailExists(String userEmail){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextEmailRegister.setError("Email already exists");
                editTextEmailRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}
</code>```

答:
boolean isExist is already defined don't need to declare it again.</p>

```<code>public void checkIfEmailExists(String userEmail){
        databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                boolean isExist = dataSnapshot.exists();
                if (isExist){
                    editTextEmailRegister.setError("Email already exists");
                    editTextEmailRegister.requestFocus();
                    if(isExist){
                      //call your required method to do next steps
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

     }
</code>```

Body:
I am trying to make a register page. Before registering that user I will try to validate the username and email do not exist in the database. But I somehow cannot set the variable to be false when the username/email already exist so it will end up still registering the user.

How can I do this? Please guide me on this.

Checking if username and email already exist before register user:

            if (!checkIfUsernameExists(userName) && !checkIfEmailExists(userEmail)){
            registerUser();
        }

Method for checking if the username exists or not:

    public boolean checkIfUsernameExists(String userName){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userName").equalTo(userName).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextUserNameRegister.setError("Username already exists");
                editTextUserNameRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}

Method for checking if the email already exists or not:

    public boolean checkIfEmailExists(String userEmail){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextEmailRegister.setError("Email already exists");
                editTextEmailRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}

Body:
boolean isExist is already defined don't need to declare it again.

public void checkIfEmailExists(String userEmail){
        databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                boolean isExist = dataSnapshot.exists();
                if (isExist){
                    editTextEmailRegister.setError("Email already exists");
                    editTextEmailRegister.requestFocus();
                    if(isExist){
                      //call your required method to do next steps
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

     }


问:
Unable to display Upvote/Downvote count in Rail app views
I'm currently using the 'acts_as_votable' Ruby gem to give the Upvote/Downvote function to comments in a basic rails app. In the comments_controller.rb the functions look like this:

```<code>    def upvote
      @comment = Comment.find(params[:id])
      @comment.upvote_by current_user
      redirect_to comments_path
    end

    def downvote
      @comment = Comment.find(params[:id])
      @comment.downvote_by current_user
      redirect_to comment_path
    end
</code>```

and in the roputes.rb:

```<code>  resources :comments do
    member do
     put "like", to: "comments#upvote"
     put "dislike", to: "comments#downvote"
    end
  end
</code>```

and the loop in the views looks like this:

```<code> <div class="box">
 <% @comment.each do |w| %>
    <tr>
      <td><b><%= w.title %></b></td><br>
      <td><%= w.location %></td><br>
      <td><%= w.body %></td><br>
      <%= link_to "upvote", like_comment_path(w), method: :put %>
      <%= @comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(w), method: :put %>
      </tr>
    <% end %>
 </div>
</code>```

There are no problems with this, except for with this line of code:

```<code><%= @comment.upvote_by.size %>
</code>```

which is returning the following error:

```<code>undefined method `upvote_by' for #
<Comment::ActiveRecord_Relation:0x007faa8dbf0560>
</code>```

I'm not sure why the method is undefined as I assume this is either a method that is built in to the gem, or a ruby method. I also don't know if this is an error message that is thrown up for some other reason, but I'm not sure what this could be. I've tried to use 'upvote_from' instead but this didn't work. If I remove the line then the app runs fine.

I can't work out what else could be causing this, so I would really appreciate some help here, thanks.

答:
If you are inside an index, I would recommand to use @comments instead of @comment, I would also rename w for comment so that it's more clear it's a comment.

```<code><div class="box">
 <% @comments.each do |comment| %>
    <tr>
      <td><b><%= comment.title %></b></td><br>
      <td><%= comment.location %></td><br>
      <td><%= comment.body %></td><br>
      <%= link_to "upvote", like_comment_path(comment), method: :put %>
      <%= comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(comment), method: :put %>
      </tr>
    <% end %>
 </div>
</code>```

Body:
I'm currently using the 'acts_as_votable' Ruby gem to give the Upvote/Downvote function to comments in a basic rails app. In the comments_controller.rb the functions look like this:

    def upvote
      @comment = Comment.find(params[:id])
      @comment.upvote_by current_user
      redirect_to comments_path
    end

    def downvote
      @comment = Comment.find(params[:id])
      @comment.downvote_by current_user
      redirect_to comment_path
    end

and in the roputes.rb:

  resources :comments do
    member do
     put "like", to: "comments#upvote"
     put "dislike", to: "comments#downvote"
    end
  end

and the loop in the views looks like this:

 <% @comment.each do |w| %>

      <%= w.title %>

      <%= w.location %>

      <%= w.body %>

      <%= link_to "upvote", like_comment_path(w), method: :put %>
      <%= @comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(w), method: :put %>

    <% end %>

There are no problems with this, except for with this line of code:

<%= @comment.upvote_by.size %>

which is returning the following error:

undefined method `upvote_by' for #
<Comment::ActiveRecord_Relation:0x007faa8dbf0560>

I'm not sure why the method is undefined as I assume this is either a method that is built in to the gem, or a ruby method. I also don't know if this is an error message that is thrown up for some other reason, but I'm not sure what this could be. I've tried to use 'upvote_from' instead but this didn't work. If I remove the line then the app runs fine.

I can't work out what else could be causing this, so I would really appreciate some help here, thanks.

Body:
If you are inside an index, I would recommand to use @comments instead of @comment, I would also rename w for comment so that it's more clear it's a comment.

<div class="box">
 <% @comments.each do |comment| %>
    <tr>
      <td><b><%= comment.title %></b></td><br>
      <td><%= comment.location %></td><br>
      <td><%= comment.body %></td><br>
      <%= link_to "upvote", like_comment_path(comment), method: :put %>
      <%= comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(comment), method: :put %>
      </tr>
    <% end %>
 </div>


问:
Bat To ini converter
Basically what I want to do is rename the batch file to .ini instead of .bat and put 1= for the first line and 2= before the second and so on and so on.

My batch file:

```<code>@echo off

color F0

cls

:strt

echo Drag your file in this window to make a ini from it.

set /p file=File path with " " :

del config.ini

for /F "usebackq tokens=* delims=*" %%j in (%file%) do echo 1=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=1" %%j in (%file%) do echo 2=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=2" %%j in (%file%) do echo 3=%%j>>config.ini

exit
</code>```

and my result is this when I use a random text file:

```<code>1=lol1

1=lol2

1=lol3

1=lol4

2=lol1

2=lol2

2=lol3

2=lol4

3=lol1

3=lol2

3=lol3

3=lol4
</code>```

and what I want is this:

```<code>1=lol1

2=lol2

3=lol3
</code>```

while the original .txt is:

```<code>lol1

lol2

lol3

lol4
</code>```

so it basically works but it does not stop at the end of the first line it writes it writes the whole file how do I solve this? Cause I'm out of options.

答:
Here you go champ.
If you would want some explanation, just ask </p>

```<code>@echo off
cls
set file=c:/mmm.txt

del config.ini
setlocal EnableDelayedExpansion
for /f "tokens=* delims=*" %%i in (%file%) do (
set variable=%%i
set num=!variable:~3,1!
echo !num!=!variable! >>config.ini
)
endlocal

goto :eof
</code>```

Title: Bat To ini converter

Body:
Basically what I want to do is rename the batch file to .ini instead of .bat and put 1= for the first line and 2= before the second and so on and so on.

My batch file:

@echo off

color F0

cls

:strt

echo Drag your file in this window to make a ini from it.

set /p file=File path with " " :

del config.ini

for /F "usebackq tokens=* delims=*" %%j in (%file%) do echo 1=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=1" %%j in (%file%) do echo 2=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=2" %%j in (%file%) do echo 3=%%j>>config.ini

exit

and my result is this when I use a random text file:

1=lol1

1=lol2

1=lol3

1=lol4

2=lol1

2=lol2

2=lol3

2=lol4

3=lol1

3=lol2

3=lol3

3=lol4

and what I want is this:

1=lol1

2=lol2

3=lol3

while the original .txt is:

lol1

lol2

lol3

lol4

so it basically works but it does not stop at the end of the first line it writes it writes the whole file how do I solve this? Cause I'm out of options.

Body:
Here you go champ.
If you would want some explanation, just ask

@echo off
cls
set file=c:/mmm.txt

del config.ini
setlocal EnableDelayedExpansion
for /f "tokens=* delims=*" %%i in (%file%) do (
set variable=%%i
set num=!variable:~3,1!
echo !num!=!variable! >>config.ini
)
endlocal

goto :eof

ContentLicense: CC BY-SA 2.5


问:
How do you find the disk size of a Postgres / PostgreSQL table and its indexes
I'm coming to Postgres from Oracle and looking for a way to find the table and index size in terms of bytes/MB/GB/etc, or even better the size for all tables.  In Oracle I had a nasty long query that looked at user_lobs and user_segments to give back an answer.

I assume in Postgres there's something I can use in the information_schema tables, but I'm not seeing where.

答:
Just for info, I have got the excelent answer from @aib and modified it a little for:

getting only tables from "public" schema

show also materialized views data and index size

On materialized view we can use index for refreshing materialized views concurrently, which allows using them while updating.

Well,  my query will be the following:

```<code>SELECT
    table_name,
    pg_size_pretty(table_size) AS table_size,
    pg_size_pretty(indexes_size) AS indexes_size,
    pg_size_pretty(total_size) AS total_size
FROM (
    SELECT
        table_name,
        pg_table_size(table_name) AS table_size,
        pg_indexes_size(table_name) AS indexes_size,
        pg_total_relation_size(table_name) AS total_size
    FROM (
        -- tables from 'public'
        SELECT table_name
        FROM information_schema.tables
        where table_schema = 'public' and table_type = 'BASE TABLE'
        union
        -- materialized views
        SELECT oid::regclass::text as table_name
        FROM pg_class
        WHERE relkind = 'm'
        order by table_name
    ) AS all_tables
    -- ORDER BY total_size DESC
    order by table_name
) AS pretty_sizes
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Just for info, I have got the excelent answer from @aib and modified it a little for:

getting only tables from "public" schema

show also materialized views data and index size

On materialized view we can use index for refreshing materialized views concurrently, which allows using them while updating.

Well,  my query will be the following:

SELECT
    table_name,
    pg_size_pretty(table_size) AS table_size,
    pg_size_pretty(indexes_size) AS indexes_size,
    pg_size_pretty(total_size) AS total_size
FROM (
    SELECT
        table_name,
        pg_table_size(table_name) AS table_size,
        pg_indexes_size(table_name) AS indexes_size,
        pg_total_relation_size(table_name) AS total_size
    FROM (
        -- tables from 'public'
        SELECT table_name
        FROM information_schema.tables
        where table_schema = 'public' and table_type = 'BASE TABLE'
        union
        -- materialized views
        SELECT oid::regclass::text as table_name
        FROM pg_class
        WHERE relkind = 'm'
        order by table_name
    ) AS all_tables
    -- ORDER BY total_size DESC
    order by table_name
) AS pretty_sizes


问:
Regex capture all words in a line before the last 2
I have a bunch of line data I need to capture like so:

```<code>Level production data TD Index
Total Agriculture\Production data TS Index
</code>```

I need to capture everything before the last two words, for example in this case my regex output should be Level production data for the first match.  How can I do this while also assuming varying number of words before the TD Index. Thanks!

答:
You can try this:

```<code>import re
s = ["Level production data TD Index", "Total Agriculture\Production data TS Index"]
new_s = [re.findall('[\w\s\W]{1,}(?=\s\w+\s\w+$)', i)[0] for i in s]
</code>```

Output:

```<code>['Level production data', 'Total Agriculture\\Production data']
</code>```

Body:
I have a bunch of line data I need to capture like so:

Level production data TD Index
Total Agriculture\Production data TS Index

I need to capture everything before the last two words, for example in this case my regex output should be Level production data for the first match.  How can I do this while also assuming varying number of words before the TD Index. Thanks!

Body:
You can try this:

import re
s = ["Level production data TD Index", "Total Agriculture\Production data TS Index"]
new_s = [re.findall('[\w\s\W]{1,}(?=\s\w+\s\w+$)', i)[0] for i in s]

Output:

['Level production data', 'Total Agriculture\\Production data']


问:
How to call a Python function from Node.js
I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries?</p>

答:
Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:

It uses the child_process core module:

```<code>const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('python', ['./../pypy.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))
</code>```

It doesn't require sys module in your Python script.

Below is a more modular way of performing the task using Promise:

```<code>const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./../pypy.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(fromRunpy) {
        console.log(fromRunpy.toString());
        res.end(fromRunpy);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))
</code>```

Body:
Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:

It uses the child_process core module:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('python', ['./../pypy.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

It doesn't require sys module in your Python script.

Below is a more modular way of performing the task using Promise:

const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./../pypy.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(fromRunpy) {
        console.log(fromRunpy.toString());
        res.end(fromRunpy);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))


问:
Adding Constraints to VARRAY UDT inside a Table in PLSQL
I'm stuck figuring out how to add some constraints to the attributes of my UDTs.

Here's my situation. I've got a UDT that represents the daily number of hours an employee should work (forgive me for using Italian names).

```<code>CREATE OR REPLACE TYPE TURNO_GIORNALIERO AS OBJECT(
    GIORNO   VARCHAR(15),
    ORA_INIZIO DATE,
    NUMERO_ORE  NUMBER,

    MEMBER FUNCTION getOreLavoro RETURN NUMBER
);
</code>```

Then I defined new Type as a VARRAY(5) of TURNO_GIORNALIERO, named TURNI_SETTIMANALI (that is a Varray containing the number of hours an employee should work for each day of the week).

```<code>CREATE OR REPLACE TYPE TURNI_SETTIMANALI AS VARRAY(5) OF TURNO_GIORNALIERO;
</code>```

In the end, I've created the table that contains TURNI_SETTIMANALI.

```<code>CREATE TABLE TURNO_LAVORO(
    ID_TURNO CHAR(9) PRIMARY KEY,
    TURNO   TURNI_SETTIMANALI NOT NULL,
);
</code>```

What I want to do is to add a constraint to the table TURNO_LAVORO in order to check if NUMERO_ORE (defined in TURNO GIORNALIERO) is greater than 5.

Could someone please help me? I've tried several solutions but nothing worked.

答:
I doubt it is possible in check constraint. Documentation says:

Conditions of check constraints cannot contain the following
  constructs:

Calls to user-defined functions

Nested table columns or attributes

You could use trigger however. Test types and table:

```<code>create or replace type daily_cycle
    as object(day varchar(15), hour_start date, hour_count number);
create or replace type week_cycle
    as varray(5) of daily_cycle;

create table test(id int, shift week_cycle);
</code>```

Trigger:

```<code>create or replace trigger hour_check before insert on test for each row
begin
  for i in 1..:new.shift.count() loop
    if :new.shift(i).hour_count < 5 then
      raise_application_error(-20001,'hours less than 5');
    end if;
  end loop;
end;
</code>```

First insert works, second no:

```<code>insert into test values (1,
    week_cycle(daily_cycle('a', date '2017-12-01',  5),
               daily_cycle('b', date '2017-12-02',  8) ) );

insert into test values (2,
    week_cycle(daily_cycle('a', date '2017-12-03',  3),
               daily_cycle('b', date '2017-12-04', 12),
               daily_cycle('b', date '2017-12-05',  7) ) );
</code>```

Body:
I'm stuck figuring out how to add some constraints to the attributes of my UDTs.

Here's my situation. I've got a UDT that represents the daily number of hours an employee should work (forgive me for using Italian names).

CREATE OR REPLACE TYPE TURNO_GIORNALIERO AS OBJECT(
    GIORNO   VARCHAR(15),
    ORA_INIZIO DATE,
    NUMERO_ORE  NUMBER,

    MEMBER FUNCTION getOreLavoro RETURN NUMBER
);

Then I defined new Type as a VARRAY(5) of TURNO_GIORNALIERO, named TURNI_SETTIMANALI (that is a Varray containing the number of hours an employee should work for each day of the week).

CREATE OR REPLACE TYPE TURNI_SETTIMANALI AS VARRAY(5) OF TURNO_GIORNALIERO;

In the end, I've created the table that contains TURNI_SETTIMANALI.

CREATE TABLE TURNO_LAVORO(
    ID_TURNO CHAR(9) PRIMARY KEY,
    TURNO   TURNI_SETTIMANALI NOT NULL,
);

What I want to do is to add a constraint to the table TURNO_LAVORO in order to check if NUMERO_ORE (defined in TURNO GIORNALIERO) is greater than 5.

Could someone please help me? I've tried several solutions but nothing worked.

Body:
I doubt it is possible in check constraint. Documentation says:

Conditions of check constraints cannot contain the following
  constructs:

Calls to user-defined functions

Nested table columns or attributes

You could use trigger however. Test types and table:

create or replace type daily_cycle
    as object(day varchar(15), hour_start date, hour_count number);
create or replace type week_cycle
    as varray(5) of daily_cycle;

create table test(id int, shift week_cycle);

Trigger:

create or replace trigger hour_check before insert on test for each row
begin
  for i in 1..:new.shift.count() loop
    if :new.shift(i).hour_count < 5 then
      raise_application_error(-20001,'hours less than 5');
    end if;
  end loop;
end;

First insert works, second no:

insert into test values (1,
    week_cycle(daily_cycle('a', date '2017-12-01',  5),
               daily_cycle('b', date '2017-12-02',  8) ) );

insert into test values (2,
    week_cycle(daily_cycle('a', date '2017-12-03',  3),
               daily_cycle('b', date '2017-12-04', 12),
               daily_cycle('b', date '2017-12-05',  7) ) );


问:
How do GC work in middle of scope
I have code like:

```<code>public void foo()
{
    Object x = new LongObject();
    doSomething(x);
    //More Code

    // x is never used again
    // x = null helps GB??
    Object x2 = new LongObject();
    doSomething(x2);
}
</code>```

I would like that memory alocated by x could be free by GC if it's needed. But I don't know if set to null is necesary or compiler do it.

答:
In point of fact, the JIT does liveness analysis on references (which at bytecode level are stored as slots in the current frame). If a reference is never again read from, its slot can be reused, and the JIT will know that. It is completely possible for an object to be garbage collected while a variable that refers to it is still in lexical scope, so long as the compiler and JIT are able to prove that the variable will never again be dereferenced.

The point is: scope is a construct of the language, and specifies what a name like x means at any point in the text of the program code that it occurs. Lifetime is a property of objects, and the JIT and GC manage that -- often in non-obvious ways.

Remember that the JIT can recompile your code while it's running, and will optimize your code as it sees what happens when it executes. Unless you're really certain you know what you're doing, don't try to outsmart the JIT. Write code that is correct and let the JIT do its job, and only worry about it if you have evidence that the JIT hasn't done its job well enough.

Title: How do GC work in middle of scope

Body:
I have code like:

public void foo()
{
    Object x = new LongObject();
    doSomething(x);
    //More Code

    // x is never used again
    // x = null helps GB??
    Object x2 = new LongObject();
    doSomething(x2);
}

I would like that memory alocated by x could be free by GC if it's needed. But I don't know if set to null is necesary or compiler do it.


问:
Failed to resolve: junit:junit: 4.12
Failed to resolve: junit:junit:4.12

What is the solution to this problem
I have tried several solutions

答:
You most probably forgot to specify a repository where dependencies should be looked for.

Add for example

```<code>repositories {
    mavenCentral()
}
</code>```

or

```<code>repositories {
    jcenter()
}
</code>```

to your build script and junit will resolve properly.

If not, please post more information like your build script, and the outut of the Gradle run with using -i to get info level logging.

Btw. please read and obey http://stackoverflow.com/help/how-to-ask and https://stackoverflow.com/help/someone-answers for the future.

Title: Failed to resolve: junit:junit: 4.12

Body:
You most probably forgot to specify a repository where dependencies should be looked for.

Add for example

repositories {
    mavenCentral()
}

or

repositories {
    jcenter()
}

to your build script and junit will resolve properly.

If not, please post more information like your build script, and the outut of the Gradle run with using -i to get info level logging.

Btw. please read and obey http://stackoverflow.com/help/how-to-ask and https://stackoverflow.com/help/someone-answers for the future.


问:
How do I filter rows of an array so that only records with a particular value are displayed?
Imagine I am running 2 queries each one against a different database.

The query result from source #1 will be stored in an array.
The query result from source #2 will also be stored in an array.

Source #2 records will contain a foreign key that may or may not match up with particular records in an ID field in source #1.

So if I were to loop through source #1 and then I wanted to display only the source #2 records that matched the ID of source #1 is there a handy command within PHP that will allow me to get the filtered results that I could run once each time I ran the loop.

What I would like to avoid is having a loop within a loop to check the result before determining if it should be displayed (hopefully a built in filter command if available will have less overhead).

Any suggestions on commands that filter an array within PHP?

答:
A row in a given array is either an object or an array. We cannot run array_intersect on the entire result array because array elements are not scalar values.

I would create one loop to store the primary key indices, then call array_filter on it in which the function would check for a valid correspondence.

```<code>global $aIds;
$aIds = array();

foreach($array_masters  as $item) {
    $aIds[] = $item->master_id;
}

function filter_correspondant($row) {
    global $aIds;
    return in_array($row->slave_id, $aIds);
}

$array_slaves_filtered = array_filter($array_slaves, 'filter_correspondant');
</code>```

In the above snippet, the two arrays are $array_masters and $array_slaves. The resulting intersected array is $array_slaves_filtered which contains rows from $array_slaves that match the foreign key constraint.

Body:
A row in a given array is either an object or an array. We cannot run array_intersect on the entire result array because array elements are not scalar values.

I would create one loop to store the primary key indices, then call array_filter on it in which the function would check for a valid correspondence.

global $aIds;
$aIds = array();

foreach($array_masters  as $item) {
    $aIds[] = $item->master_id;
}

function filter_correspondant($row) {
    global $aIds;
    return in_array($row->slave_id, $aIds);
}

$array_slaves_filtered = array_filter($array_slaves, 'filter_correspondant');

In the above snippet, the two arrays are $array_masters and $array_slaves. The resulting intersected array is $array_slaves_filtered which contains rows from $array_slaves that match the foreign key constraint.


问:
Redux store and PouchDB not syncing with redux-pouchdb
I am trying to get my redux state to be synced to a PouchDB instance, but having trouble with this.

As it seems in the logs, neither is my redux state synced to PouchDB after an action happened, nor is the PouchDB document synced to the redux state on update.

I tried to implement redux-pouchdb as it is implemented in jrzerr/react-redux-pouchdb but neither do I get an error, nor does the sync work.

This is the code I am working with:

Reducer (modules/mainbase.js):

```<code>import { persistentReducer } from 'redux-pouchdb';
export const INPUT_CHANGED = 'mainbase/INPUT_CHANGED'

const initialState = {}

function mainbase (state = initialState, action) {
    switch (action.type) {
        case INPUT_CHANGED:
            state[action.key] = action.value;
            return {...state}
        default:
            return state;
    }
}

export default persistentReducer(mainbase);

export const inputChanged = (key, value) => {
  return dispatch => {
    dispatch({
      type: INPUT_CHANGED,
      key: key,
      value: value
    })
  }
}
</code>```

Root reducer (modules/index.js):

```<code>import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import mainbase from './mainbase'

export default combineReducers({
  router: routerReducer,
  mainbase
})
</code>```

Store (store.js):

```<code>import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './modules'
import { persistentStore } from 'redux-pouchdb'
import PouchDB from 'pouchdb'

export const history = createHistory()

const db = new PouchDB('testproject')

const initialState = {}

const enhancers = [
  persistentStore(db)
]

const middleware = [
  thunk,
  routerMiddleware(history)
]

const composedEnhancers = compose(
  applyMiddleware(...middleware),
  ...enhancers
)

const store = createStore(
  rootReducer,
  initialState,
  composedEnhancers
)

export default store
</code>```

I am grateful for any help.

答: In mainbase you are updating state directly. This usually does not work well. You should first create a copy of the current state, update the copy and return the updated copy as the new state.

Body:
I am trying to get my redux state to be synced to a PouchDB instance, but having trouble with this.

As it seems in the logs, neither is my redux state synced to PouchDB after an action happened, nor is the PouchDB document synced to the redux state on update.

I tried to implement redux-pouchdb as it is implemented in jrzerr/react-redux-pouchdb but neither do I get an error, nor does the sync work.

This is the code I am working with:

Reducer (modules/mainbase.js):

import { persistentReducer } from 'redux-pouchdb';
export const INPUT_CHANGED = 'mainbase/INPUT_CHANGED'

const initialState = {}

function mainbase (state = initialState, action) {
    switch (action.type) {
        case INPUT_CHANGED:
            state[action.key] = action.value;
            return {...state}
        default:
            return state;
    }
}

export default persistentReducer(mainbase);

export const inputChanged = (key, value) => {
  return dispatch => {
    dispatch({
      type: INPUT_CHANGED,
      key: key,
      value: value
    })
  }
}

Root reducer (modules/index.js):

import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import mainbase from './mainbase'

export default combineReducers({
  router: routerReducer,
  mainbase
})

Store (store.js):

import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './modules'
import { persistentStore } from 'redux-pouchdb'
import PouchDB from 'pouchdb'

export const history = createHistory()

const db = new PouchDB('testproject')

const initialState = {}

const enhancers = [
  persistentStore(db)
]

const middleware = [
  thunk,
  routerMiddleware(history)
]

const composedEnhancers = compose(
  applyMiddleware(...middleware),
  ...enhancers
)

const store = createStore(
  rootReducer,
  initialState,
  composedEnhancers
)

export default store

I am grateful for any help.


问:
How to fetch list or array of all getter setter properies inside generic method in ES6 javascript class?
I created ES6 class which has several properties. Like this :

```<code>class CustomLocalStorage {
//#region userName
get userName() {
    this._userName = localStorage.getItem("25ciWC16Hh");
    this._userName = this._userName ? decryptText(this._userName) : "";
    return this._userName;
}

set userName(newValue) {
    if(newValue) {
        this._userName = encryptText(newValue + "");
        localStorage.setItem("25ciWC16Hh", this._userName);
    }

}
remove_userName() {
    this._userName = null;
    localStorage.removeItem("25ciWC16Hh");
}
//#endregion userName

//#region webapi
get webapi() {
    this._webapi = localStorage.getItem("ALOrVJuVKt");
    this._webapi = this._webapi;
    return this._webapi;
}

set webapi(newValue) {
    this._webapi = newValue;
    localStorage.setItem("ALOrVJuVKt", this._webapi)
}
remove_webapi() {
    this._webapi = null;
    localStorage.removeItem("ALOrVJuVKt");
}
//#endregion webapi
</code>```

As seen in above code, each property is bonded to the localStorage object. Now, I want one generic method which fetches all getter/setter properties and removes it from localStorage.

So, for that I wrote following method inside the class:

```<code>removeAll() {
    for (var key in this) {
        if(key != "_settings" && key != "") {
            this[key] = null;
            localStorage.remove(key);
        }
    }
}
</code>```

But it is not fetching any getter/setter properties. Can anyone tell me where I am wrong?

答:
The problem is that getters/setters are not enumerable (like basically anything defined in a class). You can still iterate them through Object.getOwnPropertyNames though. In your case:

```<code>removeAll() {
    for (const name of Object.getOwnPropertyNames(CustomLocalStorage.prototype))
        if (name.startsWith("remove_")) // not "removeAll"!
            this[name]();
}
</code>```

Body:
I created ES6 class which has several properties. Like this :

class CustomLocalStorage {
//#region userName
get userName() {
    this._userName = localStorage.getItem("25ciWC16Hh");
    this._userName = this._userName ? decryptText(this._userName) : "";
    return this._userName;
}

set userName(newValue) {
    if(newValue) {
        this._userName = encryptText(newValue + "");
        localStorage.setItem("25ciWC16Hh", this._userName);
    }

}
remove_userName() {
    this._userName = null;
    localStorage.removeItem("25ciWC16Hh");
}
//#endregion userName

//#region webapi
get webapi() {
    this._webapi = localStorage.getItem("ALOrVJuVKt");
    this._webapi = this._webapi;
    return this._webapi;
}

set webapi(newValue) {
    this._webapi = newValue;
    localStorage.setItem("ALOrVJuVKt", this._webapi)
}
remove_webapi() {
    this._webapi = null;
    localStorage.removeItem("ALOrVJuVKt");
}
//#endregion webapi

As seen in above code, each property is bonded to the localStorage object. Now, I want one generic method which fetches all getter/setter properties and removes it from localStorage.

So, for that I wrote following method inside the class:

removeAll() {
    for (var key in this) {
        if(key != "_settings" && key != "") {
            this[key] = null;
            localStorage.remove(key);
        }
    }
}

But it is not fetching any getter/setter properties. Can anyone tell me where I am wrong?

Body:
The problem is that getters/setters are not enumerable (like basically anything defined in a class). You can still iterate them through Object.getOwnPropertyNames though. In your case:

removeAll() {
    for (const name of Object.getOwnPropertyNames(CustomLocalStorage.prototype))
        if (name.startsWith("remove_")) // not "removeAll"!
            this[name]();
}


问:
Cloning an object does not update bound values in UI - WPF
I've searched through many questions but I can only find mentions of 'observable' collections which isn't applicable to my situation.

I have a basic WPF app, an Address class and a simple form which contains 'delivery address' and 'billing address' along with a checkbox to copy the del address to billing address (which I do by cloning the Address object). I can see the billing address properties updated to that as entered for the delivery address, but this values are not updated back to the UI. I'm sure there is a better way to accomplish this. So far I ahve

```<code><Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel Orientation="Vertical">
    <TextBox Text="{Binding Path=DelAddress.Line1, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=DelAddress.Line2, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=DelAddress.Line3, Mode=TwoWay}"></TextBox>

    <CheckBox Checked="CopyDelAddress"> Same as Delivery</CheckBox>
        <TextBox Text="{Binding Path=BillAddress.Line1, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=BillAddress.Line2, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=BillAddress.Line3, Mode=TwoWay}"></TextBox>
    </StackPanel>
</Grid>
</code>```

```<code>namespace WpfApp1 {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {

    public class Address {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string Line3 { get; set; }
        public Address Clone() {
            return (Address)this.MemberwiseClone();
        }
    }
    public Address DelAddress { get; set; }
    public Address BillAddress { get; set; }
    public MainWindow() {
        InitializeComponent();

        BillAddress = new Address();
        DelAddress = new Address();

        DataContext = this;
    }

    private void CopyDelAddress(object sender, RoutedEventArgs e) {
        BillAddress = DelAddress.Clone();
    // Values are copied to BillAddress but don't appear in the UI
    }
}
}
</code>```

答:
How do you expect the UI to know that you changed the value of the property? You never told it.

You should move BillAddress and DelAddress to a viewmodel class that implements INotifyPropertyChanged and make that your DataContext.

This code is C#7. If you're using an earlier version, let me know and I'll fix it to be compatible with your compiler.

MainWindow.xaml.cs

```<code>public MainWindow() {
    InitializeComponent();

    DataContext = new MainViewModel();
}

public MainViewModel ViewModel => (MainViewModel)DataContext;

private void CopyDelAddress(object sender, RoutedEventArgs e) {
    ViewModel.BillAddress = ViewModel.DelAddress.Clone();

    //  Values ARE NOT copied to BillAddress. A clone of DelAddress
    //  is assigned to BillAddress.
}
</code>```

ViewModels.cs

```<code>public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        BillAddress = new Address();
        DelAddress = new Address();
    }

    private Address _billAddress = null;
    public Address BillAddress
    {
        get { return _billAddress; }
        set
        {
            if (value != _billAddress)
            {
                _billAddress = value;
                OnPropertyChanged();
            }
        }
    }

    private Address _delAddress = null;
    public Address DelAddress
    {
        get { return _delAddress; }
        set
        {
            if (value != _delAddress)
            {
                _delAddress = value;
                OnPropertyChanged();
            }
        }
    }
}

public class ViewModelBase : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propName = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    #endregion INotifyPropertyChanged
}
</code>```

Body:
I've searched through many questions but I can only find mentions of 'observable' collections which isn't applicable to my situation.

I have a basic WPF app, an Address class and a simple form which contains 'delivery address' and 'billing address' along with a checkbox to copy the del address to billing address (which I do by cloning the Address object). I can see the billing address properties updated to that as entered for the delivery address, but this values are not updated back to the UI. I'm sure there is a better way to accomplish this. So far I ahve

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel Orientation="Vertical">
    <TextBox Text="{Binding Path=DelAddress.Line1, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=DelAddress.Line2, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=DelAddress.Line3, Mode=TwoWay}"></TextBox>

    <CheckBox Checked="CopyDelAddress"> Same as Delivery</CheckBox>
        <TextBox Text="{Binding Path=BillAddress.Line1, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=BillAddress.Line2, Mode=TwoWay}"></TextBox>
        <TextBox Text="{Binding Path=BillAddress.Line3, Mode=TwoWay}"></TextBox>
    </StackPanel>
</Grid>

namespace WpfApp1 {
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window {

    public class Address {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string Line3 { get; set; }
        public Address Clone() {
            return (Address)this.MemberwiseClone();
        }
    }
    public Address DelAddress { get; set; }
    public Address BillAddress { get; set; }
    public MainWindow() {
        InitializeComponent();

        BillAddress = new Address();
        DelAddress = new Address();

        DataContext = this;
    }

    private void CopyDelAddress(object sender, RoutedEventArgs e) {
        BillAddress = DelAddress.Clone();
    // Values are copied to BillAddress but don't appear in the UI
    }
}
}

Body:
How do you expect the UI to know that you changed the value of the property? You never told it.

You should move BillAddress and DelAddress to a viewmodel class that implements INotifyPropertyChanged and make that your DataContext.

This code is C#7. If you're using an earlier version, let me know and I'll fix it to be compatible with your compiler.

MainWindow.xaml.cs

public MainWindow() {
    InitializeComponent();

    DataContext = new MainViewModel();
}

public MainViewModel ViewModel => (MainViewModel)DataContext;

private void CopyDelAddress(object sender, RoutedEventArgs e) {
    ViewModel.BillAddress = ViewModel.DelAddress.Clone();

    //  Values ARE NOT copied to BillAddress. A clone of DelAddress
    //  is assigned to BillAddress.
}

ViewModels.cs

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        BillAddress = new Address();
        DelAddress = new Address();
    }

    private Address _billAddress = null;
    public Address BillAddress
    {
        get { return _billAddress; }
        set
        {
            if (value != _billAddress)
            {
                _billAddress = value;
                OnPropertyChanged();
            }
        }
    }

    private Address _delAddress = null;
    public Address DelAddress
    {
        get { return _delAddress; }
        set
        {
            if (value != _delAddress)
            {
                _delAddress = value;
                OnPropertyChanged();
            }
        }
    }
}

public class ViewModelBase : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propName = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    #endregion INotifyPropertyChanged
}


问:
Intergrating Mobile Money like Mpesa and AirtelMoney with Android App
In Kenya and now spreading to Africa and the rest of the world we have an amazing way of sending and receiving money via cellphones coined mobile money. Two leading service providers Safaricom and Airtel have their mobile money platforms namely Mpesa and AirtelMoney respectively.

Since Google Merchant services are not available in Kenya and also using them will shy off potential consumers, I have been thinking of using both Mpesa and AirtelMoney to sell my app to users. Now both Mobile Money services send confirmation text messages to the sender and receivers whenever a transaction occurs.

Now how will i use this services on my app since i have been unsuccessfuly to use available apis which use web platform among other technologies. Not all of my users use internet on a daily basis since mine is an app that is used by church members. But for sure they do use mobile money on a daily basis. I will appreciate any effort towards this.

I want my app to be able to change from trial to premium when a user pays me via Mpesa because it kind of appears working with sms is easier compared with web apis

答:
Safaricom has released the M-Pesa APIs as RESTful APIs accessible through their developer portal.

The Safaricom github repository, has a sample android application that uses "Lipa na M-Pesa Online" API. This API initiates an M-Pesa transaction on behalf of the user of an app, the user needs only to input their M-Pesa PIN to complete the transaction.


问:
Unknown column error in where clause when using includes
I have this query:

```<code>includes(:foo).where(foo: { price: 0 })
</code>```

I am calling it from a class called Recipe.

Foo's have the decimal type column price:

```<code>>> Recipe.first.foo
=> #<Foo id: 1, price: #<BigDecimal:928b000,'0.0',9(18)>, slug: "something", created_at: "2017-12-05 07:54:29", updated_at: "2017-12-05 13:00:51">
</code>```

I get this error:

Mysql2::Error: Unknown column 'foo.price' in 'where clause': SELECT recipes.id AS t0_r0, recipes.foo_id AS t0_r1, recipes.parent_recipe_id AS t0_r2, recipes.name AS t0_r3, recipes.description AS t0_r4, quantities.slug AS t0_r5, recipes.created_at AS t0_r6, quantities.updated_at AS t0_r7, foos.id AS t1_r0, foos.category_id AS t1_r1, foos.price AS t1_r2, foos.slug AS t1_r3, foos.created_at AS t1_r4, foos.updated_at AS t1_r5 FROM recipes LEFT OUTER JOIN foos ON foos.id = recipes.foo_id WHERE foo.price = 0.0

Why isn't this working? I am using other queries which are all working perfectly fine.

答:
You should replace foo: (the name of your association) with foos: (the name of your table) in the where clause.

```<code>includes(:foo).where(foos: { price: 0 })
</code>```

Body:
I have this query:

includes(:foo).where(foo: { price: 0 })

I am calling it from a class called Recipe.

Foo's have the decimal type column price:

>> Recipe.first.foo
=> #<Foo id: 1, price: #<BigDecimal:928b000,'0.0',9(18)>, slug: "something", created_at: "2017-12-05 07:54:29", updated_at: "2017-12-05 13:00:51">

I get this error:

Mysql2::Error: Unknown column 'foo.price' in 'where clause': SELECT recipes.id AS t0_r0, recipes.foo_id AS t0_r1, recipes.parent_recipe_id AS t0_r2, recipes.name AS t0_r3, recipes.description AS t0_r4, quantities.slug AS t0_r5, recipes.created_at AS t0_r6, quantities.updated_at AS t0_r7, foos.id AS t1_r0, foos.category_id AS t1_r1, foos.price AS t1_r2, foos.slug AS t1_r3, foos.created_at AS t1_r4, foos.updated_at AS t1_r5 FROM recipes LEFT OUTER JOIN foos ON foos.id = recipes.foo_id WHERE foo.price = 0.0

Why isn't this working? I am using other queries which are all working perfectly fine.

Body:
You should replace foo: (the name of your association) with foos: (the name of your table) in the where clause.

includes(:foo).where(foos: { price: 0 })


问:
Cannot load map package using ArcGIS Runtime .Net for WPF local service
I am trying to load a local map package to the main window using ArcGIS Runtime .Net for WPF (Version 100.1). But somehow the local server cannot find layers in the map package. Here's my script:

```<code>        public MainWindow()
    {
        InitializeComponent();
        StartLocalServer();
    }

    private Esri.ArcGISRuntime.LocalServices.LocalServer _localServer;

    private async void StartLocalServer()
    {
       _localServer = Esri.ArcGISRuntime.LocalServices.LocalServer.Instance;
        await _localServer.StartAsync();
        var mapService = new Esri.ArcGISRuntime.LocalServices.LocalMapService(@"C:\mappackage.mpk");
        await mapService.StartAsync();
        var mapServiceUrl = mapService.Url;

    }
</code>```

I checked the generated url of the local service and not a single layer in that map package was found. See the screenshot here:
screenshot of local service
The map package was created in ArcMap 10.5 with Runtime support enabled. It contains 2 point layers, 2 polyline layers, and 1 polygon layer.

Any help would be appreciated! Thank you!

答: The Local Server deployment created automatically contains only minimum resources required by default. If the map package contains shapefiles, raster data, etc, it needs to be specified in additional deployment options in the deployment config file.</p>

Body:
I am trying to load a local map package to the main window using ArcGIS Runtime .Net for WPF (Version 100.1). But somehow the local server cannot find layers in the map package. Here's my script:

        public MainWindow()
    {
        InitializeComponent();
        StartLocalServer();
    }

    private Esri.ArcGISRuntime.LocalServices.LocalServer _localServer;

    private async void StartLocalServer()
    {
       _localServer = Esri.ArcGISRuntime.LocalServices.LocalServer.Instance;
        await _localServer.StartAsync();
        var mapService = new Esri.ArcGISRuntime.LocalServices.LocalMapService(@"C:\mappackage.mpk");
        await mapService.StartAsync();
        var mapServiceUrl = mapService.Url;

    }

I checked the generated url of the local service and not a single layer in that map package was found. See the screenshot here:
screenshot of local service
The map package was created in ArcMap 10.5 with Runtime support enabled. It contains 2 point layers, 2 polyline layers, and 1 polygon layer.

Any help would be appreciated! Thank you!


问:
How can I delete the current Git branch?
I have a branch called Test_Branch. When I try to delete it using the recommend method, I get the following error:

Cannot delete branch 'Test_Branch' checked out at '[directory
location]'.

I get no other information besides that. I can blow away the remote branch easy but the local branch won't go away.

答: If you have created multiple worktrees with git worktree, you'll need to run git worktree prune before you can delete the branch


问:
Julia function type instability
Still a bit confused about to to make functions type stable in Julia.
Here is my function

```<code>function tran7(C::Array{Float64,1}, flux_up::Float64, D::Array{Float64,1},
    v::Array{Float64,1}, AFDW::Array{Float64,1}, VF::Array{Float64,1},
    VF_mid::Array{Float64,1})

    C_up = Float64[];
    flux = Array{Float64,1}(N+1); dC = Array{Float64, 1}(N)

    C_up = (flux_up + VF[1]*(D[1]/dx_aux[1] + (1-AFDW[1])*v[1])*C[1])/
    (VF[1]*(D[1]/dx_aux[1] + AFDW[1]*v[1]))

    flux = -VF.*D.*(vcat(C_up,C,C[N])[2:(N+2)] -
            vcat(C_up,C,C[N])[1:(N+1)])./dx_aux +
            VF.*v.*(AFDW.*vcat(C_up,C) + (1-AFDW).*vcat(C,C[N]))
    flux[1] = flux_up
    dC = -(flux[2:(N+1)] - flux[1:N])./(VF_mid.*dx)
    return dC
end
</code>```

And here is the @code_warntype results

```<code>Variables:
  #self# <optimized out>
  C::Array{Float64,1}
  flux_up::Float64
  D::Array{Float64,1}
  v::Array{Float64,1}
  AFDW::Array{Float64,1}
  VF::Array{Float64,1}
  VF_mid::Array{Float64,1}
  #200::##200#203
  #201::##201#204
  #202::##202#205
  C_down <optimized out>
  C_up::ANY
  flux::ANY
  dC::ANY
  #temp#@_16::Core.MethodInstance
  #temp#@_17::ANY
  #temp#@_18::Core.MethodInstance
  #temp#@_19::ANY
  #temp#@_20 <optimized out>

Body:
  begin
      C_up::ANY = $(Expr(:foreigncall, :(:jl_alloc_array_1d),
Array{Float64,1}, svec(Any, Int64), Array{Float64,1}, 0, 0, 0)) # line 5:
      $(Expr(:foreigncall, :(:jl_alloc_array_1d), Array{Float64,1}, svec(Any, Int64), Array{Float64,1}, 0, 0, 0)) # line 6:
  flux::ANY = (Array{Float64,1})((Main.N + 1)::ANY)::Array{Float64,1} # line 6:
  dC::ANY = (Array{Float64,1})(Main.N)::Array{Float64,1} # line 8:
  SSAValue(21) = (Base.arrayref)(VF::Array{Float64,1}, 1)::Float64
  SSAValue(20) = (((Base.arrayref)(D::Array{Float64,1}, 1)::Float64 / (Main.getindex)(Main.dx_aux, 1)::ANY)::ANY + (Base.mul_float)((Base.sub_float)((Base.sitofp)(Float64, 1)::Float64, (Base.arrayref)(AFDW::Array{Float64,1}, 1)::Float64)::Float64, (Base.arrayref)(v::Array{Float64,1}, 1)::Float64)::Float64)::ANY
  SSAValue(19) = (Base.arrayref)(C::Array{Float64,1}, 1)::Float64
  $(Expr(:inbounds, false))
  # meta: location operators.jl * 424
  SSAValue(22) = ((SSAValue(21) * SSAValue(20))::ANY * SSAValue(19))::ANY
  # meta: pop location
  $(Expr(:inbounds, :pop))
  C_up::ANY = ((flux_up::Float64 + SSAValue(22))::ANY / ((Base.arrayref)(VF::Array{Float64,1}, 1)::Float64 * (((Base.arrayref)(D::Array{Float64,1}, 1)::Float64 / (Main.getindex)(Main.dx_aux, 1)::ANY)::ANY + (Base.mul_float)((Base.arrayref)(AFDW::Array{Float64,1}, 1)::Float64, (Base.arrayref)(v::Array{Float64,1}, 1)::Float64)::Float64)::ANY)::ANY)::ANY # line 11:
  #200::##200#203 = $(Expr(:new, :(Main.##200#203)))
  SSAValue(1) = $(Expr(:invoke, MethodInstance for -(::Array{Float64,1}), :(Main.-), :(VF)))
  SSAValue(3) = (Main.vcat)(C_up::ANY, C::Array{Float64,1}, (Main.getindex)(C::Array{Float64,1}, Main.N)::ANY)::ANY
  SSAValue(4) = (Main.getindex)(SSAValue(3), (Main.colon)(2, (Main.N + 2)::ANY)::ANY)::ANY
  SSAValue(5) = (Main.vcat)(C_up::ANY, C::Array{Float64,1}, (Main.getindex)(C::Array{Float64,1}, Main.N)::ANY)::ANY
  SSAValue(6) = (Main.getindex)(SSAValue(5), (Main.colon)(1, (Main.N + 1)::ANY)::ANY)::ANY
  SSAValue(7) = (SSAValue(4) - SSAValue(6))::ANY
  SSAValue(33) = D::Array{Float64,1}
  SSAValue(34) = Main.dx_aux
  $(Expr(:inbounds, false))
  # meta: location broadcast.jl broadcast 434
  SSAValue(26) = SSAValue(7)
  SSAValue(27) = SSAValue(34)
  # meta: location broadcast.jl containertype 34
  SSAValue(25) = (Base.Broadcast.promote_containertype)(Array, (Base.Broadcast.promote_containertype)((Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(26))::DataType)::ANY, (Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(27))::DataType)::ANY)::ANY)::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  unless (SSAValue(25) isa Type{Array})::Bool goto 37
  #temp#@_16::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Array})
  goto 46
  37:
  unless (SSAValue(25) isa Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})::Bool goto 41
  #temp#@_16::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})
  goto 46
  41:
  goto 43
  43:
  #temp#@_17::ANY = (Base.Broadcast.promote_containertype)(Array, SSAValue(25))::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  goto 48
  46:
  #temp#@_17::ANY = $(Expr(:invoke, :(#temp#@_16), :(Base.Broadcast.promote_containertype), Array, SSAValue(25)))
  48:
  # meta: pop location
  # meta: pop location
  $(Expr(:inbounds, :pop))
  SSAValue(8) = (Base.Broadcast.broadcast_c)(#200::##200#203, #temp#@_17::ANY, SSAValue(1), SSAValue(33), SSAValue(7), SSAValue(34))::ANY
  #201::##201#204 = $(Expr(:new, :(Main.##201#204)))
  SSAValue(12) = ((Base.broadcast)(Main.*, AFDW::Array{Float64,1}, (Main.vcat)(C_up::ANY, C::Array{Float64,1})::ANY)::ANY + (Base.broadcast)(Main.*, $(Expr(:invoke, MethodInstance for -(::Int64, ::Array{Float64,1}), :(Main.-), 1, :(AFDW))), (Main.vcat)(C::Array{Float64,1}, (Main.getindex)(C::Array{Float64,1}, Main.N)::ANY)::ANY)::ANY)::ANY
  $(Expr(:inbounds, false))
  # meta: location broadcast.jl broadcast 434
  # meta: location broadcast.jl containertype 34
  SSAValue(28) = (Base.Broadcast.promote_containertype)(Array, (Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(12))::DataType)::ANY)::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  unless (SSAValue(28) isa Type{Array})::Bool goto 62
  #temp#@_18::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Array})
  goto 71
  62:
  unless (SSAValue(28) isa Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})::Bool goto 66
  #temp#@_18::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})
  goto 71
  66:
  goto 68
  68:
  #temp#@_19::ANY = (Base.Broadcast.promote_containertype)(Array, SSAValue(28))::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  goto 73
  71:
  #temp#@_19::ANY = $(Expr(:invoke, :(#temp#@_18), :(Base.Broadcast.promote_containertype), Array, SSAValue(28)))
  73:
  # meta: pop location
  # meta: pop location
  $(Expr(:inbounds, :pop))
  SSAValue(13) = (Base.Broadcast.broadcast_c)(#201::##201#204, #temp#@_19::ANY, VF::Array{Float64,1}, v::Array{Float64,1}, SSAValue(12))::ANY
  flux::ANY = (SSAValue(8) + SSAValue(13))::ANY # line 14:
  (Main.setindex!)(flux::ANY, flux_up::Float64, 1)::ANY # line 15:
  #202::##202#205 = $(Expr(:new, :(Main.##202#205)))
  SSAValue(15) = -(((Main.getindex)(flux::ANY, (Main.colon)(2, (Main.N + 1)::ANY)::ANY)::ANY - (Main.getindex)(flux::ANY, (Main.colon)(1, Main.N)::ANY)::ANY)::ANY)::ANY
  SSAValue(35) = VF_mid::Array{Float64,1}
  SSAValue(36) = Main.dx
  $(Expr(:inbounds, false))
  # meta: location broadcast.jl broadcast 434
  SSAValue(32) = (Base.Broadcast.promote_containertype)((Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(15))::DataType)::ANY, (Base.Broadcast.promote_containertype)(Array, (Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(36))::DataType)::ANY)::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}})::ANY
  # meta: pop location
  $(Expr(:inbounds, :pop))
  dC::ANY = (Base.Broadcast.broadcast_c)(#202::##202#205, SSAValue(32), SSAValue(15), SSAValue(35), SSAValue(36))::ANY # line 16:
  return dC::ANY
  end::ANY
</code>```

I have a few questions. (1) why do the variables that were preallocated (dC, C_up, flux) still have type  any? (2) if I have a parameter (constant) defined outside of the function, such as dx_aux in here, is there an advantage of including it as an input? (3) what's the best way to deal with complex intermediary computational results?

答:
C_up, flux, and dC are not defined in the function header, so I assume they are globals. Globals can always change types because

```<code>x = 3
x = 2.0
</code>```

works in the REPL, so the functions do not specialize on the type of global variables out of fear of getting the type wrong. However, if it's a constant,

```<code>const x = 3
</code>```

then the compiler can make the assumption it won't change, and thus specialize on the type and fix this issue. Note that the value of arrays is their reference, so

```<code>const x = [3,4,5]
x[2] = 6
</code>```

is fine because the value of x is just the reference, so it doesn't change even when internal values of the array change.

(3) what's the best way to deal with complex intermediary computational results?

Cache arrays like you have here, or callable types with a cache, or ..., this is far too broad to answer well.

I'll leave with two links:

http://www.stochasticlifestyle.com/7-julia-gotchas-handle/

That describes that global variable problem and why it happens. But also:

https://github.com/JuliaLang/julia/issues/8870

suggests a new syntax:

```<code>x::Int = 3
</code>```

so that non-constant globals can have a declared type that is inferred in further functions. This seems like it won't make 1.0, but it will be a 1.x.

Title: Julia function type instability

Body:
Still a bit confused about to to make functions type stable in Julia.
Here is my function

function tran7(C::Array{Float64,1}, flux_up::Float64, D::Array{Float64,1},
    v::Array{Float64,1}, AFDW::Array{Float64,1}, VF::Array{Float64,1},
    VF_mid::Array{Float64,1})

    C_up = Float64[];
    flux = Array{Float64,1}(N+1); dC = Array{Float64, 1}(N)

    C_up = (flux_up + VF[1]*(D[1]/dx_aux[1] + (1-AFDW[1])*v[1])*C[1])/
    (VF[1]*(D[1]/dx_aux[1] + AFDW[1]*v[1]))

    flux = -VF.*D.*(vcat(C_up,C,C[N])[2:(N+2)] -
            vcat(C_up,C,C[N])[1:(N+1)])./dx_aux +
            VF.*v.*(AFDW.*vcat(C_up,C) + (1-AFDW).*vcat(C,C[N]))
    flux[1] = flux_up
    dC = -(flux[2:(N+1)] - flux[1:N])./(VF_mid.*dx)
    return dC
end

And here is the @code_warntype results

Variables:
  #self# <optimized out>
  C::Array{Float64,1}
  flux_up::Float64
  D::Array{Float64,1}
  v::Array{Float64,1}
  AFDW::Array{Float64,1}
  VF::Array{Float64,1}
  VF_mid::Array{Float64,1}
  #200::##200#203
  #201::##201#204
  #202::##202#205
  C_down <optimized out>
  C_up::ANY
  flux::ANY
  dC::ANY
  #temp#@_16::Core.MethodInstance
  #temp#@_17::ANY
  #temp#@_18::Core.MethodInstance
  #temp#@_19::ANY
  #temp#@_20 <optimized out>

Body:
  begin
      C_up::ANY = $(Expr(:foreigncall, :(:jl_alloc_array_1d),
Array{Float64,1}, svec(Any, Int64), Array{Float64,1}, 0, 0, 0)) # line 5:
      $(Expr(:foreigncall, :(:jl_alloc_array_1d), Array{Float64,1}, svec(Any, Int64), Array{Float64,1}, 0, 0, 0)) # line 6:
  flux::ANY = (Array{Float64,1})((Main.N + 1)::ANY)::Array{Float64,1} # line 6:
  dC::ANY = (Array{Float64,1})(Main.N)::Array{Float64,1} # line 8:
  SSAValue(21) = (Base.arrayref)(VF::Array{Float64,1}, 1)::Float64
  SSAValue(20) = (((Base.arrayref)(D::Array{Float64,1}, 1)::Float64 / (Main.getindex)(Main.dx_aux, 1)::ANY)::ANY + (Base.mul_float)((Base.sub_float)((Base.sitofp)(Float64, 1)::Float64, (Base.arrayref)(AFDW::Array{Float64,1}, 1)::Float64)::Float64, (Base.arrayref)(v::Array{Float64,1}, 1)::Float64)::Float64)::ANY
  SSAValue(19) = (Base.arrayref)(C::Array{Float64,1}, 1)::Float64
  $(Expr(:inbounds, false))
  # meta: location operators.jl * 424
  SSAValue(22) = ((SSAValue(21) * SSAValue(20))::ANY * SSAValue(19))::ANY
  # meta: pop location
  $(Expr(:inbounds, :pop))
  C_up::ANY = ((flux_up::Float64 + SSAValue(22))::ANY / ((Base.arrayref)(VF::Array{Float64,1}, 1)::Float64 * (((Base.arrayref)(D::Array{Float64,1}, 1)::Float64 / (Main.getindex)(Main.dx_aux, 1)::ANY)::ANY + (Base.mul_float)((Base.arrayref)(AFDW::Array{Float64,1}, 1)::Float64, (Base.arrayref)(v::Array{Float64,1}, 1)::Float64)::Float64)::ANY)::ANY)::ANY # line 11:
  #200::##200#203 = $(Expr(:new, :(Main.##200#203)))
  SSAValue(1) = $(Expr(:invoke, MethodInstance for -(::Array{Float64,1}), :(Main.-), :(VF)))
  SSAValue(3) = (Main.vcat)(C_up::ANY, C::Array{Float64,1}, (Main.getindex)(C::Array{Float64,1}, Main.N)::ANY)::ANY
  SSAValue(4) = (Main.getindex)(SSAValue(3), (Main.colon)(2, (Main.N + 2)::ANY)::ANY)::ANY
  SSAValue(5) = (Main.vcat)(C_up::ANY, C::Array{Float64,1}, (Main.getindex)(C::Array{Float64,1}, Main.N)::ANY)::ANY
  SSAValue(6) = (Main.getindex)(SSAValue(5), (Main.colon)(1, (Main.N + 1)::ANY)::ANY)::ANY
  SSAValue(7) = (SSAValue(4) - SSAValue(6))::ANY
  SSAValue(33) = D::Array{Float64,1}
  SSAValue(34) = Main.dx_aux
  $(Expr(:inbounds, false))
  # meta: location broadcast.jl broadcast 434
  SSAValue(26) = SSAValue(7)
  SSAValue(27) = SSAValue(34)
  # meta: location broadcast.jl containertype 34
  SSAValue(25) = (Base.Broadcast.promote_containertype)(Array, (Base.Broadcast.promote_containertype)((Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(26))::DataType)::ANY, (Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(27))::DataType)::ANY)::ANY)::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  unless (SSAValue(25) isa Type{Array})::Bool goto 37
  #temp#@_16::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Array})
  goto 46
  37:
  unless (SSAValue(25) isa Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})::Bool goto 41
  #temp#@_16::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})
  goto 46
  41:
  goto 43
  43:
  #temp#@_17::ANY = (Base.Broadcast.promote_containertype)(Array, SSAValue(25))::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  goto 48
  46:
  #temp#@_17::ANY = $(Expr(:invoke, :(#temp#@_16), :(Base.Broadcast.promote_containertype), Array, SSAValue(25)))
  48:
  # meta: pop location
  # meta: pop location
  $(Expr(:inbounds, :pop))
  SSAValue(8) = (Base.Broadcast.broadcast_c)(#200::##200#203, #temp#@_17::ANY, SSAValue(1), SSAValue(33), SSAValue(7), SSAValue(34))::ANY
  #201::##201#204 = $(Expr(:new, :(Main.##201#204)))
  SSAValue(12) = ((Base.broadcast)(Main.*, AFDW::Array{Float64,1}, (Main.vcat)(C_up::ANY, C::Array{Float64,1})::ANY)::ANY + (Base.broadcast)(Main.*, $(Expr(:invoke, MethodInstance for -(::Int64, ::Array{Float64,1}), :(Main.-), 1, :(AFDW))), (Main.vcat)(C::Array{Float64,1}, (Main.getindex)(C::Array{Float64,1}, Main.N)::ANY)::ANY)::ANY)::ANY
  $(Expr(:inbounds, false))
  # meta: location broadcast.jl broadcast 434
  # meta: location broadcast.jl containertype 34
  SSAValue(28) = (Base.Broadcast.promote_containertype)(Array, (Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(12))::DataType)::ANY)::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  unless (SSAValue(28) isa Type{Array})::Bool goto 62
  #temp#@_18::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Array})
  goto 71
  62:
  unless (SSAValue(28) isa Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})::Bool goto 66
  #temp#@_18::Core.MethodInstance = MethodInstance for promote_containertype(::Type{Array}, ::Type{Base.SparseArrays.HigherOrderFns.PromoteToSparse})
  goto 71
  66:
  goto 68
  68:
  #temp#@_19::ANY = (Base.Broadcast.promote_containertype)(Array, SSAValue(28))::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}}
  goto 73
  71:
  #temp#@_19::ANY = $(Expr(:invoke, :(#temp#@_18), :(Base.Broadcast.promote_containertype), Array, SSAValue(28)))
  73:
  # meta: pop location
  # meta: pop location
  $(Expr(:inbounds, :pop))
  SSAValue(13) = (Base.Broadcast.broadcast_c)(#201::##201#204, #temp#@_19::ANY, VF::Array{Float64,1}, v::Array{Float64,1}, SSAValue(12))::ANY
  flux::ANY = (SSAValue(8) + SSAValue(13))::ANY # line 14:
  (Main.setindex!)(flux::ANY, flux_up::Float64, 1)::ANY # line 15:
  #202::##202#205 = $(Expr(:new, :(Main.##202#205)))
  SSAValue(15) = -(((Main.getindex)(flux::ANY, (Main.colon)(2, (Main.N + 1)::ANY)::ANY)::ANY - (Main.getindex)(flux::ANY, (Main.colon)(1, Main.N)::ANY)::ANY)::ANY)::ANY
  SSAValue(35) = VF_mid::Array{Float64,1}
  SSAValue(36) = Main.dx
  $(Expr(:inbounds, false))
  # meta: location broadcast.jl broadcast 434
  SSAValue(32) = (Base.Broadcast.promote_containertype)((Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(15))::DataType)::ANY, (Base.Broadcast.promote_containertype)(Array, (Base.Broadcast._containertype)((Base.Broadcast.typeof)(SSAValue(36))::DataType)::ANY)::UNION{TYPE{ARRAY}, TYPE{BASE.SPARSEARRAYS.HIGHERORDERFNS.PROMOTETOSPARSE}})::ANY
  # meta: pop location
  $(Expr(:inbounds, :pop))
  dC::ANY = (Base.Broadcast.broadcast_c)(#202::##202#205, SSAValue(32), SSAValue(15), SSAValue(35), SSAValue(36))::ANY # line 16:
  return dC::ANY
  end::ANY

I have a few questions. (1) why do the variables that were preallocated (dC, C_up, flux) still have type  any? (2) if I have a parameter (constant) defined outside of the function, such as dx_aux in here, is there an advantage of including it as an input? (3) what's the best way to deal with complex intermediary computational results?

Body:
C_up, flux, and dC are not defined in the function header, so I assume they are globals. Globals can always change types because

x = 3
x = 2.0

works in the REPL, so the functions do not specialize on the type of global variables out of fear of getting the type wrong. However, if it's a constant,

const x = 3

then the compiler can make the assumption it won't change, and thus specialize on the type and fix this issue. Note that the value of arrays is their reference, so

const x = [3,4,5]
x[2] = 6

is fine because the value of x is just the reference, so it doesn't change even when internal values of the array change.

(3) what's the best way to deal with complex intermediary computational results?

Cache arrays like you have here, or callable types with a cache, or ..., this is far too broad to answer well.

I'll leave with two links:

http://www.stochasticlifestyle.com/7-julia-gotchas-handle/

That describes that global variable problem and why it happens. But also:

https://github.com/JuliaLang/julia/issues/8870

suggests a new syntax:

x::Int = 3

so that non-constant globals can have a declared type that is inferred in further functions. This seems like it won't make 1.0, but it will be a 1.x.


问:
How to make string to json with javascript? (like A//a1,A//a2,A//a3//a31 ..)
How to convert a string to JSON with javascript or jQuery? I've been thinking all day, but I do not get a good idea.

This task is to dynamically create the treeview in the client side (ASP.Net). My idea is to convert the string to an object and convert to JSON type. (String -> object -> JSON) I tried, but the day is gone. It is difficult to construct 2 more depth like A->a3->a31.

String is

```<code>var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";
</code>```

and JSON format is

{
  "title": "A",
  "key": "1",
  "folder": true,
  "children": [{
      "title": "a1",
      "key": "2"
    }, {
      "title": "a2",
      "key": "3"
    }, {
      "title": "a3",
      "key": "4",
      "folder": true,
      "children": [{
          "title": "a31",
          "key": "5"
        }...
      }]
  }```

(This is fancytreeview plugin)

‘//‘ is depth and ‘,’ is split.

Please help me..

Edit)
I want to turn ‘sString’ to JSON format.. but It’s ok just JSON type string.

Please understand that my sentence is strange because my native language is not English.

Edit2)
oh.. I want to convert the string to an object and then convert it back to JSON format. I do not have the confidence to convert that string into JSON format right away. Because there are more than 8000 variants. If It’s can, let me know how.

答:
Try below code. I have used associative array to store already processed folder for faster lookup.

I hope it helps you.

var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

var sArr = sString.split(","); // We will split it by comma so that we can iterate through its items.
var output = []; // Final result will be stored here.
var hash = {}; // It used to keep track of itemObjectect's position for faster lookup.
var counter = 1; // Its value will be used to assign to key;
for(var i = 0; i < sArr.length; i++){
    var items = sArr[i].split("//");
    var itemObject = {}; // Object to store value of each item.
    var parentItemObject = {}; // It will refer to current parentObject during iteration.
    for(var j = 0; j < items.length; j++){
   // Check if item is already processed and stored in hash map.
   if(hash.hasOwnProperty(items[j])){
     // Check if parent Object value is empty then we will fetch it from hash directly.
     if(isEmpty(parentItemObject)){
    parentItemObject = output[hash[items[j]]];
     }
     else{
    // It is parent element but is child of another element. Then we will fetch it from it's children array.
    if(typeof parentItemObject.children !== "undefined"){
      parentItemObject = parentItemObject.children[hash[items[j]]];
    }
     }
     continue;
   }

    itemObject.title = items[j];
    itemObject.key = counter++;

     // Check if it is a folder item.
     if(j != items.length -1){
    itemObject.folder = true;
    itemObject.children = [];
    if(isEmpty(parentItemObject)){
     parentItemObject = itemObject;
     hash[itemObject.title] = output.length;
     output.push(itemObject);
    }
    else{
     if(typeof parentItemObject.children !== "undefined"){
       hash[itemObject.title] = parentItemObject.children.length;
       parentItemObject.children.push(itemObject);
     }
     parentItemObject = itemObject;
    }
     }
     else{

    if(isEmpty(parentItemObject)){
     parentItemObject = itemObject;
     hash[itemObject.title] = output.length;
     output.push(itemObject);
    }
    if(typeof parentItemObject.children !== "undefined"){
      hash[itemObject.title] = parentItemObject.children.length;
      parentItemObject.children.push(itemObject);
    }
     }

   itemObject = {};
    }

    //console.log(items);
  }

function isEmpty(itemObject) {
  return Object.keys(itemObject).length === 0;
}

//console.log(hash);
console.log(JSON.stringify(output,null,2));```

Body:
How to convert a string to JSON with javascript or jQuery? I've been thinking all day, but I do not get a good idea.

This task is to dynamically create the treeview in the client side (ASP.Net). My idea is to convert the string to an object and convert to JSON type. (String -> object -> JSON) I tried, but the day is gone. It is difficult to construct 2 more depth like A->a3->a31.

String is

var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

and JSON format is

{
  "title": "A",
  "key": "1",
  "folder": true,
  "children": [{
      "title": "a1",
      "key": "2"
    }, {
      "title": "a2",
      "key": "3"
    }, {
      "title": "a3",
      "key": "4",
      "folder": true,
      "children": [{
          "title": "a31",
          "key": "5"
        }...
      }]
  }

(This is fancytreeview plugin)

‘//‘ is depth and ‘,’ is split.

Please help me..

Edit)
I want to turn ‘sString’ to JSON format.. but It’s ok just JSON type string.

Please understand that my sentence is strange because my native language is not English.

Edit2)
oh.. I want to convert the string to an object and then convert it back to JSON format. I do not have the confidence to convert that string into JSON format right away. Because there are more than 8000 variants. If It’s can, let me know how.


问:
Create table at runtime with Ecto
According to this issue – Dynamic Models in Phoenix Framework – it is possible to dynamically create a model in Elixir using Module.create.

Is it also possible to create a table in the database for this model during runtime, i.e. without using Ecto migration files?

答: In your case (creating new report table every month) I would ditch creating DB table idea and consider using ETS / DETS combo. They are key-value stores (ETS - in-memory, DETS - data saved on disk - this is what you basically need) and you can read more about them here.</p>

Title: Create table at runtime with Ecto


问:
What means an InvalidOperationException on Process.ExitTime "Process was not started by this object, so requested information cannot be determined."
We have a tool that manages several processes of a computer and from time to time in uncertain conditions we get an InvalidOperationExceptionwhen accessing the MSDN: Process.ExitTime property.

The exception message says

process was not started by this object, so requested information
  cannot be determined

Does that mean that I can only get the exit time of a process that I've started myself? That's not documented anywhere.

答: According to the example from MSDN at first you need to start a process, then you need to wait it to exit and at this point you can get a myProcess.ExitCode value. Probably you just filled some fields in created Process object but didn't started it. Also if you want to get an exit time of foreign process you didn't allowed to control, you need to use some monitors or hooks to get an exit time. Even though, the information you gave doesn't enough to grasp your intention, so provide it if you don't mind.</p>