问:
Unit testing with stubs and mocks
I'm trying to write tests for some classes. The classes I want to test use different repositories to to get and save things from my database.

A simplified example

```<code>public class MyClass
{
    private readonly IGroupRepository _groupRepo;

  public MyClass(IGroupRepository groupRepo){
    _groupRepo = groupRepo;
  }

  public void Execute(PersonInfo personInfo, string id){
  var group = _groupRepo.GetById(id);

  var person = group.Persons.First(p=> p.Id == personInfo.Id);

  person.FirstName = personInfo.FirstName;
  person.LastName = personInfo.LastName;

  _groupRepo.Save(group);
  }
}
</code>```

What I want to do is make sure that what is saved into the db is correct.

So I have a unit test like this:

```<code>[TestMethod]
public void TestMethod(){
    var groupId = "ABC";
    var personId = 1;

    ver personInfo = new PersonInfo()
    {
      Id = personId,
      FirstName = "Sam",
      LastName = "Smith"
    }

    var groupStub = new Mock<IGroupRepository>;
    groupStub.Setup(x=> x.GetById(groupId)).Returns(new Group(){
            Id = groupId,
            Persons = List<Person>()
            {
                new Person()
                {
                    Id = personId,
                    FirstName = "George",
                    LastName = "Bolton",
                }
            }
        }
    });

    var myClass = new MyClass();
    myClass.Execute(personInfo, groupId);

    var group = groupStub.GetById(groupId);
    var person = group.Persons.First(p=> p.Id == personId);

    Assert.AreEqual(personInfo.FirstName, person.FirstName);
}
</code>```

I thought this was fine, but then I was reading more up on it and I read that you are not supposed to assert on a sub, which I think I'm doing in my assert statement? I'm getting info from the stub, then using Assert on the result?

So I'm not sure if this is the correct way to test. If not, why and what is the correct way?

答:
Yes, you are correct that there is something wrong with how the test is written. In fact, you are not testing MyClass. You are instead testing that the
mocking framework you use works. As proof, comment the two lines that use MyClass and run the test again. It will still pass:

```<code>[TestMethod]
public void TestMethod()
{
    var groupId = "ABC";
    var personId = 1;

    ver personInfo = new PersonInfo()
    {
      Id = personId,
      FirstName = "Sam",
      LastName = "Smith"  `
    }

    var groupStub = new Mock<IGroupRepository>;
    groupStub.Setup(x=> x.GetById(groupId)).Returns(new Group(){
            Id = groupId,
            Persons = List<Person>()
            {
                new Person()
                {
                    Id = personId,
                    FirstName = "George",
                    LastName = "Bolton",
                }
            }
        }
    });

    // var myClass = new MyClass();
    // myClass.Execute(personInfo, groupId);

    var group = groupStub.GetById(groupId);
    var person = group.Persons.First(p=> p.Id == personId);

    Assert.AreEqual(personInfo.FirstName, person.FirstName);
}
</code>```

What generally helps me in writing unit tests, is asking myself first what behaviour I am really testing. In this particular case, I believe you want to test that when calling MyClass.Execute,
you expect that IGroupRepository.Save is called with the person's name changed.

Writing that assertion in the mocking framework I am familiar with (NSubstitute), looks like this:

```<code>groupStub.Received().Save(
    Arg.Is<Group>(group =>
    {
        return groupId.Id == groupId &&
            group.Persons[0].Id == personId &&
            group.Persons[0].FirstName == "Sam" &&
            group.Persons[0].LastName == "Smith";
    });
</code>```

There should be something similar in the mocking framework you use.

Title: Unit testing with stubs and mocks

Body:
I'm trying to write tests for some classes. The classes I want to test use different repositories to to get and save things from my database.

A simplified example

public class MyClass
{
    private readonly IGroupRepository _groupRepo;

  public MyClass(IGroupRepository groupRepo){
    _groupRepo = groupRepo;
  }

  public void Execute(PersonInfo personInfo, string id){
  var group = _groupRepo.GetById(id);

  var person = group.Persons.First(p=> p.Id == personInfo.Id);

  person.FirstName = personInfo.FirstName;
  person.LastName = personInfo.LastName;

  _groupRepo.Save(group);
  }
}

What I want to do is make sure that what is saved into the db is correct.

So I have a unit test like this:

[TestMethod]
public void TestMethod(){
    var groupId = "ABC";
    var personId = 1;

    ver personInfo = new PersonInfo()
    {
      Id = personId,
      FirstName = "Sam",
      LastName = "Smith"
    }

    var groupStub = new Mock<IGroupRepository>;
    groupStub.Setup(x=> x.GetById(groupId)).Returns(new Group(){
            Id = groupId,
            Persons = List<Person>()
            {
                new Person()
                {
                    Id = personId,
                    FirstName = "George",
                    LastName = "Bolton",
                }
            }
        }
    });

    var myClass = new MyClass();
    myClass.Execute(personInfo, groupId);

    var group = groupStub.GetById(groupId);
    var person = group.Persons.First(p=> p.Id == personId);

    Assert.AreEqual(personInfo.FirstName, person.FirstName);
}

I thought this was fine, but then I was reading more up on it and I read that you are not supposed to assert on a sub, which I think I'm doing in my assert statement? I'm getting info from the stub, then using Assert on the result?

So I'm not sure if this is the correct way to test. If not, why and what is the correct way?

Body:
Yes, you are correct that there is something wrong with how the test is written. In fact, you are not testing MyClass. You are instead testing that the
mocking framework you use works. As proof, comment the two lines that use MyClass and run the test again. It will still pass:

[TestMethod]
public void TestMethod()
{
    var groupId = "ABC";
    var personId = 1;

    ver personInfo = new PersonInfo()
    {
      Id = personId,
      FirstName = "Sam",
      LastName = "Smith"  `
    }

    var groupStub = new Mock<IGroupRepository>;
    groupStub.Setup(x=> x.GetById(groupId)).Returns(new Group(){
            Id = groupId,
            Persons = List<Person>()
            {
                new Person()
                {
                    Id = personId,
                    FirstName = "George",
                    LastName = "Bolton",
                }
            }
        }
    });

    // var myClass = new MyClass();
    // myClass.Execute(personInfo, groupId);

    var group = groupStub.GetById(groupId);
    var person = group.Persons.First(p=> p.Id == personId);

    Assert.AreEqual(personInfo.FirstName, person.FirstName);
}

What generally helps me in writing unit tests, is asking myself first what behaviour I am really testing. In this particular case, I believe you want to test that when calling MyClass.Execute,
you expect that IGroupRepository.Save is called with the person's name changed.

Writing that assertion in the mocking framework I am familiar with (NSubstitute), looks like this:

groupStub.Received().Save(
    Arg.Is<Group>(group =>
    {
        return groupId.Id == groupId &&
            group.Persons[0].Id == personId &&
            group.Persons[0].FirstName == "Sam" &&
            group.Persons[0].LastName == "Smith";
    });

There should be something similar in the mocking framework you use.


来源: stackexchange

问:
document.getElementById giving Null by JS not by HTML
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

```<code><input class="easyui-combobox" name="language" style="width:30%;" id= "XX">
</code>```

JS Code:

```<code>var cc = document.getElementById("XX");
</code>```

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

```<code>var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
</code>```

Here I am getting null after applying this:

```<code>var cc = document.getElementById("XX");
</code>```

答:
You have created your element using -

```<code>var input = document.createElement("input");
</code>```

Now you need to append it to HTML so that you can find it on DOM.

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);

var fetchedElement = document.getElementById("XX");
console.log(fetchedElement);```

createElement() creates an Element Node.

appendChild() adds your element node to DOM.

ContentLicense: CC BY-SA 3.0

Body:
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

<input class="easyui-combobox" name="language" style="width:30%;" id= "XX">

JS Code:

var cc = document.getElementById("XX");

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";

Here I am getting null after applying this:

var cc = document.getElementById("XX");

Body:
You have created your element using -

var input = document.createElement("input");

Now you need to append it to HTML so that you can find it on DOM.

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);

var fetchedElement = document.getElementById("XX");
console.log(fetchedElement);

createElement() creates an Element Node.

appendChild() adds your element node to DOM.


问:
Can't update android studio on Ubuntu
I am trying to update my studio from version 2.2.3 to 2.3 in Ubuntu 16.04 LTS. I am very new to Ubuntu and I can't seem to figure out as why is studio not updating. When I click update and restart it downloads the patches and closes and doesn't restarts. When I open it manually then it still is on the version 2.2.3 and again prompts to download and install latest version.

答:
I am having a similar problem while updating from 2.3.2 to 2.3.3.

Go to the bin folder of your Android Studio installation folder:  e.g. cd opt/android-studio/bin

Provide run permission for studio.sh file:  chmod +x studio.sh

Run Android Studio from here: ./studio.sh

and try "update and restart" from android studio.

Title: Can't update android studio on Ubuntu


问:
Authentication errors in HTTP requisitions with AngularJs and Keycloak
I'm trying to create an app for study purposes with AngularJS and Keycloak.

And I'm experiencing some errors in my HTML requisitions:

Failed to load resource: the server responded with a status of 401 ()

XMLHttpRequest cannot load http://127.0.0.1:8081/customers. Response for preflight has invalid HTTP status code 401

My problem is in the requests made by the app. The requests made by Postman works fine.

My HTTP Requisition:

```<code>$http({
  method: 'GET',
  url: 'http://127.0.0.1:8081/customers'
}).then(function success(response) {
  console.log('success');
}, function error() {
  console.log('error');
});
</code>```

My angular configs:

```<code>app.config(['$httpProvider', function ($httpProvider) {
   $httpProvider.interceptors.push('BearerAuthInterceptor');
}]);

app.factory('BearerAuthInterceptor', function () {
  var token = window._keycloak.token;

  return {
    request: function (config) {
      config.headers = config.headers || {};
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    }
  };
});
</code>```

From what I saw, the token is being sent in the header correctly.

I would be grateful if anyone could help me.

答:
add "enable-cors":true  on backend application keycloak.json file.

And add this class also.

```<code>@Component
public class CORSFilter implements Filter {
    static Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}
</code>```

Body:
I'm trying to create an app for study purposes with AngularJS and Keycloak.

And I'm experiencing some errors in my HTML requisitions:

Failed to load resource: the server responded with a status of 401 ()

XMLHttpRequest cannot load http://127.0.0.1:8081/customers. Response for preflight has invalid HTTP status code 401

My problem is in the requests made by the app. The requests made by Postman works fine.

My HTTP Requisition:

$http({
  method: 'GET',
  url: 'http://127.0.0.1:8081/customers'
}).then(function success(response) {
  console.log('success');
}, function error() {
  console.log('error');
});

My angular configs:

app.config(['$httpProvider', function ($httpProvider) {
   $httpProvider.interceptors.push('BearerAuthInterceptor');
}]);

app.factory('BearerAuthInterceptor', function () {
  var token = window._keycloak.token;

  return {
    request: function (config) {
      config.headers = config.headers || {};
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    }
  };
});

From what I saw, the token is being sent in the header correctly.

I would be grateful if anyone could help me.

Body:
add "enable-cors":true  on backend application keycloak.json file.

And add this class also.

@Component
public class CORSFilter implements Filter {
    static Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}


问:
doinbackground() method is not called in aync task
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

```<code>private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}
</code>```

Any help is appreciated.
Thank you

答: Remove Toast from the doInBackground() and put the either in onPostExecute() or run the toast in  runonUIthread()</p>

Body:
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}

Any help is appreciated.
Thank you


问:
Python Itertools permutations with strings
i want to use itertools permutations for strings instead of just letters.

```<code>import itertools
lst = list(permutations(("red","blue"),3))
#This returns []
</code>```

I know i can do something like:

```<code>a = list(permutations(range(3),3))
for i in range(len(a)):
a[i] = list(map(lambda x: 'red' if x==0 else 'blue' if x==1 else 'green',a[i]))
</code>```

EDIT:
I want to key in this as my input, and get this as my output

```<code>input: ("red","red","blue")

output:
[(’red’, ’red’, ’red’), (’red’, ’red’, ’blue’),\
(’red’, ’blue’, ’red’), (’red’, ’blue’, ’blue’), (’blue’, ’red’, ’red’), \
(’blue’, ’red’, ’blue’), (’blue’, ’blue’, ’red’), (’blue’, ’blue’, ’blue’)]
</code>```

答:
You can try with itertools.product like this:

```<code>import itertools
lst = list(set(itertools.product(("red","red","blue"),repeat=3))) # use set to drop duplicates
lst
</code>```

lst will be:

```<code>[('red', 'blue', 'red'),
 ('blue', 'red', 'red'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue'),
 ('blue', 'red', 'blue'),
 ('red', 'blue', 'blue'),
 ('red', 'red', 'blue'),
 ('red', 'red', 'red')]
</code>```

Update:

```<code>import itertools
lst = list(itertools.product(("red","blue"),repeat=3))
lst
</code>```

output:

```<code>[('red', 'red', 'red'),
 ('red', 'red', 'blue'),
 ('red', 'blue', 'red'),
 ('red', 'blue', 'blue'),
 ('blue', 'red', 'red'),
 ('blue', 'red', 'blue'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue')]
</code>```

Body:
i want to use itertools permutations for strings instead of just letters.

import itertools
lst = list(permutations(("red","blue"),3))
#This returns []

I know i can do something like:

a = list(permutations(range(3),3))
for i in range(len(a)):
a[i] = list(map(lambda x: 'red' if x==0 else 'blue' if x==1 else 'green',a[i]))

EDIT:
I want to key in this as my input, and get this as my output

input: ("red","red","blue")

output:
[(’red’, ’red’, ’red’), (’red’, ’red’, ’blue’),\
(’red’, ’blue’, ’red’), (’red’, ’blue’, ’blue’), (’blue’, ’red’, ’red’), \
(’blue’, ’red’, ’blue’), (’blue’, ’blue’, ’red’), (’blue’, ’blue’, ’blue’)]

Body:
You can try with itertools.product like this:

import itertools
lst = list(set(itertools.product(("red","red","blue"),repeat=3))) # use set to drop duplicates
lst

lst will be:

[('red', 'blue', 'red'),
 ('blue', 'red', 'red'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue'),
 ('blue', 'red', 'blue'),
 ('red', 'blue', 'blue'),
 ('red', 'red', 'blue'),
 ('red', 'red', 'red')]

Update:

import itertools
lst = list(itertools.product(("red","blue"),repeat=3))
lst

output:

[('red', 'red', 'red'),
 ('red', 'red', 'blue'),
 ('red', 'blue', 'red'),
 ('red', 'blue', 'blue'),
 ('blue', 'red', 'red'),
 ('blue', 'red', 'blue'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue')]


问:
Prevent validation when you have hide field Codeigniter
I am doing an airline reservation and I have 2 radio button.

1) One way

2) Round Trip

The things that I've done is when I select the Round Trip, all the fields are there(Depart, return and number of passengers) but I when select One way radio button the return field should hide.

In my controller, I have validation that all fields are required. The problem is, whenever I tried to search in One Way(the return field is hidden) it gives me an "Return field is required" error

Question: How can I prevent the validation in return field when I choice the One Way radio button?

View

```<code><div class="pure-u-1-1 searchcontainer center">
            <div class="pure-u-1-1 findcheaptxt">
               <span>Find Cheap Flights</span>
            </div>
            <div class="pure-u-1-1 radiobtn">
               <form action="">
                  <input type="radio" name="flight_type"  value="one_way" class="onew" style=""  >One Way
                  <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
               </form>
            </div>

            <form method="post" enctype="multipart/form-data" action="<?= base_url() .'User/search'?>">
            <?= validation_errors(); ?>
            <div class="pure-u-1-1 fromto">
               <div class="pure-u-1-1">
                  <label for="from" class="margin2px">From</label>

                  <select name="flight_from">
                    <option value="">-- Please select depature --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>

                  </select>

               </div>
                <div class="pure-u-1-1">
                  <label for="to" class="tomargin">To</label>
                  <!-- <input type="text" class="fromto"><br> -->
                  <select class="fromto" name="flight_to">
                    <option value="">-- Please select destination --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>
                  </select>
                </div>
               <div class="pure-u-1-1 dr" name ="depart">
                  <label for="depart" class="drr">Depart</label>
                  <input type="date" id="depart" name="depart" class="departreturn">

               </div>
                <div class="pure-u-1-1 dr" id="try">
                  <label for="return" class="drr">Return</label>
                  <input type="date" id="return" name="return" class="departreturn"><br>

                  </div>
            </div>

            <div class="pure-u-1-1 personfield">
                <!--  <div class="pure-u-1-5 margin">
                    Adult<br>
                    <input type="text" name="" class="person">
                 </div>
                 <div class="pure-u-1-5 margin">
                    Seniors<br>
                    <input type="text" name="" class="person">
                 </div>
                 <div class="pure-u-1-5 margin">
                    Children<br>
                    <input type="text" name="" class="person">
                 </div>
                 <div class="pure-u-1-5">
                    Class<br>
                    <input type="text" name="" class="person">
                 </div> -->
                  <div class="pure-u-1-5 margin">
                    Number of Passengers<br>
                    <input type="text" name="no_of_passengers" class="person">
                 </div>

            </div>
                 <div class="pure-u-1-1 center">
                      <button class="submitbtn">Search Now</button>
               </form>
            </div>
         </div>
      </div>
</code>```

Controller

```<code>public function search()
{
    $data['countries'] = $this->CrudModel->get('countries');
    $this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
    $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
    $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');

    if ($_POST['flight_type'] == 'round_trip')
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $return = $_POST['return'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
            $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$return,$no_of_passengers);
            $this->load->view('partials/header');
            $this->load->view('partials/nav');
            $this->load->view('result',$data);
        }

    }
    else
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$no_of_passengers);
        $this->load->view('partials/header');
        $this->load->view('partials/nav');
        $this->load->view('result',$data);
        }

    }
}
</code>```

My ajax/js when hiding the return field

```<code> <script type="text/javascript">
$(document).on('change', 'input:radio[name=flight_type]', function(){
    $('div[id^="try"]').toggle(); // hide all DIVs begining with "my_radio_"
    $('#' + $(this).attr('id') + '_text').show(); // show the current one
});
</script>
</code>```

答:
First of all you have to add value to round trip:

```<code> <input type="radio" name="flight_type" value="round_trip" class="roundw" style="" checked>Round Trip
</code>```

Then do validation condition like below:

```<code>  // Global validation for this method
 if ($_POST['flight_type'] == 'round_trip')
   {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
   }
   else if($_POST['flight_type'] == 'one_way'){
       // add validation for one way trip
   }
</code>```

Body:
I am doing an airline reservation and I have 2 radio button.

1) One way

2) Round Trip

The things that I've done is when I select the Round Trip, all the fields are there(Depart, return and number of passengers) but I when select One way radio button the return field should hide.

In my controller, I have validation that all fields are required. The problem is, whenever I tried to search in One Way(the return field is hidden) it gives me an "Return field is required" error

Question: How can I prevent the validation in return field when I choice the One Way radio button?

View

               Find Cheap Flights

               <form action="">
                  <input type="radio" name="flight_type"  value="one_way" class="onew" style=""  >One Way
                  <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
               </form>

            <form method="post" enctype="multipart/form-data" action="<?= base_url() .'User/search'?>">
            <?= validation_errors(); ?>

                  From

                  <select name="flight_from">
                    <option value="">-- Please select depature --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>

                  </select>

                  To

                  <select class="fromto" name="flight_to">
                    <option value="">-- Please select destination --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>
                  </select>

                  Depart
                  <input type="date" id="depart" name="depart" class="departreturn">

                  Return
                  <input type="date" id="return" name="return" class="departreturn">

                    Number of Passengers

                    <input type="text" name="no_of_passengers" class="person">

                      <button class="submitbtn">Search Now</button>
               </form>

Controller

public function search()
{
    $data['countries'] = $this->CrudModel->get('countries');
    $this->form_validation->set_error_delimiters('
', '
');
    $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
    $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');

    if ($_POST['flight_type'] == 'round_trip')
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $return = $_POST['return'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
            $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$return,$no_of_passengers);
            $this->load->view('partials/header');
            $this->load->view('partials/nav');
            $this->load->view('result',$data);
        }

    }
    else
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$no_of_passengers);
        $this->load->view('partials/header');
        $this->load->view('partials/nav');
        $this->load->view('result',$data);
        }

    }
}

My ajax/js when hiding the return field

Body:
First of all you have to add value to round trip:

 <input type="radio" name="flight_type" value="round_trip" class="roundw" style="" checked>Round Trip

Then do validation condition like below:

  // Global validation for this method
 if ($_POST['flight_type'] == 'round_trip')
   {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
   }
   else if($_POST['flight_type'] == 'one_way'){
       // add validation for one way trip
   }


问:
How to programmatically click on facet value to filter events on a Simile Timeline Widget?
I have a facet set up thus:

```<code><div ex:role="facet" ex:expression=".chapter" ex:facetLabel="Chapter" ex:sortMode=".count" ex:fixedOrder="1;2;3;4;5;6;7;8;9;10;11;12" ></div>
</code>```

It's for filtering Chapter numbers of timeline events. How would I programmatically select one of the facet choices to filter visible timeline events? I tried simulating a click event on the anchor in the generated HTMl, and have been unable to expose anything in the API.

The end goal is to allow filtering by chapter by getting a URL param.

http://www.jamesfishwick.com/timeline/

答:
The attribute ex:selection can be used to pre-filter items.

I was able to add the attribute (i.e. ex:selection="3") from a param with no problems.

ContentLicense: CC BY-SA 2.5

Body:
I have a facet set up thus:

It's for filtering Chapter numbers of timeline events. How would I programmatically select one of the facet choices to filter visible timeline events? I tried simulating a click event on the anchor in the generated HTMl, and have been unable to expose anything in the API.

The end goal is to allow filtering by chapter by getting a URL param.

http://www.jamesfishwick.com/timeline/


问:
Ruby: How to solve a simple grep function using regular expression?
I am trying to find a way to solve this:

Implement a simple grep function that takes a string x as input, and prints the lines of a file having any occurrences of string x anywhere in a line. You need to do a simple regular expression match after reading lines from a file. The output should also include the line numbers.

Here is a sample of the code I have written.  NOTE: I did not create a function just yet, I first need to get the code to recognize the file and display the corresponding message.

```<code>x=/you/

aFile = File.open("filename1.txt", "r")

a = ""

aFile.each {|line|
    a << line
}

sentence = a.split(".")

puts sentence

if sentence=~x
    puts "yes"
else
    puts "no"
end

aFile.close
</code>```

And here is the contents of filename1.txt:

```<code>See you tomorrow. Have a good day Mr. Jones. See you tomorrow. Have a good
day. See you tomorrow. See you tomorrow.
</code>```

I can display the file but cannot compare it to a regular expression.  It has been printing out an error when I try to compare it. Could someone point out the error in my code and help me find the solution to my problem?

答:
You can write a method like this and pass the word and file name. NOTE: you have to handle exceptions appropriately. The method will return actual line number with content containing the word.

```<code>  def search_word_in_file(word, file_name)
    regex = Regexp.new(word, "gi") # you may get rid of gi if you want exact match
    lines_with_number = {}
    f = File.open(file_name, 'r')
    f.each_line.with_index do |line, index|
      actual_line_number = index + 1
      if (regex).match(line)
        lines_with_number[actual_line_number] ||= []
        lines_with_number[actual_line_number] << line
      end
    end
    f.close
    lines_with_number
  end
</code>```

So,

```<code>search_word_in_file('you', 'filename1.txt')
</code>```

should work

Body:
I am trying to find a way to solve this:

Implement a simple grep function that takes a string x as input, and prints the lines of a file having any occurrences of string x anywhere in a line. You need to do a simple regular expression match after reading lines from a file. The output should also include the line numbers.

Here is a sample of the code I have written.  NOTE: I did not create a function just yet, I first need to get the code to recognize the file and display the corresponding message.

x=/you/

aFile = File.open("filename1.txt", "r")

a = ""

aFile.each {|line|
    a << line
}

sentence = a.split(".")

puts sentence

if sentence=~x
    puts "yes"
else
    puts "no"
end

aFile.close

And here is the contents of filename1.txt:

See you tomorrow. Have a good day Mr. Jones. See you tomorrow. Have a good
day. See you tomorrow. See you tomorrow.

I can display the file but cannot compare it to a regular expression.  It has been printing out an error when I try to compare it. Could someone point out the error in my code and help me find the solution to my problem?

Body:
You can write a method like this and pass the word and file name. NOTE: you have to handle exceptions appropriately. The method will return actual line number with content containing the word.

  def search_word_in_file(word, file_name)
    regex = Regexp.new(word, "gi") # you may get rid of gi if you want exact match
    lines_with_number = {}
    f = File.open(file_name, 'r')
    f.each_line.with_index do |line, index|
      actual_line_number = index + 1
      if (regex).match(line)
        lines_with_number[actual_line_number] ||= []
        lines_with_number[actual_line_number] << line
      end
    end
    f.close
    lines_with_number
  end

So,

search_word_in_file('you', 'filename1.txt')

should work


问:
CMD command to check connected USB devices
I would like to obtain by a command prompt a list of all USB devices connected to my computer (O.S. Windows 10). I've googled to find such a command, but all results seems useless to me or worse workless. Does anybody know how can I do that?

Thank you

答: you can download USBview and get all the information you need. Along with the list of devices, it will also show you the configuration of each device.</p>

ContentLicense: CC BY-SA 4.0


问:
I am unable to get over the java.lang.NullPointerException in android studio when using file provider class
This is my Manifest file code

```<code><activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </activity>
</code>```

And the code for my new resource xml file is

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="external_files" path="."/>
  </paths>
</code>```

My main activity code is

```<code>public class MainActivity extends Activity {

    private ImageView image;
    private final int CameraKey = 1;
    Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button click_button = (Button) findViewById(R.id.button);
        image = (ImageView) findViewById(R.id.imageView3);

        click_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = getFile();
                Uri apkURI = FileProvider.getUriForFile(
                        context,
                        context.getApplicationContext()
                                .getPackageName() + ".provider", file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, apkURI);
                startActivityForResult(intent, CameraKey);

            }
        });
    }

    private File getFile(){
        File store = new File("sdcard/Digiwrite");
        if(store.exists()){
            store.mkdir();
        }

        File image = new File(store,"Images.jpg");
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CameraKey && resultCode == RESULT_OK){
            String path = "sdcard/Digiwrite/Images.jpg";

            image.setImageDrawable(Drawable.createFromPath(path));

        }
    }
</code>```

I keep getting this error:

FATAL EXCEPTION: main
                                                                                Process: com.mukesh.android.digiwrite, PID: 30365
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method
  'android.content.res.XmlResourceParser
  android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager,
  java.lang.String)' on a null object reference
                                                                                at
  android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                                at
  android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                                at
  android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                                at
  com.mukesh.android.digiwrite.MainActivity$1.onClick(MainActivity.java:37)
                                                                                at android.view.View.performClick(View.java:5637)
                                                                                at android.view.View$PerformClick.run(View.java:22433)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

I am completely new to Android studio. I have tried various methods available but I don't get how to make file provider work. May I know where I went wrong?

I tried running this code on lower versions using file.getUri() method and it was working fine. So as to make it run on higher versions I have been trying to convert this to use file provider. But I am stuck. Pls help me out.

答:
use this permission in your xml file.

<uses-permission android:name="com.company.app.fileprovider.READ"/>

Body:
This is my Manifest file code

<activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </activity>

And the code for my new resource xml file is

  <?xml version="1.0" encoding="utf-8"?>
  <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="external_files" path="."/>
  </paths>

My main activity code is

public class MainActivity extends Activity {

    private ImageView image;
    private final int CameraKey = 1;
    Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button click_button = (Button) findViewById(R.id.button);
        image = (ImageView) findViewById(R.id.imageView3);

        click_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = getFile();
                Uri apkURI = FileProvider.getUriForFile(
                        context,
                        context.getApplicationContext()
                                .getPackageName() + ".provider", file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, apkURI);
                startActivityForResult(intent, CameraKey);

            }
        });
    }

    private File getFile(){
        File store = new File("sdcard/Digiwrite");
        if(store.exists()){
            store.mkdir();
        }

        File image = new File(store,"Images.jpg");
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CameraKey && resultCode == RESULT_OK){
            String path = "sdcard/Digiwrite/Images.jpg";

            image.setImageDrawable(Drawable.createFromPath(path));

        }
    }

I keep getting this error:

FATAL EXCEPTION: main
                                                                                Process: com.mukesh.android.digiwrite, PID: 30365
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method
  'android.content.res.XmlResourceParser
  android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager,
  java.lang.String)' on a null object reference
                                                                                at
  android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                                at
  android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                                at
  android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                                at
  com.mukesh.android.digiwrite.MainActivity$1.onClick(MainActivity.java:37)
                                                                                at android.view.View.performClick(View.java:5637)
                                                                                at android.view.View$PerformClick.run(View.java:22433)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

I am completely new to Android studio. I have tried various methods available but I don't get how to make file provider work. May I know where I went wrong?

I tried running this code on lower versions using file.getUri() method and it was working fine. So as to make it run on higher versions I have been trying to convert this to use file provider. But I am stuck. Pls help me out.


问:
Proguard.cfg Missing
I made the mistake of upgrading eclipse today and now can't get my a new Android project to get going.

I get the message Proguard.cfg (the file can't be found).

Where is this thing I can't seem to find it? Is it possible to get rid of it I don't need Obfuscation in this project...

Thanks

答:
If you really don't need Proguard to obfuscate your release builds, you can remove the following line from the default.properties file in your project root folder:

proguard.config=proguard.cfg

If you want a proguard.cfg template, you can create a new Android project from scratch with Eclipse's project wizard, then copy proguard.cfg from the new project over to the previous one.

Title: Proguard.cfg Missing


问:
Spring boot package with difference config file
I have three application config file.

application.yml

application-prod.yml

application-dev.yml

The application.yml default profiles.active is dev, how could i package a production jar with prod file without modify profiles.active property. Something like mvn clean package --profiles.active=prod.

答:
You can do via cmd too

In the normal Spring way, you can use a spring.profiles.active Environment property to specify which profiles are active. You can specify the property in any of the usual ways, for example you could include it in your application.properties:

spring.profiles.active=dev,hsqldb

or specify on the command line using the switch

--spring.profiles.active=dev,hsqldb.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html


问:
Why won't these collisions sense? (Swift SpriteKit)
In my project I am trying to detect a collision between two SKSpriteNodes, but it will not work.
Here is my code for the physics category
:

```<code>struct PhysicsCategory {
static let enemy : UInt32 = 0x1 << 1
static let player : UInt32 = 0x1 << 3
static let neutral : UInt32 = 0x1 << 2
 }
</code>```

For the neutral, enemy and player bodies

```<code>  neutral = SKSpriteNode(imageNamed: "Cave-Bottom")
    neutral.size = CGSize(width: self.frame.width, height: self.frame.height / 8)
    neutral.position = CGPoint(x: 0, y: self.frame.height / -2.5)
    neutral.zPosition = 2
    neutral.physicsBody?.categoryBitMask = PhysicsCategory.neutral
    neutral.physicsBody?.collisionBitMask = PhysicsCategory.player
    neutral.physicsBody?.contactTestBitMask = PhysicsCategory.player
    neutral.physicsBody = SKPhysicsBody.init(rectangleOf:              neutral.size)

    enemy = SKSpriteNode(imageNamed: "spike")
    enemy.size = CGSize(width: 40, height: 40)
    enemy.position = CGPoint(x: 0, y: 0)
    enemy.zPosition = 2
    enemy.physicsBody = SKPhysicsBody.init(rectangleOf: enemy.size)
    enemy.physicsBody?.categoryBitMask = PhysicsCatagory.enemy
    enemy.physicsBody?.collisionBitMask = PhysicsCatagory.player
    enemy.physicsBody?.contactTestBitMask = PhysicsCatagory.player

    player = SKSpriteNode(imageNamed: "bob")
    player.size = CGSize(width: 40, height: 40)
    bob.zPosition = 3
    player.physicsBody?.categoryBitMask = PhysicsCatagory.player
    player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
    player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
    player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)
</code>```

And the code for my ContactHasBegan function:

```<code>  func didBegin(_ contact: SKPhysicsContact) {

   print("collided!")

    if (contact.bodyA.categoryBitMask == PhysicsCatagory.enemy && contact.bodyB.categoryBitMask == PhysicsCatagory.player) {
        print("player and enemy!")
    }
    if (contact.bodyB.categoryBitMask == PhysicsCatagory.enemy && contact.bodyA.categoryBitMask == PhysicsCatagory.player) {
        print("player and enemy!")
    }
    if (contact.bodyA.categoryBitMask == PhysicsCatagory.neutral && contact.bodyB.categoryBitMask == PhysicsCatagory.player) {
        print("neutral and player!")
    }
    if contact.bodyB.categoryBitMask == PhysicsCatagory.neutral && contact.bodyA.categoryBitMask == PhysicsCatagory.player{
        print("neutral and player")
    }          }
</code>```

For some reason it only detects a collision between the player and enemy and prints "Collided!" and none of the if statements in the didBeginContact function test out positive.

答:
Because player's physicsBody doesn't have it's category and contactTest bit masks set corrcetly.

You've created the player's physicsBody AFTER you tried to set the player's physicsBody's attributes:

```<code>player.physicsBody?.categoryBitMask = PhysicsCatagory.player
player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)
</code>```

In the first 3 lines of code, because player.physicsBody is an optional, the rest of the line is ignored, as there is no physicsBody.

So the physics body is created with all properties set to default i.e. it collides with everything and contacts nothing.

You need to move the line :

```<code>player.physicsBody = SKPhysicsBody.init(....
</code>```

to before the code where you set the physics body's attributes:

```<code>player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)
player.physicsBody?.categoryBitMask = PhysicsCatagory.player
player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
</code>```

Body:
In my project I am trying to detect a collision between two SKSpriteNodes, but it will not work.
Here is my code for the physics category
:

struct PhysicsCategory {
static let enemy : UInt32 = 0x1 << 1
static let player : UInt32 = 0x1 << 3
static let neutral : UInt32 = 0x1 << 2
 }

For the neutral, enemy and player bodies

  neutral = SKSpriteNode(imageNamed: "Cave-Bottom")
    neutral.size = CGSize(width: self.frame.width, height: self.frame.height / 8)
    neutral.position = CGPoint(x: 0, y: self.frame.height / -2.5)
    neutral.zPosition = 2
    neutral.physicsBody?.categoryBitMask = PhysicsCategory.neutral
    neutral.physicsBody?.collisionBitMask = PhysicsCategory.player
    neutral.physicsBody?.contactTestBitMask = PhysicsCategory.player
    neutral.physicsBody = SKPhysicsBody.init(rectangleOf:              neutral.size)

    enemy = SKSpriteNode(imageNamed: "spike")
    enemy.size = CGSize(width: 40, height: 40)
    enemy.position = CGPoint(x: 0, y: 0)
    enemy.zPosition = 2
    enemy.physicsBody = SKPhysicsBody.init(rectangleOf: enemy.size)
    enemy.physicsBody?.categoryBitMask = PhysicsCatagory.enemy
    enemy.physicsBody?.collisionBitMask = PhysicsCatagory.player
    enemy.physicsBody?.contactTestBitMask = PhysicsCatagory.player

    player = SKSpriteNode(imageNamed: "bob")
    player.size = CGSize(width: 40, height: 40)
    bob.zPosition = 3
    player.physicsBody?.categoryBitMask = PhysicsCatagory.player
    player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
    player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
    player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)

And the code for my ContactHasBegan function:

  func didBegin(_ contact: SKPhysicsContact) {

   print("collided!")

    if (contact.bodyA.categoryBitMask == PhysicsCatagory.enemy && contact.bodyB.categoryBitMask == PhysicsCatagory.player) {
        print("player and enemy!")
    }
    if (contact.bodyB.categoryBitMask == PhysicsCatagory.enemy && contact.bodyA.categoryBitMask == PhysicsCatagory.player) {
        print("player and enemy!")
    }
    if (contact.bodyA.categoryBitMask == PhysicsCatagory.neutral && contact.bodyB.categoryBitMask == PhysicsCatagory.player) {
        print("neutral and player!")
    }
    if contact.bodyB.categoryBitMask == PhysicsCatagory.neutral && contact.bodyA.categoryBitMask == PhysicsCatagory.player{
        print("neutral and player")
    }          }

For some reason it only detects a collision between the player and enemy and prints "Collided!" and none of the if statements in the didBeginContact function test out positive.

Body:
Because player's physicsBody doesn't have it's category and contactTest bit masks set corrcetly.

You've created the player's physicsBody AFTER you tried to set the player's physicsBody's attributes:

player.physicsBody?.categoryBitMask = PhysicsCatagory.player
player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)

In the first 3 lines of code, because player.physicsBody is an optional, the rest of the line is ignored, as there is no physicsBody.

So the physics body is created with all properties set to default i.e. it collides with everything and contacts nothing.

You need to move the line :

player.physicsBody = SKPhysicsBody.init(....

to before the code where you set the physics body's attributes:

player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)
player.physicsBody?.categoryBitMask = PhysicsCatagory.player
player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral


答:
You can do it, also, with combinations from itertools module, like this example:

```<code>from itertools import combinations
final = list(set(combinations(("red","red","blue")*3, 3)))

print(final)
</code>```

Output:

```<code>[('red', 'blue', 'red'),
 ('blue', 'red', 'red'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue'),
 ('blue', 'red', 'blue'),
 ('red', 'blue', 'blue'),
 ('red', 'red', 'blue'),
 ('red', 'red', 'red')]
</code>```

Title: Python Itertools permutations with strings

Body:
You can do it, also, with combinations from itertools module, like this example:

from itertools import combinations
final = list(set(combinations(("red","red","blue")*3, 3)))

print(final)

Output:

[('red', 'blue', 'red'),
 ('blue', 'red', 'red'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue'),
 ('blue', 'red', 'blue'),
 ('red', 'blue', 'blue'),
 ('red', 'red', 'blue'),
 ('red', 'red', 'red')]


问:
What is a fractal?
Duplicate of How to program a fractal

What are fractals?

Is this is one of the concepts that is brought over from Mathematics to programming to simplify or solve a particular set of problems?

 I am closing this question and have posted a related  question

答:
If you want to know about fractals in a general non-programming way, I would suggest looking at a general non-programming site. Wikipedia has a good article on them. If you want to know about programming fractals, I would suggest looking at this already asked question:

How to program a fractal

It even has a fractal tag.

OwnerDisplayName: Nick

Title: What is a fractal?

LastEditorDisplayName: Nick

OwnerDisplayName: EBGreen

LastEditorDisplayName: David Schmitt


问:
how to configure cypal plugins into eclipse
I am trying to configure the eclipse with the cypal studio  to run GWT (Google Web Toolkit) into java application. now i am trying to find libraries for cypal to configure into eclipse but i am not able to find the proper solution for installing plugins in eclipse.</p>

答:
here i got difference.
Collection is a data structure. Based on the problem you decide which collection to be used like ArrayList, LinekedList (Considering time and space complexity) . Where as Stream is just a processing kind of tool, which makes your life easy.
Other difference is, you can consider Collection as in-memory data structure, where you can add , remove element. Where as in Stream you can perform two kind of operation:

a. Intermediate operation : Filter, map ,sort,limit on the result set
b. Terminal operation : forEach ,collect the result set to a collection.

But if you notice, with stream you can't add or remove elements.
Stream is kind of iterator, you can traverse collection through stream. Note, you can traverse stream only once, let me give you an example to have better understanding:
Example:

```<code>List<String> employeeNameList = Arrays.asList("John","Peter","Sachin");
Stream<String> s = employeeNameList.stream();

// iterate through list
s.dorEach(System.out :: println);  // this work's perfectly fine
s.dorEach(System.out :: println);  // you will get IllegalStateException, stating stream already operated upon
</code>```

So, what you can infer is, collection you can iterate as many times as you want. But for the stream, once you iterate , it won't remember what it is supposed to do. So, you need to instruct it again.

Body:
here i got difference.
Collection is a data structure. Based on the problem you decide which collection to be used like ArrayList, LinekedList (Considering time and space complexity) . Where as Stream is just a processing kind of tool, which makes your life easy.
Other difference is, you can consider Collection as in-memory data structure, where you can add , remove element. Where as in Stream you can perform two kind of operation:

a. Intermediate operation : Filter, map ,sort,limit on the result set
b. Terminal operation : forEach ,collect the result set to a collection.

But if you notice, with stream you can't add or remove elements.
Stream is kind of iterator, you can traverse collection through stream. Note, you can traverse stream only once, let me give you an example to have better understanding:
Example:

List<String> employeeNameList = Arrays.asList("John","Peter","Sachin");
Stream<String> s = employeeNameList.stream();

// iterate through list
s.dorEach(System.out :: println);  // this work's perfectly fine
s.dorEach(System.out :: println);  // you will get IllegalStateException, stating stream already operated upon

So, what you can infer is, collection you can iterate as many times as you want. But for the stream, once you iterate , it won't remember what it is supposed to do. So, you need to instruct it again.


问:
In Celery Python, output of a task to parallel processing task
I have created a task

```<code>@app.task
def mainTask(msg,nc):
    decryptFunction.decryptFunc(msg)
    if len(decryptFunction.messageJson):
</code>```

I am receiving data asynchronously.

```<code>def on_message(client, userdata, msg):
    result = mainTask.delay(msg.payload.decode("utf-8"),1)
</code>```

i need to use output decryptFunction.messageJson in 5 tasks and run concurrently

答:
What I am understanding from your requirement, I would suggest, Instead of making mainTask as async you can call the other 5 tasks as celery tasks, from mainTask i.e,

```<code>def mainTask(msg, nc):
     decryptFunction.decryptFunc(msg)
     if len(decryptFunction.messageJson):
         response1 = task1.delay(decryptFunction.messageJson)
         response2 = task2.delay(decryptFunction.messageJson)
         response3 = task3.delay(decryptFunction.messageJson)
         response4 = task4.delay(decryptFunction.messageJson)
         response5 = task5.delay(decryptFunction.messageJson)
</code>```

and your on_message function as:

```<code>def on_message(client, userdata, msg):
    result = mainTask(msg.payload.decode("utf-8"),1)
</code>```

But this is assuming that your other 5 tasks are mutually exclusive and response of one, doesn't affect the other task, because if they are not, you cannot make them async tasks.

But if your mainTask is time consuming you can use it as a Celery task.

Body:
I have created a task

@app.task
def mainTask(msg,nc):
    decryptFunction.decryptFunc(msg)
    if len(decryptFunction.messageJson):

I am receiving data asynchronously.

def on_message(client, userdata, msg):
    result = mainTask.delay(msg.payload.decode("utf-8"),1)

i need to use output decryptFunction.messageJson in 5 tasks and run concurrently

Body:
What I am understanding from your requirement, I would suggest, Instead of making mainTask as async you can call the other 5 tasks as celery tasks, from mainTask i.e,

def mainTask(msg, nc):
     decryptFunction.decryptFunc(msg)
     if len(decryptFunction.messageJson):
         response1 = task1.delay(decryptFunction.messageJson)
         response2 = task2.delay(decryptFunction.messageJson)
         response3 = task3.delay(decryptFunction.messageJson)
         response4 = task4.delay(decryptFunction.messageJson)
         response5 = task5.delay(decryptFunction.messageJson)

and your on_message function as:

def on_message(client, userdata, msg):
    result = mainTask(msg.payload.decode("utf-8"),1)

But this is assuming that your other 5 tasks are mutually exclusive and response of one, doesn't affect the other task, because if they are not, you cannot make them async tasks.

But if your mainTask is time consuming you can use it as a Celery task.


问:
Match one of several bytes in nom
I am using nom to parse some binary 65c816 assembly data. Part of my parser structure splits opcodes into their separate forms and then grabs their parameters if they have any. An example parser currently looks like this:

```<code>named!(absolute_long<Instruction>,
    do_parse!(op: bits!(alt!(
        opcode!(0x0F) | opcode!(0x22) | opcode!(0x2F) | opcode!(0x4F) |
        opcode!(0x5C) | opcode!(0x6F) | opcode!(0x8F) | opcode!(0xAF) |
        opcode!(0xCF) | opcode!(0xEF)))
>> param: le_u24
>> (Instruction::AbsoluteLong(op, param))));
</code>```

Where opcode! is a macro I made that does the following:

```<code>macro_rules! opcode(
    ($i:expr, $op:expr) => (
        tag_bits!($i, u8, 8, $op);
    );
    ($i:expr, $f:expr) => (
        opcode!($i, call!($f));
    );
);
</code>```

I would instead like to have code like the following but am unable to figure out how I'd make a macro or function to do it:

```<code>named!(absolute_long<Instruction>,
    do_parse!(op: opcodes!(
        0x0F, 0x22, 0x2F, 0x4F, 0x5C, 0x6F, 0x8F, 0xAF,
        0xCF, 0xEF)
    >> param: le_u24
    >> (Instruction::AbsoluteLong(op, parm)));
</code>```

The closest I got was making this macro, but it almost immediately runs into recursion limits and it seems really sub-optimal in general:

```<code>macro_rules! opcodes(
    ($i:expr, $op:expr) => {
        opcode!($i, $op)
    };

    ($i:expr, $op:expr, $($more:expr), *) => (
        bits!($i, alt!(opcode!($op) | opcodes!($($more),*)))
    );
);
</code>```

Is there any way I can implement something like this or am I better off just using tag_bits? I feel like I should be able to use one_of, but I am unable to get it to work with bytes.

答:
We can use one_of!(..) like so:

```<code>#[macro_use]
extern crate nom;
use nom::*;

// Your type might look a different, I infered what I could:
#[derive(Debug)]
enum Instruction {
    AbsoluteLong(u8, u32)
}

named!(absolute_long<Instruction>, do_parse!(
       op: one_of!([0x0F, 0x22, 0x2F, 0x4F, 0x5C, 0x6F, 0x8F, 0xAF, 0xCF, 0xEF].as_ref())
    >> param: le_u24
    >> (Instruction::AbsoluteLong(op as u8, param))
));

fn main() {
    println!("{:?}", absolute_long(&[0x0F, 0x01, 0x01, 0x01, 0x01]));
}
</code>```

one_of! must be given a slice to work with. We can get one by casting an array to it with .as_ref().

Title: Match one of several bytes in nom

Body:
I am using nom to parse some binary 65c816 assembly data. Part of my parser structure splits opcodes into their separate forms and then grabs their parameters if they have any. An example parser currently looks like this:

named!(absolute_long<Instruction>,
    do_parse!(op: bits!(alt!(
        opcode!(0x0F) | opcode!(0x22) | opcode!(0x2F) | opcode!(0x4F) |
        opcode!(0x5C) | opcode!(0x6F) | opcode!(0x8F) | opcode!(0xAF) |
        opcode!(0xCF) | opcode!(0xEF)))
>> param: le_u24
>> (Instruction::AbsoluteLong(op, param))));

Where opcode! is a macro I made that does the following:

macro_rules! opcode(
    ($i:expr, $op:expr) => (
        tag_bits!($i, u8, 8, $op);
    );
    ($i:expr, $f:expr) => (
        opcode!($i, call!($f));
    );
);

I would instead like to have code like the following but am unable to figure out how I'd make a macro or function to do it:

named!(absolute_long<Instruction>,
    do_parse!(op: opcodes!(
        0x0F, 0x22, 0x2F, 0x4F, 0x5C, 0x6F, 0x8F, 0xAF,
        0xCF, 0xEF)
    >> param: le_u24
    >> (Instruction::AbsoluteLong(op, parm)));

The closest I got was making this macro, but it almost immediately runs into recursion limits and it seems really sub-optimal in general:

macro_rules! opcodes(
    ($i:expr, $op:expr) => {
        opcode!($i, $op)
    };

    ($i:expr, $op:expr, $($more:expr), *) => (
        bits!($i, alt!(opcode!($op) | opcodes!($($more),*)))
    );
);

Is there any way I can implement something like this or am I better off just using tag_bits? I feel like I should be able to use one_of, but I am unable to get it to work with bytes.

Body:
We can use one_of!(..) like so:

#[macro_use]
extern crate nom;
use nom::*;

// Your type might look a different, I infered what I could:
#[derive(Debug)]
enum Instruction {
    AbsoluteLong(u8, u32)
}

named!(absolute_long<Instruction>, do_parse!(
       op: one_of!([0x0F, 0x22, 0x2F, 0x4F, 0x5C, 0x6F, 0x8F, 0xAF, 0xCF, 0xEF].as_ref())
    >> param: le_u24
    >> (Instruction::AbsoluteLong(op as u8, param))
));

fn main() {
    println!("{:?}", absolute_long(&[0x0F, 0x01, 0x01, 0x01, 0x01]));
}

one_of! must be given a slice to work with. We can get one by casting an array to it with .as_ref().


问:
display a success message on different portlet
I have form on a porlet, after submission of that form, page is redirecting to another portlet for that i am using actionResponse.sendRedirect("/abc/bcd/newWebPage")
and i am landing on to different page. One that page the same potlet is added with different screen, Now i want to display a success message on next page.

for that i am using portlet session and passing parameter to jsp.

```<code>PortletSession session = actionRequest.getPortletSession();
                            session.setAttribute("SUCCESSA", "Successfully",PortletSession.APPLICATION_SCOPE);
</code>```

But its not working.

Any help how to achieve that?

答:
When you say One that page the same potlet is added with different screen, I understand that you have another instance of the same portlet in different page. By the way, you haven't explained what is not working for you. I assume you are wondering how to read in the JSP page. It's pretty straight forward:

In Controller:

```<code>PortletUtils.setSessionAttribute(request, "SUCCESSA", "Successfully", PortletSession.APPLICATION_SCOPE);
</code>```

In JSP:

```<code>pageContext.setAttribute("succcessa", PortletUtils.getSessionAttribute(renderRequest, "SUCCESSA", PortletSession.APPLICATION_SCOPE));
</code>```

The PortletUtils does the same as setting the attribute using the PortletRequest object but its preferrable.

To remove the session attribute:

```<code>PortletUtils.setSessionAttribute(request, "SUCCESSA", null, PortletSession.APPLICATION_SCOPE);
</code>```

The implementation of PortletUtils is that it removes the session attribute if value is null, if a session existed at all.

Body:
I have form on a porlet, after submission of that form, page is redirecting to another portlet for that i am using actionResponse.sendRedirect("/abc/bcd/newWebPage")
and i am landing on to different page. One that page the same potlet is added with different screen, Now i want to display a success message on next page.

for that i am using portlet session and passing parameter to jsp.

PortletSession session = actionRequest.getPortletSession();
                            session.setAttribute("SUCCESSA", "Successfully",PortletSession.APPLICATION_SCOPE);

But its not working.

Any help how to achieve that?

Body:
When you say One that page the same potlet is added with different screen, I understand that you have another instance of the same portlet in different page. By the way, you haven't explained what is not working for you. I assume you are wondering how to read in the JSP page. It's pretty straight forward:

In Controller:

PortletUtils.setSessionAttribute(request, "SUCCESSA", "Successfully", PortletSession.APPLICATION_SCOPE);

In JSP:

pageContext.setAttribute("succcessa", PortletUtils.getSessionAttribute(renderRequest, "SUCCESSA", PortletSession.APPLICATION_SCOPE));

The PortletUtils does the same as setting the attribute using the PortletRequest object but its preferrable.

To remove the session attribute:

PortletUtils.setSessionAttribute(request, "SUCCESSA", null, PortletSession.APPLICATION_SCOPE);

The implementation of PortletUtils is that it removes the session attribute if value is null, if a session existed at all.


问:
Why my for loop for my curve returns `Inf` in R?
I'm trying to loop over 2 curves in R but only one of the curves shows. More importantly, I call axis() command two times (for x and y axes) but I get the following error:

Error in axis(1, at = success/trials) : no locations are finite

'to' must be a finite number

Question

I'm wondering (a) why only my first curve is showing and (b) why I'm getting Inf/-Inf in my axis() calls?

Here is my R code:

```<code>success = c(10, 50) ; trials = 100

for(i in 1:length(success)){

success = success[i]
    col = (1:length(success))[i]

c = curve( dbinom(success, trials, x), 0, 1, add = ifelse(i > 1, T, F), ty = "l", xlim = c(0, 1),
           col = col, yaxt = "n")

text(success/trials, max(c$y), bquote(bolditalic(H[.(i)])), pos = 3, xpd = T )

axis(1, at = success/trials)

}

axis(2, at = seq(0, max(c$y), len = 7), labels = round(seq(0, max(c$y), len = 7), 2), las = 1 )
</code>```

答:
In your first pass through the loop you set success to success[1] and in the second pass through the loop you set success to success[2] but success was at that point length 1, so it becomes NA.

Similarly, the second plot doesn't show because col becomes NA for the same reason.

To fix this, use a different name for the list of successes and the variable in the loop. For example, use successes = c(10,50) and then use successes when setting success and col inside the loop. (Alternatively for col, just set col = i.)

Applying that to your code:

```<code>successes = c(10, 50) ; trials = 100
for(i in 1:length(successes)){
    success = successes[i]
    col = i
    c = curve( dbinom(success, trials, x), 0, 1, add = ifelse(i > 1, T, F), ty = "l", xlim = c(0, 1),
               col = col, yaxt = "n")
    text(success/trials, max(c$y), bquote(bolditalic(H[.(i)])), pos = 3, xpd = T )
    axis(1, at = success/trials)
}
axis(2, at = seq(0, max(c$y), len = 7), labels = round(seq(0, max(c$y), len = 7), 2), las = 1 )
</code>```

Body:
I'm trying to loop over 2 curves in R but only one of the curves shows. More importantly, I call axis() command two times (for x and y axes) but I get the following error:

Error in axis(1, at = success/trials) : no locations are finite

'to' must be a finite number

Question

I'm wondering (a) why only my first curve is showing and (b) why I'm getting Inf/-Inf in my axis() calls?

Here is my R code:

success = c(10, 50) ; trials = 100

for(i in 1:length(success)){

success = success[i]
    col = (1:length(success))[i]

c = curve( dbinom(success, trials, x), 0, 1, add = ifelse(i > 1, T, F), ty = "l", xlim = c(0, 1),
           col = col, yaxt = "n")

text(success/trials, max(c$y), bquote(bolditalic(H[.(i)])), pos = 3, xpd = T )

axis(1, at = success/trials)

}

axis(2, at = seq(0, max(c$y), len = 7), labels = round(seq(0, max(c$y), len = 7), 2), las = 1 )

Body:
In your first pass through the loop you set success to success[1] and in the second pass through the loop you set success to success[2] but success was at that point length 1, so it becomes NA.

Similarly, the second plot doesn't show because col becomes NA for the same reason.

To fix this, use a different name for the list of successes and the variable in the loop. For example, use successes = c(10,50) and then use successes when setting success and col inside the loop. (Alternatively for col, just set col = i.)

Applying that to your code:

successes = c(10, 50) ; trials = 100
for(i in 1:length(successes)){
    success = successes[i]
    col = i
    c = curve( dbinom(success, trials, x), 0, 1, add = ifelse(i > 1, T, F), ty = "l", xlim = c(0, 1),
               col = col, yaxt = "n")
    text(success/trials, max(c$y), bquote(bolditalic(H[.(i)])), pos = 3, xpd = T )
    axis(1, at = success/trials)
}
axis(2, at = seq(0, max(c$y), len = 7), labels = round(seq(0, max(c$y), len = 7), 2), las = 1 )


问:
How to use PAX CDI with Declarative service
We are using CXF + DOSGI rest services

Interface:

```<code>@Path("/")
public interface DefaultApi{
 @POST
    @Path("/public/login")
    @Consumes({ "application/json" })
    @Produces({ "application/json" })
    public Response login(@HeaderParam("User-Agent") String userAgent,@QueryParam("username") String username,@QueryParam("password") String password,
                     @Context UriInfo uriInfo,
                     @Context ResourceContext recourceContext);
</code>```

Implementation:

```<code>@Component(immediate = true, configurationPolicy = ConfigurationPolicy.REQUIRE, configurationPid = "frontend.rest")
public class DefaultApiImpl implements DefaultApi {
</code>```

Is it possible to use  Apache Deltaspike for Method level Authorization along with CXF + DOSGI
https://deltaspike.apache.org/documentation/security.html
If possible how to do it ?

Is there any other alternative to do method level authorization with CXF + DOSGI

答:
You can not mix deltaspike and declarative services. Deltaspike security is a cdi extension so you need to use pax cdi to expose your OSGi service.

Another thing is that you need to do the authentication in some way. I recommend to use the CXF JAASAuthenticationFeature. It can do basic auth against the configured jaas provider in karaf. The result is a jaas login that you probably can use in deltaspike security to base your authorization on.

Body:
We are using CXF + DOSGI rest services

Interface:

@Path("/")
public interface DefaultApi{
 @POST
    @Path("/public/login")
    @Consumes({ "application/json" })
    @Produces({ "application/json" })
    public Response login(@HeaderParam("User-Agent") String userAgent,@QueryParam("username") String username,@QueryParam("password") String password,
                     @Context UriInfo uriInfo,
                     @Context ResourceContext recourceContext);

Implementation:

@Component(immediate = true, configurationPolicy = ConfigurationPolicy.REQUIRE, configurationPid = "frontend.rest")
public class DefaultApiImpl implements DefaultApi {

Is it possible to use  Apache Deltaspike for Method level Authorization along with CXF + DOSGI
https://deltaspike.apache.org/documentation/security.html
If possible how to do it ?

Is there any other alternative to do method level authorization with CXF + DOSGI


问:
Check if DataGridView Contains specific word
I'm currently doing a school project and I need to know how to check if in any row of the datagridview contains a specific word in any column, and hide the rows that don't contain that word, in any column.
I have no code yet, just the datagridview and the textbox on the form.</p>

答:
I am assuming that you are using DataTable as DataSource.

When you are passing the TextBox.Textas RowFilter and clear it, it becomes an empty string.

In the TextChanged event, just check if the TextBox is empty. Your event would look something like this:

```<code>private void textBoxFilter_TextChanged(object sender, EventArgs e)
{
    if(!string.IsNullOrWhiteSpace(textBox1.Text))
    {
        (dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
    }
}
</code>```

Body:
I am assuming that you are using DataTable as DataSource.

When you are passing the TextBox.Textas RowFilter and clear it, it becomes an empty string.

In the TextChanged event, just check if the TextBox is empty. Your event would look something like this:

private void textBoxFilter_TextChanged(object sender, EventArgs e)
{
    if(!string.IsNullOrWhiteSpace(textBox1.Text))
    {
        (dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
    }
}


问:
When insert rows using python psycopg2, docker postgres process is terminated
Database is postgresql-9.5.1 in docker. My host machine has 3.75 GB memory, linux. In some methods I am inserting 490000 rows one after another using psycopg2 with below code.

```<code>student_list = [(name, surname, explanation)]
args_str = ','.join(cur.mogrify("(%s,%s,%s)", x) for x in student_list)
cur.execute('INSERT INTO students (name, surname, explanation) VALUES ' + args_str)
</code>```

This makes my database docker memory seems full and gives these errors:

LOG:  server process (PID 11219) was terminated by signal 9:
  Killed
 DETAIL:  Failed process was running
 LOG:  terminating
  any other active server processes
 docker@test_db WARNING:
  terminating connection because of crash of another server process

  docker@test_db DETAIL:  The postmaster has commanded this server
  process to roll back the current transaction and exit, because another
  server process exited abnormally and possibly corrupted shared
  memory.
 docker@test_db HINT:  In a moment you should be able to
  reconnect to the database and repeat your command.
 docker@test_db
  WARNING:  terminating connection because of crash of another server
  process
 docker@test_db DETAIL:  The postmaster has commanded this
  server process to roll back the current transaction and exit, because
  another server process exited abnormally and possibly corrupted shared
  memory.
 ... docker@test_db FATAL:  the database system is in
  recovery mode
 LOG:  all server processes terminated;
  reinitializing
 LOG:  database system was interrupted; last known
  up at 2017-06-06 09:39:40 UTC
 LOG:  database system was not
  properly shut down; automatic recovery in progress
 docker@test_db
  FATAL:  the database system is in recovery mode
 docker@test_db
  FATAL:  the database system is in recovery mode
 docker@test_db
  FATAL:  the database system is in recovery mode
 LOG:  autovacuum
  launcher started

Script gives that log:

Inner exception

  SSL SYSCALL error: EOF detected

I tried put some sleep time between consecutive queries but got same result. Is there any limitation for that?
Also I tried to connect and disconnect for each query but got same result. These are my connect and disconnect methods.

```<code>def connect():
    conn = psycopg2.connect(database=database_name,
                            user=database_user,
                            host=database_host,
                            port=database_port)
    conn
  .set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
    cur = conn.cursor()
    return conn, cur

def disconnect(conn, cur):
    cur.close()
    conn.close()
</code>```

答: Here is what I did. Actually my memory was full enough. That's why linux OS used to kill the process in Postgresql. There were 1M values in every insert process. The trick was I divided data lists to chunks and tried it 100k by 100k. That works very well. Thanks for your helps.</p>

Body:
Database is postgresql-9.5.1 in docker. My host machine has 3.75 GB memory, linux. In some methods I am inserting 490000 rows one after another using psycopg2 with below code.

student_list = [(name, surname, explanation)]
args_str = ','.join(cur.mogrify("(%s,%s,%s)", x) for x in student_list)
cur.execute('INSERT INTO students (name, surname, explanation) VALUES ' + args_str)

This makes my database docker memory seems full and gives these errors:

LOG:  server process (PID 11219) was terminated by signal 9:
  Killed
 DETAIL:  Failed process was running
 LOG:  terminating
  any other active server processes
 docker@test_db WARNING:
  terminating connection because of crash of another server process

  docker@test_db DETAIL:  The postmaster has commanded this server
  process to roll back the current transaction and exit, because another
  server process exited abnormally and possibly corrupted shared
  memory.
 docker@test_db HINT:  In a moment you should be able to
  reconnect to the database and repeat your command.
 docker@test_db
  WARNING:  terminating connection because of crash of another server
  process
 docker@test_db DETAIL:  The postmaster has commanded this
  server process to roll back the current transaction and exit, because
  another server process exited abnormally and possibly corrupted shared
  memory.
 ... docker@test_db FATAL:  the database system is in
  recovery mode
 LOG:  all server processes terminated;
  reinitializing
 LOG:  database system was interrupted; last known
  up at 2017-06-06 09:39:40 UTC
 LOG:  database system was not
  properly shut down; automatic recovery in progress
 docker@test_db
  FATAL:  the database system is in recovery mode
 docker@test_db
  FATAL:  the database system is in recovery mode
 docker@test_db
  FATAL:  the database system is in recovery mode
 LOG:  autovacuum
  launcher started

Script gives that log:

Inner exception

  SSL SYSCALL error: EOF detected

I tried put some sleep time between consecutive queries but got same result. Is there any limitation for that?
Also I tried to connect and disconnect for each query but got same result. These are my connect and disconnect methods.

def connect():
    conn = psycopg2.connect(database=database_name,
                            user=database_user,
                            host=database_host,
                            port=database_port)
    conn
  .set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
    cur = conn.cursor()
    return conn, cur

def disconnect(conn, cur):
    cur.close()
    conn.close()


问:
Scala Twenty Two Again
Scala case classes can have 22+ properties these days, but AFAIA compiler does not compile apply/unapply methods then.

Is there a way to generate apply/unapply by means of a plugin at compile time or at least generate methods using IDE etc?

Note

please don't start asking - why do you need this? It is for mapping existing JSON schema from a mongoDB using Reactive Mongo

please don't advise to group properties into smaller case classes and etc. Schema was created by someone else & already exists on production.

Thank you for your answers in advance.

答:
Yes, Scala supports >22 fields from version 2.11. However, there are certain limitations - the case class will no more have unapply or unapplyseq and tupled(you'll no longer convert case class to tuple) functions because scala still don't support tuple with more that 22 values.

```<code>val tup = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22) //will compile
val tup = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23) //will fail
</code>```

Because of this, case class is much more like regular class class and many other libraries will be unable to fully utilize this case class. Such as, json serializer libraries.

I have faced with this issue when I tried to use macros read/write to serialize case class to json and viceversa in a playframework project it won't compile because case class no longer contain unapply() method. The one work around for this is to provide custom implicit read/writes for the case class instead of using macros.

```<code>case class Person(name: String, age: Int, lovesChocolate: Boolean)

implicit val personReads = Json.reads[Person] //this wond work, need to write custom read as below.
implicit val personReads = (
  (__ \ 'name).read[String] and
  (__ \ 'age).read[Int] and
  (__ \ 'lovesChocolate).read[Boolean]
)(Person)
</code>```

please don't start asking - why do you need this? It is for mapping
  existing JSON schema from a mongoDB using Reactive Mongo

I'm assuming your is the same situation, you are using reactivemongo macros for json to/from case class serialization.

```<code>implicit val personReader: BSONDocumentReader[Person] = Macros.reader[Person]
implicit val personWriter: BSONDocumentWriter[Person] = Macros.writer[Person]
//or Handler
Macros.handler[Person]
</code>```

Therefore, I would suggest you to use custom BSON reader and writer for the case class as documented here.

Title: Scala Twenty Two Again

Body:
Yes, Scala supports >22 fields from version 2.11. However, there are certain limitations - the case class will no more have unapply or unapplyseq and tupled(you'll no longer convert case class to tuple) functions because scala still don't support tuple with more that 22 values.

val tup = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22) //will compile
val tup = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23) //will fail

Because of this, case class is much more like regular class class and many other libraries will be unable to fully utilize this case class. Such as, json serializer libraries.

I have faced with this issue when I tried to use macros read/write to serialize case class to json and viceversa in a playframework project it won't compile because case class no longer contain unapply() method. The one work around for this is to provide custom implicit read/writes for the case class instead of using macros.

case class Person(name: String, age: Int, lovesChocolate: Boolean)

implicit val personReads = Json.reads[Person] //this wond work, need to write custom read as below.
implicit val personReads = (
  (__ \ 'name).read[String] and
  (__ \ 'age).read[Int] and
  (__ \ 'lovesChocolate).read[Boolean]
)(Person)

please don't start asking - why do you need this? It is for mapping
  existing JSON schema from a mongoDB using Reactive Mongo

I'm assuming your is the same situation, you are using reactivemongo macros for json to/from case class serialization.

implicit val personReader: BSONDocumentReader[Person] = Macros.reader[Person]
implicit val personWriter: BSONDocumentWriter[Person] = Macros.writer[Person]
//or Handler
Macros.handler[Person]

Therefore, I would suggest you to use custom BSON reader and writer for the case class as documented here.


问:
Is FeatureCollection necessary for ol.layer.VectorTile layer in openlayers?
I am looking to create a ol.layer.VectorTile layer from an array of GeoJSON Point objects in ol3.  Right now the data that is being returned to me is an array of objects, with each object being a GeoJSON of type "Point".  In examples I have seen, VectorTile layers were created from a "FeatureCollection" which contained all the Point objects as features.  I am wondering if the api would need to return the data as a "FeatureCollection" or I would need to create one myself from the data being returned, in order to ultimately be able to create a vectorTile layer?</p>

答: Your api just needs to return the geometries(ie. point,line, polygon). It could be in any parsable format like GeoJson/WKT.Then create OL3 feature from the geometries returned by your API. Create an instance of ol.Collection. Then add each feature in the newly created collection. And use this featurecollection as a source in a vector layer.</p>


问:
Idiomatic Python: Propagating yields or flattening sequences?
I'm writing a breadth depth-first tree traversal function, and what I want to do is this:

```<code>def traverse(node):
    yield node
    for n in node.children:
        yield_all traverse(n) # << if Python had a yield_all statement
</code>```

The idea is to end up with a (flat) sequence of nodes in the tree.

Approach #1: (propagating yields)

```<code>def traverse(node):
    yield node
    for n in node.children:
        for m in traverse(n):
            yield m
</code>```

Approach #2: (flattening sequences)

```<code>def traverse(node):
    return itertools.chain([node],*(traverse(n) for n in node.children))
</code>```

The first approach seems more clean, but I feel weird explicitly yielding each node in the subtree at each level.

The second approach is terse and slightly dirty, but it matches what I would write in Haskell:

```<code>traverse node = node : concatMap traverse (children node)
</code>```

So my question is: Which is better? Or am I missing a best 3rd option?

答:
This is an opinions question, so all the answers will just be value judgments. As far as I can think there's no elegant third way, though.

My opinion is that the first way wins hands down. It's clearer and easier to read -- Python isn't Haskell, even though it can do some functional stuff, and often the functional approach just doesn't look as neat.

Body:
I'm writing a breadth depth-first tree traversal function, and what I want to do is this:

def traverse(node):
    yield node
    for n in node.children:
        yield_all traverse(n) # << if Python had a yield_all statement

The idea is to end up with a (flat) sequence of nodes in the tree.

Approach #1: (propagating yields)

def traverse(node):
    yield node
    for n in node.children:
        for m in traverse(n):
            yield m

Approach #2: (flattening sequences)

def traverse(node):
    return itertools.chain([node],*(traverse(n) for n in node.children))

The first approach seems more clean, but I feel weird explicitly yielding each node in the subtree at each level.

The second approach is terse and slightly dirty, but it matches what I would write in Haskell:

traverse node = node : concatMap traverse (children node)

So my question is: Which is better? Or am I missing a best 3rd option?