问:
Can I negate (!) a collection of spring profiles?
Is it possible to configure a bean in such a way that it wont be used by a group of profiles? Currently I can do this (I believe):

```<code>@Profile("!dev, !qa, !local")
</code>```

Is there a neater notation to achieve this? Let's assume I have lots of profiles. Also, if I have a Mock and concrete implementation of some service (or whatever), Can I just annotate one of them, and assume the other will be used in all other cases? In other words, is this, for example, necessary:

```<code>@Profile("dev, prof1, prof2")
public class MockImp implements MyInterface {...}

@Profile("!dev, !prof1, !prof2") //assume for argument sake that there are many other profiles
public class RealImp implements MyInterface {...}
</code>```

Could I just annotate one of them, and stick a @Primary annotation on the other instead?

In essence I want this:

```<code>@Profile("!(dev, prof1, prof2)")
</code>```

Thanks in advance!

答:
From what I understand, what you want to do is be capable of replacing some of your beans with some stub/mock beans for specific profiles. There are 2 ways to address this:

Exclude the not needed beans for the corresponding profiles and include by default everything else

Include only the required beans for each profile

The first option is feasible but difficult. This is because the default behaviour of Spring when providing multiple profiles in @Profile annotation is an OR condition (not an AND as you would need in your case). This behaviour of Spring is the more intuitive, because ideally each profile should correspond to each configuration of your application (production, unit testing, integration testing etc.), so only one profile should be active at each time. This is the reason OR makes more sense than AND between profiles. As a result of this, you can work around this limitation, probably by nesting profiles, but you would make your configuration very complex and less maintainable.

Thus, I suggest you go with the second approach. Have a single profile for each configuration of your application. All the beans that are the same for every configuration can reside in a class that will have no @Profile specified. As a result, these beans will be instantiated by all the profiles. For the remaining beans that should be distinct for each different configuration, you should create a separate @Configuration class (for each Spring profile), having all of them with the @Profile set to the corresponding profile. This way, it will be really easy to tract what is injected in every case.

This should be like below:

```<code>@Profile("dev")
public class MockImp implements MyInterface {...}

@Profile("prof1")
public class MockImp implements MyInterface {...}

@Profile("prof2")
public class MockImp implements MyInterface {...}

@Profile("the-last-profile") //you should define an additional profile, not rely on excluding as described before
public class RealImp implements MyInterface {...}
</code>```

Last, @Primary annotation is used to override an existing beans. When there are 2 beans with the same type, if there is no @Primary annotation, you will get an instantiation error from Spring. If you define a @Primary annotation for one of the beans, there will be no error and this bean will be injected everywhere this type is required (the other one will be ignored). As you see, this is only useful if you have a single Profile. Otherwise, this will also become complicated as the first choice.

TL;DR: Yes you can. For each type, define one bean for each profile and add a @Profile annotation with only this profile.

Body:
Is it possible to configure a bean in such a way that it wont be used by a group of profiles? Currently I can do this (I believe):

@Profile("!dev, !qa, !local")

Is there a neater notation to achieve this? Let's assume I have lots of profiles. Also, if I have a Mock and concrete implementation of some service (or whatever), Can I just annotate one of them, and assume the other will be used in all other cases? In other words, is this, for example, necessary:

@Profile("dev, prof1, prof2")
public class MockImp implements MyInterface {...}

@Profile("!dev, !prof1, !prof2") //assume for argument sake that there are many other profiles
public class RealImp implements MyInterface {...}

Could I just annotate one of them, and stick a @Primary annotation on the other instead?

In essence I want this:

@Profile("!(dev, prof1, prof2)")

Thanks in advance!

Body:
From what I understand, what you want to do is be capable of replacing some of your beans with some stub/mock beans for specific profiles. There are 2 ways to address this:

Exclude the not needed beans for the corresponding profiles and include by default everything else

Include only the required beans for each profile

The first option is feasible but difficult. This is because the default behaviour of Spring when providing multiple profiles in @Profile annotation is an OR condition (not an AND as you would need in your case). This behaviour of Spring is the more intuitive, because ideally each profile should correspond to each configuration of your application (production, unit testing, integration testing etc.), so only one profile should be active at each time. This is the reason OR makes more sense than AND between profiles. As a result of this, you can work around this limitation, probably by nesting profiles, but you would make your configuration very complex and less maintainable.

Thus, I suggest you go with the second approach. Have a single profile for each configuration of your application. All the beans that are the same for every configuration can reside in a class that will have no @Profile specified. As a result, these beans will be instantiated by all the profiles. For the remaining beans that should be distinct for each different configuration, you should create a separate @Configuration class (for each Spring profile), having all of them with the @Profile set to the corresponding profile. This way, it will be really easy to tract what is injected in every case.

This should be like below:

@Profile("dev")
public class MockImp implements MyInterface {...}

@Profile("prof1")
public class MockImp implements MyInterface {...}

@Profile("prof2")
public class MockImp implements MyInterface {...}

@Profile("the-last-profile") //you should define an additional profile, not rely on excluding as described before
public class RealImp implements MyInterface {...}

Last, @Primary annotation is used to override an existing beans. When there are 2 beans with the same type, if there is no @Primary annotation, you will get an instantiation error from Spring. If you define a @Primary annotation for one of the beans, there will be no error and this bean will be injected everywhere this type is required (the other one will be ignored). As you see, this is only useful if you have a single Profile. Otherwise, this will also become complicated as the first choice.

TL;DR: Yes you can. For each type, define one bean for each profile and add a @Profile annotation with only this profile.


来源: stackexchange

问:
JTree displaying drive does not show up at all
My task is to show a tree of all directories/files of a PC drive,
I have a class DirectoryNode that extends DefaultMutableTreeNode with File field directoryPath. I build nodes recursively:

```<code>public void buildDirectoryTree(){
    if(!directoryPath.isDirectory()){
            return;
    }

    for(File f : directoryPath.listFiles()){
        if(f.isHidden() || !f.exists()) continue;
        DirectoryNode newChild = new DirectoryNode(f);
        add(newChild);
        newChild.buildDirectoryTree();
    }
}
</code>```

It works fine for concrete directories, but when I try to use it for whole drive, or some large directories, JTree with this node does not show up at all
I think it encounters a problem with specific directories. I've add exists and is Hidden checks to skip this problem roots, but it didn't help.

In addition, exists, isHidden and isDirectory return false for some of my valid directories directories (I am using Windows 10).

答:
File.listFiles() is one of those ancient methods that violates Java's convention/good practice to never return null from a method that returns an array. So you have to check for null.

From the docs:

An array of abstract pathnames denoting the files and directories in
  the directory denoted by this abstract pathname. The array will be
  empty if the directory is empty. Returns null if this abstract
  pathname does not denote a directory, or if an I/O error occurs.

I have changed your code to make it a little safer. If it's called from the EDT, you might want to add some log message or the like instead of throwing the exception into nirvana.

```<code>public void buildDirectoryTree() throws IOException {
    if (!directoryPath.isDirectory()) {
            return;
    }
    final File[] files = directoryPath.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isHidden() || !f.exists()) continue;
            DirectoryNode newChild = new DirectoryNode(f);
            add(newChild);
            newChild.buildDirectoryTree();
        }
    } else {
        throw new IOException("Failed to list files for " + directoryPath);
    }
}
</code>```

As others have pointed out, there are more modern APIs and they have been introduced for good reasons. I recommend to read up on NIO2 and the Path APIs for better solutions.

ContentLicense: CC BY-SA 3.0

Body:
My task is to show a tree of all directories/files of a PC drive,
I have a class DirectoryNode that extends DefaultMutableTreeNode with File field directoryPath. I build nodes recursively:

public void buildDirectoryTree(){
    if(!directoryPath.isDirectory()){
            return;
    }

    for(File f : directoryPath.listFiles()){
        if(f.isHidden() || !f.exists()) continue;
        DirectoryNode newChild = new DirectoryNode(f);
        add(newChild);
        newChild.buildDirectoryTree();
    }
}

It works fine for concrete directories, but when I try to use it for whole drive, or some large directories, JTree with this node does not show up at all
I think it encounters a problem with specific directories. I've add exists and is Hidden checks to skip this problem roots, but it didn't help.

In addition, exists, isHidden and isDirectory return false for some of my valid directories directories (I am using Windows 10).

Body:
File.listFiles() is one of those ancient methods that violates Java's convention/good practice to never return null from a method that returns an array. So you have to check for null.

From the docs:

An array of abstract pathnames denoting the files and directories in
  the directory denoted by this abstract pathname. The array will be
  empty if the directory is empty. Returns null if this abstract
  pathname does not denote a directory, or if an I/O error occurs.

I have changed your code to make it a little safer. If it's called from the EDT, you might want to add some log message or the like instead of throwing the exception into nirvana.

public void buildDirectoryTree() throws IOException {
    if (!directoryPath.isDirectory()) {
            return;
    }
    final File[] files = directoryPath.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isHidden() || !f.exists()) continue;
            DirectoryNode newChild = new DirectoryNode(f);
            add(newChild);
            newChild.buildDirectoryTree();
        }
    } else {
        throw new IOException("Failed to list files for " + directoryPath);
    }
}

As others have pointed out, there are more modern APIs and they have been introduced for good reasons. I recommend to read up on NIO2 and the Path APIs for better solutions.


问:
Throttling MSMQ messages / prioritising messages
I'm not sure how best to describe this, or the best title, so bear with me!

I'm using MSMQ to queue up a large number of commands that will fire off HTTP requests to various websites and APIs. In order to avoid hammering these services (and to stay within certain pre-defined request limits) I need to ensure tasks hitting the same domain are executed only after a minimum time has elapsed from the last request.

Previously I was using a database to queue the tasks, and so could perform a query to achieve this, but we rapidly outgrew that solution with the number of tasks (way too many deadlocks on the table).

Does anyone have any suggestions as to what approach we could take? I've considered just keeping taking items off the queue until you find one that you can execute - but I'm conscious there's nothing to stop the ordering on the queue meaning we could take off thousands for the same domain before finding one on a different domain.

Thanks!

答:
Erm, I disagree completely with the sentiments Remus Rusanu's answer.

MSMQ is not in any way a step down from a database table, and in many ways can be a step up, which if you required them, you'd need to build manually for a table based solution.

See MSMQ v Database Table

In saying that, for your requirements the database table seems to be the best fit.

MSMQ is good for communication between apps you dont own
if you dont require immediate results, and need reliable delivery
(i.e. you can use MSMQ while disconnected from the DB, whereas to use the table approach you need DB access.)
MSMQ can be load balanced

ContentLicense: CC BY-SA 2.5


问:
set div to position fixed on the relative location
Is it possible to make a div fixed on the location where it is drawn (it's standard 'static/relative' location)?

So I want div .one, .three and .four to be fixed in the location where it is drawn initially. So that it doesn't scroll. https://jsfiddle.net/sor8hntk/2/

答:
Yes! https://jsfiddle.net/sor8hntk/7/</p>

```<code>body {
  margin-top:40px;
}

.one {
  float:left;
  background-color:green;
  width:33%;
  height:50px;
  position: fixed;
}
.two {
  float:left;
  background-color:red;
  width:33%;
  height:500px;
  left: 33%;
  position: absolute;
}

.three {
  float:left;
  background-color:blue;
  width:33%;
  height:50px;
  position: fixed;
  left: 66%;
}

.four {
  width:33%;
  background-color:purple;
  height:10px;
  position: fixed;
}

.five {
  width:100%;
  background-color:pink;
  margin-top: 10px;
}

.six {
  width:100%;
  height:10px;
  background-color:yellow;
}
</code>```

Body:
Yes! https://jsfiddle.net/sor8hntk/7/

body {
  margin-top:40px;
}

.one {
  float:left;
  background-color:green;
  width:33%;
  height:50px;
  position: fixed;
}
.two {
  float:left;
  background-color:red;
  width:33%;
  height:500px;
  left: 33%;
  position: absolute;
}

.three {
  float:left;
  background-color:blue;
  width:33%;
  height:50px;
  position: fixed;
  left: 66%;
}

.four {
  width:33%;
  background-color:purple;
  height:10px;
  position: fixed;
}

.five {
  width:100%;
  background-color:pink;
  margin-top: 10px;
}

.six {
  width:100%;
  height:10px;
  background-color:yellow;
}


问:
Web Hosting on VPS
I registered a domain name and a VPS with GoDaddy. Created a user account on the WHM cpanel. Via my IP/cpanel i have been able to access my cpanel and upload files on the server, but i can not access my site using my domain name. I can only access the uploaded files via my IP/~USERACCOUNT. Each time i access my domain name i see "You have registered your domain now put it work". I have also changed the DNS to that of the webhost but still can not access the site via my domain name except through IP/~USERACCOUNT.</p>

答: Did you point your domain to your VPS IP by adding A-record

Title: Web Hosting on VPS


问:
Get another component input value React js
I have two components one is app component and other one is sidebar component i have been using input field in side bar and i want to get the value of that input field in my app component  on click how this could be possible ?</p>

答: In pure react it is possible by adding callback from one component and use it into parent component to change their state and then send input value from parent's state to props of your second component </p>


问:
How to check the radio button in RadioGroup in ListView Android
I am developing a apps for quiz. There are ten questions, each with four answers A, B, C, D and represented RadioGroup and the end is submit button. The list of questions is represented by one ListView. The user selects the answer, then they click submit button. I have a question: How to check the answers in turn in ListView ? Please help me. Thanks so much!

this is the code of questions custom:

```<code>public class mAdapter extends ArrayAdapter<Question> {
    Activity context;
    int resource;
    List<Question> objects;

    public mAdapter(Activity context, int resource, List<Question> objects) {
        super(context, resource, objects);
        this.context = context;
        this.objects = objects;
        this.resource = resource;
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = this.context.getLayoutInflater();
        View row = inflater.inflate(this.resource, null);

        final Question question = this.objects.get(position);

        RadioGroup rg = (RadioGroup) row.findViewById(R.id.btnGroup);
        TextView txtID = (TextView) row.findViewById(R.id.txtID);
        TextView txtContent = (TextView) row.findViewById(R.id.txtContent);
        RadioButton btnA = (RadioButton) row.findViewById(R.id.btnA);
        RadioButton btnB = (RadioButton) row.findViewById(R.id.btnB);
        RadioButton btnC = (RadioButton) row.findViewById(R.id.btnC);
        RadioButton btnD = (RadioButton) row.findViewById(R.id.btnD);

        txtID.setText((position + 1) + "");
        txtContent.setText(question.getContent());
        btnA.setText(question.getOptionA());
        btnB.setText(question.getOptionB());
        btnC.setText(question.getOptionC());
        btnD.setText(question.getOptionD());

        return row;
    }

}
</code>```

This is the code that pushes the question into listView

```<code>lvQuestion= (ListView) findViewById(R.id.lvQuestion);
testAdapter = new mAdapter(this, R.layout.custom_lisview, listQuestion);
lvQuestion.setAdapter(testAdapter);

btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

       }
   });
</code>```

答:
To handle radioButton in listView

```<code>btnA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked)
      btnA.setText(question.getOptionA());
     }
 });

btnB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked)
     btnB.setText(question.getOptionB());
       }
});

// others code
</code>```

To get the answer by OnClick

```<code>btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
     final int child=listView.getChildCount();
      for(int i=0;i<child;i++) {
        if(listView.childAt(i) instanceof RadioGroup){
         RadioGroup rg = (RadioGroup) row.findViewById(R.id.btnGroup);
         rg=(RadioGroup)listView.childAt(i);
         int a = rg.getChildCount();
         for(int j=0;j<a;++j) {
            if((RadioButton)rg.getChildAt(j).isChecked()==true) {
           System.out.println("RadioButton At "+j+" Is Selected");}
          }
       }
  }
}
});
</code>```

Body:
I am developing a apps for quiz. There are ten questions, each with four answers A, B, C, D and represented RadioGroup and the end is submit button. The list of questions is represented by one ListView. The user selects the answer, then they click submit button. I have a question: How to check the answers in turn in ListView ? Please help me. Thanks so much!

this is the code of questions custom:

public class mAdapter extends ArrayAdapter<Question> {
    Activity context;
    int resource;
    List<Question> objects;

    public mAdapter(Activity context, int resource, List<Question> objects) {
        super(context, resource, objects);
        this.context = context;
        this.objects = objects;
        this.resource = resource;
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = this.context.getLayoutInflater();
        View row = inflater.inflate(this.resource, null);

        final Question question = this.objects.get(position);

        RadioGroup rg = (RadioGroup) row.findViewById(R.id.btnGroup);
        TextView txtID = (TextView) row.findViewById(R.id.txtID);
        TextView txtContent = (TextView) row.findViewById(R.id.txtContent);
        RadioButton btnA = (RadioButton) row.findViewById(R.id.btnA);
        RadioButton btnB = (RadioButton) row.findViewById(R.id.btnB);
        RadioButton btnC = (RadioButton) row.findViewById(R.id.btnC);
        RadioButton btnD = (RadioButton) row.findViewById(R.id.btnD);

        txtID.setText((position + 1) + "");
        txtContent.setText(question.getContent());
        btnA.setText(question.getOptionA());
        btnB.setText(question.getOptionB());
        btnC.setText(question.getOptionC());
        btnD.setText(question.getOptionD());

        return row;
    }

}

This is the code that pushes the question into listView

lvQuestion= (ListView) findViewById(R.id.lvQuestion);
testAdapter = new mAdapter(this, R.layout.custom_lisview, listQuestion);
lvQuestion.setAdapter(testAdapter);

btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

       }
   });

Body:
To handle radioButton in listView

btnA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked)
      btnA.setText(question.getOptionA());
     }
 });

btnB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked)
     btnB.setText(question.getOptionB());
       }
});

// others code

To get the answer by OnClick

btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
     final int child=listView.getChildCount();
      for(int i=0;i<child;i++) {
        if(listView.childAt(i) instanceof RadioGroup){
         RadioGroup rg = (RadioGroup) row.findViewById(R.id.btnGroup);
         rg=(RadioGroup)listView.childAt(i);
         int a = rg.getChildCount();
         for(int j=0;j<a;++j) {
            if((RadioButton)rg.getChildAt(j).isChecked()==true) {
           System.out.println("RadioButton At "+j+" Is Selected");}
          }
       }
  }
}
});


问:
Python class inheritance __init__
So, here's the problem..

if you do this:

```<code>class x(object):
  def __init__(self):
    pass
</code>```

why would you explicitly call init in child class to access parent class attribute? (class y has class x attribute anyway.)

```<code>class y(x):
  def __init__(self):
    x.__init__(self)
</code>```

Cheers.

Edit:

I read this article https://linuxmeerkat.wordpress.com/2015/04/28/why-you-should-use-super-in-python/, it says "In real life we tend to run the initializer for every parent class. This is simply because of how program designs tend to be. In our simple example a way to solve this is to explicitly call the initializer of A:" Could someone please explain?

答:
Instead of calling to the init function explicitly,  you should use the super() method instead.

In python 3.0+, you can jusy use:

```<code>class y(x):
    def __init__(self):
        super().__init__()
</code>```

In python 2.7 or under, use:

```<code>class y(x):
    def __init__(self):
        super(self.__class__, self).__init__()
</code>```

super() lets you avoid referring to the base class explicitly.

Title: Python class inheritance __init__

Body:
So, here's the problem..

if you do this:

class x(object):
  def __init__(self):
    pass

why would you explicitly call init in child class to access parent class attribute? (class y has class x attribute anyway.)

class y(x):
  def __init__(self):
    x.__init__(self)

Cheers.

Edit:

I read this article https://linuxmeerkat.wordpress.com/2015/04/28/why-you-should-use-super-in-python/, it says "In real life we tend to run the initializer for every parent class. This is simply because of how program designs tend to be. In our simple example a way to solve this is to explicitly call the initializer of A:" Could someone please explain?

Body:
Instead of calling to the init function explicitly,  you should use the super() method instead.

In python 3.0+, you can jusy use:

class y(x):
    def __init__(self):
        super().__init__()

In python 2.7 or under, use:

class y(x):
    def __init__(self):
        super(self.__class__, self).__init__()

super() lets you avoid referring to the base class explicitly.


问:
Python: Frequency Analysis of Sound Files
I am generating some sound files that play tones at various frequencies with a certain number of harmonics.

Ultimately, these sounds will be played on a device with a small speaker.

I have the frequency response curve of the speaker and want to do the following in Python:

Plot the frequency spectrum of sound file. I need a take the FFT of the file and plot it with gnuplot

Apply a nonlinear transfer function based on the frequency response curve in the data sheet.

Plot the result after the function is applied.

Does anyone know :

What the simplest way to do this would be?

or of an Application (GNU/Linux based) that could do this for me?

答:
I know you didn't mention Pylab/Matplotlib, but it works. Here is an example (assumes single-channel signal):</p>

```<code>x, fs, nbits = audiolab.wavread('schubert.wav')
audiolab.play(x, fs)
N = 4*fs    # four seconds of audio
X = scipy.fft(x[:N])
Xdb = 20*scipy.log10(scipy.absolute(X))
f = scipy.linspace(0, fs, N, endpoint=False)
pylab.plot(f, Xdb)
pylab.xlim(0, 5000)   # view up to 5 kHz

Y = X*H
y = scipy.real(scipy.ifft(Y))
</code>```

Body:
I know you didn't mention Pylab/Matplotlib, but it works. Here is an example (assumes single-channel signal):

x, fs, nbits = audiolab.wavread('schubert.wav')
audiolab.play(x, fs)
N = 4*fs    # four seconds of audio
X = scipy.fft(x[:N])
Xdb = 20*scipy.log10(scipy.absolute(X))
f = scipy.linspace(0, fs, N, endpoint=False)
pylab.plot(f, Xdb)
pylab.xlim(0, 5000)   # view up to 5 kHz

Y = X*H
y = scipy.real(scipy.ifft(Y))


问:
Node.js BinaryServer: Send a message to the client on stream end?
I'm using a node.js BinaryServer for streaming binary data and I want a callback event from the server, after the client calls for the .Stream.end() function.

I can't seem to understand - How can I send a message or some kind of notification when the node.js server actually closes the stream connection ?

Node JS:

```<code>server.on('connection', function(client) {

    client.on('stream', function (stream, meta) {

        stream.on('end', function () {
            fileWriter.end();
            // <--- I want to send an event to the client here
        });
    });

});
</code>```

client JS:

```<code>client = new BinaryClient(nodeURL);
window.Stream = client.createStream({ metaData });
....
window.Stream.end();
//  <--- I want to recieve the callback message
</code>```

答:
On the server side, you can send streams to the client with .send. You can send a variety of data types, but a simple string will probably suffice in this case.

On the client side you can also listen to the 'stream' event to receive data back from the server.

Node JS:

```<code>server.on('connection', function(client) {
    client.on('stream', function (stream, meta) {
        stream.on('end', function () {
            fileWriter.end();
            client.send('finished');
        });
    });
});
</code>```

client JS:

```<code>client = new BinaryClient(nodeURL);
client.on('stream', data => {
    console.log(data); // do something with data
});
window.Stream = client.createStream({ metaData });
....
window.Stream.end();
</code>```

Body:
I'm using a node.js BinaryServer for streaming binary data and I want a callback event from the server, after the client calls for the .Stream.end() function.

I can't seem to understand - How can I send a message or some kind of notification when the node.js server actually closes the stream connection ?

Node JS:

server.on('connection', function(client) {

    client.on('stream', function (stream, meta) {

        stream.on('end', function () {
            fileWriter.end();
            // <--- I want to send an event to the client here
        });
    });

});

client JS:

client = new BinaryClient(nodeURL);
window.Stream = client.createStream({ metaData });
....
window.Stream.end();
//  <--- I want to recieve the callback message

Body:
On the server side, you can send streams to the client with .send. You can send a variety of data types, but a simple string will probably suffice in this case.

On the client side you can also listen to the 'stream' event to receive data back from the server.

Node JS:

server.on('connection', function(client) {
    client.on('stream', function (stream, meta) {
        stream.on('end', function () {
            fileWriter.end();
            client.send('finished');
        });
    });
});

client JS:

client = new BinaryClient(nodeURL);
client.on('stream', data => {
    console.log(data); // do something with data
});
window.Stream = client.createStream({ metaData });
....
window.Stream.end();


问:
Mapbox markers do no render
I am trying to populate a mapbox map using data from a public API call without success. I have tried many things but for some reason the markers are not rendering onto the map. Has anyone experienced similar problem?

Codepen

Thank you in advance.

JS

```<code>// Provide your access token
L.mapbox.accessToken = 'pk.eyJ1IjoiZGllZ29vcmlhbmkiLCJhIjoiY2lvcmQ1ZDRiMDAweXZrbTJ2dmlub2dtaSJ9.1JJGPZzeB3TWfIsTvMvRpA';

var coordinates = []
var commonName = []
geoJson = []

//Data
$.getJSON( "https://api.tfl.gov.uk/BikePoint", function( data ) {

  //i = number of loops / val = object
  $.each( data, function( i, val ) {
    coordinates.push(data[i].lat + ", " + data[i].lon);
    commonName.push(data[i].commonName);

    geoJson.push(
    {
      "type": "Feature",
      "geometry": {
          "type": "Point",
          "coordinates": [coordinates[i]]
      },
      "properties": {
          'Name': commonName[i],
          'marker-color': '#3ca0d3',
          'marker-size': 'large',
          'marker-symbol': 'rocket',
      }
    });
  });
  //console.log(coordinates);
  //console.log(commonName);
});

var mapSimple = L.mapbox.map('map_simple', 'mapbox.light')
  .setView([51.494, -0.171], 14);
var myLayer = L.mapbox.featureLayer().setGeoJSON(geoJson).addTo(mapSimple);
mapSimple.scrollWheelZoom.disable();

console.log(geoJson)
</code>```

HTML

```<code><html>

<head>
  <meta charset=utf-8 />
  <title></title>
  <script src='https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.js'></script>
  <link href='https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.css' rel='stylesheet' />

</head>

<body>
  <div id='map_simple' class='map'> </div>
</body>

</html>
</code>```

答:
I strongly suspect that you are calling the invalid 'marker-symbol'. In  Mapbox Studio, rocket symbol usually comes with the number determining exact style, for example 'rocket-11', not just 'rocket'.

Open your style in MapboxStudio and check the exact name of your rocket icon.

Title: Mapbox markers do no render

Body:
I am trying to populate a mapbox map using data from a public API call without success. I have tried many things but for some reason the markers are not rendering onto the map. Has anyone experienced similar problem?

Codepen

Thank you in advance.

JS

// Provide your access token
L.mapbox.accessToken = 'pk.eyJ1IjoiZGllZ29vcmlhbmkiLCJhIjoiY2lvcmQ1ZDRiMDAweXZrbTJ2dmlub2dtaSJ9.1JJGPZzeB3TWfIsTvMvRpA';

var coordinates = []
var commonName = []
geoJson = []

//Data
$.getJSON( "https://api.tfl.gov.uk/BikePoint", function( data ) {

  //i = number of loops / val = object
  $.each( data, function( i, val ) {
    coordinates.push(data[i].lat + ", " + data[i].lon);
    commonName.push(data[i].commonName);

    geoJson.push(
    {
      "type": "Feature",
      "geometry": {
          "type": "Point",
          "coordinates": [coordinates[i]]
      },
      "properties": {
          'Name': commonName[i],
          'marker-color': '#3ca0d3',
          'marker-size': 'large',
          'marker-symbol': 'rocket',
      }
    });
  });
  //console.log(coordinates);
  //console.log(commonName);
});

var mapSimple = L.mapbox.map('map_simple', 'mapbox.light')
  .setView([51.494, -0.171], 14);
var myLayer = L.mapbox.featureLayer().setGeoJSON(geoJson).addTo(mapSimple);
mapSimple.scrollWheelZoom.disable();

console.log(geoJson)

HTML

  <meta charset=utf-8 />
  <title></title>

  <link href='https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.css' rel='stylesheet' />


问:
show download link if file already uploaded or show file upload field in gravity forms
I have a form created by gravity forms which will allow the user to enter the data and upload two files (form has two input file fields - gravity forms provided file upload field). Once the user submit the page, I will save the data in to custom table with file path as one of the column inside the table.

But once form reloads, it will show the same form with already entered data, but don't know how to show the file link inside the form.

What I am trying to do is, I have to show the link with remove button if file already uploaded or show the file upload field again to allow user to upload the file again.

Could somebody help me please?

答:
I guess when you will store the entered data on the custom table, store the file names as well.
Then have another function to check if the file is in the specified directory (ex. uploads).

This is a lazy solution, so keep an eye on your thread for a better one.


问:
behind proxy error while ionic installation via npm
npm ERR! npm  v2.14.7

npm ERR! code ECONNRESET

npm ERR! errno ECONNRESET

npm ERR! syscall read

npm ERR! network read ECONNRESET

npm ERR! network This is most likely not a problem with npm itself

npm ERR! network and is related to network connectivity.

npm ERR! network In most cases you are behind a proxy or have bad network
settings.

npm ERR! network

npm ERR! network If you are behind a proxy, please make sure that the

npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Windows_NT 6.1.7601

npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "-g" "-d" "ionic"

npm ERR! node v4.2.2

npm ERR! npm  v2.14.7

npm ERR! code ECONNRESET

npm ERR! errno ECONNRESET

npm ERR! syscall read

npm ERR! network read ECONNRESET

npm ERR! network This is most likely not a problem with npm itself

npm ERR! network and is related to network connectivity.

npm ERR! network In most cases you are behind a proxy or have bad network settings.

npm ERR! network

npm ERR! network If you are behind a proxy, please make sure that the

npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "-g" "-d" "ionic"

npm ERR! node v4.2.2

npm ERR! npm  v2.14.7

npm ERR! code ECONNRESET

npm ERR! errno ECONNRESET

npm ERR! syscall read

npm ERR! network read ECONNRESET

npm ERR! network This is most likely not a problem with npm itself

npm ERR! network and is related to network connectivity.

npm ERR! network In most cases you are behind a proxy or have bad network settings.

npm ERR! network

npm ERR! network If you are behind a proxy, please make sure that the

npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Windows_NT 6.1.7601

答:
```<code>npm config set <key> <value> [-g|--global]
npm config get <key>
npm config delete <key>
npm config list
npm config edit
npm get <key>
npm set <key> <value> [-g|--global]
</code>```

npmrc.txt will run you can change your link and port

```<code>proxy =http://proxy.company.com:8080

 https-proxy = http://proxy.company.com:8080
</code>```

reference

Body:
npm config set <key> <value> [-g|--global]
npm config get <key>
npm config delete <key>
npm config list
npm config edit
npm get <key>
npm set <key> <value> [-g|--global]

npmrc.txt will run you can change your link and port

proxy =http://proxy.company.com:8080

 https-proxy = http://proxy.company.com:8080

reference


问:
ASP .NET WebApi POST method keeping request body in memory
I've noticed I had big memory usage on my server, so when I inspected it I saw the IIS process takes 200-400 megabytes of memory at all times after receiving one request. After some checking I stripped my web service method completely to this, and the problem persists:

```<code>public IHttpActionResult Post([FromBody]JToken json)
{
return Ok();
}
</code>```

Usually the arriving json is pretty big, but to my knowledge the WebApi should dispose of it after returning Ok. Is that related to IIS cache or some sort?

答:
but to my knowledge the WebApi should dispose of it after returning Ok.

That's not necessarily true. What will happen after you return Ok(); is that the json variable will fall out of scope. And when a variable falls out of scope it becomes elligible for garbage collection. This doesn't mean at all that will be disposed immediately. It will be disposed when the next GC occurs. Which might happen if there's memory pressure for example. It is something that the CLR takes care of and you shouldn't be concerned much about. It is pretty normal to have the worker process in IIS take some memory. On Server OSes, the GC is optimized so that it runs only when necessary to clean up resources to avoid wasting precious CPU cycles.

Body:
I've noticed I had big memory usage on my server, so when I inspected it I saw the IIS process takes 200-400 megabytes of memory at all times after receiving one request. After some checking I stripped my web service method completely to this, and the problem persists:

public IHttpActionResult Post([FromBody]JToken json)
{
return Ok();
}

Usually the arriving json is pretty big, but to my knowledge the WebApi should dispose of it after returning Ok. Is that related to IIS cache or some sort?


问:
Update custom field from other custom fields values
i need to update the product price based on values from some custom fields

this is how i’ve build and saving the custom fields, at the end i’m trying to update _regular_price based on the values of the customs fields when i save, update, publish the product but nothing is happening, what am i missing?

all code goes into function.php for now

```<code>//BUILD AND SAVE FIELDS
// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '<div class="options_group">';

// Product URL
woocommerce_wp_checkbox(
array(
    'label' => __('Product URL', 'woocommerce' ),
    $post_id = $_GET['post'],
    $produrl = get_post_meta( $post_id, 'productOriginalUrl', true),
    'description'   => '<a href="' . $produrl . '" class="button button-primary button-large" target="_blank">' . __('View Product', 'woocommerce') . '</a>',
    )
);

    // Number Field
woocommerce_wp_text_input(
    array(
        'id'                => '_price_usd',
        'label'             => __( 'Price in USD', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Enter the custom value here.', 'woocommerce' ),
        'type'              => 'number',
        'custom_attributes' => array(
                'step'  => 'any',
                'min'   => '0'
            )
    )
);
woocommerce_wp_text_input(
    array(
        'id'                => '_price_tax',
        'label'             => __( 'TAX', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Enter the custom value here.', 'woocommerce' ),
        'type'              => 'number',
        'custom_attributes' => array(
                'step'  => 'any',
                'min'   => '0'
            )
    )

);
woocommerce_wp_text_input(
    array(
        'id'                => '_price_shipping',
        'label'             => __( 'Shipping', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Enter the custom value here.', 'woocommerce' ),
        'type'              => 'number',
        'custom_attributes' => array(
                'step'  => 'any',
                'min'   => '0'
            )
    )

);

// Select
woocommerce_wp_select(
array(
    'id'      => '_shipping_weight',
    'label'   => __( 'Shipping Weight', 'woocommerce' ),
    'options' => array(
        '3.75'   => __( 'Less Than 0.5 KG', 'woocommerce' ),
        '7.5'   => __( '0.5 KG', 'woocommerce' ),
        '15' => __( '1 KG', 'woocommerce' )
        )
    )
);

// Hidden field
woocommerce_wp_hidden_input(
array(
    'id'    => '_usd_rate',
    'value' => '18'
    )
);
    echo '</div>';
};

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){

    // Number Field
    $woo_price_usd = $_POST['_price_usd'];
    if( !empty( $woo_price_usd ) )
        update_post_meta( $post_id, '_price_usd', esc_attr( $woo_price_usd ) );

    $woo_price_tax = $_POST['_price_tax'];
    if( !empty( $woo_price_tax ) )
        update_post_meta( $post_id, '_price_tax', esc_attr( $woo_price_tax ) );

    $woo_price_shipping = $_POST['_price_shipping'];
    if( !empty( $woo_price_shipping ) )
        update_post_meta( $post_id, '_price_shipping', esc_attr( $woo_price_shipping ) );

    // Select
    $woo_shipping_weight = $_POST['_shipping_weight'];
    if( !empty( $woo_shipping_weight ) )
        update_post_meta( $post_id, '_shipping_weight', esc_attr( $woo_shipping_weight ) );

    // Hidden Field
    $woo_usd_rate = $_POST['_usd_rate'];
    if( !empty( $woo_usd_rate ) )
        update_post_meta( $post_id, '_usd_rate', esc_attr( $woo_usd_rate ) );

}

//UPDATE PRICE REGULAR
function wpa104760_default_price( $post_id, $post ) {

    if ( isset( $_POST['_regular_price'] )) {
$post_id = $_GET['post'];
        $woo_price_usd = get_post_meta($post_id, '_price_usd', true);
        $woo_price_tax = get_post_meta($post_id, '_price_tax', true);
        $woo_price_shipping = get_post_meta($post_id, '_price_shipping', true);
        $woo_shipping_weight = get_post_meta($post_id, '_shipping_weight', true);
        $woo_usd_rate = get_post_meta($post_id, '_usd_rate', true);

$woo_new_product_price = (($woo_price_usd + (($woo_price_usd*$woo_price_tax)/100) + $woo_price_shipping + $woo_shipping_weight) * $woo_usd_rate );

update_post_meta( $post_id, '_regular_price', $woo_new_product_price );
        }

}
add_action( 'woocommerce_process_product_meta', 'wpa104760_default_price' );
</code>```

答:
the answer was simple,

it needed a filter to update the _regular_price and the _sale_price

```<code>//price new

function return_custom_price($price, $product) {
global $post;
$new_total = get_post_meta( $post->ID, '_total_egp', true);
$price = get_post_meta($post->ID, '_regular_price', true);
$sale_price = get_post_meta($post->ID, '_sale_price', true);
$now_price = get_post_meta($post->ID, '_price', true);

if($price != 0 ){
update_post_meta($post->ID, '_regular_price', $new_total);
update_post_meta($post->ID, '_sale_price', $new_total);
update_post_meta($post->ID, '_price', $new_total);
return $price;
    }
}
add_filter('woocommerce_get_price', 'return_custom_price', 10, 2);
</code>```

Body:
i need to update the product price based on values from some custom fields

this is how i’ve build and saving the custom fields, at the end i’m trying to update _regular_price based on the values of the customs fields when i save, update, publish the product but nothing is happening, what am i missing?

all code goes into function.php for now

//BUILD AND SAVE FIELDS
// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '
';

// Product URL
woocommerce_wp_checkbox(
array(
    'label' => __('Product URL', 'woocommerce' ),
    $post_id = $_GET['post'],
    $produrl = get_post_meta( $post_id, 'productOriginalUrl', true),
    'description'   => '' . __('View Product', 'woocommerce') . '',
    )
);

    // Number Field
woocommerce_wp_text_input(
    array(
        'id'                => '_price_usd',
        'label'             => __( 'Price in USD', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Enter the custom value here.', 'woocommerce' ),
        'type'              => 'number',
        'custom_attributes' => array(
                'step'  => 'any',
                'min'   => '0'
            )
    )
);
woocommerce_wp_text_input(
    array(
        'id'                => '_price_tax',
        'label'             => __( 'TAX', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Enter the custom value here.', 'woocommerce' ),
        'type'              => 'number',
        'custom_attributes' => array(
                'step'  => 'any',
                'min'   => '0'
            )
    )

);
woocommerce_wp_text_input(
    array(
        'id'                => '_price_shipping',
        'label'             => __( 'Shipping', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Enter the custom value here.', 'woocommerce' ),
        'type'              => 'number',
        'custom_attributes' => array(
                'step'  => 'any',
                'min'   => '0'
            )
    )

);

// Select
woocommerce_wp_select(
array(
    'id'      => '_shipping_weight',
    'label'   => __( 'Shipping Weight', 'woocommerce' ),
    'options' => array(
        '3.75'   => __( 'Less Than 0.5 KG', 'woocommerce' ),
        '7.5'   => __( '0.5 KG', 'woocommerce' ),
        '15' => __( '1 KG', 'woocommerce' )
        )
    )
);

// Hidden field
woocommerce_wp_hidden_input(
array(
    'id'    => '_usd_rate',
    'value' => '18'
    )
);
    echo '
';
};

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){

    // Number Field
    $woo_price_usd = $_POST['_price_usd'];
    if( !empty( $woo_price_usd ) )
        update_post_meta( $post_id, '_price_usd', esc_attr( $woo_price_usd ) );

    $woo_price_tax = $_POST['_price_tax'];
    if( !empty( $woo_price_tax ) )
        update_post_meta( $post_id, '_price_tax', esc_attr( $woo_price_tax ) );

    $woo_price_shipping = $_POST['_price_shipping'];
    if( !empty( $woo_price_shipping ) )
        update_post_meta( $post_id, '_price_shipping', esc_attr( $woo_price_shipping ) );

    // Select
    $woo_shipping_weight = $_POST['_shipping_weight'];
    if( !empty( $woo_shipping_weight ) )
        update_post_meta( $post_id, '_shipping_weight', esc_attr( $woo_shipping_weight ) );

    // Hidden Field
    $woo_usd_rate = $_POST['_usd_rate'];
    if( !empty( $woo_usd_rate ) )
        update_post_meta( $post_id, '_usd_rate', esc_attr( $woo_usd_rate ) );

}

//UPDATE PRICE REGULAR
function wpa104760_default_price( $post_id, $post ) {

    if ( isset( $_POST['_regular_price'] )) {
$post_id = $_GET['post'];
        $woo_price_usd = get_post_meta($post_id, '_price_usd', true);
        $woo_price_tax = get_post_meta($post_id, '_price_tax', true);
        $woo_price_shipping = get_post_meta($post_id, '_price_shipping', true);
        $woo_shipping_weight = get_post_meta($post_id, '_shipping_weight', true);
        $woo_usd_rate = get_post_meta($post_id, '_usd_rate', true);

$woo_new_product_price = (($woo_price_usd + (($woo_price_usd*$woo_price_tax)/100) + $woo_price_shipping + $woo_shipping_weight) * $woo_usd_rate );

update_post_meta( $post_id, '_regular_price', $woo_new_product_price );
        }

}
add_action( 'woocommerce_process_product_meta', 'wpa104760_default_price' );

Body:
the answer was simple,

it needed a filter to update the _regular_price and the _sale_price

//price new

function return_custom_price($price, $product) {
global $post;
$new_total = get_post_meta( $post->ID, '_total_egp', true);
$price = get_post_meta($post->ID, '_regular_price', true);
$sale_price = get_post_meta($post->ID, '_sale_price', true);
$now_price = get_post_meta($post->ID, '_price', true);

if($price != 0 ){
update_post_meta($post->ID, '_regular_price', $new_total);
update_post_meta($post->ID, '_sale_price', $new_total);
update_post_meta($post->ID, '_price', $new_total);
return $price;
    }
}
add_filter('woocommerce_get_price', 'return_custom_price', 10, 2);


问:
Rendering a sublist of a list in .net MVC
I'm still learning .net MVC, and perhaps am not searching correctly for what I need to find a solution to.

In short, I have a table in the database that is structured as:

```<code>ID    Category    Subcategory    FK
</code>```

So each category may appear multiple times, as well as each subcategory, which is unique to the category.

I want to render a menu in the view that looks like:

```<code>Category 1
    Subcategory 1a
    Subcategory 1b
    Subcategory 1c
Category 2
    Subcategory 2a
    Subcategory 2b
</code>```

And so on.  Right now in the controller I have:

```<code>var categories = db.Category
                     .Where(oa => oa.Category != "")
                     .GroupBy(oa => new { oa.Category, oa.Subcategory })
                     .Select(oa => oa.FirstOrDefault());
</code>```

However, I'm not sure how to do what I want to achieve in the view.  I know I have to loop through the list somehow, but I'm not sure how.  I know it involved something along the lines of:

```<code>@foreach (var item in Model)
{
    <li>
        <a id="@item.ID" href="#">@item.Category</a>
    </li>
}
</code>```

But I only want each category to appear once, and then need all subcategories to appear under the parent category.  Or maybe I need to change the controller and how it sends the data?

答:
Start by creating a simple view model to represent what you want to display in the view

```<code>public class CategoryVM
{
    public string Name { get; set; }
    public IEnumerable<string> SubCategories { get; set; }
}
</code>```

Then project your query to a collection of that view model and return it to the view

```<code>var model = db.Category.Where(x => x.Category != "")
    .GroupBy(x => x.Category).Select(x => new CategoryVM
    {
        Name = x.Key,
        SubCategories = x.Select(y => y.Subcategory)
    });
return View(model);
</code>```

and in the view

```<code>@model IEnumerable<CategoryVM>
....
@foreach(var category in Model)
{
    <h2>@category.Name</h2>
    <ul>
        @foreach(var subCategory in category.SubCategories)
        {
            <li>@subCategory</li>
        }
    </ul>
}
</code>```

Body:
I'm still learning .net MVC, and perhaps am not searching correctly for what I need to find a solution to.

In short, I have a table in the database that is structured as:

ID    Category    Subcategory    FK

So each category may appear multiple times, as well as each subcategory, which is unique to the category.

I want to render a menu in the view that looks like:

Category 1
    Subcategory 1a
    Subcategory 1b
    Subcategory 1c
Category 2
    Subcategory 2a
    Subcategory 2b

And so on.  Right now in the controller I have:

var categories = db.Category
                     .Where(oa => oa.Category != "")
                     .GroupBy(oa => new { oa.Category, oa.Subcategory })
                     .Select(oa => oa.FirstOrDefault());

However, I'm not sure how to do what I want to achieve in the view.  I know I have to loop through the list somehow, but I'm not sure how.  I know it involved something along the lines of:

@foreach (var item in Model)
{

        @item.Category

}

But I only want each category to appear once, and then need all subcategories to appear under the parent category.  Or maybe I need to change the controller and how it sends the data?

Body:
Start by creating a simple view model to represent what you want to display in the view

public class CategoryVM
{
    public string Name { get; set; }
    public IEnumerable<string> SubCategories { get; set; }
}

Then project your query to a collection of that view model and return it to the view

var model = db.Category.Where(x => x.Category != "")
    .GroupBy(x => x.Category).Select(x => new CategoryVM
    {
        Name = x.Key,
        SubCategories = x.Select(y => y.Subcategory)
    });
return View(model);

and in the view

@model IEnumerable<CategoryVM>
....
@foreach(var category in Model)
{
    <h2>@category.Name</h2>
    <ul>
        @foreach(var subCategory in category.SubCategories)
        {
            <li>@subCategory</li>
        }
    </ul>
}


问:
"Wildcard" key with foreach PHP
Ok, so I have an array that looks like this:

```<code>$array = ["person1" => ["person2" => ["something", "something else", "something else again"], "person3" => ["hey", "hi", "hello"]], "person4" => ["person5" => ["bob", "bill", "bobby", "billy"], "person6" => ["there", "their", "here"]]]
</code>```

or, in other "words"

```<code>$array = Array(
    "person1" => Array(
        "person2" => Array(
            "something", "something else", "something else again"),
        "person3" => Array(
            "hey", "hi", "hello")
    ),
    "person4" => Array(
        "person5" => Array(
            "bob", "bill", "bobby", "billy"),
        "person6" => Array(
            "there", "their", "here")
    )
);
</code>```

I have a foreach loop that looks like this:

```<code>foreach($array["person1"] as $value){
}
</code>```

I want to get to the third level of the array (where all the words like "something" are), but there's a key in the way that I don't know ("person2" or "person3")
Is there a sort of "wildcard" I can use as the key? (Like $array["person1"][wildcard][0]?

答:
There are no "wildcards" for array keys, since the keys are identifiers.

Simply iterate through the array and echo the first element:

```<code>foreach ($array['person1'] as $key => $items) {
    // $key will contain the key, if you would need it.
    // $items contains the array of each child
    echo $items[0] . '<br />';
}
</code>```

Title: "Wildcard" key with foreach PHP

Body:
Ok, so I have an array that looks like this:

$array = ["person1" => ["person2" => ["something", "something else", "something else again"], "person3" => ["hey", "hi", "hello"]], "person4" => ["person5" => ["bob", "bill", "bobby", "billy"], "person6" => ["there", "their", "here"]]]

or, in other "words"

$array = Array(
    "person1" => Array(
        "person2" => Array(
            "something", "something else", "something else again"),
        "person3" => Array(
            "hey", "hi", "hello")
    ),
    "person4" => Array(
        "person5" => Array(
            "bob", "bill", "bobby", "billy"),
        "person6" => Array(
            "there", "their", "here")
    )
);

I have a foreach loop that looks like this:

foreach($array["person1"] as $value){
}

I want to get to the third level of the array (where all the words like "something" are), but there's a key in the way that I don't know ("person2" or "person3")
Is there a sort of "wildcard" I can use as the key? (Like $array["person1"][wildcard][0]?

Body:
There are no "wildcards" for array keys, since the keys are identifiers.

Simply iterate through the array and echo the first element:

foreach ($array['person1'] as $key => $items) {
    // $key will contain the key, if you would need it.
    // $items contains the array of each child
    echo $items[0] . '<br />';
}


问:
What is the alternative to cursors to retrieve large amounts of data from a database?
Searching through stackoverflow I found a large number of answers condemning the use of cursors in database programming. However I don't really understand what the alternative is.

I'm creating a program which reads a large number of rows (hundreds of thousands) from the database and keeps them in memory, for performance reasons. I can't really run a SELECT * FROM table and process all the results at once, can I?

The best way I have found is to use cursors and retrieve the rows in increments, for example 10 at a time.

Could someone enlighten me? I use PostgreSQL 9 on linux.

Thanks

答:
I suppose that the best way is to use COPY to get needed data directly to your client application.

I also did not have any problem when using cursors. I far as I understand, cursor is keeping a snapshot of data for you, and formally it (and COPY) is the only correct way to page through the results as otherwise when using LIMIT..OFFSET can lead to the inconsistencies, as the offset is changed by the newly inserted records.


问:
Zebble For Xamarin - Extension Installation issue with Visual Studio Community 2017 RC
I would like to try the new Zebble for Xamarin.

I'm having the following problem/error:

The extension cannot be installed to this product due to prerequisites
  that cannot be resolved.

Notes:

When I run the extension installer, I get: Digital Signature:None

I have installed and am using Visual Studio Community 2017 RC.

答:
According to this source, Zebble is now compatible with Visual Studio 2017. In your post you state you're running the release client. I recommend updating to the released version. You'll also want to ensure you have Xamarin installed.

Source


Title: Symbolic solve in Octave isn't the same as in MATLAB

Body:
I'm using the following OCTAVE command to solve an equation:

syms lambda
f = 0.9999999999999999614356461247534*lambda^8 + 0.010136594318889089056437488043559*lambda^7 + 0.000015602822908760063058460837969499*lambda^6 - 0.000000047482181730798751628339904656436*lambda^5 - 1.6804583575154387080270563605856e-10*lambda^4 - 1.9779236089667689638174134679895e-13*lambda^3 - 1.1091457134190232245774382079799e-16*lambda^2 - 2.9823717782777009154185183839051e-20*lambda - 3.202469692780878591525091765936e-24
solve(f==0, lambda)

The answer I get is

ans = {}(0x0)

On the other hand, when I try to use the same command in MATLAB, I get the following answer:

ans =
 0.0027518081408059183214532684717853
-0.0075831287286429577224408168637228
- 0.00029575583281255452382838468617809 - 0.0001257455668418381216048479457788*i
- 0.0016381334730465236707629472401125 - 0.00001988265276086766636376330275894*i
- 0.0016381334730465236707629472401125 + 0.00001988265276086766636376330275894*i
- 0.00071874755966694673136475169368249 - 0.00019245511322083820223381924903732*i
- 0.00029575583281255452382838468617809 + 0.0001257455668418381216048479457788*i
- 0.00071874755966694673136475169368249 + 0.00019245511322083820223381924903732*i

Is there any way I can make OCTAVE's output equal to MATLAB's output, may be with some tweaks?

Body:
You shouldn't use sysm here:

c = [0.9999999999999999614356461247534,
     0.010136594318889089056437488043559,
     0.000015602822908760063058460837969499,
     - 0.000000047482181730798751628339904656436,
     - 1.6804583575154387080270563605856e-10,
     - 1.9779236089667689638174134679895e-13,
     - 1.1091457134190232245774382079799e-16,
     - 2.9823717782777009154185183839051e-20,
     - 3.202469692780878591525091765936e-24];

octave> format long
octave> roots (c)
ans =

    -0.00758312872864296 + 0.00000000000000000i
     0.00275180814080592 + 0.00000000000000000i
    -0.00163813347304650 + 0.00001988265276021i
    -0.00163813347304650 - 0.00001988265276021i
    -0.00071874755966697 + 0.00019245511322079i
    -0.00071874755966697 - 0.00019245511322079i
    -0.00029575583281256 + 0.00012574556684184i
    -0.00029575583281256 - 0.00012574556684184i

which gives the same roots as the other software product does


问:
Hadoop HDFS Data File : Displaying Datanodes & Blocks
I've put a file into HDFS, and I want to know precisely how it was scattered through the DFS (Which Blocks are in which datanodes).

Tried fsck but I get an "invalid path" error when I specify the name of the data file that' i've put in the DFS.

Any Ideas ?

答:
Try

```<code>hdfs fsck /path/to/file -files -blocks -locations
</code>```

This will print out locations for every block of the file.

Namenode Web UI also would provide this information. Under Utilities --> Browse the file system, Select the file to view the Block Information.

Body:
Try

hdfs fsck /path/to/file -files -blocks -locations

This will print out locations for every block of the file.

Namenode Web UI also would provide this information. Under Utilities --> Browse the file system, Select the file to view the Block Information.


问:
Bot that DM's chosen keywords to chosen users
What I'm looking to do is to create a bot that will be in a private channel only accessible to the admins. All users will have keywords that they have chosen prior and will get notified about. Lets say user 'x', has chosen "brown" as a keyword, when a comment comes into the private channel containing the keyword "brown", I want the bot to send that message, copy and pasted, directly to the user 'x' that chose that keyword. So basically I would like to know how to make a bot they has a keyword feature that copies that exact message and dm's that user that chose that keyword.

Is this possible, if so how would I go about it?
Thanks

答:
Most of the bots i have made, i have used python.
Selenium web-driver is fairly easy to use if you intend on scraping the data from HTML pages.

In any case, you could use flask and mysql.connector to create the user interface and login for control of the bot.

If there are any other things you want it to do, i'm sure there's a library out there to do it, or you could just launch some kind of macro or script on the server.

Be very careful of permissions and whatnot if you intend on allowing remote control of other scripts and data on the server though.


问:
How do I select distinct values from multiple mysql columns and put them in one PHP array?
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

```<code>genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz
</code>```

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

答:
```<code>SELECT genre1, genre2, genre3 FROM table
</code>```

Assuming that this comes back as an array of arrays, then:

```<code>function coalesce_into_array($aggregate, $row) {
    foreach ($row as $genre) {
        $aggregate[] = $genre;
    }

    return $aggregate;
}

$data = array_unique(array_reduce($data, 'coalesce_into_array', array()));
sort($data);
</code>```

However, I would not recommend this in a serious application. The database design is bad. Read about database normalization to find out how to improve it.

Body:
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

Body:
SELECT genre1, genre2, genre3 FROM table

Assuming that this comes back as an array of arrays, then:

function coalesce_into_array($aggregate, $row) {
    foreach ($row as $genre) {
        $aggregate[] = $genre;
    }

    return $aggregate;
}

$data = array_unique(array_reduce($data, 'coalesce_into_array', array()));
sort($data);

However, I would not recommend this in a serious application. The database design is bad. Read about database normalization to find out how to improve it.


问:
Rails 5 Simpleform not updating nested attributes
Sorry I've looked at similar questions to this but still can't figure it out for some reason...

I'm using Devise and I'm trying to update my User model and a City model at the same time (through the edit registrations page) using a nested form.

I'm updating the users city based on a set of predefined values that are in the database. So all the user has to do is select a city they are living in from a list and then it save.

All that happens at the moment is the form submits but the city isn't changed.

Thanks in advance!

```<code>#user.rb
class User < ApplicationRecord
  belongs_to :city
end

#city.rb
class City < ApplicationRecord
  has_many :users
end
</code>```

My Controller:

```<code>class UsersController < ApplicationController
  def index
    @users = User.all
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])

    if @user.update(user_params)
      redirect_to @user
    else
      render 'edit'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  private

  def user_params
    params.require(:user).permit(city_attributes: [:id, :name, :user_id])
  end
end
</code>```

And my form:

```<code><%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

      <%= f.simple_fields_for :city do |c| %>

      <%= c.input :city_id, collection: City.all.order(name: :asc), label_method: :name, value_method: :id, label: "City", include_blank: false, selected: @user.city_id %>

      <% end %>
<% end %>
</code>```

答:
Okay so I sorted my problem out based on the comment from Iceman and response from ajerferson.

(However the issue that the nested form doesnt work still remains, but my issue is fixed)

As Iceman said Devise was permitting its own parameters in my application controller. So I moved the parameters there (instead of changing my routes).

```<code># application_controller.rb
def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])
    devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :date_of_birth, :gender, city_attributes: [:id, :name, :user_id]])
  end
</code>```

I tried again but the same problems were occuring. So what I did was actually scrap the nested form and simply change my application controller to this and targetting the city_id foreign key:

```<code>def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])
    devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :date_of_birth, :gender, :city_id])
  end
</code>```

My form:

```<code><%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

  <%= f.input :city_id, collection: City.all.order(name: :asc), label: "City" %>

<%= f.button :submit, "Save" %>
<% end %>
</code>```

and now it works perfectly fine!

Body:
Sorry I've looked at similar questions to this but still can't figure it out for some reason...

I'm using Devise and I'm trying to update my User model and a City model at the same time (through the edit registrations page) using a nested form.

I'm updating the users city based on a set of predefined values that are in the database. So all the user has to do is select a city they are living in from a list and then it save.

All that happens at the moment is the form submits but the city isn't changed.

Thanks in advance!

#user.rb
class User < ApplicationRecord
  belongs_to :city
end

#city.rb
class City < ApplicationRecord
  has_many :users
end

My Controller:

class UsersController < ApplicationController
  def index
    @users = User.all
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])

    if @user.update(user_params)
      redirect_to @user
    else
      render 'edit'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  private

  def user_params
    params.require(:user).permit(city_attributes: [:id, :name, :user_id])
  end
end

And my form:

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

      <%= f.simple_fields_for :city do |c| %>

      <%= c.input :city_id, collection: City.all.order(name: :asc), label_method: :name, value_method: :id, label: "City", include_blank: false, selected: @user.city_id %>

      <% end %>
<% end %>

Body:
Okay so I sorted my problem out based on the comment from Iceman and response from ajerferson.

(However the issue that the nested form doesnt work still remains, but my issue is fixed)

As Iceman said Devise was permitting its own parameters in my application controller. So I moved the parameters there (instead of changing my routes).

# application_controller.rb
def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])
    devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :date_of_birth, :gender, city_attributes: [:id, :name, :user_id]])
  end

I tried again but the same problems were occuring. So what I did was actually scrap the nested form and simply change my application controller to this and targetting the city_id foreign key:

def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])
    devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :date_of_birth, :gender, :city_id])
  end

My form:

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

  <%= f.input :city_id, collection: City.all.order(name: :asc), label: "City" %>

<%= f.button :submit, "Save" %>
<% end %>

and now it works perfectly fine!


问:
Adding bower components to vue webpack
Is there any way to add bower_components to vue-webpack.
I tried some way it does not work.

webpack.base.conf.js

http://pastebin.com/Gae193xP

Component file

```<code><script type="text/babel">
  import $ from 'jquery'
  require('x-editable')
</script>
</code>```

Error

答:
You should config the webpack config file for resolving packages from bower. For example, in webpack.config.js

```<code>module.exports = {
  resolve: {
    modulesDirectories: ["web_modules", "node_modules", "bower_components"]
  },
  plugins: [
    new webpack.ResolverPlugin(
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(".bower.json", ["main"])
      )
  ]
}
</code>```

You may refer to https://webpack.github.io/docs/usage-with-bower.html

Title: Adding bower components to vue webpack

Body:
Is there any way to add bower_components to vue-webpack.
I tried some way it does not work.

webpack.base.conf.js

http://pastebin.com/Gae193xP

Component file

Error

Body:
You should config the webpack config file for resolving packages from bower. For example, in webpack.config.js

module.exports = {
  resolve: {
    modulesDirectories: ["web_modules", "node_modules", "bower_components"]
  },
  plugins: [
    new webpack.ResolverPlugin(
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(".bower.json", ["main"])
      )
  ]
}

You may refer to https://webpack.github.io/docs/usage-with-bower.html


答:
Its prerequisites are:

Xamarin extension for Visual Studio

Universal Windows Platform tools (2.0)

Please ensure you have already installed these extensions in your Visual Studio.

Title: Zebble For Xamarin - Extension Installation issue with Visual Studio Community 2017 RC

Body:
I would like to try the new Zebble for Xamarin.

I'm having the following problem/error:

The extension cannot be installed to this product due to prerequisites
  that cannot be resolved.

Notes:

When I run the extension installer, I get: Digital Signature:None

I have installed and am using Visual Studio Community 2017 RC.


问:
Trying to add text from a random line from a text file
I am making a game in pygame for my sister for practising in pygame and I am trying to add a random line from a text file in to window name:

import pygame,random,sys

```<code>RandomMess = open('GameText.txt')
pygame.display.set_caption('Dream Land: {}').
#The .txt file currently has 4 lines but will be a lot more in the future...
#These are the test lines: This is in beta, hi :), hello, hi
</code>```

I have all the rest of the code in case anyone says that I haven't done any other code to make the window or anything.
I want it to say: Dream Land: {} then in the braces add a random line from the file.

答:
You're looking for readlines() and random.choice().</p>

```<code>import random,sys

RandomMess = open('GameText.txt')

# .readlines() will create a list of the lines in the file.
# So in our case ['This is in beta', 'hi :)', 'hello', 'hi']
# random.choice() then picks one item from this list.
line = random.choice(RandomMess.readlines())

# Then use .format() to add the line into the caption
pygame.display.set_caption('Dream Land: {}'.format(line))
</code>```

Body:
I am making a game in pygame for my sister for practising in pygame and I am trying to add a random line from a text file in to window name:

import pygame,random,sys

RandomMess = open('GameText.txt')
pygame.display.set_caption('Dream Land: {}').
#The .txt file currently has 4 lines but will be a lot more in the future...
#These are the test lines: This is in beta, hi :), hello, hi

I have all the rest of the code in case anyone says that I haven't done any other code to make the window or anything.
I want it to say: Dream Land: {} then in the braces add a random line from the file.

Body:
You're looking for readlines() and random.choice().

import random,sys

RandomMess = open('GameText.txt')

# .readlines() will create a list of the lines in the file.
# So in our case ['This is in beta', 'hi :)', 'hello', 'hi']
# random.choice() then picks one item from this list.
line = random.choice(RandomMess.readlines())

# Then use .format() to add the line into the caption
pygame.display.set_caption('Dream Land: {}'.format(line))


问:
Undefined namespace html (adding a css file to blade) laravel
I'm having trouble with importing a css style sheet located in public/css in a blade file located in resources/views/includes.

The code I used in the blade file is

```<code>{{ HTML::style('css/layout.css') }}
</code>```

which didn't work. I also tried

```<code>{{ HTML::style('css/layout.css', array('media' => 'print')) }}
</code>```

The error I get is Class 'HTML' not found

I followed the steps in this question, so

I added "laravelcollective/html": "5.4.16" in composer.json

run composer update

added in config/app.php

```<code>'providers' => [
Collective\Html\HtmlServiceProvider::class,
]
</code>```

and

```<code>'aliases' => [

        'Form' => Collective\Html\FormFacade::class,
        'HTML' => Collective\Html\HtmlFacade::class,
]
</code>```

Now the error I get is

```<code>Class 'Collective\Html\HtmlServiceProvider' not found
</code>```

And I don't understand why, as I added it to app.php. Indeed, when I go to app.php and the line where I added Collective.., the "Html" is colored in red and when I hover over it it says

```<code>Undefined namespace Html
</code>```

What should I do about it? All this laravel thing is getting confusing to me.

Apart from the fact that I don't know what to do with,

```<code>{{HTML::linkAction('MemberController@show', 'view', array($value->id))}}
</code>```

i found nothing online regarding the arguments of "linkAction"

答:
1:Remove "laravelcollective/html": "5.4.16" in composer.json and clean other config for this package in config/app.php.

2:Run composer update

3:Run composer require laravelcollective/html

4:Add 'Collective\Html\HtmlServiceProvider::class', in config/app.php (providers)

5:Add 'Form' => Collective\Html\FormFacade::class, and 'Html' => Collective\Html\HtmlFacade::class,  in config/app.php (aliases)

6:In controller try use Html;  and use Form;

If you get any other error please share composer.json and config/app.php.

Body:
I'm having trouble with importing a css style sheet located in public/css in a blade file located in resources/views/includes.

The code I used in the blade file is

{{ HTML::style('css/layout.css') }}

which didn't work. I also tried

{{ HTML::style('css/layout.css', array('media' => 'print')) }}

The error I get is Class 'HTML' not found

I followed the steps in this question, so

I added "laravelcollective/html": "5.4.16" in composer.json

run composer update

added in config/app.php

'providers' => [
Collective\Html\HtmlServiceProvider::class,
]

and

'aliases' => [

        'Form' => Collective\Html\FormFacade::class,
        'HTML' => Collective\Html\HtmlFacade::class,
]

Now the error I get is

Class 'Collective\Html\HtmlServiceProvider' not found

And I don't understand why, as I added it to app.php. Indeed, when I go to app.php and the line where I added Collective.., the "Html" is colored in red and when I hover over it it says

Undefined namespace Html

What should I do about it? All this laravel thing is getting confusing to me.

Apart from the fact that I don't know what to do with,

{{HTML::linkAction('MemberController@show', 'view', array($value->id))}}

i found nothing online regarding the arguments of "linkAction"


问:
Pointer tho another Object
I  have a little problem ..  I want to do car registration and i want to have owner(pointer to a Person object) but when i want to take the owner with get function i can't do that ... and this is mystery for me ... Maybe i have a little mistake somewhere and i can't find it .. Please help :) </p>

```<code>class Person
{
    friend class Cars;
public:
    Person(){}
    Person(uint8_t age, string name) :m_age(age), m_name(name)
    {
        m_idGener = s_idGenerator++;
    }

    int getId()
    {
        return m_idGener;
     }
    uint8_t getAge()
    {
        return m_age;
    }
    string getName()
    {
     return m_name;
    }
 private:
    string m_name;
    uint8_t m_age;
    static int s_idGenerator;
    int m_idGener;

 };
 class Cars:public Person
 {

 public:
     Person *m_owner; // this is my pointer which i want to point to cars     Object
  it will stay public for the test after the test i will move it in the     private section
    Cars()
    {
    }
   // getters and setters

    Cars setOwner(Cars &object, Person &owner) // with this function i set the owner
    {
      object.m_owner = &owner;
    }
    Cars getOwner(Cars &object) /// here is my problem i can't take the owner
    {
       return *(object.m_owner); // but i can't take the owner
    }

     uint16_t getHorsePower()
    {
       return horsePower;
    }
     string getRegNumber()
    {
       return registrationNumber;
    }
  private:
     string m_manufacturerName;
     string modelName;
     uint16_t horsePower;
    string registrationNumber;

};

int Person::s_idGenerator = 0;
</code>```

答:
Here:

```<code>Cars setOwner(Cars &object, Person &owner) // with this function i set the owner
{
object.m_owner = &owner;
}
</code>```

You declared out value type as "Cars" but you don't return anything.

And here:

```<code>Cars getOwner(Cars &object) /// here is my problem i can't take the owner
{
return *(object.m_owner); // but i can't take the owner
}
</code>```

You want to return "Person" object but again you declared out value type as "Cars".

So you can change this functions like that:

First:

```<code>void setOwner(Cars &object, Person &owner);
</code>```

Second:

```<code>Person getOwner(Cars &object);
</code>```

Title: Pointer tho another Object

Body:
I  have a little problem ..  I want to do car registration and i want to have owner(pointer to a Person object) but when i want to take the owner with get function i can't do that ... and this is mystery for me ... Maybe i have a little mistake somewhere and i can't find it .. Please help :)

class Person
{
    friend class Cars;
public:
    Person(){}
    Person(uint8_t age, string name) :m_age(age), m_name(name)
    {
        m_idGener = s_idGenerator++;
    }

    int getId()
    {
        return m_idGener;
     }
    uint8_t getAge()
    {
        return m_age;
    }
    string getName()
    {
     return m_name;
    }
 private:
    string m_name;
    uint8_t m_age;
    static int s_idGenerator;
    int m_idGener;

 };
 class Cars:public Person
 {

 public:
     Person *m_owner; // this is my pointer which i want to point to cars     Object
  it will stay public for the test after the test i will move it in the     private section
    Cars()
    {
    }
   // getters and setters

    Cars setOwner(Cars &object, Person &owner) // with this function i set the owner
    {
      object.m_owner = &owner;
    }
    Cars getOwner(Cars &object) /// here is my problem i can't take the owner
    {
       return *(object.m_owner); // but i can't take the owner
    }

     uint16_t getHorsePower()
    {
       return horsePower;
    }
     string getRegNumber()
    {
       return registrationNumber;
    }
  private:
     string m_manufacturerName;
     string modelName;
     uint16_t horsePower;
    string registrationNumber;

};

int Person::s_idGenerator = 0;

Body:
Here:

Cars setOwner(Cars &object, Person &owner) // with this function i set the owner
{
object.m_owner = &owner;
}

You declared out value type as "Cars" but you don't return anything.

And here:

Cars getOwner(Cars &object) /// here is my problem i can't take the owner
{
return *(object.m_owner); // but i can't take the owner
}

You want to return "Person" object but again you declared out value type as "Cars".

So you can change this functions like that:

First:

void setOwner(Cars &object, Person &owner);

Second:

Person getOwner(Cars &object);


答:
First you need to declare:

md-cols Number of columns in the grid.

In your case (8+2=10):

<md-grid-list md-cols="10" ...

Then your items:

<md-grid-tile md-colspan="8">...</md-grid-tile>

<md-grid-tile md-colspan="2">...</md-grid-tile>

Codepen Sample - Angular Material Docs

Title: Angularjs material one row with 2 columns

Body:
i am trying to achieve that, and can't figure how:

|-------------80%---------------------|----20%---|

one row with 2 columns with specific width.

i don't understand something, columns (usage in Material) are look to me like rows > in rows

|-------------------------------------|----//---|
|-------------------------------------|----//---|
|-------------------------------------|----//---|

and not like my example.

How can i achieve it?


问:
Javascript push input into Array causes several arrays not one
This is a follow up to my question, seen here

I am trying to write that when a user enters in their name (string) into the field and hits enter, it pushes it into an array.  It works, kinda.  But I get an error when I try it one and then it produces multiple arrays when I try it another.  I don't want to use jQuery.

Here is the HTML

```<code><input type="text"
   class="theplayer pre"
   name="Player"
   id="bind"
   placeholder="Enter Names"
    />
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>
</code>```

Here is my js that works but it creates multiple arrays instead of pushing everything into one array (because the nextElementSibling is not called, I know this, see next block

```<code>let namesOfPlayers = [];
let currentValue = document.getElementById("bind").value;
let button = currentValue.nextElementSibling;
document.addEventListener('keypress', function (e) {
    const key = e.which || e.keyCode;
    if (key === 13) {
        namesOfPlayers.push(currentValue);
        console.log('namesOfPlayers', namesOfPlayers);
    }
});
</code>```

Here is my js that throws an error (I don't want to use jQuery)

I want that when a user hits enter or clicks the button that the string is submitted and added into the empty array.  I can't for the life of me figure out how to make that work.

Thanks for your help!

答:
CurrentValue is defined outside of the event listener, so it only gets called once, on initialisation. That's why the push call only injects empty strings. Also, the button doesn't do anything because it doesn't have a listener.

Here's the updated code:

```<code>let namesOfPlayers = [];
// It's better to get the button by id instead of getting it by a previous child.
// This is because it might cause some unexpected behaviour if someone changed the HTML.
const button = document.getElementById("thego");

button.addEventListener('click', function (e) {
    addItemToArray(namesOfPlayers);
});

document.addEventListener('keypress', function (e) {
  const key = e.which || e.keyCode;
  if (key === 13) {
    addItemToArray(namesOfPlayers);
  }
});

function addItemToArray(namesOfPlayers) {
  const currentValue = document.getElementById("bind").value;
  namesOfPlayers.push(currentValue);
  console.log('namesOfPlayers', namesOfPlayers);
}
</code>```

https://fiddle.jshell.net/4k4a9m6y/

But, you're better off with a form to improve performance.

let namesOfPlayers = [];
const form = document.getElementById("form");

form.addEventListener('submit', function (e) {
  const currentValue = document.getElementById("bind").value;
  namesOfPlayers.push(currentValue);
  console.log('namesOfPlayers', namesOfPlayers);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form"
      action="javascript:void(0);">
  <input type="text"
         class="theplayer pre"
         name="Player"
         id="bind"
         placeholder="Enter Names"
         />
  <button type="submit" id="thego" class="pre enterteam" value="click">Go</button>
</form></code>```

https://fiddle.jshell.net/4k4a9m6y/2/

Body:
This is a follow up to my question, seen here

I am trying to write that when a user enters in their name (string) into the field and hits enter, it pushes it into an array.  It works, kinda.  But I get an error when I try it one and then it produces multiple arrays when I try it another.  I don't want to use jQuery.

Here is the HTML

<input type="text"
   class="theplayer pre"
   name="Player"
   id="bind"
   placeholder="Enter Names"
    />
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>

Here is my js that works but it creates multiple arrays instead of pushing everything into one array (because the nextElementSibling is not called, I know this, see next block

let namesOfPlayers = [];
let currentValue = document.getElementById("bind").value;
let button = currentValue.nextElementSibling;
document.addEventListener('keypress', function (e) {
    const key = e.which || e.keyCode;
    if (key === 13) {
        namesOfPlayers.push(currentValue);
        console.log('namesOfPlayers', namesOfPlayers);
    }
});

Here is my js that throws an error (I don't want to use jQuery)

I want that when a user hits enter or clicks the button that the string is submitted and added into the empty array.  I can't for the life of me figure out how to make that work.

Thanks for your help!

Body:
CurrentValue is defined outside of the event listener, so it only gets called once, on initialisation. That's why the push call only injects empty strings. Also, the button doesn't do anything because it doesn't have a listener.

Here's the updated code:

let namesOfPlayers = [];
// It's better to get the button by id instead of getting it by a previous child.
// This is because it might cause some unexpected behaviour if someone changed the HTML.
const button = document.getElementById("thego");

button.addEventListener('click', function (e) {
    addItemToArray(namesOfPlayers);
});

document.addEventListener('keypress', function (e) {
  const key = e.which || e.keyCode;
  if (key === 13) {
    addItemToArray(namesOfPlayers);
  }
});

function addItemToArray(namesOfPlayers) {
  const currentValue = document.getElementById("bind").value;
  namesOfPlayers.push(currentValue);
  console.log('namesOfPlayers', namesOfPlayers);
}

https://fiddle.jshell.net/4k4a9m6y/

But, you're better off with a form to improve performance.

let namesOfPlayers = [];
const form = document.getElementById("form");

form.addEventListener('submit', function (e) {
  const currentValue = document.getElementById("bind").value;
  namesOfPlayers.push(currentValue);
  console.log('namesOfPlayers', namesOfPlayers);
});

<form id="form"
      action="javascript:void(0);">
  <input type="text"
         class="theplayer pre"
         name="Player"
         id="bind"
         placeholder="Enter Names"
         />
  <button type="submit" id="thego" class="pre enterteam" value="click">Go</button>
</form>

https://fiddle.jshell.net/4k4a9m6y/2/


问:
How do I access individual words after splitting a string?
```<code>std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";
</code>```

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

```<code>if (word[0] == "something")
   do_this();
else
   do_that();
</code>```

答:
You would first have to define what makes a word.

If it's whitespace, iss >> token is the default option:

```<code>std::string line("This is a sentence.");
std::istringstream iss(line);

std::vector<std::string> words.
std::string token;
while(iss >> token)
  words.push_back(token);
</code>```

This should find

```
This
is
a
sentence.
```

as words.

If it's anything more complicated than whitespace, you will have to write your own lexer.

Body:
std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

if (word[0] == "something")
   do_this();
else
   do_that();

Body:
You would first have to define what makes a word.

If it's whitespace, iss >> token is the default option:

std::string line("This is a sentence.");
std::istringstream iss(line);

std::vector<std::string> words.
std::string token;
while(iss >> token)
  words.push_back(token);

This should find

This
is
a
sentence.

as words.

If it's anything more complicated than whitespace, you will have to write your own lexer.


问:
Custom helper classes in Laravel 5.4
I have some helper classes in app/Helpers. How do I load these classes using a service provider to use them in blade templates?

e.g. If I have a class CustomHelper that contains a method fooBar() :

```<code><?php

nampespace App\Helpers;

class CustomHelper
{
    static function fooBar()
    {
        return 'it works!';
    }
}
</code>```

I want to be able to do something like this in my blade templates:

```<code>{{ fooBar() }}
</code>```

instead of doing this:

```<code>{{ \App\Helpers\CustomHelper::fooBar() }}
</code>```

P.S: @andrew-brown's answer in Best practices for custom helpers on Laravel 5 deals with non-class files. It would be nice to have a class based solution so that the helper functions can be organized among classes.

答:
I don't think it's possible to use only function when you have code in your classes. Well, you could try with extending Blade but it's too much.

What you should do is creating one extra file, for example app\Helpers\helpers.php and in your composer.json file put:

```<code>"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": ["app/Helpers/helpers.php"] // <- this line was added
},
</code>```

create app/Helpers/helpers.php file and run

```<code>composer dump-autoload
</code>```

Now in your app/Helpers/helpers.php file you could add those custom functions for example like this:

```<code>if (! function_exists('fooBar')) {
   function fooBar()
   {
      return \App\Helpers\CustomHelper::fooBar();
   }
}
</code>```

so you define global functions but in fact all of them might use specific public methods from some classes.

By the way this is exactly what Laravel does for its own helpers for example:

```<code>if (! function_exists('array_add')) {
    function array_add($array, $key, $value)
    {
        return Arr::add($array, $key, $value);
    }
}
</code>```

as you see array_add is only shorter (or maybe less verbose) way of writing Arr::add

Title: Custom helper classes in Laravel 5.4

Body:
I have some helper classes in app/Helpers. How do I load these classes using a service provider to use them in blade templates?

e.g. If I have a class CustomHelper that contains a method fooBar() :

<?php

nampespace App\Helpers;

class CustomHelper
{
    static function fooBar()
    {
        return 'it works!';
    }
}

I want to be able to do something like this in my blade templates:

{{ fooBar() }}

instead of doing this:

{{ \App\Helpers\CustomHelper::fooBar() }}

P.S: @andrew-brown's answer in Best practices for custom helpers on Laravel 5 deals with non-class files. It would be nice to have a class based solution so that the helper functions can be organized among classes.

Body:
I don't think it's possible to use only function when you have code in your classes. Well, you could try with extending Blade but it's too much.

What you should do is creating one extra file, for example app\Helpers\helpers.php and in your composer.json file put:

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": ["app/Helpers/helpers.php"] // <- this line was added
},

create app/Helpers/helpers.php file and run

composer dump-autoload

Now in your app/Helpers/helpers.php file you could add those custom functions for example like this:

if (! function_exists('fooBar')) {
   function fooBar()
   {
      return \App\Helpers\CustomHelper::fooBar();
   }
}

so you define global functions but in fact all of them might use specific public methods from some classes.

By the way this is exactly what Laravel does for its own helpers for example:

if (! function_exists('array_add')) {
    function array_add($array, $key, $value)
    {
        return Arr::add($array, $key, $value);
    }
}

as you see array_add is only shorter (or maybe less verbose) way of writing Arr::add