问:
configuration script init.lua for neovim instead of init.vim
As Lua is now built-in as of neovim 0.2 (https://github.com/neovim/neovim/wiki/FAQ), can one use a ~/.config/nvim/init.lua configuration file instead of init.vim?

What would an example of init.lua look like?

Because vimscript is driving me crazy.

答:
No.

I'm going to go ahead and answer this since the message from core developers seems to have been that VimL will not be replaced for this purpose. See Thiago's comments a few years back on Reddit. To summarise, back then the idea was that Lua would act as a runtime for VimL although that PR eventually stalled due to performance concerns.

So for the time being at least, you can write plugins in Lua but you can't use Lua as the configuration language.


来源: stackexchange

问:
How do I make my layout fill the screen when I rotate it?
I have one problem with my code and I could use some help. I made an app that tracks the statistics of a football game.The app works fine the problem is when I rotate my phone screen which is when 2 problems appear:
The layout doesn´t match the screen width, making the text and buttons overlap one another and when I turn the phone around, for some reason, the scores reset. I have a reset button but I don´t know why it activates when I rotate the screen. Would appreciate some help. Thanks for reading!
Here´s the code in XML and Java:

```<code>public class MainActivity extends AppCompatActivity {
int golosA = 0;
int faltasA = 0;
int forasDeJogoA = 0;
int cartoesAmarelosA = 0;
int expulsoesA = 0;
int golosB = 0;
int faltasB = 0;
int forasDeJogoB = 0;
int cartoesAmarelosB = 0;
int expulsoesB = 0;
int cantosA = 0 ;
int cantosB = 0 ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void resetScore(View v) {
    golosA=0;
    faltasA=0;
    expulsoesA=0;
    cartoesAmarelosA = 0;
    forasDeJogoA = 0 ;
    golosB=0;
    faltasB=0;
    expulsoesB=0;
    cartoesAmarelosB = 0;
    forasDeJogoB = 0 ;
    cantosA = 0 ;
    cantosB = 0 ;

    displayFaltasEquipaA(0);
    displayGolosButtonA(0);
    displayExpulsoes(0);
    displayCartoesA(0);
    displayForasJogoA(0);
    displayCartoesB(0);
    displayExpulsoesB(0);
    displayForasJogoB(0);
    displayGolosButtonB(0);
    displayFaltasEquipaB(0);
    displayCantosA(0);
    displayCantosB(0);
}

public void displayGolosButtonA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamA(View view) {
    golosA = golosA + 1;
    displayGolosButtonA(golosA);
}

public void displayFaltasEquipaA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamA(View view) {
    faltasA = faltasA + 1;
    displayFaltasEquipaA(faltasA);
}
public void displayCantosA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamA);
    scoreView.setText(String.valueOf(score));
}

public void cantosA(View view) {
  cantosA  = cantosA + 1;
    displayCantosA(cantosA);
}
public void displayCantosB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamB);
    scoreView.setText(String.valueOf(score));
}

public void cantosB(View view) {
    cantosB  = cantosB + 1;
    displayCantosB(cantosB);
}

public void displayForasJogoA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void forasEquipaA(View view) {
    forasDeJogoA = forasDeJogoA + 1;
    displayForasJogoA(forasDeJogoA + 1);
}

public void displayCartoesA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_a);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamA(View view) {
    cartoesAmarelosA = cartoesAmarelosA + 1;
    displayCartoesA(cartoesAmarelosA);
}

public void displayExpulsoes(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_a);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesTeamA(View view) {
    expulsoesA = expulsoesA + 1;
    displayExpulsoes(expulsoesA);
}

public void displayGolosButtonB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamB(View view) {
    golosB = golosB + 1;
    displayGolosButtonB(golosB);
}

public void displayFaltasEquipaB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamB(View view) {
    faltasB = faltasB + 1;
    displayFaltasEquipaB(faltasB);
}

public void displayForasJogoB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void forasJogoB(View view) {
    forasDeJogoB = forasDeJogoB + 1;
    displayForasJogoB(forasDeJogoB + 1);
}

public void displayCartoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_b);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamB(View view) {
    cartoesAmarelosB = cartoesAmarelosB + 1;
    displayCartoesB(cartoesAmarelosB);
}

public void displayExpulsoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_b);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesB(View v) {
    expulsoesB = expulsoesB + 1;
    displayExpulsoesB(expulsoesB);
}
</code>```

}

答:
For the score resetting problem, try adding the line :

```<code><activity android:name=".YourActivity"
        android:configChanges="orientation|screenSize" >
</code>```

into your manifest file.  It tells your activity to not react to screen orientation changes.  It will still rotate, but will prevent the variables to resets.

For the rotation problem, have you tried editing the rotated version of you app ?  I don't know which editor you're using, but in Android Studio, in the Design page, you got the option to create the landscape version and changes his design manually.

ContentLicense: CC BY-SA 3.0

Body:
I have one problem with my code and I could use some help. I made an app that tracks the statistics of a football game.The app works fine the problem is when I rotate my phone screen which is when 2 problems appear:
The layout doesn´t match the screen width, making the text and buttons overlap one another and when I turn the phone around, for some reason, the scores reset. I have a reset button but I don´t know why it activates when I rotate the screen. Would appreciate some help. Thanks for reading!
Here´s the code in XML and Java:

public class MainActivity extends AppCompatActivity {
int golosA = 0;
int faltasA = 0;
int forasDeJogoA = 0;
int cartoesAmarelosA = 0;
int expulsoesA = 0;
int golosB = 0;
int faltasB = 0;
int forasDeJogoB = 0;
int cartoesAmarelosB = 0;
int expulsoesB = 0;
int cantosA = 0 ;
int cantosB = 0 ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void resetScore(View v) {
    golosA=0;
    faltasA=0;
    expulsoesA=0;
    cartoesAmarelosA = 0;
    forasDeJogoA = 0 ;
    golosB=0;
    faltasB=0;
    expulsoesB=0;
    cartoesAmarelosB = 0;
    forasDeJogoB = 0 ;
    cantosA = 0 ;
    cantosB = 0 ;

    displayFaltasEquipaA(0);
    displayGolosButtonA(0);
    displayExpulsoes(0);
    displayCartoesA(0);
    displayForasJogoA(0);
    displayCartoesB(0);
    displayExpulsoesB(0);
    displayForasJogoB(0);
    displayGolosButtonB(0);
    displayFaltasEquipaB(0);
    displayCantosA(0);
    displayCantosB(0);
}

public void displayGolosButtonA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamA(View view) {
    golosA = golosA + 1;
    displayGolosButtonA(golosA);
}

public void displayFaltasEquipaA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamA(View view) {
    faltasA = faltasA + 1;
    displayFaltasEquipaA(faltasA);
}
public void displayCantosA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamA);
    scoreView.setText(String.valueOf(score));
}

public void cantosA(View view) {
  cantosA  = cantosA + 1;
    displayCantosA(cantosA);
}
public void displayCantosB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamB);
    scoreView.setText(String.valueOf(score));
}

public void cantosB(View view) {
    cantosB  = cantosB + 1;
    displayCantosB(cantosB);
}

public void displayForasJogoA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void forasEquipaA(View view) {
    forasDeJogoA = forasDeJogoA + 1;
    displayForasJogoA(forasDeJogoA + 1);
}

public void displayCartoesA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_a);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamA(View view) {
    cartoesAmarelosA = cartoesAmarelosA + 1;
    displayCartoesA(cartoesAmarelosA);
}

public void displayExpulsoes(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_a);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesTeamA(View view) {
    expulsoesA = expulsoesA + 1;
    displayExpulsoes(expulsoesA);
}

public void displayGolosButtonB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamB(View view) {
    golosB = golosB + 1;
    displayGolosButtonB(golosB);
}

public void displayFaltasEquipaB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamB(View view) {
    faltasB = faltasB + 1;
    displayFaltasEquipaB(faltasB);
}

public void displayForasJogoB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void forasJogoB(View view) {
    forasDeJogoB = forasDeJogoB + 1;
    displayForasJogoB(forasDeJogoB + 1);
}

public void displayCartoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_b);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamB(View view) {
    cartoesAmarelosB = cartoesAmarelosB + 1;
    displayCartoesB(cartoesAmarelosB);
}

public void displayExpulsoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_b);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesB(View v) {
    expulsoesB = expulsoesB + 1;
    displayExpulsoesB(expulsoesB);
}

}

Body:
For the score resetting problem, try adding the line :

<activity android:name=".YourActivity"
        android:configChanges="orientation|screenSize" >

into your manifest file.  It tells your activity to not react to screen orientation changes.  It will still rotate, but will prevent the variables to resets.

For the rotation problem, have you tried editing the rotated version of you app ?  I don't know which editor you're using, but in Android Studio, in the Design page, you got the option to create the landscape version and changes his design manually.


问:
CSS not centering
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png"></img>
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.

答:
Your .divOuter is correctly centered, but the problem is that you're apply a fixed width of 150px to your three inner elements. Swapping this to a percentage-based width of 100% correctly centers the elements:

.divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png" />
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

If you want to make use of a fixed width, you can do so by definining it on .divOuter:

.divOuter {
  width: 150px;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png" />
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

Also note that the  tag is self-closing; there is no  tag.

Hope this helps! :)

Title: CSS not centering

Body:
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.

Body:
Your .divOuter is correctly centered, but the problem is that you're apply a fixed width of 150px to your three inner elements. Swapping this to a percentage-based width of 100% correctly centers the elements:

.divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

<div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png" />
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div>

If you want to make use of a fixed width, you can do so by definining it on .divOuter:

.divOuter {
  width: 150px;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

<div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png" />
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div>

Also note that the <img> tag is self-closing; there is no </img> tag.

Hope this helps! :)


问:
C++11 packaged_task running with its own thread need a join() in order to get future
From the C++11 book I recently got, I am trying to build the example on page 123 (packaged_task 5.3.5.2) and after a few things to make this work with XCode, I have a couple of questions:

First, there seems to be a requirement to pass a function pointer to the packaged_task ctor. The text doesn't show the ampersand, so maybe it's a typo or a late standard change?

Then, and more important, I had to add thread.join(s) to be able to call get and avoid getting a sigabrt and the process exits without printing anything. I was under the impression that a call to get future would block till the thread returns a value, but this doesn't seem to be the case. Adding the join also seem to defy the asynchronous (non-blocking) nature of the code. Why can't get on the future do the join itself if it needs to? Reading from the docs, it says that a get will call implicitly wait and even by adding wait in the code, this still causes a sigabrt. This is very puzzling.

I am using c language dialect c11, -std=gnu++11 and libc++ (with c++11 support). I tried other options with no luck (when using gnuc++, it can't find ). This seems to be the only combinations I can use to build the code. XCode is very picky about what it needs to compile c++11.

Thanks for your help in advance.

Here is the test case from the book with my 'fixes' to make the code run:

```<code>    #include <iostream>
    #include <numeric>
    #include <vector>
    #include <thread>
    #include <future>

    using namespace std;

    double accum(double *beg, double *end, double init)
    {
        return accumulate(beg, end, init);
    }

    double comp2(vector<double>& v)
    {

        using Task_type = double(double*,double*,double);

        packaged_task<Task_type> pt0 {&accum}; //use '&' to compile
        packaged_task<Task_type> pt1 {&accum}; //use '&' to compile

        future<double> f0 {pt0.get_future()};
        future<double> f1 {pt1.get_future()};

        double* first=&v[0];
        thread t1 {move(pt0), first, first+v.size()/2, 0};
        thread t2 {move(pt1), first+v.size()/2, first+v.size(), 0};

        // need this to run
        t1.join();
        t2.join();

        // using this instead of the join doesn't work
//      f0.wait();
//      f1.wait();

        return f0.get() + f1.get();
    }

    int main()
    {
        vector<double> v {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        cout<<comp2(v)<<endl;
        return 0;
    }
</code>```

答:
I think the current answers didn't answer the question directly. You don't need to explicitly create threads to run the tasks. For example:

```<code>#include <future>
#include <stdexcept>
#include <iostream>
#include <thread>
#include <utility>
#include <functional>

using namespace std;

int ff(int i)
{
  return i;
}

int main(int argc, char *argv[])
{

  packaged_task<int(int)> pt1 (ff);
  auto v1 = pt1.get_future();
  thread t1(move(pt1), 1);
  t1.join();

  packaged_task<int(int)> pt2(ff);
  auto v2 = pt2.get_future();
  pt2(1);
  cout << v2.get() << endl;

  return 0;
}
</code>```

If you compile the above example you will see 1 as the stdout.

But what confused me is that, if I comment out the first packaged_task, then I see a std::system_error, the complete code is:

```<code>#include <future>
#include <stdexcept>
#include <iostream>
#include <thread>
#include <utility>
#include <functional>

using namespace std;

int ff(int i)
{
  return i;
}

int main(int argc, char *argv[])
{

  // packaged_task<int(int)> pt1 (ff);
  // auto v1 = pt1.get_future();
  // thread t1(move(pt1), 1);
  // t1.join();

  packaged_task<int(int)> pt2(ff);
  auto v2 = pt2.get_future();
  pt2(1);
  cout << v2.get() << endl;

  return 0;
}
</code>```

Apparently the two packaged_tasks are independent and yet removing the first one will cause the second one to fail with a system_error.

This is not an answer to the question, but rather an attempt to clarify the question.

Body:
From the C++11 book I recently got, I am trying to build the example on page 123 (packaged_task 5.3.5.2) and after a few things to make this work with XCode, I have a couple of questions:

First, there seems to be a requirement to pass a function pointer to the packaged_task ctor. The text doesn't show the ampersand, so maybe it's a typo or a late standard change?

Then, and more important, I had to add thread.join(s) to be able to call get and avoid getting a sigabrt and the process exits without printing anything. I was under the impression that a call to get future would block till the thread returns a value, but this doesn't seem to be the case. Adding the join also seem to defy the asynchronous (non-blocking) nature of the code. Why can't get on the future do the join itself if it needs to? Reading from the docs, it says that a get will call implicitly wait and even by adding wait in the code, this still causes a sigabrt. This is very puzzling.

I am using c language dialect c11, -std=gnu++11 and libc++ (with c++11 support). I tried other options with no luck (when using gnuc++, it can't find ). This seems to be the only combinations I can use to build the code. XCode is very picky about what it needs to compile c++11.

Thanks for your help in advance.

Here is the test case from the book with my 'fixes' to make the code run:

    #include <iostream>
    #include <numeric>
    #include <vector>
    #include <thread>
    #include <future>

    using namespace std;

    double accum(double *beg, double *end, double init)
    {
        return accumulate(beg, end, init);
    }

    double comp2(vector<double>& v)
    {

        using Task_type = double(double*,double*,double);

        packaged_task<Task_type> pt0 {&accum}; //use '&' to compile
        packaged_task<Task_type> pt1 {&accum}; //use '&' to compile

        future<double> f0 {pt0.get_future()};
        future<double> f1 {pt1.get_future()};

        double* first=&v[0];
        thread t1 {move(pt0), first, first+v.size()/2, 0};
        thread t2 {move(pt1), first+v.size()/2, first+v.size(), 0};

        // need this to run
        t1.join();
        t2.join();

        // using this instead of the join doesn't work
//      f0.wait();
//      f1.wait();

        return f0.get() + f1.get();
    }

    int main()
    {
        vector<double> v {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        cout<<comp2(v)<<endl;
        return 0;
    }

Body:
I think the current answers didn't answer the question directly. You don't need to explicitly create threads to run the tasks. For example:

#include <future>
#include <stdexcept>
#include <iostream>
#include <thread>
#include <utility>
#include <functional>

using namespace std;

int ff(int i)
{
  return i;
}

int main(int argc, char *argv[])
{

  packaged_task<int(int)> pt1 (ff);
  auto v1 = pt1.get_future();
  thread t1(move(pt1), 1);
  t1.join();

  packaged_task<int(int)> pt2(ff);
  auto v2 = pt2.get_future();
  pt2(1);
  cout << v2.get() << endl;

  return 0;
}

If you compile the above example you will see 1 as the stdout.

But what confused me is that, if I comment out the first packaged_task, then I see a std::system_error, the complete code is:

#include <future>
#include <stdexcept>
#include <iostream>
#include <thread>
#include <utility>
#include <functional>

using namespace std;

int ff(int i)
{
  return i;
}

int main(int argc, char *argv[])
{

  // packaged_task<int(int)> pt1 (ff);
  // auto v1 = pt1.get_future();
  // thread t1(move(pt1), 1);
  // t1.join();

  packaged_task<int(int)> pt2(ff);
  auto v2 = pt2.get_future();
  pt2(1);
  cout << v2.get() << endl;

  return 0;
}

Apparently the two packaged_tasks are independent and yet removing the first one will cause the second one to fail with a system_error.

This is not an answer to the question, but rather an attempt to clarify the question.


问:
InputStream read(byte[] b, int off, int len) - Drop the rest of the file?
This is an extension of a question I asked on here this morning so please don't disregard if you think you've seen this code before :D

```<code>for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[10];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 1){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(org.apache.commons.codec.binary.Hex.encodeHexString(b));
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}
</code>```

Hi there, after hours of struggling to get this code to how it is, I've almost finished the particular component that I am working on. The program takes in a specified file and is supposed to convert the first 10 bytes of that file into Hex. Once it has acquired the first 10 bytes of that file, it should stop and move onto the next specified file. Currently, it takes the entirety of the file and divides it into multiple 10 byte 'chunks' which it then prints out. In other words, it isn't stopping after the first 10 bytes which  I thought read(byte[] b, int off, int len) did

Example output:

74656173676173677361

67616773617367616773

61676173617367616773

but instead it should produce

74656173676173677361

Any advice would be hugely appreciated it and I really do mean that :)

答:
What about dropping the while-loop? As I already told you in your first question, the following is the way to go in case you're sure there are always at least 10 bytes:

```<code>byte[] b = new byte[10];
new DataInputStream(new FileInputStream(input.readUTF())).readFully(b);
</code>```

Otherwise go for something like this:

```<code>byte[] b = new byte[10];
int count = 0;
while (count < b.length) {
    int n = in.read(b, count, b.length-count);
    if (n==-1) break;
    count += n;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is an extension of a question I asked on here this morning so please don't disregard if you think you've seen this code before :D

for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[10];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 1){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(org.apache.commons.codec.binary.Hex.encodeHexString(b));
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}

Hi there, after hours of struggling to get this code to how it is, I've almost finished the particular component that I am working on. The program takes in a specified file and is supposed to convert the first 10 bytes of that file into Hex. Once it has acquired the first 10 bytes of that file, it should stop and move onto the next specified file. Currently, it takes the entirety of the file and divides it into multiple 10 byte 'chunks' which it then prints out. In other words, it isn't stopping after the first 10 bytes which  I thought read(byte[] b, int off, int len) did

Example output:

74656173676173677361

67616773617367616773

61676173617367616773

but instead it should produce

74656173676173677361

Any advice would be hugely appreciated it and I really do mean that :)

Body:
What about dropping the while-loop? As I already told you in your first question, the following is the way to go in case you're sure there are always at least 10 bytes:

byte[] b = new byte[10];
new DataInputStream(new FileInputStream(input.readUTF())).readFully(b);

Otherwise go for something like this:

byte[] b = new byte[10];
int count = 0;
while (count < b.length) {
    int n = in.read(b, count, b.length-count);
    if (n==-1) break;
    count += n;
}


问:
How can I watch for changes to localStorage in Angular2?
I was trying to figure out how to get a menu to appear and disappear based on being logged in in a previous post.  But I think a better and possibly easier question would be, how can I watch for changes to localstorage?

I am using json web tokens in local storage for my authentication, I would love to watch for a change to localStorage and then re-update my view on new information.

I set my localStorage with this

```<code>localStorage.setItem('jwt', my_token);
</code>```

The things I would like to do is check if I have a token, if I don't nothing happens, but when there is a change fire an event.  I would especially like it if I could only watch for a certain named event like localStorage.getItem('jwt').

Thanks!

EDIT:

Gunter pointed me in the right direction but just in case anyone is still fairly confused by that, here is a plunker showing you how to do it.
http://plnkr.co/edit/TiUasGdutCsll1nI6USC?p=preview

答:
The key thing is to use window.addEventListener("storage", . While the library probably does it the "right" way for angular, here is a "light" version I put together, using .bind(this) instead of mucking about in angular's internals.

    import { Injectable, OnDestroy } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    import { share } from 'rxjs/operators';

    @Injectable()
    export class StorageService implements OnDestroy {
      private onSubject = new Subject<{ key: string, value: any }>();
      public changes = this.onSubject.asObservable().pipe(share());

      constructor() {
        this.start();
      }

      ngOnDestroy() {
        this.stop();
      }

      public getStorage() {
        let s = [];
        for (let i = 0; i < localStorage.length; i++) {
          s.push({
            key: localStorage.key(i),
            value: JSON.parse(localStorage.getItem(localStorage.key(i)))
          });
        }
        return s;
      }

      public store(key: string, data: any): void {
        localStorage.setItem(key, JSON.stringify(data));
        this.onSubject.next({ key: key, value: data})
      }

      public clear(key) {
        localStorage.removeItem(key);
        this.onSubject.next({ key: key, value: null });
      }

      private start(): void {
        window.addEventListener("storage", this.storageEventListener.bind(this));
      }

      private storageEventListener(event: StorageEvent) {
        if (event.storageArea == localStorage) {
          let v;
          try { v = JSON.parse(event.newValue); }
          catch (e) { v = event.newValue; }
          this.onSubject.next({ key: event.key, value: v });
        }
      }

      private stop(): void {
        window.removeEventListener("storage", this.storageEventListener.bind(this));
        this.onSubject.complete();
      }
    }
```

Body:
I was trying to figure out how to get a menu to appear and disappear based on being logged in in a previous post.  But I think a better and possibly easier question would be, how can I watch for changes to localstorage?

I am using json web tokens in local storage for my authentication, I would love to watch for a change to localStorage and then re-update my view on new information.

I set my localStorage with this

localStorage.setItem('jwt', my_token);

The things I would like to do is check if I have a token, if I don't nothing happens, but when there is a change fire an event.  I would especially like it if I could only watch for a certain named event like localStorage.getItem('jwt').

Thanks!

EDIT:

Gunter pointed me in the right direction but just in case anyone is still fairly confused by that, here is a plunker showing you how to do it.
http://plnkr.co/edit/TiUasGdutCsll1nI6USC?p=preview

ContentLicense: CC BY-SA 4.0


问:
Google maps API js errors
I have integrated Google maps using the API v3 and everything is working correctly however i am getting some console errors and wanted to see if anyone could point out why.

On Chrome i get:
Uncaught TypeError: Cannot read property 'lat' of null VM262:13(anonymous function) VM262:13T.trigger main.js:15N.Hc VM261:137(anonymous function) main.js:13T.trigger main.js:15N.Xl VM261:122(anonymous function)

On firefox i get:
TypeError: s is null

Based on reading other answers it would appear that the dom hasn't fully loaded when the map is initialised but this does not seem to be the case as i'm running it on load. My code is below, if anyone could point me in the direction of why these errors might be occurring (everything seems to work correctly!) then that would be greatly appreciated (fyi there is some php code in here used to insert db variables into the js):

```<code>var map;
var infos = [];
var ib = new InfoBox();
var infowindow;

function initialize() {
    var contentString = '';
    infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    map = new google.maps.Map(document.getElementById('map-canvas'));
    var address = 'Netherlands';
    var geocoder = new google.maps.Geocoder();
       geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            map.fitBounds(results[0].geometry.viewport);
          }
        });
    var markers = [
    [1, '52.350785','5.264702', 2, 'Almere', '01345'],[1, '52.992753','6.564228', 2, 'Assen', '012345678']
    ];
    for (var i = 0; i < markers.length; i++) {
        setMarkers(map, markers[i]);
    }
}

function setMarkers(map, beach) {
    var image = new google.maps.MarkerImage('/img/marker.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(21, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(5, 34));

    var html = '<div class="phoney">'+beach[4]+'<br>'+beach[5]+'<\/div>';
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: image,
    content:html,
    title: beach[4],
    zIndex: beach[3]
    });

    var boxText = document.createElement("div");
    boxText.style.cssText = "border: 2px solid #4a5461; margin-top: 8px;background: #ffffff; padding: 5px;font-family: \'ff-din-web-n6\',\'ff-din-web\',sans-serif; font-size: 17px; color: #4a5461;";
    boxText.innerHTML = beach[4] + '<br>' + beach[5];

    var myOptions = {
    content:boxText,
    disableAutoPan: false,
    maxWidth: 0,
    pixelOffset: new google.maps.Size(-140, 0),
    zIndex: null,
    boxStyle: {
        width: "200px"
    },
    closeBoxMargin: "13px 5px 2px 2px",
    closeBoxURL: "/img/close.png",
    infoBoxClearance: new google.maps.Size(1, 1),
    isHidden: false,
    pane: "floatPane",
    enableEventPropagation: false
    };

    google.maps.event.addListener(marker, "click", function (e) {
    ib.setOptions(myOptions);
    ib.open(map, marker);
    });
}

$( document ).ready(function() {
    google.maps.event.addDomListener(window, 'load', initialize);
});
</code>```

Thanks very much,

Dave

答:
Dave,

Make sure that lat, long are decimal values as such:

var center = { lat: -25.363, lng: 131.044 };

Title: Google maps API js errors

Body:
I have integrated Google maps using the API v3 and everything is working correctly however i am getting some console errors and wanted to see if anyone could point out why.

On Chrome i get:
Uncaught TypeError: Cannot read property 'lat' of null VM262:13(anonymous function) VM262:13T.trigger main.js:15N.Hc VM261:137(anonymous function) main.js:13T.trigger main.js:15N.Xl VM261:122(anonymous function)

On firefox i get:
TypeError: s is null

Based on reading other answers it would appear that the dom hasn't fully loaded when the map is initialised but this does not seem to be the case as i'm running it on load. My code is below, if anyone could point me in the direction of why these errors might be occurring (everything seems to work correctly!) then that would be greatly appreciated (fyi there is some php code in here used to insert db variables into the js):

var map;
var infos = [];
var ib = new InfoBox();
var infowindow;

function initialize() {
    var contentString = '';
    infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    map = new google.maps.Map(document.getElementById('map-canvas'));
    var address = 'Netherlands';
    var geocoder = new google.maps.Geocoder();
       geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            map.fitBounds(results[0].geometry.viewport);
          }
        });
    var markers = [
    [1, '52.350785','5.264702', 2, 'Almere', '01345'],[1, '52.992753','6.564228', 2, 'Assen', '012345678']
    ];
    for (var i = 0; i < markers.length; i++) {
        setMarkers(map, markers[i]);
    }
}

function setMarkers(map, beach) {
    var image = new google.maps.MarkerImage('/img/marker.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(21, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(5, 34));

    var html = '
'+beach[4]+'
'+beach[5]+'<\/div>';
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: image,
    content:html,
    title: beach[4],
    zIndex: beach[3]
    });

    var boxText = document.createElement("div");
    boxText.style.cssText = "border: 2px solid #4a5461; margin-top: 8px;background: #ffffff; padding: 5px;font-family: \'ff-din-web-n6\',\'ff-din-web\',sans-serif; font-size: 17px; color: #4a5461;";
    boxText.innerHTML = beach[4] + '
' + beach[5];

    var myOptions = {
    content:boxText,
    disableAutoPan: false,
    maxWidth: 0,
    pixelOffset: new google.maps.Size(-140, 0),
    zIndex: null,
    boxStyle: {
        width: "200px"
    },
    closeBoxMargin: "13px 5px 2px 2px",
    closeBoxURL: "/img/close.png",
    infoBoxClearance: new google.maps.Size(1, 1),
    isHidden: false,
    pane: "floatPane",
    enableEventPropagation: false
    };

    google.maps.event.addListener(marker, "click", function (e) {
    ib.setOptions(myOptions);
    ib.open(map, marker);
    });
}

$( document ).ready(function() {
    google.maps.event.addDomListener(window, 'load', initialize);
});

Thanks very much,

Dave


问:
wordpress mysql - delete all custom post type
I've got a wordpress/mysql set up using the 'custom post type' which currently holds about 40,000 rows of data in the wp_posts table of the database.   I'm trying to work on an SQL query that will remove all the rows of a certain custom post type in one go but it keeps telling me I've got a syntax error. The code I'm using is below, apologies if it's simple but SQL is alien to me and I'm struggling to find anything in the forums.

```<code>DELETE FROM `wp_posts`
WHERE  `post_type` =  'prefix-numberplates'
LIMIT 0 , 3000
</code>```

There are ` around wp_posts & post_type but it won't let me style them on here.
Any help is greatly appreciated.

答:
```<code>delete p,m from wp_posts p left join wp_postmeta m on p.ID = m.post_id where p.post_type = "my_custom_post_type"
</code>```

Body:
I've got a wordpress/mysql set up using the 'custom post type' which currently holds about 40,000 rows of data in the wp_posts table of the database.   I'm trying to work on an SQL query that will remove all the rows of a certain custom post type in one go but it keeps telling me I've got a syntax error. The code I'm using is below, apologies if it's simple but SQL is alien to me and I'm struggling to find anything in the forums.

DELETE FROM `wp_posts`
WHERE  `post_type` =  'prefix-numberplates'
LIMIT 0 , 3000

There are ` around wp_posts & post_type but it won't let me style them on here.
Any help is greatly appreciated.


问:
When can we avoid using a constructor to initialize state?

In the example given on the reactnativeexpress website here, state = {count: 0} is used in place of a constructor to initialize the count variable.

In the official Facebook docs here, they've said

In general, you should initialize state in the constructor, and then call setState when you want to change it.

So I created a constructor to initialize count in the same manner:

```<code>constructor(props) {
  super(props);
  this.state = {count: 0}
}
</code>```

The code seems to work the same way (at least on the surface), so what's the difference between creating a constructor and initializing count as in the example?

答:
In the example that you attach as a link they use the ES Class Fields which is a proposal (currently in stage 2).

That means you will need some extra presets / plugins of babel (or any other JavaScript compiler) to support it as it's not part of the official specifications of ECMAScript yet.

In the other example, you use the class constructor which is part of  ES2015.

Both will get you the same results, a property attached to the instance of the class.

which is basically just a syntactic sugar for the prototype pattern.

Body:
In the example given on the reactnativeexpress website here, state = {count: 0} is used in place of a constructor to initialize the count variable.

In the official Facebook docs here, they've said

In general, you should initialize state in the constructor, and then call setState when you want to change it.

So I created a constructor to initialize count in the same manner:

constructor(props) {
  super(props);
  this.state = {count: 0}
}

The code seems to work the same way (at least on the surface), so what's the difference between creating a constructor and initializing count as in the example?


问:
C# Namespace, Folders, Compiler Error
I'm using VS 2017 v15.5.0.

I have a minimal Console project named, Con_02. The namespace for the main class in this project is simply Con_02 (the class is shown below).

Within this project I add a new folder named, Business. Within the Business folder I create a class named, Employee. The default namespace generated by VS for the Employee class is Con_02.Business. I simplify this namespace to Business.

Back in my main class I instantiate Employee. Here is my full main class:

```<code>namespace Con_02 {
    class Program {
        Business.Employee e1 = new Business.Employee();

        private static void Main() { }
    }
}
</code>```

So far, so good. Everything compiles.

Now, I create another class, Company, in the Business folder. VS generates a namespace, Con_02.Business.

Now, the main Con_02.Program class no longer compiles. Specifically, the creation of the Business.Employee object which had previously compiled just fine, gives me a compiler error:

The type or namespace name 'Employee' does not exist in the namespace 'Con_02.Business' (are you missing an assembly reference?)

I'm not asking how to fix the problem so much as I'm trying to understand why compiler seems to assume a namespace relative to Con_02.

答:
Since you are creating a new namespace called Con_02.Business which contains Company class the Business.Employee is considered to be under Con_02.Business namespace but Con_02.Business contains nothing but Company class.

Better to change

```<code>namespace Con_02.Business
{
    class Company
    {
    }
}
</code>```

to

```<code>namespace Business
{
    class Company
    {
    }
}
</code>```

or just use Employee e1 = new Employee();

Remember namespace is only about grouping the classes.

Title: C# Namespace, Folders, Compiler Error

Body:
I'm using VS 2017 v15.5.0.

I have a minimal Console project named, Con_02. The namespace for the main class in this project is simply Con_02 (the class is shown below).

Within this project I add a new folder named, Business. Within the Business folder I create a class named, Employee. The default namespace generated by VS for the Employee class is Con_02.Business. I simplify this namespace to Business.

Back in my main class I instantiate Employee. Here is my full main class:

namespace Con_02 {
    class Program {
        Business.Employee e1 = new Business.Employee();

        private static void Main() { }
    }
}

So far, so good. Everything compiles.

Now, I create another class, Company, in the Business folder. VS generates a namespace, Con_02.Business.

Now, the main Con_02.Program class no longer compiles. Specifically, the creation of the Business.Employee object which had previously compiled just fine, gives me a compiler error:

The type or namespace name 'Employee' does not exist in the namespace 'Con_02.Business' (are you missing an assembly reference?)

I'm not asking how to fix the problem so much as I'm trying to understand why compiler seems to assume a namespace relative to Con_02.

Body:
Since you are creating a new namespace called Con_02.Business which contains Company class the Business.Employee is considered to be under Con_02.Business namespace but Con_02.Business contains nothing but Company class.

Better to change

namespace Con_02.Business
{
    class Company
    {
    }
}

to

namespace Business
{
    class Company
    {
    }
}

or just use Employee e1 = new Employee();

Remember namespace is only about grouping the classes.


问:
Why does compiling bitflags 1.0 produce an "expected ident, found #" error?
When I try to build a project in Rust with bitflags v1.0.1 in macOS Sierra 10.12.6 the code fails with the following error:

Compiling bitflags v1.0.1
error: expected ident, found #
   --> /Users/kenneth.marete/.cargo/registry/src/github.com-1ecc6299db9ec823/bitflags-1.0.1/src/lib.rs:423:29
    |
423 |                               #[allow(deprecated)]
    |                               ^
    |
   ::: /Users/kenneth.marete/.cargo/registry/src/github.com-1ecc6299db9ec823/bitflags-1.0.1/src/example_generated.rs
    |
4   | / bitflags! {
5   | |     /// This is the same `Flags` struct defined in the [crate level example](../index.html#example).
6   | |     /// Note that this struct is just for documentation purposes only, it must not be used outside
7   | |     /// this crate.
...   |
13  | |     }
14  | | }
    | |_- in this macro invocation
```

I expected it to build successfully.

答:
Some crates may fail to compile due to compiling with a version of Rust older than the minimum required. It has nothing to do with the OS version or the application itself.

I had rustc 1.19.0 (0ade33941 2017-07-17) while bitflags version 1.0.1 had a minimum supported Rust version of 1.20 due to the use of associated constants.

From time to time, update the Rust compiler by running rustup update.

Body:
When I try to build a project in Rust with bitflags v1.0.1 in macOS Sierra 10.12.6 the code fails with the following error:

Compiling bitflags v1.0.1
error: expected ident, found #
   --> /Users/kenneth.marete/.cargo/registry/src/github.com-1ecc6299db9ec823/bitflags-1.0.1/src/lib.rs:423:29
    |
423 |                               #[allow(deprecated)]
    |                               ^
    |
   ::: /Users/kenneth.marete/.cargo/registry/src/github.com-1ecc6299db9ec823/bitflags-1.0.1/src/example_generated.rs
    |
4   | / bitflags! {
5   | |     /// This is the same `Flags` struct defined in the [crate level example](../index.html#example).
6   | |     /// Note that this struct is just for documentation purposes only, it must not be used outside
7   | |     /// this crate.
...   |
13  | |     }
14  | | }
    | |_- in this macro invocation

I expected it to build successfully.


问:
Kephas evaluation for Dependency Injection.
When evaluating Kephas, I’ve seen that it uses then Managed Extensibility Framework from Microsoft (System.Composition package). However, we use Ninject for Dependency Injection. Am I forced into changing the DI container, or may I use Ninject?</p>

答:
You don't have to change anything about your DI framework you use, in this case Ninject. However, depending on your migration strategy, you have to consider the following:

Kephas uses a DI abstraction which can run theoretically on any concrete DI implementation, so technically speaking you could use under the hood your Ninject container.

= but =

Kephas makes extensive use of DI metadata, and from what I know Ninject does not support metadata.

So you have the following options:

Use two DI containers. This may be practical for the time bridging the complete migration, but I would not recommend it for the long run.

Use another DI container supporting metadata. If you are not satisfied with the System.Composition (MEF) adapter, for which built-in support is provided, an alternative would be Autofac, but to use it you will have to provide the container adapter (which is not that complicated). By doing so you will have only one DI container.

Conclusion: even if you don't have to change the DI framework, for the reasons provided above it is recommended to do it.

You may want to check the DI wiki for more information.

Disclaimer: I am the lead developer of Kephas Framework.


问:
JSON Error when create react app
Trying to follow tutorial on react (Here: https://hackernoon.com/simple-react-development-in-2017-113bd563691f), but I keep getting JSON error "Error parsing JSON. unexpected end of JSON input." I'm using yarn. How do i fix the JSON input? </p>

答:
i faced the same issue & this solved the issue :

try the below command in your terminal

npm cache clean --force

solution ref

Title: JSON Error when create react app


问:
Panel events won't work in c#
Hi all
I'm struggling with some problem in a project from college.
I'm building a "4 in a row" game in c# for a project in my c# course at my college.

I have created a Form named GameForm and inside it I added a Panel named panelBoardGame.
to that panelBoardGame I added an array of labels to be clickable (to execute a move) and i added a matrix of labels too , to represent the Board itself.

Now, my mission is whenever the mouse is inside the Panel area, the CoinImage of a certain player is moving along with the Cursor as long it is inside the panel area. when the mouse is outside the area, the CoinImage wont show.

To do so I tried triggering the onMouseEnter,OnMouseLeave events of the panelBoardGame, but somehow they wont even get executed.
Whenever my mouse is inside the panelBoardGame area the code inside panelBoardGame_MouseMove(......) function doesn't get executed.

Anyone could help me with that?

Since im new here i cant post images, but ive uploaded the image to here Image of the Form

Here is the image of the Form, inside it with a border in black around it is the panel and inside the panel i added labels

答:
Most likely the Move and Hover events go to the topmost control (the labels). Is any of your Panel showing?

You might be able to Capture the mouse in the MouseEnter event of the Panel.

```<code>boardPanel.Capture = true;
</code>```

But this might interfere with the mouse-handling in the labels.

All in all, you'll probably find that getting this (UI) right is a lot harder than it looks. Consider a simpler act-on-click design. To start with.

Title: Panel events won't work in c#

Body:
Most likely the Move and Hover events go to the topmost control (the labels). Is any of your Panel showing?

You might be able to Capture the mouse in the MouseEnter event of the Panel.

boardPanel.Capture = true;

But this might interfere with the mouse-handling in the labels.

All in all, you'll probably find that getting this (UI) right is a lot harder than it looks. Consider a simpler act-on-click design. To start with.


问:
In Spark Streaming how to process old data and delete processed Data
We are running a Spark streaming job that retrieves files from a directory (using textFileStream).
One concern we are having is the case where the job is down but files are still being added to the directory.
Once the job starts up again, those files are not being picked up (since they are not new or changed while the job is running) but we would like them to be processed.

1) Is there a solution for that? Is there a way to keep track what files have been processed and can we "force" older files to be picked up?

2) Is there a way to delete the processed files?

答:
The article below pretty much covers all your questions.

https://blog.yanchen.ca/2016/06/28/fileinputdstream-in-spark-streaming/

1) Is there a solution for that? Is there a way to keep track what files have been processed and can we "force" older files to be picked up?

Stream reader initiates batch window using the system clock when a job/application is launched. Apparently all the files created before would be ignored. Try enabling checkpointing.

2) Is there a way to delete the processed files?

Deleting files might be unnecessary. If checkpointing works, the files not being processed are identified by Spark. If for some reason the files are to be deleted, implement a custom input format and reader (please refer article) to capture the file name and use this information as appropriate. But I wouldn't recommend this approach.


问:
Pivot Table No calculation
I have a simple dataset as follow:

```<code>Name    Question    Answer
A       Allergy     Y
A       Cancer      N
A       Flu         N
B       Allergy     Y
B       Cancer      Y
B       Flu         N
C       Allergy     N
C       Flu         N
</code>```

I would like to display it in the form (in excel)

```<code>      Allergy   Cancer Flu
A     Y            N   N
B     Y            Y   N
C     N                N
</code>```

And I wonder if using pivot table is the way to go. If not, is there a way to display data using my format above? Please note, the dataset I presented above is just a simplified version of a database with million records.

I tried to use Pivot Table in excel with Name in the Row, Question in the Column and Answer in the detail with calculation function Max. The results did not turn out as expected.

Please advise how I should tweak the results to get what I want. I do not need any calculation performed, just show the result as is. Possible?

答:
by using a pivot table it is nessesary to have a numeric field to place in values, otherwise it will count the number of occurences of every class.

So I think a good solution would be to creatre a binary variable definied as follows:= 1 if Yes 0 otherwise

then you would have something like this (A contingency table):

Title: Pivot Table No calculation

Body:
I have a simple dataset as follow:

Name    Question    Answer
A       Allergy     Y
A       Cancer      N
A       Flu         N
B       Allergy     Y
B       Cancer      Y
B       Flu         N
C       Allergy     N
C       Flu         N

I would like to display it in the form (in excel)

      Allergy   Cancer Flu
A     Y            N   N
B     Y            Y   N
C     N                N

And I wonder if using pivot table is the way to go. If not, is there a way to display data using my format above? Please note, the dataset I presented above is just a simplified version of a database with million records.

I tried to use Pivot Table in excel with Name in the Row, Question in the Column and Answer in the detail with calculation function Max. The results did not turn out as expected.

Please advise how I should tweak the results to get what I want. I do not need any calculation performed, just show the result as is. Possible?


问:
After a few successful urlopen(s), start getting 403
I have a list of URLs for Digikey product pages.  The goal is to open each URL then scrape pricing info and create a BoM.

The challenge I am having is that after opening a few URLs, URLError starts occurring with 403 (Forbidden) - even though I can open these URLs in my (Chrome) browser (on Mac).

What reasons could there be to go from opening each URL to deciding my opening a URL is forbidden within the Python script?  Thank you!

Here is the code:

```<code>from urllib.request import urlopen, Request, URLError
urls = ['https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RC0805JR-071KL',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=08055C333KAT2A',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=B72660M0251K072',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=HI1206T500R-10',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=LVR005NK-2',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RL1220S-120-F',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RMCF0805JT330R',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=IND-LED',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CHV1206-JW-224ELF',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RAC03-3.3SGA',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=202R18W102KV4E',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=GRM32DR72H104KW10L',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CRE1S0505S3C',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=SJ-3523-SMT-TR',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=ATM90E26-YU-RCT-ND',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CL21F104ZBCNNNC',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CL21A106KQCLRNC',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=535-9865-1-ND',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=c',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CL21C180JBANNNC',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=BLM15AG100SN1D',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RMCF0805JT51R0',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=SI8651BB-B-IS1']
#####################################
for url in urls:
    print(url)
    try:
        with urlopen(url) as response:
            html = response.read()
            print (html)
        print("DONE WITH THIS URL.")
    except URLError as e:
        print(e.reason)
</code>```

答:
Thanks to the comments, indeed digikey was assuming my code was a bot.  The "workaround" included:

not using scripts in the URL

randomly selecting a different user agent if get a http 403.

Thank you.

Body:
I have a list of URLs for Digikey product pages.  The goal is to open each URL then scrape pricing info and create a BoM.

The challenge I am having is that after opening a few URLs, URLError starts occurring with 403 (Forbidden) - even though I can open these URLs in my (Chrome) browser (on Mac).

What reasons could there be to go from opening each URL to deciding my opening a URL is forbidden within the Python script?  Thank you!

Here is the code:

from urllib.request import urlopen, Request, URLError
urls = ['https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RC0805JR-071KL',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=08055C333KAT2A',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=B72660M0251K072',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=HI1206T500R-10',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=LVR005NK-2',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RL1220S-120-F',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RMCF0805JT330R',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=IND-LED',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CHV1206-JW-224ELF',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RAC03-3.3SGA',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=202R18W102KV4E',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=GRM32DR72H104KW10L',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CRE1S0505S3C',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=SJ-3523-SMT-TR',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=ATM90E26-YU-RCT-ND',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CL21F104ZBCNNNC',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CL21A106KQCLRNC',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=535-9865-1-ND',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=c',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=CL21C180JBANNNC',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=BLM15AG100SN1D',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=RMCF0805JT51R0',
'https://www.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&keywords=SI8651BB-B-IS1']
#####################################
for url in urls:
    print(url)
    try:
        with urlopen(url) as response:
            html = response.read()
            print (html)
        print("DONE WITH THIS URL.")
    except URLError as e:
        print(e.reason)


问:
Jest+Enzyme. Cannot read property '_isMockFunction' of undefined. Simulate keyDown of Arrow
I have a serious problem with testing methods of my main  component. My actual test after many retries still don't work and looks like this:

```<code>describe('<App />:', () => {
    beforeEach(() => {
        wrapper = mount(<Provider store={store}><App /></Provider>);
    });
    describe('Interaction:', () => {
        it('should call ArrowDown()', () => {
            const instance = wrapper.instance();
            spy = jest.spyOn(instance, 'ArrowDown');
            instance.forceUpdate();
            wrapper.simulate('keyDown', {key: 'Arrow down'});
            expect(spy).toHaveBeenCalled();
        });
    });
});
</code>```

What I get from the console is:

TypeError: Cannot read property '_isMockFunction' of undefined

Other tests like snapshoting or finding other components inside of App works fine. I was searching for simillar problems but solutions I have found do not work as you can see. Please for help.

PS: Same error when I use prototype:

```<code>describe('<App />:', () => {
    beforeEach(() => {
        wrapper = mount(<Provider store={store}><App /></Provider>);
    });
    describe('Interaction:', () => {
            it('should call ArrowDown()', () => {
            spy = jest.spyOn(App.prototype, 'ArrowDown');
            wrapper = mount(<Provider store={store}><App /></Provider>);
            wrapper.simulate('keyDown', {key: 'Arrow down'});
            expect(spy).toHaveBeenCalled();
        });
    });
});
</code>```

答:
It looks like jest.SpyOn(App.prototype, 'ArrowDown') is the line causing your issue. I'm not exactly sure why without looking at your App declaration but I would point out that this isn't how I would go about testing, and I'd venture that maybe this isn't the way that Jest/Enzyme is intended to be used.

In this test you're not actually testing anything other than the fact that React has successfully bound a keypress to a component function, which doesn't really exercise anything meaningful about your code, or any particular logic. I would normally write a test that simulates a button click and then inspects the new DOM state to check that the button click had the desired effect.

If there was a service call involved, I'd probably spy on the service layer, check that it was being called correctly and return a controlled value, then make sure that the DOM was in the correct state. Spying on individual component methods isn't really necessary when you do things this way.

Body:
I have a serious problem with testing methods of my main  component. My actual test after many retries still don't work and looks like this:

describe('<App />:', () => {
    beforeEach(() => {
        wrapper = mount(<Provider store={store}><App /></Provider>);
    });
    describe('Interaction:', () => {
        it('should call ArrowDown()', () => {
            const instance = wrapper.instance();
            spy = jest.spyOn(instance, 'ArrowDown');
            instance.forceUpdate();
            wrapper.simulate('keyDown', {key: 'Arrow down'});
            expect(spy).toHaveBeenCalled();
        });
    });
});

What I get from the console is:

TypeError: Cannot read property '_isMockFunction' of undefined

Other tests like snapshoting or finding other components inside of App works fine. I was searching for simillar problems but solutions I have found do not work as you can see. Please for help.

PS: Same error when I use prototype:

describe('<App />:', () => {
    beforeEach(() => {
        wrapper = mount(<Provider store={store}><App /></Provider>);
    });
    describe('Interaction:', () => {
            it('should call ArrowDown()', () => {
            spy = jest.spyOn(App.prototype, 'ArrowDown');
            wrapper = mount(<Provider store={store}><App /></Provider>);
            wrapper.simulate('keyDown', {key: 'Arrow down'});
            expect(spy).toHaveBeenCalled();
        });
    });
});


问:
Remove margin on inside of R plot
I am trying to plot return against date, and I would like the line to start and end at the line border. The plot code I am using -

```<code>minX = min(hf_instl$date)
maxX = max(hf_instl$date)
plot(df$date, cumsum(df$return), type = "l", col = rgb(0, 0.447, 0.741), xlim = c(minX, maxX), ylim = c(minY, maxY), yaxt = "n", xlab = NA, ylab = NA)
</code>```

What I get is this -

Any solution to this in the base plot package? ggplot2 solutions are also okay.

答:
You can use the xaxs property for that:

```<code># create some fake data for the example
hf_instl = data.frame(date=seq(Sys.Date()-200,Sys.Date(),by='day'),return=runif(201,-1,1.5))
df = hf_instl
minX = min(hf_instl$date)
maxX = max(hf_instl$date)
minY=0
maxY=sum(df$return)+10

# your plot
plot(df$date, cumsum(df$return), type = "l", col = rgb(0, 0.447, 0.741),
    xlim = c(minX, maxX), ylim = c(minY, maxY), yaxt = "n",
    xlab = NA, ylab = NA,xaxs='i')
</code>```

Hope this helps!

Title: Remove margin on inside of R plot

Body:
I am trying to plot return against date, and I would like the line to start and end at the line border. The plot code I am using -

minX = min(hf_instl$date)
maxX = max(hf_instl$date)
plot(df$date, cumsum(df$return), type = "l", col = rgb(0, 0.447, 0.741), xlim = c(minX, maxX), ylim = c(minY, maxY), yaxt = "n", xlab = NA, ylab = NA)

What I get is this -

Any solution to this in the base plot package? ggplot2 solutions are also okay.

Body:
You can use the xaxs property for that:

# create some fake data for the example
hf_instl = data.frame(date=seq(Sys.Date()-200,Sys.Date(),by='day'),return=runif(201,-1,1.5))
df = hf_instl
minX = min(hf_instl$date)
maxX = max(hf_instl$date)
minY=0
maxY=sum(df$return)+10

# your plot
plot(df$date, cumsum(df$return), type = "l", col = rgb(0, 0.447, 0.741),
    xlim = c(minX, maxX), ylim = c(minY, maxY), yaxt = "n",
    xlab = NA, ylab = NA,xaxs='i')

Hope this helps!


问:
How Can I Make WordPress's <?php the_title_attribute(); ?> Render %20 for Spaces?
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

```<code><a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
</code>```

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

```<code>a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet</a>
</code>```

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

答:
A value of 0 passed to the_title_attribute() makes it return rather than echo it's result.

```<code><?php
  $urltitle= str_replace(' ','%20',the_title_attribute('echo=0')); //value of 0 to return rather than echo result
?>

<a href="http://twitter.com/share?text=<?php echo $urltitle; ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
</code>```

Body:
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

<a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

Body:
A value of 0 passed to the_title_attribute() makes it return rather than echo it's result.

<?php
  $urltitle= str_replace(' ','%20',the_title_attribute('echo=0')); //value of 0 to return rather than echo result
?>

<a href="http://twitter.com/share?text=<?php echo $urltitle; ?>&amp;via=ianhines&amp;url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>


问:
Calculate session length android
How can I calculate session length of a user in android so that I can push ads at the right time? Is there a library that can help me with this. I am using google analytics to get average session length but how do I get that of individual users?</p>

答:
Using Kotlin and Android Architecture Components:</p>

```<code>//In application class
ProcessLifecycleOwner.get().getLifecycle().addObserver(appLifecycleObserver);

class AppLifecycleObserver @Inject constructor(val appConfig: ApplicationConfig) : LifecycleObserver {

  private var startTime: Long? = null

  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  fun onEnterForeground() {
    startTime = System.currentTimeMillis()
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  private fun onEnterBackground() {
    if (startTime != null && appConfig.getBoolean(MPARTICLE_ENABLED)) {
      //Session duration
      val sessionLength = System.currentTimeMillis() - startTime!!
    }
  }
}
</code>```

Title: Calculate session length android

Body:
Using Kotlin and Android Architecture Components:

//In application class
ProcessLifecycleOwner.get().getLifecycle().addObserver(appLifecycleObserver);

class AppLifecycleObserver @Inject constructor(val appConfig: ApplicationConfig) : LifecycleObserver {

  private var startTime: Long? = null

  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  fun onEnterForeground() {
    startTime = System.currentTimeMillis()
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  private fun onEnterBackground() {
    if (startTime != null && appConfig.getBoolean(MPARTICLE_ENABLED)) {
      //Session duration
      val sessionLength = System.currentTimeMillis() - startTime!!
    }
  }
}


问:
Cookie Laravel 5-4
I try to work with Cookie in my website ,but always it marked as session and dont stay for all the time declared , it desespere after the browser close:

Here is my code to create the Cookie :

```<code>Cookie::queue('credits_sv', serialize($data), 60 * 24 * 30 * 365);
</code>```

Here is my code to get data of Cookie :

```<code>Cookie::get('credits_sv')
</code>```

Here the result :

Thank you for any help.

答:
You currently have the cookie lifetime set to 30 years. I think you really meant it to be 1 year instead of 30.

Moreover, from this previous answer:

If you set a date past 2038 in PHP, the number will wrap around and
  you'll get a cookie that expires instantly.

So to fix the code, change it to:

Cookie::queue('credits_sv', serialize($data), 60 * 24 * 365);

Title: Cookie Laravel 5-4

Body:
I try to work with Cookie in my website ,but always it marked as session and dont stay for all the time declared , it desespere after the browser close:

Here is my code to create the Cookie :

Cookie::queue('credits_sv', serialize($data), 60 * 24 * 30 * 365);

Here is my code to get data of Cookie :

Cookie::get('credits_sv')

Here the result :

Thank you for any help.


问:
Representing a sine wave given LSB/V
I create a sine wave of a voltage signal.
How can I represent that in the scale factor 128 LSB/Volts ?
The amplitude is 180 Volts.
Obs: I guess LSB is "LOW SIGNIFICANT BIT".

My code:

```<code>int main(int argc, char **argv) {
    int i = 0;
    short value;
    double amp = 180, freq = 60, freq_samp;

    freq_samp = atof(argv[2]);
    printf("\n** Sample frequency: %f **",freq_samp);
    while(1) {
        value = amp*sin(2*i*PI*freq/freq_samp);
        printf("\nValue = %d",value);
        i = i + 1;
        sleep(1);
    }

    return 0;
}
</code>```

答:
I just creat a LSB variable e then do amplitude*LSB:</p>

```<code>int main(int argc, char **argv) {
    int i = 0;
    short value, LSB;
    double amp = 180, freq = 60, freq_samp;

    freq_samp = atof(argv[2]);
    printf("\n** Sample frequency: %f **",freq_samp);
    while(1) {
        value = LSB*amp*sin(2*i*PI*freq/freq_samp);
        printf("\nValue = %d",value);
        i = i + 1;
        sleep(1);
    }

    return 0;
}
</code>```

Title: Representing a sine wave given LSB/V

Body:
I create a sine wave of a voltage signal.
How can I represent that in the scale factor 128 LSB/Volts ?
The amplitude is 180 Volts.
Obs: I guess LSB is "LOW SIGNIFICANT BIT".

My code:

int main(int argc, char **argv) {
    int i = 0;
    short value;
    double amp = 180, freq = 60, freq_samp;

    freq_samp = atof(argv[2]);
    printf("\n** Sample frequency: %f **",freq_samp);
    while(1) {
        value = amp*sin(2*i*PI*freq/freq_samp);
        printf("\nValue = %d",value);
        i = i + 1;
        sleep(1);
    }

    return 0;
}

Body:
I just creat a LSB variable e then do amplitude*LSB:

int main(int argc, char **argv) {
    int i = 0;
    short value, LSB;
    double amp = 180, freq = 60, freq_samp;

    freq_samp = atof(argv[2]);
    printf("\n** Sample frequency: %f **",freq_samp);
    while(1) {
        value = LSB*amp*sin(2*i*PI*freq/freq_samp);
        printf("\nValue = %d",value);
        i = i + 1;
        sleep(1);
    }

    return 0;
}


问:
heron activate Error: cluster/role/environ does not match. Topology 'WordCountTopology' is running at local/root/default, not local/yitian/default
As following error happened, when I running Twitter Heron on local machine using the command:

```<code>heron activate local WordCountTopology.
</code>```

The error information:

```<code>[root@localhost Desktop]# heron activate local WordCountTopology
[2017-12-02 05:23:32 +0000] [INFO]: Using cluster definition in /usr/local/heron/conf/local
[2017-12-02 05:23:32 +0000] [ERROR]: cluster/role/environ does not match. Topology 'WordCountTopology' is running at local/root/default, not local/yitian/default
[2017-12-02 05:23:32 +0000] [ERROR]: Failed to activate topology: WordCountTopology
</code>```

答:
It will be great if we can see the verbose logs - can you please do the following?

```<code>heron activate local --verbose WordCountTopology
</code>```

It will print several logs and this will help identify if there is an issue.

Body:
As following error happened, when I running Twitter Heron on local machine using the command:

heron activate local WordCountTopology.

The error information:

[root@localhost Desktop]# heron activate local WordCountTopology
[2017-12-02 05:23:32 +0000] [INFO]: Using cluster definition in /usr/local/heron/conf/local
[2017-12-02 05:23:32 +0000] [ERROR]: cluster/role/environ does not match. Topology 'WordCountTopology' is running at local/root/default, not local/yitian/default
[2017-12-02 05:23:32 +0000] [ERROR]: Failed to activate topology: WordCountTopology

Body:
It will be great if we can see the verbose logs - can you please do the following?

heron activate local --verbose WordCountTopology

It will print several logs and this will help identify if there is an issue.


问:
Run SQL queries without external database
I have a text file of tab separated data. Millions of rows so I can't open it in Excel.

Is there a way to use some SQL client to load the file and run queries on it without uploading the file to a database? I.e. can my local machine function as my database?

I know I could solve this with command line scripting but I'm trying to find a solution that I can then share with the accounting department and they're scared of the command line.

答: You can create an ODBC datasource based on the Microsoft Text Driver. That driver should come pre-installed on any Windows PC. This uses the Jet Engine which is still somewhere in the Windows OS. Then you can use any Query tool (even MS Query) to analyse your data.</p>


问:
Move xml nodes between parents and delete duplicates - xslt 2.0
I have an xml as follows and would like to 1) move values in the Data node to Header if the match the attribute name or 2) delete nodes under Data if the name attribute is the same as an existing node in the header using xsl tranform, if possible.  Any help would be greatly appreciated.

Initial xml:

```<code><HEADER>
   <KEY name="child1" value="value1" />
   <KEY name="child2" value="value2" />
   <KEY name="child3" value="value3" />
   <KEY name="child4" value="value4" />
</HEADER>
<DATA>
   <KEY name="child1" value="value1.data" />
   <KEY name="child3" value="value3.data" />
   <KEY name="child5" value="value5" />
   <KEY name="child7" value="value7" />
</DATA>
</code>```

If Child 5 is the node to move, the result is...After Transform:

```<code><HEADER>
   <KEY name="child1" value="value1" />
   <KEY name="child2" value="value2" />
   <KEY name="child3" value="value3" />
   <KEY name="child4" value="value4" />
   <KEY name="child5" value="value5" />
</HEADER>
<DATA>
   <KEY name="child7" value="value7" />
</DATA>
</code>```

current xsl:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output omit-xml-declaration="no" method="xml" indent="yes" />

    <!-- <xsl:variable name="ReplaceLiveDate" select="false()" /> -->
    <xsl:variable name="ReplaceLiveDate" select="true()" />

    <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
    <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />

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

    <!-- in HEADER: output ROLE sorted by @name -->
    <xsl:template match="HEADER">
        <xsl:copy>
            <xsl:apply-templates select="KEY">
                <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />
                <!-- <xsl:sort select="@name" /> -->
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <!-- in DATA: output KEY sorted by @name -->
    <xsl:template match="DATA">
        <xsl:copy>
            <xsl:apply-templates select="KEY">
                <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />
                <!-- <xsl:sort select="@name" /> -->
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</code>```

I have the following to remove nodes, but unsure how to only do it if the node exist in the header section

```<code><!-- remove processing nodes -->
<xsl:template match="KEY[starts-with(@name, 'child1')]"/>
</code>```

答:
there are many ways to do that transformation, but in this case i think that the smart one is to use the xslt keys feature see here for a brief description

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">
    <xsl:output omit-xml-declaration="no" method="xml" indent="yes" />

    <!-- <xsl:variable name="ReplaceLiveDate" select="false()" /> -->
    <xsl:variable name="ReplaceLiveDate" select="true()" />

    <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
    <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />

    <!-- index all the KEY element of the HEADER -->
    <xsl:key name='head' match='HEADER/KEY' use='@name' />

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

    <xsl:template match='HEADER'>
        <xsl:copy>
            <!--  move the child5 'KEY element' under the header  -->
            <xsl:copy-of select="//DATA/KEY[@name = 'child5']"/>
            <!--  apply to childs   -->
            <xsl:apply-templates select="KEY">
                <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <!-- delete key nodes duplicated in Header, that is elments not indexed by the 'head' key -->
    <xsl:template match="DATA/KEY[key('head',@name)]">
    </xsl:template>

    <!--  delete the node to be moved -->
    <xsl:template match="DATA/KEY[@name = 'child5']" />

</xsl:stylesheet>
</code>```

For simplicity the stylesheet above won't sort the header keys in alphabethical order, if you really need it, then a perform-sort is necessary.

I tried to keep much as possible of your original stylesheet, but I didn't  find out any other solution following that way.

Below the template if you want key sorted by the @name attribute

```<code><xsl:template match='HEADER'>

    <xsl:variable name='unsorted_keys'>
        <xsl:copy-of select="//DATA/KEY[@name = 'child5']"/>
        <!--  apply to childs   -->
        <xsl:apply-templates select="KEY">
        </xsl:apply-templates>
    </xsl:variable>

    <xsl:copy>
        <!--  make sure to copy HEADER attributes  -->
        <xsl:apply-templates select='@*'/>

        <!--  perform sort  -->
        <xsl:perform-sort select="$unsorted_keys/KEY">
            <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />
        </xsl:perform-sort>
    </xsl:copy>
</xsl:template>
</code>```

Hope this helps

Body:
I have an xml as follows and would like to 1) move values in the Data node to Header if the match the attribute name or 2) delete nodes under Data if the name attribute is the same as an existing node in the header using xsl tranform, if possible.  Any help would be greatly appreciated.

Initial xml:

   <KEY name="child1" value="value1" />
   <KEY name="child2" value="value2" />
   <KEY name="child3" value="value3" />
   <KEY name="child4" value="value4" />

<DATA>
   <KEY name="child1" value="value1.data" />
   <KEY name="child3" value="value3.data" />
   <KEY name="child5" value="value5" />
   <KEY name="child7" value="value7" />
</DATA>

If Child 5 is the node to move, the result is...After Transform:

   <KEY name="child1" value="value1" />
   <KEY name="child2" value="value2" />
   <KEY name="child3" value="value3" />
   <KEY name="child4" value="value4" />
   <KEY name="child5" value="value5" />

<DATA>
   <KEY name="child7" value="value7" />
</DATA>

current xsl:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output omit-xml-declaration="no" method="xml" indent="yes" />

    <xsl:variable name="ReplaceLiveDate" select="true()" />

    <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
    <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />

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

    <xsl:template match="HEADER">
        <xsl:copy>
            <xsl:apply-templates select="KEY">
                <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />

            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="DATA">
        <xsl:copy>
            <xsl:apply-templates select="KEY">
                <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />

            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

I have the following to remove nodes, but unsure how to only do it if the node exist in the header section

<xsl:template match="KEY[starts-with(@name, 'child1')]"/>

Body:
there are many ways to do that transformation, but in this case i think that the smart one is to use the xslt keys feature see here for a brief description

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">
    <xsl:output omit-xml-declaration="no" method="xml" indent="yes" />

    <!-- <xsl:variable name="ReplaceLiveDate" select="false()" /> -->
    <xsl:variable name="ReplaceLiveDate" select="true()" />

    <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
    <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />

    <!-- index all the KEY element of the HEADER -->
    <xsl:key name='head' match='HEADER/KEY' use='@name' />

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

    <xsl:template match='HEADER'>
        <xsl:copy>
            <!--  move the child5 'KEY element' under the header  -->
            <xsl:copy-of select="//DATA/KEY[@name = 'child5']"/>
            <!--  apply to childs   -->
            <xsl:apply-templates select="KEY">
                <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <!-- delete key nodes duplicated in Header, that is elments not indexed by the 'head' key -->
    <xsl:template match="DATA/KEY[key('head',@name)]">
    </xsl:template>

    <!--  delete the node to be moved -->
    <xsl:template match="DATA/KEY[@name = 'child5']" />

</xsl:stylesheet>

For simplicity the stylesheet above won't sort the header keys in alphabethical order, if you really need it, then a perform-sort is necessary.

I tried to keep much as possible of your original stylesheet, but I didn't  find out any other solution following that way.

Below the template if you want key sorted by the @name attribute

<xsl:template match='HEADER'>

    <xsl:variable name='unsorted_keys'>
        <xsl:copy-of select="//DATA/KEY[@name = 'child5']"/>
        <!--  apply to childs   -->
        <xsl:apply-templates select="KEY">
        </xsl:apply-templates>
    </xsl:variable>

    <xsl:copy>
        <!--  make sure to copy HEADER attributes  -->
        <xsl:apply-templates select='@*'/>

        <!--  perform sort  -->
        <xsl:perform-sort select="$unsorted_keys/KEY">
            <xsl:sort select="translate(@name, $smallcase, $uppercase)" order="ascending" />
        </xsl:perform-sort>
    </xsl:copy>
</xsl:template>

Hope this helps


问:
How to create array in PHP with strings from another array as position names?

Basically what I'm trying to do is create an array that has strings for their position names, such as:

```<code>$types = [
    "Methods" => array(),
    "Systems" => array(),
    "Equipment" => array()
]
</code>```

This is what var_dump($types) results in:

```<code>array(3) { ["Methods"]=> array(0) { } ["Systems"]=> array(0) { } ["Equipment"]=> array(0) { } }
</code>```

However, instead of declaring $types like this, I want to have an array $list...

```<code>$list = ['Foo', 'Bar', 'Baz', ...];
</code>```

...that generates an array $types...

```<code>$types = ["Foo" => array(), "Bar" => array(),"Baz" => array(), ...]
</code>```

Is it possible? I have tried doing array_push($types, $list) but that just copies the the string array into the last position of $types

答:
Use  array_fill_keys function</p>

```<code>$types = array_fill_keys($list, []);
</code>```

Body:
Basically what I'm trying to do is create an array that has strings for their position names, such as:

$types = [
    "Methods" => array(),
    "Systems" => array(),
    "Equipment" => array()
]

This is what var_dump($types) results in:

array(3) { ["Methods"]=> array(0) { } ["Systems"]=> array(0) { } ["Equipment"]=> array(0) { } }

However, instead of declaring $types like this, I want to have an array $list...

$list = ['Foo', 'Bar', 'Baz', ...];

...that generates an array $types...

$types = ["Foo" => array(), "Bar" => array(),"Baz" => array(), ...]

Is it possible? I have tried doing array_push($types, $list) but that just copies the the string array into the last position of $types

Body:
Use  array_fill_keys function

$types = array_fill_keys($list, []);


问:
AngularJS: Sorting of ng-repeat table which contains function
In this code i am trying to sort data in particular column by clicking on table header. It works fine till end date of course after that sorting doesnt work. It dont work on column no of days & no of days remaining. Anyone have any solution?

```<code>                var app= angular.module("myapp",[]);
                app.controller("mycontroller",function ($scope, $http)

                    {

                        //subtraction between dates
                        $scope.CurrentDate=new Date();
                        $scope.calDate = function(date1, date2){
                           var dateOut1 = new Date(date1);
                           var dateOut2 = new Date(date2);
                           var timeDiff = Math.abs(dateOut2.getTime() - dateOut1.getTime());

                           var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
                           return diffDays;
                        };
                        $scope.getToday = function(){
                            return new Date();
                        }

                    });

</script>
<body ng-app ="myapp" ng-controller="mycontroller">
    <table border=1>
                <tr>

                    <th ng-click="sortData('name')">Name of student <div ng-class="getSortClass('name')"></div></th>
                   .
                   .
                   .
                   .
                    <th ng-click="sortData('edate')">End date of course <div ng-class="getSortClass('edate')" ></th>
                    <th> No of days </th>  //sorting is not working on this column
                    <th>No of Days remaining </th> //sorting is not working on this column

                </tr>
                    <tr   ng-repeat="x in names  | filter: searchText | orderBy:sortColumn:reverSort">

                        <td>{{x.name}}</td>
                        <td>{{x.cname}}</td>
                        <td >{{x.cfees}}</td>
                        <td>{{x.fpaid }}</td>
                        <td>{{x.bfees}}</td>
                        <td>{{x.sdate | date:'dd-MM-yyyy'}}</td>
                        <td>{{x.edate | date:'dd-MM-yyyy'}}</td>
                        <td>{{calDate(x.edate,x.sdate)}}</td>
                        <td>{{calDate(x.edate,getToday()| date:'dd-MM-yyyy')}}</td>
                </tr>

            </table>
</code>```

答:
calDate is a function and it is not part of your ng-repeat data. Try to add it to the names collection as below.

```<code> $scope.names = <your code to populate names>;

    angular.forEach($scope.names, function(name){
          name.NoOfDays = $scope.calDate(name.edate, name.sdate);
          name.DaysRemaining = $scope.calDate(name.edate, $scope.gettoday());
   });
</code>```

Then you can bind it in HTML as below.

```<code><td>{{x.NoOfDays}}</td>
<td>{{x.DaysRemaining| date:'dd-MM-yyyy')}}</td>
</code>```

Body:
In this code i am trying to sort data in particular column by clicking on table header. It works fine till end date of course after that sorting doesnt work. It dont work on column no of days & no of days remaining. Anyone have any solution?

                var app= angular.module("myapp",[]);
                app.controller("mycontroller",function ($scope, $http)

                    {

                        //subtraction between dates
                        $scope.CurrentDate=new Date();
                        $scope.calDate = function(date1, date2){
                           var dateOut1 = new Date(date1);
                           var dateOut2 = new Date(date2);
                           var timeDiff = Math.abs(dateOut2.getTime() - dateOut1.getTime());

                           var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
                           return diffDays;
                        };
                        $scope.getToday = function(){
                            return new Date();
                        }

                    });

</script>

                    Name of student

                   .
                   .
                   .
                   .
                    End date of course

                     No of days 	  //sorting is not working on this column
                    No of Days remaining 	 //sorting is not working on this column

                        {{x.name}}
                        {{x.cname}}
                        {{x.cfees}}
                        {{x.fpaid }}
                        {{x.bfees}}
                        {{x.sdate | date:'dd-MM-yyyy'}}
                        {{x.edate | date:'dd-MM-yyyy'}}
                        {{calDate(x.edate,x.sdate)}}
                        {{calDate(x.edate,getToday()| date:'dd-MM-yyyy')}}

Body:
calDate is a function and it is not part of your ng-repeat data. Try to add it to the names collection as below.

 $scope.names = <your code to populate names>;

    angular.forEach($scope.names, function(name){
          name.NoOfDays = $scope.calDate(name.edate, name.sdate);
          name.DaysRemaining = $scope.calDate(name.edate, $scope.gettoday());
   });

Then you can bind it in HTML as below.

<td>{{x.NoOfDays}}</td>
<td>{{x.DaysRemaining| date:'dd-MM-yyyy')}}</td>