问:
WPF Sorting an ObservableCollection de-selects a ComboBox
I have a ComboBox where a user can select what JobType they are working on.  The ComboBox has a list of AllJobTypes.  The problem stems from when a user adds a new JobType, I add the JobType to the AllJobTypes ObservableCollection, then sort it.  When the sorting happens the ComboBox get's de-selected and not really sure why.  The JobConfig.SelectedJobType.Name never changes in this process.  Is there a way to sort an observable collection where it doesn't break the ComboBox?

```<code>public class JobTypeList : ObservableCollection<JobType> {

  public void SortJobTypes() {
    var sortableList = new List<JobType>(this);
    sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
    //this works but it creates a bug in the select for JobTypes
    for (int i = 0; i < sortableList.Count; i++) {
        this.Move(this.IndexOf(sortableList[i]), i);
    }
  }
</code>```

And in the XAML

```<code><ComboBox Grid.Column="0" SelectionChanged="JobTypeComboBox_SelectionChanged"
                              Name="JobTypeComboBox"
                              ItemsSource="{Binding Path=AllJobTypes}"
                              DisplayMemberPath="Name"
                              SelectedValuePath="Name"
                              SelectedValue="{Binding
Path=JobConfig.SelectedJobType.Name}" />
</code>```

答:
Instead of sorting the collection in the view model, you should bind the ComboBox's ItemsSource to a CollectionViewSource, where you can specify a SortDescription:

```<code><Window ...
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    ...>
    <Window.Resources>
        <CollectionViewSource x:Key="cvs" Source="{Binding AllJobTypes}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Name"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>

    ...
    <ComboBox ItemsSource="{Binding Source={StaticResource cvs}}"
              DisplayMemberPath="Name"
              SelectedValuePath="Name"
              SelectedValue="{Binding JobConfig.SelectedJobType.Name}"/>
    ...

</Window>
</code>```

For further information see How to: Sort and Group Data Using a View in XAML

Body:
I have a ComboBox where a user can select what JobType they are working on.  The ComboBox has a list of AllJobTypes.  The problem stems from when a user adds a new JobType, I add the JobType to the AllJobTypes ObservableCollection, then sort it.  When the sorting happens the ComboBox get's de-selected and not really sure why.  The JobConfig.SelectedJobType.Name never changes in this process.  Is there a way to sort an observable collection where it doesn't break the ComboBox?

public class JobTypeList : ObservableCollection<JobType> {

  public void SortJobTypes() {
    var sortableList = new List<JobType>(this);
    sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
    //this works but it creates a bug in the select for JobTypes
    for (int i = 0; i < sortableList.Count; i++) {
        this.Move(this.IndexOf(sortableList[i]), i);
    }
  }

And in the XAML

<ComboBox Grid.Column="0" SelectionChanged="JobTypeComboBox_SelectionChanged"
                              Name="JobTypeComboBox"
                              ItemsSource="{Binding Path=AllJobTypes}"
                              DisplayMemberPath="Name"
                              SelectedValuePath="Name"
                              SelectedValue="{Binding
Path=JobConfig.SelectedJobType.Name}" />

Body:
Instead of sorting the collection in the view model, you should bind the ComboBox's ItemsSource to a CollectionViewSource, where you can specify a SortDescription:

<Window ...
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    ...>
    <Window.Resources>
        <CollectionViewSource x:Key="cvs" Source="{Binding AllJobTypes}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Name"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>

    ...
    <ComboBox ItemsSource="{Binding Source={StaticResource cvs}}"
              DisplayMemberPath="Name"
              SelectedValuePath="Name"
              SelectedValue="{Binding JobConfig.SelectedJobType.Name}"/>
    ...

</Window>

For further information see How to: Sort and Group Data Using a View in XAML


来源: stackexchange

问:
Can an anonymous union be instantiated in c++?
I have this piece of code:

```<code>class test {
  private:
  union {
    double x;
    std::vector<double> y;
  } amIValid;
};
</code>```

I wonder if the union instance amIValid is valid?

答:
An unnamed union can be instantiated in C++:

```<code>union { int i; double d; } my_thing;
my_thing.i = 3;
// etc.
</code>```

An anonymous union is an unnamed union that is not instantiated (scroll down). You can access its members directly:

```<code>union { int i; double d; };
i = 3;
// etc.
</code>```

So the answer to the question in the title is that an anonymous union cannot be instantiated because instantiating it means that it is not an anonymous union.

ContentLicense: CC BY-SA 3.0

Body:
I have this piece of code:

class test {
  private:
  union {
    double x;
    std::vector<double> y;
  } amIValid;
};

I wonder if the union instance amIValid is valid?

Body:
An unnamed union can be instantiated in C++:

union { int i; double d; } my_thing;
my_thing.i = 3;
// etc.

An anonymous union is an unnamed union that is not instantiated (scroll down). You can access its members directly:

union { int i; double d; };
i = 3;
// etc.

So the answer to the question in the title is that an anonymous union cannot be instantiated because instantiating it means that it is not an anonymous union.


问:
Can I customize a Dynamics AX field in list page grid with a query that does a calculation?
Looking to customize an AX2012 list page grid view column for users that would query and return: open transactions amount short paid on the All Customers list page grid. Is this possible using the add fields feature and entering a query within system name?</p>

答:
It is not possible to achieve that requirement by using the Add fields feature from the Personalisation form.

You would need to create (develop) a new display method in the Customers (CustTable) table (if it hasn't been created already) and add that display method to the CustTableListPage form in the Application Object Tree.

This is a development task, not a personalisation.


问:
Performance issue Flattening XML in SQL using Nodes, value methods and cross apply
I am trying to flatten the XML into SQL table using below  code. The input datatable (@incomingTable) contains 10k un typed XMLs the query takes 7 sec to return the output. When I checked the Execution Plan found most of the time is spent on "Table Vaued Functions (XML Reader with XPATH filter)" step. My guess is this step  refers to Value method in query.

The value() method uses the Transact-SQL CONVERT operator implicitly and tries to convert the result of the XQuery expression, to the corresponding SQL type specified by Transact-SQL conversion.

Questions:Is there any other XML method to retrieve element/attribute value without data type converting . because I want the data as string anyhow. Helps me compare the results for two approaches.

Is there any other way to optimize this query?

```<code>select
sqlXml.value('@ID', 'varchar(50)') as XMLFieldName,
sqlXml.value('@TS', 'varchar(50)') as XMLTSValue,
sqlXml.value('.','varchar(800)') as XMLFieldValue
from @incomingTable
cross apply playfieldvalues.nodes('/PlayAttributes/PlayFields/PlayField') as
XMLData(sqlXml)
</code>```

答:
Try to use OPENXML:

```<code>DECLARE @idoc int;

EXEC sp_xml_preparedocument @idoc OUTPUT, @incomingTable;

SELECT    *
FROM       OPENXML (@idoc, '/PlayAttributes/PlayFields/PlayField',1)
            WITH (XMLFieldName  varchar(50) '@ID',
                  XMLTSValue varchar(50) '@TS',
                  XMLFieldValue varchar(800) '.');

EXEC sp_xml_removedocument @idoc;
</code>```

OPENXML allows accessing XML data as if it were a relational recordset. It provides a tabular (rowset) view of in-memory representation of an XML document. Technically, OPENXML is a rowset provider similar to a table or a view; hence it can be used wherever a table or a view is used. For instance, you can use OPENXML with SELECT or SELECT INTO statements, to work on an XML document that is retained in memory.

Source

Body:
I am trying to flatten the XML into SQL table using below  code. The input datatable (@incomingTable) contains 10k un typed XMLs the query takes 7 sec to return the output. When I checked the Execution Plan found most of the time is spent on "Table Vaued Functions (XML Reader with XPATH filter)" step. My guess is this step  refers to Value method in query.

The value() method uses the Transact-SQL CONVERT operator implicitly and tries to convert the result of the XQuery expression, to the corresponding SQL type specified by Transact-SQL conversion.

Questions:Is there any other XML method to retrieve element/attribute value without data type converting . because I want the data as string anyhow. Helps me compare the results for two approaches.

Is there any other way to optimize this query?

select
sqlXml.value('@ID', 'varchar(50)') as XMLFieldName,
sqlXml.value('@TS', 'varchar(50)') as XMLTSValue,
sqlXml.value('.','varchar(800)') as XMLFieldValue
from @incomingTable
cross apply playfieldvalues.nodes('/PlayAttributes/PlayFields/PlayField') as
XMLData(sqlXml)

Body:
Try to use OPENXML:

DECLARE @idoc int;

EXEC sp_xml_preparedocument @idoc OUTPUT, @incomingTable;

SELECT    *
FROM       OPENXML (@idoc, '/PlayAttributes/PlayFields/PlayField',1)
            WITH (XMLFieldName  varchar(50) '@ID',
                  XMLTSValue varchar(50) '@TS',
                  XMLFieldValue varchar(800) '.');

EXEC sp_xml_removedocument @idoc;

OPENXML allows accessing XML data as if it were a relational recordset. It provides a tabular (rowset) view of in-memory representation of an XML document. Technically, OPENXML is a rowset provider similar to a table or a view; hence it can be used wherever a table or a view is used. For instance, you can use OPENXML with SELECT or SELECT INTO statements, to work on an XML document that is retained in memory.

Source


问:
Nodejs-mongoose-0.0.5 error when run app.js
```<code>/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40
          continue;
         ^^^^^^^^
node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
SyntaxError: Illegal continue statement
    at Module._compile (node.js:418:29)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)
    at require (node.js:367:23)
    at Object.<anonymous> (/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/model.js:2:13)
    at Module._compile (node.js:423:30)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)
</code>```

And the code is just:

```<code>var mongoose = require('mongoose').Mongoose;

mongoose.model('User', {
    properties: ['user', 'pass', 'widgets' ],
    indexes: [ { 'user' : 1 } , { unique : true }  ],
});
.......
</code>```

/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40

```<code> else {
       // Prevent never-ending loop
       if (target === d.value) {
             continue;
       }
</code>```

even if i comment the continue statement, causes another error log:

```<code>node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
Error: ECONNREFUSED, Connection refused
    at Socket._onConnect (net.js:548:18)
    at IOWatcher.onWritable [as callback] (net.js:165:12)
</code>```

Any idea?

答:
/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js

Edit this file and change line 40 from continue; to return;

In Array.prototype.forEach, continue is not supported (you can use the example below to test return vs continue in firebug's console)

```<code>[1,2,3,4].forEach(function(val, arr) {
  if(val != 1) {
    console.log(val);
    return;
    //continue;
  }

  console.log('here');
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40
          continue;
         ^^^^^^^^
node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
SyntaxError: Illegal continue statement
    at Module._compile (node.js:418:29)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)
    at require (node.js:367:23)
    at Object.<anonymous> (/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/model.js:2:13)
    at Module._compile (node.js:423:30)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)

And the code is just:

var mongoose = require('mongoose').Mongoose;

mongoose.model('User', {
    properties: ['user', 'pass', 'widgets' ],
    indexes: [ { 'user' : 1 } , { unique : true }  ],
});
.......

/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40

 else {
       // Prevent never-ending loop
       if (target === d.value) {
             continue;
       }

even if i comment the continue statement, causes another error log:

node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
Error: ECONNREFUSED, Connection refused
    at Socket._onConnect (net.js:548:18)
    at IOWatcher.onWritable [as callback] (net.js:165:12)

Any idea?

Body:
/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js

Edit this file and change line 40 from continue; to return;

In Array.prototype.forEach, continue is not supported (you can use the example below to test return vs continue in firebug's console)

[1,2,3,4].forEach(function(val, arr) {
  if(val != 1) {
    console.log(val);
    return;
    //continue;
  }

  console.log('here');
});


问:
Calling GMainLoop.quit() for mainloop running in child process, from parent process
I need to run a gstreamer pipeline to perform video streaming. The GStreamer pipeline requires a GObject.MainLoop object which has a run() method that does not terminate until quit() is called.
For this I create a process (P2) from my main application process (P1), which runs the GObject.MainLoop instance in its main thread. The problem is that loop goes on indefinitly within the process P2 and I'm unable to exit/quit it from the main application process (P1).

Following is the section of code that might help understanding the scenario.

```<code>'''
start() spawns a new process P2 that runs Mainloop within its main thread.
stop() is called from P1, but does not quit the Mainloop. This is probably because
processes do not have shared memory
'''
from multiprocessing import Process
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.process = None
        self.loop = GObject.MainLoop()

    def worker(self):
        self.loop.run()

    def start(self):
        self.process=Process(target=self.worker, args=())
        self.process.start()

    def stop(self):
        self.loop.quit()
</code>```

Next, I tried using a multiprocessing Queue for sharing the 'loop' variable between the processes, but am still unable to quit the mainloop.

```<code>'''
start() spawns a new process and puts the loop object in a multiprocessing Queue
stop() calls get() from the loop and calls the quit() method, though it still does not quit the mainloop.
'''
from multiprocessing import Process, Queue
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.p=None
        self.loop = GObject.MainLoop()
        self.queue = Queue()

    def worker(self):
        self.queue.put(self.loop)
        self.loop.run()

    def start(self):
        self.p=Process(target=self.worker, args=())
        self.p.start()

    def stop(self):
        # receive loop instance shared by Child Process
        loop=self.queue.get()
        loop.quit()
</code>```

How do I call the quit method for the MainLoop object which is only accessible within the child Process P2?

答:
Ok firstly we need to be using threads not processes.  Processes will be in a different address space.

What is the difference between a process and a thread?

Try passing the main loop object to a separate thread that does the actual work.  This will make your main method in to nothing but a basic GLib event processing loop, but that is fine and the normal behavior in many GLib applciations.

Lastly, we need to handle the race condition of the child process finishing its work before the main loop activates.  We do this with the while not loop.is_running() snippet.

```<code>from threading import Thread
import gi

from gi.repository import GObject

def worker(loop):
    while not loop.is_running():
        print("waiting for loop to run")

    print("working")

    loop.quit()
    print("quitting")

class Main:
    def __init__(self):
        self.thread = None
        self.loop = GObject.MainLoop()

    def start(self):
        self.thread=Thread(target=worker, args=(self.loop,))
        self.thread.start()
        self.loop.run()

def main():
    GObject.threads_init()

    m = Main()
    m.start()

if  __name__ =='__main__' : main()
</code>```

Body:
I need to run a gstreamer pipeline to perform video streaming. The GStreamer pipeline requires a GObject.MainLoop object which has a run() method that does not terminate until quit() is called.
For this I create a process (P2) from my main application process (P1), which runs the GObject.MainLoop instance in its main thread. The problem is that loop goes on indefinitly within the process P2 and I'm unable to exit/quit it from the main application process (P1).

Following is the section of code that might help understanding the scenario.

'''
start() spawns a new process P2 that runs Mainloop within its main thread.
stop() is called from P1, but does not quit the Mainloop. This is probably because
processes do not have shared memory
'''
from multiprocessing import Process
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.process = None
        self.loop = GObject.MainLoop()

    def worker(self):
        self.loop.run()

    def start(self):
        self.process=Process(target=self.worker, args=())
        self.process.start()

    def stop(self):
        self.loop.quit()

Next, I tried using a multiprocessing Queue for sharing the 'loop' variable between the processes, but am still unable to quit the mainloop.

'''
start() spawns a new process and puts the loop object in a multiprocessing Queue
stop() calls get() from the loop and calls the quit() method, though it still does not quit the mainloop.
'''
from multiprocessing import Process, Queue
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.p=None
        self.loop = GObject.MainLoop()
        self.queue = Queue()

    def worker(self):
        self.queue.put(self.loop)
        self.loop.run()

    def start(self):
        self.p=Process(target=self.worker, args=())
        self.p.start()

    def stop(self):
        # receive loop instance shared by Child Process
        loop=self.queue.get()
        loop.quit()

How do I call the quit method for the MainLoop object which is only accessible within the child Process P2?

Body:
Ok firstly we need to be using threads not processes.  Processes will be in a different address space.

What is the difference between a process and a thread?

Try passing the main loop object to a separate thread that does the actual work.  This will make your main method in to nothing but a basic GLib event processing loop, but that is fine and the normal behavior in many GLib applciations.

Lastly, we need to handle the race condition of the child process finishing its work before the main loop activates.  We do this with the while not loop.is_running() snippet.

from threading import Thread
import gi

from gi.repository import GObject

def worker(loop):
    while not loop.is_running():
        print("waiting for loop to run")

    print("working")

    loop.quit()
    print("quitting")

class Main:
    def __init__(self):
        self.thread = None
        self.loop = GObject.MainLoop()

    def start(self):
        self.thread=Thread(target=worker, args=(self.loop,))
        self.thread.start()
        self.loop.run()

def main():
    GObject.threads_init()

    m = Main()
    m.start()

if  __name__ =='__main__' : main()


问:
Skip multiplies of 5 through 17 terms C++
I would like to write a simple program that skips all multiples of 5 such that there are 17 terms in the result.

```<code>#include <iostream>
using namespace std;

int main() {
int num = 1;
int i = 1;
while(i <= 17){
    if(num%5 != 0){
        cout << num <<endl;
    }
    i++;
    num++;
}
</code>```

I expected it to be like this: 1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19,21

However, for some reason it ends when the output reaches 17, instead of having 17 terms. So: 1,2,3,4,5,6,7,8,9,11,12,13,14,16,17

How do I fix this?

答:
The fix to your problem is: </p>

```<code>while(i <= 17){
    if(num%5 != 0){
        cout << num <<endl;
        i++;
    }

    num++;
}
</code>```

Body:
I would like to write a simple program that skips all multiples of 5 such that there are 17 terms in the result.

#include <iostream>
using namespace std;

int main() {
int num = 1;
int i = 1;
while(i <= 17){
    if(num%5 != 0){
        cout << num <<endl;
    }
    i++;
    num++;
}

I expected it to be like this: 1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19,21

However, for some reason it ends when the output reaches 17, instead of having 17 terms. So: 1,2,3,4,5,6,7,8,9,11,12,13,14,16,17

How do I fix this?

Body:
The fix to your problem is:

while(i <= 17){
    if(num%5 != 0){
        cout << num <<endl;
        i++;
    }

    num++;
}


问:
Graph Click Interface
So, what I have is a program that plots Phase trajectories. At the moment the starting points are all random, but what I am trying to add is a way for the program to start a trajectory from the point I click on. I've been fiddling with it for hours, trying everything I know, well here's the code:

```<code>public static void click(final double r, final double t) {
    MouseListener mus = new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            double r = e.getX();
            double t = e.getY();
        }
    };
}

public Vector<Graph> getGraphs() {
    // ... bunch of code that draws the graph...
    g.add(new Graph.Line());
    g.lastElement().add(r, t);
    g.lastElement().setColor(Color.blue);
</code>```

And what it tells me is that r and t can't be found. I realize that it might be hard to help without the whole code, but it is loads of code, I can email it to someone if you are really willing to help. But in any other case, anyone got an idea what I can do?

答:
1) r and t are not in scope for your getGraphs() method.

2) You don't seem to have registered your mouse adapter as a MouseListener anywhere

3) It is not clear how the click() method gets called

You need to capture the mouse clicks from a window component, let's say it is a JPanel that you are using.

Then your code would look something like this:

```<code>public class MyApplication {
    private JFrame myWindow = new JFrame("My Application");
    private JPanel myPanelYouCanClick = new JPanel();

    public MyApplication() {
        myWindow.setContantPane(myPanelYouCanClick);
        myPanelYouCanClick.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                double r = e.getX();
                double t = e.getY();
                // Code to create your new trajectory called from here, pass
                // in the values of r and t if required. Remember you are
                // running on the event dispatcher thread!
            }
        });
        myWindow.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyApplication app = new MyApplication();
            }
        });
    }
}
</code>```

Title: Graph Click Interface

Body:
So, what I have is a program that plots Phase trajectories. At the moment the starting points are all random, but what I am trying to add is a way for the program to start a trajectory from the point I click on. I've been fiddling with it for hours, trying everything I know, well here's the code:

public static void click(final double r, final double t) {
    MouseListener mus = new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            double r = e.getX();
            double t = e.getY();
        }
    };
}

public Vector<Graph> getGraphs() {
    // ... bunch of code that draws the graph...
    g.add(new Graph.Line());
    g.lastElement().add(r, t);
    g.lastElement().setColor(Color.blue);

And what it tells me is that r and t can't be found. I realize that it might be hard to help without the whole code, but it is loads of code, I can email it to someone if you are really willing to help. But in any other case, anyone got an idea what I can do?

Body:
1) r and t are not in scope for your getGraphs() method.

2) You don't seem to have registered your mouse adapter as a MouseListener anywhere

3) It is not clear how the click() method gets called

You need to capture the mouse clicks from a window component, let's say it is a JPanel that you are using.

Then your code would look something like this:

public class MyApplication {
    private JFrame myWindow = new JFrame("My Application");
    private JPanel myPanelYouCanClick = new JPanel();

    public MyApplication() {
        myWindow.setContantPane(myPanelYouCanClick);
        myPanelYouCanClick.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                double r = e.getX();
                double t = e.getY();
                // Code to create your new trajectory called from here, pass
                // in the values of r and t if required. Remember you are
                // running on the event dispatcher thread!
            }
        });
        myWindow.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyApplication app = new MyApplication();
            }
        });
    }
}


问:
CsvHelper library in C#, nulls as empty string
I am trying to use CsvHelper library to write records (or list<SomeModel>) to CSV, but SomeModel class has some reference types properties that are sometimes null. I am wondering is there a way to print nulls as empty string instead of  "null". I can see that CsvWriter.WriteRecords method is virtual so I can extend the class and create a custom implementation of it but there should be an easier way or some confirguration.

答:
You can simply set this attribute

```<code>csv.Configuration.UseNewObjectForNullReferenceMembers = true;
</code>```

it'll simply create a new object if a null reference is found.
In the ctor of the  object class, assign empty string as default.

Body:
You can simply set this attribute

csv.Configuration.UseNewObjectForNullReferenceMembers = true;

it'll simply create a new object if a null reference is found.
In the ctor of the  object class, assign empty string as default.


问:
How to subset data as per account in R?
I am trying to subset data as per one column In R using for loop. All I want to look at the different accounts in different datasets.
In the data attached I want to subset using first variable which is Account.
Code:-

```<code>for i in 1:Length(Data$Account)
{

data<- subset(Train, Train$Account==i)

df<-data
}

Account Sales   Date
1   10  1/1/2017
2   21  2/1/2017
3   23  3/1/2017
4   24  4/1/2017
4   24  5/1/2017
5   25  6/1/2017
4   25  7/1/2017
5   266 8/1/2017
6   556 9/1/2017
7   346 10/1/2017
5   42  11/1/2017
3   246 12/1/2017
2   356 1/1/2018
</code>```

My requirement should return something like this for Account 4:-

```<code>Account Sales   Date
4   24  4/1/2017
4   24  5/1/2017
4   25  7/1/2017
</code>```

答:
This approach will create multiple datasets with columns Sales and Date and the name will be the corresponding Account. The csv files will be saved in your currect working directory.

```<code>df = read.table(text = "
Account Sales   Date
1   10  1/1/2017
2   21  2/1/2017
3   23  3/1/2017
4   24  4/1/2017
4   24  5/1/2017
5   25  6/1/2017
4   25  7/1/2017
5   266 8/1/2017
6   556 9/1/2017
7   346 10/1/2017
5   42  11/1/2017
3   246 12/1/2017
2   356 1/1/2018
", header=T, stringsAsFactors=F)

library(tidyverse)

# create a dataset where data are split by account
# (print is not actually needed, but just to show you how it looks like)
df2 = df %>% group_by(Account) %>% nest() %>% print()

# # A tibble: 7 x 2
#     Account             data
#       <int>           <list>
#   1       1 <tibble [1 x 2]>
#   2       2 <tibble [2 x 2]>
#   3       3 <tibble [2 x 2]>
#   4       4 <tibble [3 x 2]>
#   5       5 <tibble [3 x 2]>
#   6       6 <tibble [1 x 2]>
#   7       7 <tibble [1 x 2]>

# map those 2 columns to a function that writes csv files
map2(df2$data, df2$Account,~ write.csv(.x, file=paste0(.y, ".csv")))
</code>```

Title: How to subset data as per account in R?

Body:
I am trying to subset data as per one column In R using for loop. All I want to look at the different accounts in different datasets.
In the data attached I want to subset using first variable which is Account.
Code:-

for i in 1:Length(Data$Account)
{

data<- subset(Train, Train$Account==i)

df<-data
}

Account Sales   Date
1   10  1/1/2017
2   21  2/1/2017
3   23  3/1/2017
4   24  4/1/2017
4   24  5/1/2017
5   25  6/1/2017
4   25  7/1/2017
5   266 8/1/2017
6   556 9/1/2017
7   346 10/1/2017
5   42  11/1/2017
3   246 12/1/2017
2   356 1/1/2018

My requirement should return something like this for Account 4:-

Account Sales   Date
4   24  4/1/2017
4   24  5/1/2017
4   25  7/1/2017

Body:
This approach will create multiple datasets with columns Sales and Date and the name will be the corresponding Account. The csv files will be saved in your currect working directory.

df = read.table(text = "
Account Sales   Date
1   10  1/1/2017
2   21  2/1/2017
3   23  3/1/2017
4   24  4/1/2017
4   24  5/1/2017
5   25  6/1/2017
4   25  7/1/2017
5   266 8/1/2017
6   556 9/1/2017
7   346 10/1/2017
5   42  11/1/2017
3   246 12/1/2017
2   356 1/1/2018
", header=T, stringsAsFactors=F)

library(tidyverse)

# create a dataset where data are split by account
# (print is not actually needed, but just to show you how it looks like)
df2 = df %>% group_by(Account) %>% nest() %>% print()

# # A tibble: 7 x 2
#     Account             data
#       <int>           <list>
#   1       1 <tibble [1 x 2]>
#   2       2 <tibble [2 x 2]>
#   3       3 <tibble [2 x 2]>
#   4       4 <tibble [3 x 2]>
#   5       5 <tibble [3 x 2]>
#   6       6 <tibble [1 x 2]>
#   7       7 <tibble [1 x 2]>

# map those 2 columns to a function that writes csv files
map2(df2$data, df2$Account,~ write.csv(.x, file=paste0(.y, ".csv")))


问:
The observer pattern is two modules or is one module?
We can say that the Observer pattern is two modules (maybe it depends on the context) ?

think: Subject is another module Observer another module (and they're related to each other. Well, we know that from the pattern).

答:
Well observer pattern can be both one module or two module. It's not specific like that. But observer pattern is mostly useful when two associated classes are in different modules or subsystem. Morever, it is used to reduce interconnection between classes and let objects communicate with each other without knowing other object's classes.

You might have already studied this picture as per my guess. Here, Subject and Observer are two different classes or modules. Observer is mostly abstract class and ConcreteObserverA and ConcreteObserverB implement Observer class's method notify() to notify respective observers. Similarly, Subject class can handles methods similar to shown in the picture. Subject class generally contain information to notify to observer.

In this way, you can split modules.

Furthermore, you can study more about Observer Pattern from book "Object Oriented Software Engineering" by Timothy C.Lethbridge and Robert Lagniere.


问:
Accessing Object Properties in Array VBA

I cannot figure out how to access object properties in an array using VBA. I have created an array like:

```<code>Dim objectArray(10) as Variant
Dim counter as Integer            'used to move to next element in array
</code>```

Next, I declared an object and store it in the array:

```<code>Dim object as Variant
objectArray(0) = object           'object stored in array[0]
counter = counter + 1             'increment counter
</code>```

I want to pass the array to a function.

```<code>Call function(objectArray())
</code>```

That function receives the array of objects like:

```<code>Public function(objectArray() as Variant)
</code>```

So far, it seems to have worked when I have debugged it. My objectArray() seems to contain the object. When I store one object in the array, the debuger shows

```<code>objectArray(0)(1,1) .... 'this is in the Watch section of the debugger
</code>```

I want to access the properties of that object in the first position of the array. That object will contain a name, several values, and a date. I've been trying to access the properties on that object like

```<code>Dim separateVar as Variant             'declare new var to hold "name"

separateVar = objectArray(0)(1,1).Value
</code>```

However, when I run the macro, I get "Some Error Occured, 13, Type Mismatch". Am I accessing the object property values incorrectly?

Any help would be appreciated. Finding articles about accessing objects is easy, but finding ones about accessing their individual properties has been very difficult.

答:
Try this.</p>

```<code>Sub T()
    Dim objInner1(1) As String
        objInner1(0) = "Hello"
        objInner1(1) = "World 1"

    Dim objInner2(1) As String
        objInner2(0) = "Hello"
        objInner2(1) = "World 2"

    Dim objInner3(1) As String
        objInner3(0) = "Hello"
        objInner3(1) = "World 3"

    Dim objOuter(2) As Variant
        objOuter(0) = objInner1
        objOuter(1) = objInner2
        objOuter(2) = objInner3

    PrintArray objOuter
End Sub

Sub PrintArray(objArray As Variant)
    Dim idx As Long
    For idx = LBound(objArray) To UBound(objArray)
        Debug.Print objArray(idx)(0) & " " & objArray(idx)(1)
    Next idx
End Sub

'Hello World 1
'Hello World 2
'Hello World 3
</code>```

Body:
I cannot figure out how to access object properties in an array using VBA. I have created an array like:

Dim objectArray(10) as Variant
Dim counter as Integer            'used to move to next element in array

Next, I declared an object and store it in the array:

Dim object as Variant
objectArray(0) = object           'object stored in array[0]
counter = counter + 1             'increment counter

I want to pass the array to a function.

Call function(objectArray())

That function receives the array of objects like:

Public function(objectArray() as Variant)

So far, it seems to have worked when I have debugged it. My objectArray() seems to contain the object. When I store one object in the array, the debuger shows

objectArray(0)(1,1) .... 'this is in the Watch section of the debugger

I want to access the properties of that object in the first position of the array. That object will contain a name, several values, and a date. I've been trying to access the properties on that object like

Dim separateVar as Variant             'declare new var to hold "name"

separateVar = objectArray(0)(1,1).Value

However, when I run the macro, I get "Some Error Occured, 13, Type Mismatch". Am I accessing the object property values incorrectly?

Any help would be appreciated. Finding articles about accessing objects is easy, but finding ones about accessing their individual properties has been very difficult.

Body:
Try this.

Sub T()
    Dim objInner1(1) As String
        objInner1(0) = "Hello"
        objInner1(1) = "World 1"

    Dim objInner2(1) As String
        objInner2(0) = "Hello"
        objInner2(1) = "World 2"

    Dim objInner3(1) As String
        objInner3(0) = "Hello"
        objInner3(1) = "World 3"

    Dim objOuter(2) As Variant
        objOuter(0) = objInner1
        objOuter(1) = objInner2
        objOuter(2) = objInner3

    PrintArray objOuter
End Sub

Sub PrintArray(objArray As Variant)
    Dim idx As Long
    For idx = LBound(objArray) To UBound(objArray)
        Debug.Print objArray(idx)(0) & " " & objArray(idx)(1)
    Next idx
End Sub

'Hello World 1
'Hello World 2
'Hello World 3


问:
Delete mysql-bin.**** files from /var/log/mysql
In the /var/log/mysql I found that are many large files

```<code>-rw-rw----  1 mysql adm  104875724 Nov 16  2016 mysql-bin.002982
    -rw-rw----  1 mysql adm  104900467 Nov 16  2016 mysql-bin.002983
 ...............
    -rw-rw----  1 mysql adm  104919093 Nov 23  2016 mysql-bin.003118
    -rw-rw----  1 mysql adm  104857817 Nov 23  2016 mysql-bin.003119
    -rw-rw----  1 mysql adm  104858056 Nov 23  2016 mysql-bin.003120
    -rw-rw----  1 mysql adm    9184221 Nov 23  2016 mysql-bin.003121
    -rw-rw----  1 mysql adm  104907549 Nov 23  2016 mysql-bin.003122
 ......
    -rw-rw----  1 mysql adm       6272 Nov 25  2016 mysql-bin.index
</code>```

Can I delete them?

Update

I don't use a replication for the database

答:
better not do it manually, you can do it through mysql.

PURGE BINARY LOGS TO 'binlogname';
PURGE BINARY LOGS BEFORE 'datetimestamp';`
```
<p>for example to delete everything before a week ago run:</p>
<pre class="lang-sql prettyprint-override"><code>PURGE BINARY LOGS BEFORE DATE(NOW() - INTERVAL 3 DAY) + INTERVAL 0 SECOND;
</code>```

or (even better) edit the my.cnf and set this parameter

```<code>[mysqld]
expire_logs_days=7
</code>```

Body:
In the /var/log/mysql I found that are many large files

-rw-rw----  1 mysql adm  104875724 Nov 16  2016 mysql-bin.002982
    -rw-rw----  1 mysql adm  104900467 Nov 16  2016 mysql-bin.002983
 ...............
    -rw-rw----  1 mysql adm  104919093 Nov 23  2016 mysql-bin.003118
    -rw-rw----  1 mysql adm  104857817 Nov 23  2016 mysql-bin.003119
    -rw-rw----  1 mysql adm  104858056 Nov 23  2016 mysql-bin.003120
    -rw-rw----  1 mysql adm    9184221 Nov 23  2016 mysql-bin.003121
    -rw-rw----  1 mysql adm  104907549 Nov 23  2016 mysql-bin.003122
 ......
    -rw-rw----  1 mysql adm       6272 Nov 25  2016 mysql-bin.index

Can I delete them?

Update

I don't use a replication for the database

Body:
better not do it manually, you can do it through mysql.

PURGE BINARY LOGS TO 'binlogname';
PURGE BINARY LOGS BEFORE 'datetimestamp';`

for example to delete everything before a week ago run:

PURGE BINARY LOGS BEFORE DATE(NOW() - INTERVAL 3 DAY) + INTERVAL 0 SECOND;

or (even better) edit the my.cnf and set this parameter

[mysqld]
expire_logs_days=7

ContentLicense: CC BY-SA 4.0


问:
Attributing values depending of another value w/ VBA ? Excel 2010
First of all, sorry if it already exists but I can't find the words in English to describe rapidly my question, hence I don't know how to search for it. Skip to third paragraph if you only need the question.

I'm using Excel to build a complete document about my work hours (arrived at, finished at, if I've been late and of how long was I late, overtime, etc etc).
I'm using VBA to smooth this task.

My workplace cuts everything into quarter of hours, which means that if you're late by one minute, you'll lose 15 minutes. If you work overtime for 14 minutes, it won't be seen as overtime. If I point at 07:45 (I'm using 24H format, not AM/PM) I'm fine. If I do it at 07:46 it'll be counted as 08:00. Same with 16:14, it'll show up as 16:00 (details are shown but on the corrected sheet used for salary, it'll show this way). If I do it at 16:15 I've confirmed my 15 minutes of overtime.

So while I could do some workarounds, what I've got in mind is shitcode, really. I'd like to know a good (clean) way to do this : I want for every timestamps I input to be cut in degressive quarter of hours (for instance, I want 17:12 to show up as 17:00 or 08:57 as 08:45).

Thanks for your help, if you didn't understand something or doubt about something I've said, it's probably because of the way I explained it, please ask whatever's needed :)

Update 01: Values are indeed Time processed by Excel, not Strings looking like a timestamp.

Update 02: Solved by @FunThomas with TimeSerial-command and some explanations. Thanks, I hope this can be of help for future reference, however I lack the words to write a better title for this problem.

答:
Assuming that you data is really time (and not a string that looks like time) and is stored in Cell A1, you can use a formula like this:

```<code>=TIME(HOUR(A1), INT(MINUTE(A1)/15) * 15, 0)
</code>```

The time-command gets three paramater (hour, minute, second).

The hour-part is simple.

For the minute, we make an integer division by 15 (resulting in values from 0..3) and multiply it back with 15 (to get 0, 15, 30 or 45).

The second is simply set to 0.

Update:
As VBA-function:

```<code>Function roundTime(t As Date) as date
    roundTime = TimeSerial(Hour(t), Int(Minute(t) / 15) * 15, 0)
End Function
</code>```

Body:
Assuming that you data is really time (and not a string that looks like time) and is stored in Cell A1, you can use a formula like this:

=TIME(HOUR(A1), INT(MINUTE(A1)/15) * 15, 0)

The time-command gets three paramater (hour, minute, second).

The hour-part is simple.

For the minute, we make an integer division by 15 (resulting in values from 0..3) and multiply it back with 15 (to get 0, 15, 30 or 45).

The second is simply set to 0.

Update:
As VBA-function:

Function roundTime(t As Date) as date
    roundTime = TimeSerial(Hour(t), Int(Minute(t) / 15) * 15, 0)
End Function


问:
Regex handle substring different
I have the following regex to check the syntax of a pseudo-function-call:

```<code>(\$[^\W]+\$)
</code>```

So if I have a path or something else I can check if the syntax of a containing function-call is valid.

A function-call always starts and ends with the $-char.

To verify the syntax of a path I have the following regex which matches the full path:

```<code>^([A-Za-z]\:|\\|\.)(\\[^\\\/:*?""<>|]*)+[\\]$
</code>```

I've tried to combine this two regular expression with | but then every functioncall which matches the path-syntax is valid.

I need a regex that checks the path-syntax and if there is a function call (leading and ending $) the function-call-syntax should be checked for that.

Valid strings

C:\temp\testfolder\

C:\$getTempPath$\testfolder\

C:\$getTempPath$\$getTestFolder$\

C:\programms (x86)\$getAppFolder$\

C:\temp\alternative$ folder name (for users)\

Invalid strings

C:\$getPrograms(x86)$\testfolder\

C:\$my function$\test\

答:
The regex provided by Wiktor Stribiżew may work if tweaked a little:

```<code>^(?:[A-Za-z]:|[\\.])(?:\\(?:\$\w+\$|(?!\$[^\\\/:*?"<>|]+\$\\)[^\\\/:*?"<>|]+))+\\$
</code>```

The changes are:

allow $ characters in path names

add a negative look-ahead expression to prevent it from allowing $ characters to surround path names

Title: Regex handle substring different

Body:
I have the following regex to check the syntax of a pseudo-function-call:

(\$[^\W]+\$)

So if I have a path or something else I can check if the syntax of a containing function-call is valid.

A function-call always starts and ends with the $-char.

To verify the syntax of a path I have the following regex which matches the full path:

^([A-Za-z]\:|\\|\.)(\\[^\\\/:*?""<>|]*)+[\\]$

I've tried to combine this two regular expression with | but then every functioncall which matches the path-syntax is valid.

I need a regex that checks the path-syntax and if there is a function call (leading and ending $) the function-call-syntax should be checked for that.

Valid strings

C:\temp\testfolder\

C:\$getTempPath$\testfolder\

C:\$getTempPath$\$getTestFolder$\

C:\programms (x86)\$getAppFolder$\

C:\temp\alternative$ folder name (for users)\

Invalid strings

C:\$getPrograms(x86)$\testfolder\

C:\$my function$\test\

Body:
The regex provided by Wiktor Stribiżew may work if tweaked a little:

^(?:[A-Za-z]:|[\\.])(?:\\(?:\$\w+\$|(?!\$[^\\\/:*?"<>|]+\$\\)[^\\\/:*?"<>|]+))+\\$

The changes are:

allow $ characters in path names

add a negative look-ahead expression to prevent it from allowing $ characters to surround path names


问:
How to fix error: redefinition of '__kstrtab_sched_setscheduler_nocheck'
I am compiling android kernel v3.10.108. I enabled kernel modules in defconfig and when tried to compile I came across this error. Here is the whole log on hastebin. Here is the kernel source. I am not an expert in programming languages and I need help. Kindly also point out why the error occurred too.</p>

答:
The kernel source is actually here. The error occurred because there were two commits that both added the line EXPORT(sched_setscheduler_nocheck); to the file "kernel/sched/core.c", leading to the redefinition errors. The commits are here and here.

The error occurred because whoever committed the changes did not check to make sure it still built properly when modules are enabled.

I suggest raising an issue on github to report the error.

You can fix the problem locally by deleting one of the problematic EXPORT(sched_setscheduler_nocheck); lines in "kernel/sched/core.c" or by reverting the second one of those two git commits locally.

EDIT:

I never noticed there were two errors in your build log. The other one is due to two commits applied to "fs/fs_struct.c" here and here.

EDIT 2

Subsequent linker errors are due to some things in the kernel .config being configured as modules (or possibly not configured at all) that are being linked to by other things configured as built-in.

Configure CONFIG_HW_RANDOM_MSM=y (not =m) to hopefully fix the "sensors_ssc.c" linker problems.

Configure CONFIG_IPV6=y (not =m) and CONFIG_NF_DEFRAG_IPV6=y (not =m) to hopefully fix the "ipc_router_security.c" linker problems.


问:
Publishing Web.Config to Azure removes Azure storage connection string
I've got a web.config that contains my SQL connection string and my Azure Blob storage connection string.

A Web.Config transformation replaces my Local SQL connection string with the Azure one.

When I publish the site to Azure, the Blob storage connection string is deleted and replaced with a duplicate SQL connection string, but with the blob storage string's name.

The only way I've found to fix is to log in via FTP and manually change the erroneous Storage connection string with the correct one from my local machine.

How do I get VS to publish my web config to Azure and leave it alone!!!

Web.Config

```<code>      <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="StorageConnectionString" connectionString="DefaultEndpointsProtocol=https;AccountName=;AccountKey=" />
  </connectionStrings>
</code>```

Web.Release.Config

```<code>  <connectionStrings>
<add name="DefaultConnection"
     connectionString="Server=.database.windows.net,1433;Database=;User ID=@;Password=!;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
     providerName="System.Data.SqlClient"
     xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</code>```

答:
I struggled with this problem this morning and I came up with a solution for VS2015/17.

So I have an Azure VM, and to publish my web app on this machine, I used the Web deploy to an Azure VM proposed by VS.

I put my connection strings in an external file, so the useful part of my web.config looks like this :

```<code>  </entityFramework>
  <connectionStrings configSource="ConnectionStrings.config">
  </connectionStrings>
</configuration>
</code>```

in order to prevent VS of adding some connection strings during publication (ADO.Net code first MSSQL database connection string in my case), you can edit the following file in your project :

...\MyProject\Properties\PublishProfiles\YourPublishProfile - WebDeploy.pubxml

In this file look into the ItemGroup part and edit it to delete the connection strings you don't need:

```<code><PublishDatabaseSettings>
  <Objects xmlns="">
    <ObjectGroup Name="MyProject.Models.MSSQL_DB" Order="1" Enabled="False">
      <Destination Path="" />
      <Object Type="DbCodeFirst">
        <Source Path="DBContext" DbContext="MyProject.Models.MSSQL_DB, MyProject" Origin="Convention" />
      </Object>
    </ObjectGroup>
  </Objects>
</PublishDatabaseSettings>
</PropertyGroup>
<ItemGroup>
    <here are some entries delete the ones you don't need/>
</ItemGroup>
</code>```

Be careful, if you add a file in this repertory, there is chances that it breaks the publication process on VS. Don't add file, just edit.

Body:
I've got a web.config that contains my SQL connection string and my Azure Blob storage connection string.

A Web.Config transformation replaces my Local SQL connection string with the Azure one.

When I publish the site to Azure, the Blob storage connection string is deleted and replaced with a duplicate SQL connection string, but with the blob storage string's name.

The only way I've found to fix is to log in via FTP and manually change the erroneous Storage connection string with the correct one from my local machine.

How do I get VS to publish my web config to Azure and leave it alone!!!

Web.Config

      <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="StorageConnectionString" connectionString="DefaultEndpointsProtocol=https;AccountName=;AccountKey=" />
  </connectionStrings>

Web.Release.Config

  <connectionStrings>
<add name="DefaultConnection"
     connectionString="Server=.database.windows.net,1433;Database=;User ID=@;Password=!;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
     providerName="System.Data.SqlClient"
     xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>

Body:
I struggled with this problem this morning and I came up with a solution for VS2015/17.

So I have an Azure VM, and to publish my web app on this machine, I used the Web deploy to an Azure VM proposed by VS.

I put my connection strings in an external file, so the useful part of my web.config looks like this :

  </entityFramework>
  <connectionStrings configSource="ConnectionStrings.config">
  </connectionStrings>
</configuration>

in order to prevent VS of adding some connection strings during publication (ADO.Net code first MSSQL database connection string in my case), you can edit the following file in your project :

...\MyProject\Properties\PublishProfiles\YourPublishProfile - WebDeploy.pubxml

In this file look into the ItemGroup part and edit it to delete the connection strings you don't need:

<PublishDatabaseSettings>
  <Objects xmlns="">
    <ObjectGroup Name="MyProject.Models.MSSQL_DB" Order="1" Enabled="False">
      <Destination Path="" />
      <Object Type="DbCodeFirst">
        <Source Path="DBContext" DbContext="MyProject.Models.MSSQL_DB, MyProject" Origin="Convention" />
      </Object>
    </ObjectGroup>
  </Objects>
</PublishDatabaseSettings>
</PropertyGroup>
<ItemGroup>
    <here are some entries delete the ones you don't need/>
</ItemGroup>

Be careful, if you add a file in this repertory, there is chances that it breaks the publication process on VS. Don't add file, just edit.


问:
Font Awesome icon size not increasing
I have Font Awesome icons installed on this site. The icons size isn't increasing even after adding the class to increase size.</p>

```<code><ul class="stay-connected-inner list-inline">
  <li><a href="#"><i class="fa fa-twitter fa-3" aria-hidden="true"></i></a></li>
  <li><a href="#"><i class="fa fa-linkedin fa-3" aria-hidden="true"></i></a></li>
  <li><a href="#"><i class="fa fa-medium fa-3" aria-hidden="true"></i></a></li>
  <li><a href="#"><i class="fa fa-linkedin fa-3" aria-hidden="true"></i></a></li>
</ul>
</code>```

答:
I had the same problem.  For some reason the fa class is overriding the fa-2x class on the awesome font library.  I found a blog that they knew it was an issue back in 2014 but haven't addressed it yet.  On my site I added the style class again and added !important which fixed my problem.

```

Title: Font Awesome icon size not increasing

Body:
I had the same problem.  For some reason the fa class is overriding the fa-2x class on the awesome font library.  I found a blog that they knew it was an issue back in 2014 but haven't addressed it yet.  On my site I added the style class again and added !important which fixed my problem.

<style>
      .fa-2x{
        font-size:2em !important;
    };
</style>


问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答:
char is a single char, eg 'h'

What you want is string pointers.

```<code> char *result[3];
</code>```

Remember if you do it this way you won't be able to change the contents of an individual string (it is a constant and stored in a different place.)

You could also do something like this

```<code> char *result[3];

 result[0] =  malloc(100 * sizeof(char));
 strcpy(result[0],"horse"); // or strncpy(result[0],5,"horse")
 etc
</code>```

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?

Body:
char is a single char, eg 'h'

What you want is string pointers.

 char *result[3];

Remember if you do it this way you won't be able to change the contents of an individual string (it is a constant and stored in a different place.)

You could also do something like this

 char *result[3];

 result[0] =  malloc(100 * sizeof(char));
 strcpy(result[0],"horse"); // or strncpy(result[0],5,"horse")
 etc


问:
No image appearing on pane, how to fix this?
I wrote this java application on NetBeans IDE 8.2 to show an image stored on my local directory in the same directory of the classes files directory (as stated in the documentation), but when running there is no image appearing on the scene although there is no exception,, anyone has any idea how to fix this??</p>

```<code>            import javafx.application.Application;
            import javafx.stage.Stage;
            import javafx.scene.Scene;
            import javafx.scene.layout.Pane;
            import javafx.scene.layout.HBox;
            import javafx.geometry.Insets;
            import javafx.scene.image.Image;
            import javafx.scene.image.ImageView;
            import javafx.geometry.Insets;
            import java.io.File;

            public class ShowImage extends Application{
                @Override
                public void start(Stage primaryStage) {
                    Pane pane = new HBox();
                    pane.setPadding(new Insets(5, 5, 5, 5));

                    Image image = new Image("image.jpg");
                    pane.getChildren().add(new ImageView(image));

                    ImageView imageView2 = new ImageView(image);
                    imageView2.setFitHeight(100);
                    imageView2.setFitWidth(100);
                    pane.getChildren().add(imageView2);

                    ImageView imageView3 = new ImageView(image);
                    imageView3.setRotate(90);
                    pane.getChildren().add(imageView3);

                    Scene scene = new Scene(pane, 300, 300);
                    primaryStage.setTitle("Show Image");
                    primaryStage.setScene(scene);
                    primaryStage.show();

                }
                public static void main(String[] args) {
                    Application.launch(args);
                }

            }
</code>```

答:
The final solution to this repeated problem is to create a new sub packadge from NetBeans under your packadge, name it "resources" for example and and put the your image in the directory of the sub package and edit the path in the code as this

```<code>Image image = new Image("resources/image.jpg");
</code>```

this will avoid the path issues, and route the file from package directly.

Body:
I wrote this java application on NetBeans IDE 8.2 to show an image stored on my local directory in the same directory of the classes files directory (as stated in the documentation), but when running there is no image appearing on the scene although there is no exception,, anyone has any idea how to fix this??

            import javafx.application.Application;
            import javafx.stage.Stage;
            import javafx.scene.Scene;
            import javafx.scene.layout.Pane;
            import javafx.scene.layout.HBox;
            import javafx.geometry.Insets;
            import javafx.scene.image.Image;
            import javafx.scene.image.ImageView;
            import javafx.geometry.Insets;
            import java.io.File;

            public class ShowImage extends Application{
                @Override
                public void start(Stage primaryStage) {
                    Pane pane = new HBox();
                    pane.setPadding(new Insets(5, 5, 5, 5));

                    Image image = new Image("image.jpg");
                    pane.getChildren().add(new ImageView(image));

                    ImageView imageView2 = new ImageView(image);
                    imageView2.setFitHeight(100);
                    imageView2.setFitWidth(100);
                    pane.getChildren().add(imageView2);

                    ImageView imageView3 = new ImageView(image);
                    imageView3.setRotate(90);
                    pane.getChildren().add(imageView3);

                    Scene scene = new Scene(pane, 300, 300);
                    primaryStage.setTitle("Show Image");
                    primaryStage.setScene(scene);
                    primaryStage.show();

                }
                public static void main(String[] args) {
                    Application.launch(args);
                }

            }

Body:
The final solution to this repeated problem is to create a new sub packadge from NetBeans under your packadge, name it "resources" for example and and put the your image in the directory of the sub package and edit the path in the code as this

Image image = new Image("resources/image.jpg");

this will avoid the path issues, and route the file from package directly.


问:
Is there any way I can pass dynamic data to a component in Angular?

I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComponent.ts

```<code>results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}
</code>```

ParentComponent.html

```<code><app-childComponent [dataNeeded]=results></app-childComponent>
</code>```

ChildComponent.ts

```<code>@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}
</code>```

So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?

答:
Why not using the Observable with the async pipe.
If you want to console-log that value use a setter.
The async pipe will also take care about unsubscribing.

```<code>results: Observable<any[]>;
ngOnInit() {
  this.results = this.http.get('url');
}
</code>```

In the HTML

```<code><app-childComponent [dataNeeded]="results | async"></app-childComponent>
</code>```

And in your child component

```<code>@Input('dataNeeded')
set dataNeeded(val: any[]) {
  console.log(val);
}
</code>```

Body:
I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComponent.ts

results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}

ParentComponent.html

<app-childComponent [dataNeeded]=results></app-childComponent>

ChildComponent.ts

@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}

So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?

Body:
Why not using the Observable with the async pipe.
If you want to console-log that value use a setter.
The async pipe will also take care about unsubscribing.

results: Observable<any[]>;
ngOnInit() {
  this.results = this.http.get('url');
}

In the HTML

<app-childComponent [dataNeeded]="results | async"></app-childComponent>

And in your child component

@Input('dataNeeded')
set dataNeeded(val: any[]) {
  console.log(val);
}


问:
For deep learning, With activation relu the output becomes NAN during training while is normal with tanh
The neural network I trained is the critic network for deep reinforcement learning. The problem is when one of the layer's activation is set to be relu or elu, the output would be nan after some training step, while the output is normal if the activation is tanh. And the code is as follows(based on tensorflow):

with tf.variable_scope('critic'):

        self.batch_size = tf.shape(self.tfs)[0]

        l_out_x = denseWN(x=self.tfs, name='l3', num_units=self.cell_size, nonlinearity=tf.nn.tanh, trainable=True,shape=[det*step*2, self.cell_size])

        l_out_x1 = denseWN(x=l_out_x, name='l3_1', num_units=32, trainable=True,nonlinearity=tf.nn.tanh, shape=[self.cell_size, 32])
        l_out_x2 = denseWN(x=l_out_x1, name='l3_2', num_units=32, trainable=True,nonlinearity=tf.nn.tanh,shape=[32, 32])
        l_out_x3 = denseWN(x=l_out_x2, name='l3_3', num_units=32, trainable=True,shape=[32, 32])

        self.v = denseWN(x=l_out_x3, name='l4', num_units=1,  trainable=True, shape=[32, 1])
```

<p>Here is the code for basic layer construction:</p>

<pre class="lang-py prettyprint-override"><code>def get_var_maybe_avg(var_name, ema,  trainable, shape):
    if var_name=='V':
        initializer = tf.contrib.layers.xavier_initializer()
        v = tf.get_variable(name=var_name, initializer=initializer, trainable=trainable, shape=shape)
    if var_name=='g':
        initializer = tf.constant_initializer(1.0)
        v = tf.get_variable(name=var_name, initializer=initializer, trainable=trainable, shape=[shape[-1]])
    if var_name=='b':
        initializer = tf.constant_initializer(0.1)
        v = tf.get_variable(name=var_name, initializer=initializer, trainable=trainable, shape=[shape[-1]])
    if ema is not None:
        v = ema.average(v)
    return v

def get_vars_maybe_avg(var_names, ema, trainable, shape):
    vars=[]
    for vn in var_names:
        vars.append(get_var_maybe_avg(vn, ema, trainable=trainable, shape=shape))
    return vars

def denseWN(x, name, num_units, trainable, shape, nonlinearity=None, ema=None, **kwargs):
    with tf.variable_scope(name):
        V, g, b = get_vars_maybe_avg(['V', 'g', 'b'], ema, trainable=trainable, shape=shape)
        x = tf.matmul(x, V)
        scaler = g/tf.sqrt(tf.reduce_sum(tf.square(V),[0]))
        x = tf.reshape(scaler,[1,num_units])*x + tf.reshape(b,[1,num_units])
        if nonlinearity is not None:
            x = nonlinearity(x)
        return x
</code>```

Here is the code to train the network:

self.tfdc_r = tf.placeholder(tf.float32, [None, 1], 'discounted_r')
self.advantage = self.tfdc_r - self.v
l1_regularizer = tf.contrib.layers.l1_regularizer(scale=0.005, scope=None)
self.weights = tf.trainable_variables()
regularization_penalty_critic = tf.contrib.layers.apply_regularization(l1_regularizer, self.weights)
self.closs = tf.reduce_mean(tf.square(self.advantage))
self.optimizer = tf.train.RMSPropOptimizer(0.0001, 0.99, 0.0, 1e-6)
self.grads_and_vars = self.optimizer.compute_gradients(self.closs)
self.grads_and_vars = [[tf.clip_by_norm(grad,5), var] for grad, var in self.grads_and_vars if grad is not None]
self.ctrain_op = self.optimizer.apply_gradients(self.grads_and_vars, global_step=tf.contrib.framework.get_global_step())
```

答:
Looks like you're facing the problem of exploding gradients with ReLu activation function (that what NaN means -- very big activations). There are several techniques to deal with this issue, e.g. batch normalization (changes the network architecture) or a delicate variable initialization (that's what I'd try first).

You are using Xavier initialization for V variables in different layers, which indeed works fine for logistic sigmoid activation (see the paper by Xavier Glorot and Yoshua Bengio), or, in other words, tanh.

The preferred initialization strategy for the ReLU activation function (and its variants, including ELU) is He initialization. In tensorflow it's implemented via tf.variance_scaling_initializer:

initializer = tf.variance_scaling_initializer()
v = tf.get_variable(name=var_name, initializer=initializer, ...)
```

You might also want to try smaller values for b and g variables, but it's hard to say the exact value just by looking at your model. If nothing helps, consider adding batch-norm layers to your model to control activation distribution.

Body:
The neural network I trained is the critic network for deep reinforcement learning. The problem is when one of the layer's activation is set to be relu or elu, the output would be nan after some training step, while the output is normal if the activation is tanh. And the code is as follows(based on tensorflow):

with tf.variable_scope('critic'):

        self.batch_size = tf.shape(self.tfs)[0]

        l_out_x = denseWN(x=self.tfs, name='l3', num_units=self.cell_size, nonlinearity=tf.nn.tanh, trainable=True,shape=[det*step*2, self.cell_size])

        l_out_x1 = denseWN(x=l_out_x, name='l3_1', num_units=32, trainable=True,nonlinearity=tf.nn.tanh, shape=[self.cell_size, 32])
        l_out_x2 = denseWN(x=l_out_x1, name='l3_2', num_units=32, trainable=True,nonlinearity=tf.nn.tanh,shape=[32, 32])
        l_out_x3 = denseWN(x=l_out_x2, name='l3_3', num_units=32, trainable=True,shape=[32, 32])

        self.v = denseWN(x=l_out_x3, name='l4', num_units=1,  trainable=True, shape=[32, 1])

Here is the code for basic layer construction:

def get_var_maybe_avg(var_name, ema,  trainable, shape):
    if var_name=='V':
        initializer = tf.contrib.layers.xavier_initializer()
        v = tf.get_variable(name=var_name, initializer=initializer, trainable=trainable, shape=shape)
    if var_name=='g':
        initializer = tf.constant_initializer(1.0)
        v = tf.get_variable(name=var_name, initializer=initializer, trainable=trainable, shape=[shape[-1]])
    if var_name=='b':
        initializer = tf.constant_initializer(0.1)
        v = tf.get_variable(name=var_name, initializer=initializer, trainable=trainable, shape=[shape[-1]])
    if ema is not None:
        v = ema.average(v)
    return v

def get_vars_maybe_avg(var_names, ema, trainable, shape):
    vars=[]
    for vn in var_names:
        vars.append(get_var_maybe_avg(vn, ema, trainable=trainable, shape=shape))
    return vars

def denseWN(x, name, num_units, trainable, shape, nonlinearity=None, ema=None, **kwargs):
    with tf.variable_scope(name):
        V, g, b = get_vars_maybe_avg(['V', 'g', 'b'], ema, trainable=trainable, shape=shape)
        x = tf.matmul(x, V)
        scaler = g/tf.sqrt(tf.reduce_sum(tf.square(V),[0]))
        x = tf.reshape(scaler,[1,num_units])*x + tf.reshape(b,[1,num_units])
        if nonlinearity is not None:
            x = nonlinearity(x)
        return x

Here is the code to train the network:

self.tfdc_r = tf.placeholder(tf.float32, [None, 1], 'discounted_r')
self.advantage = self.tfdc_r - self.v
l1_regularizer = tf.contrib.layers.l1_regularizer(scale=0.005, scope=None)
self.weights = tf.trainable_variables()
regularization_penalty_critic = tf.contrib.layers.apply_regularization(l1_regularizer, self.weights)
self.closs = tf.reduce_mean(tf.square(self.advantage))
self.optimizer = tf.train.RMSPropOptimizer(0.0001, 0.99, 0.0, 1e-6)
self.grads_and_vars = self.optimizer.compute_gradients(self.closs)
self.grads_and_vars = [[tf.clip_by_norm(grad,5), var] for grad, var in self.grads_and_vars if grad is not None]
self.ctrain_op = self.optimizer.apply_gradients(self.grads_and_vars, global_step=tf.contrib.framework.get_global_step())

Body:
Looks like you're facing the problem of exploding gradients with ReLu activation function (that what NaN means -- very big activations). There are several techniques to deal with this issue, e.g. batch normalization (changes the network architecture) or a delicate variable initialization (that's what I'd try first).

You are using Xavier initialization for V variables in different layers, which indeed works fine for logistic sigmoid activation (see the paper by Xavier Glorot and Yoshua Bengio), or, in other words, tanh.

The preferred initialization strategy for the ReLU activation function (and its variants, including ELU) is He initialization. In tensorflow it's implemented via tf.variance_scaling_initializer:

initializer = tf.variance_scaling_initializer()
v = tf.get_variable(name=var_name, initializer=initializer, ...)

You might also want to try smaller values for b and g variables, but it's hard to say the exact value just by looking at your model. If nothing helps, consider adding batch-norm layers to your model to control activation distribution.


问:
How to add a cron job to a WordPress page?
How to add a cron job to a WordPress page?

I tried adding this code:

```<code><?php

add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
    $schedules['every_three_minutes'] = array(
        'interval'  => 180,
        'display'   => __( 'Every 3 Minutes', 'textdomain' )
    );
    return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
    wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}

// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func' );
function every_three_minutes_event_func() {
    // do something

    echo "red";
}
?>
</code>```

into page-price.php

It should be printed every 3 minutes.

But this doesn't work.

答:
A cron job cannot be applied to a page. A cron job is some code which only affects the server side. Furthermore WordPress doesn't have real cron jobs by default. In WordPress the cron job tasks are triggered, if someone visits your website and the interval has passed, but the cron job execution is indepentend from the site visit (see part "Description" of wp_schedule_event()). Normally cron jobs would be triggered by the operating system of your server.

If you want something to be done on a page, you have to use a javascript based solution (see setInterval()). In the javascript function you can use ajax, if you need to execute server-side code and get information from your server.

Body:
How to add a cron job to a WordPress page?

I tried adding this code:

<?php

add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
    $schedules['every_three_minutes'] = array(
        'interval'  => 180,
        'display'   => __( 'Every 3 Minutes', 'textdomain' )
    );
    return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
    wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}

// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func' );
function every_three_minutes_event_func() {
    // do something

    echo "red";
}
?>

into page-price.php

It should be printed every 3 minutes.

But this doesn't work.


问:
Jersey custom ExceptionMapper not used if exception occurs when processing request body
I'm facing a tricky behavior from my REST resource.
The exposed method is expecting a complex json object :

```<code>@Path(RestURIConstant.NOTIFICATION_ROOT_URI)
@Component
@Scope("request")
public class NotificationResource implements RestURIConstant {

    /** Notification service. */
    @Autowired
    private INotificationService notificationService;

    @Path(RestURIConstant.COMPLEMENT_URI)
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response processNotification(final EventDTO event)
        throws BusinessException, TechnicalException {
        checkParameters(event);

        notificationService.processEvent(event);

        return Response.ok().build();
    }
}
</code>```

EventDTO has two enum fields : notificationType and eventType :

```<code>public class EventDTO {
    private ENotificationType notificationType;
    private EEventType eventType;
    private String eventDate;
    private String userName;

    //... getters, setters
}
</code>```

What I want is to map exception from any kind of data validation  error to get at the end a json response with an error code and error message. And after following jax-rs jersey: Exception Mapping for Enum bound FormParam :

So for the ENoticationType I wrote :

```<code>public enum ENotificationEventType {
    RULE,
    ALARM,
    ACK,
    INFO;

    @JsonCreator
    public static ENotificationEventType fromString(final String typeCode)
        throws BusinessException {
        if (typeCode == null) {
            throw new BusinessException(ValidationCode.VALUE_REQUIRED, "type");
        }
        try {
            return valueOf(typeCode);
        } catch (final IllegalArgumentException iae) {
            throw new BusinessException(ValidationCode.UNSUPPORTED_VALUE, "type", typeCode, Arrays.toString(values()));
        }
    }
}
</code>```

And for the Mapper I wrote :

```<code>@Provider
@Singleton
public class BusinessExceptionMapper implements ExceptionMapper<BusinessException> {

    @Override
    public Response toResponse(final BusinessException exception) {

        Status status = Status.INTERNAL_SERVER_ERROR;

        // If a validationCode error = unsupported version => CODE 410
        if (exception.getErrorCode().equals(ValidationCode.UNSUPPORTED_API_VERSION)) {
            status = Status.GONE;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(ValidationCode.class)) {
            // If a validationCode error then BAD_REQUEST (400) HTTP
            status = Status.BAD_REQUEST;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(NotFoundCode.class)) { // CODE 404
            status = Status.NOT_FOUND;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(SecurityCode.class)) { // CODE 401
            status = Status.UNAUTHORIZED;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(AdminSecurityCode.class)) { // CODE 401
            status = Status.UNAUTHORIZED;
        }

        return Response.status(status).type(MediaType.APPLICATION_JSON)
            .entity(ErrorMessageHelper.createErrorMessageHelper(
                    exception.getErrorCode(), exception.getMessage()))
                    .build();
}
</code>```

And my application-context contains <context:component-scan base-package=" com.technicolor.hovis.backend.rest, com.technicolor.hovis.admin.rest" />

I already read several answers to questions relative to Exception mapping in jersey but in my case, it's not that the mapping is not recognized but that it's not applied in all cases :

the exceptions thrown by checkParameters are mapped and the result is as expected

but if an invalid enum is sent, the @JsonCreator method is called, throw the same type of exception but this one is not mapped as expected.

So The response looks like :

 <data contentType="text/plain;charset=UTF-8" contentLength="176">
      <![CDATA[Unsupported type value : 'ALARN'. Expected values are [RULE, ALARM, ACK, INFO] (through reference chain: EventDTO["type"])]]>
</data>```
</div>
</div>
</p>

<p>And not the expected :</p>

```{
   "code": 6,
   "message": "Unsupported type value : 'ALARN'. Expected values are [RULE, ALARM, ACK, INFO]"
}
```

Any idea ?

Cyril

答:
I noticed that when I throw a checked exception in JSONCreator (just like you did), Jackson catches it and wraps it in IllegalArgumentException, so IllegalArgumentException ends up in ExceptionMapper.

Maybe this was cause of your problems?

Body:
I'm facing a tricky behavior from my REST resource.
The exposed method is expecting a complex json object :

@Path(RestURIConstant.NOTIFICATION_ROOT_URI)
@Component
@Scope("request")
public class NotificationResource implements RestURIConstant {

    /** Notification service. */
    @Autowired
    private INotificationService notificationService;

    @Path(RestURIConstant.COMPLEMENT_URI)
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response processNotification(final EventDTO event)
        throws BusinessException, TechnicalException {
        checkParameters(event);

        notificationService.processEvent(event);

        return Response.ok().build();
    }
}

EventDTO has two enum fields : notificationType and eventType :

public class EventDTO {
    private ENotificationType notificationType;
    private EEventType eventType;
    private String eventDate;
    private String userName;

    //... getters, setters
}

What I want is to map exception from any kind of data validation  error to get at the end a json response with an error code and error message. And after following jax-rs jersey: Exception Mapping for Enum bound FormParam :

So for the ENoticationType I wrote :

public enum ENotificationEventType {
    RULE,
    ALARM,
    ACK,
    INFO;

    @JsonCreator
    public static ENotificationEventType fromString(final String typeCode)
        throws BusinessException {
        if (typeCode == null) {
            throw new BusinessException(ValidationCode.VALUE_REQUIRED, "type");
        }
        try {
            return valueOf(typeCode);
        } catch (final IllegalArgumentException iae) {
            throw new BusinessException(ValidationCode.UNSUPPORTED_VALUE, "type", typeCode, Arrays.toString(values()));
        }
    }
}

And for the Mapper I wrote :

@Provider
@Singleton
public class BusinessExceptionMapper implements ExceptionMapper<BusinessException> {

    @Override
    public Response toResponse(final BusinessException exception) {

        Status status = Status.INTERNAL_SERVER_ERROR;

        // If a validationCode error = unsupported version => CODE 410
        if (exception.getErrorCode().equals(ValidationCode.UNSUPPORTED_API_VERSION)) {
            status = Status.GONE;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(ValidationCode.class)) {
            // If a validationCode error then BAD_REQUEST (400) HTTP
            status = Status.BAD_REQUEST;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(NotFoundCode.class)) { // CODE 404
            status = Status.NOT_FOUND;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(SecurityCode.class)) { // CODE 401
            status = Status.UNAUTHORIZED;
        } else if (exception.getErrorCode().getClass().isAssignableFrom(AdminSecurityCode.class)) { // CODE 401
            status = Status.UNAUTHORIZED;
        }

        return Response.status(status).type(MediaType.APPLICATION_JSON)
            .entity(ErrorMessageHelper.createErrorMessageHelper(
                    exception.getErrorCode(), exception.getMessage()))
                    .build();
}

And my application-context contains <context:component-scan base-package=" com.technicolor.hovis.backend.rest, com.technicolor.hovis.admin.rest" />

I already read several answers to questions relative to Exception mapping in jersey but in my case, it's not that the mapping is not recognized but that it's not applied in all cases :

the exceptions thrown by checkParameters are mapped and the result is as expected

but if an invalid enum is sent, the @JsonCreator method is called, throw the same type of exception but this one is not mapped as expected.

So The response looks like :

 <data contentType="text/plain;charset=UTF-8" contentLength="176">
      <![CDATA[Unsupported type value : 'ALARN'. Expected values are [RULE, ALARM, ACK, INFO] (through reference chain: EventDTO["type"])]]>
</data>

And not the expected :

{
   "code": 6,
   "message": "Unsupported type value : 'ALARN'. Expected values are [RULE, ALARM, ACK, INFO]"
}

Any idea ?

Cyril


问:
What are some software and techniques for extracting proper names from a text?
I have a large corpus of text-based documents (100,000+) from which I want to extract proper names (e.g. a person's name).

Could anyone recommend techniques and/or software that would be useful in accomplishing this goal. I'm not particularly interested in low-level text parsing, so much as I am in more high-level things such as recognizing and/or ranking.

答:
Are you looking for Named Entity Recognition? Take a look at the wikipedia article.

The Stanford NLP group has a decent ready-to-use package here, with both GPL and commerical licenses available.


问:
Can I have multiple databases on oracle express edition
Can I have multiple databases on oracle express edition? Please let me know what are steps to setup?</p>

答:
We were using separate virtual machine instances with Windows XP installed to create multiple oracle xe databases. However virtual machines consume too much memory for that simple task.

Now I'm using docker. Below you can find the docker image I'm currently using:

https://github.com/MaksymBilenko/docker-oracle-xe-11g

After you install docker to your computer, you can use the following commands to create the database:

```<code># Create a folder for data in your home folder or somewhere else
mkdir /home/sedran/mydb1

# Download the docker image
docker pull sath89/oracle-xe-11g

# Create and start a new container with oracle-xe running on it
docker run --name oracle11g_mydb1 -d -p 1522:1521 -p 49163:8080 -v /home/sedran/mydb1:/u01/app/oracle sath89/oracle-xe-11g
</code>```

Then you can connect to this DB from localhost:1522/XE

To create a second database, execute the following commands:

```<code>mkdir /home/sedran/mydb2
docker run --name oracle11g_mydb2 -d -p 1523:1521 -p 49164:8080 -v /home/sedran/mydb2:/u01/app/oracle sath89/oracle-xe-11g
</code>```

The new DB will listen to port 1523 on localhost.

Do not forget to assign different ports, names and data folders (volumes) to every container.

Body:
We were using separate virtual machine instances with Windows XP installed to create multiple oracle xe databases. However virtual machines consume too much memory for that simple task.

Now I'm using docker. Below you can find the docker image I'm currently using:

https://github.com/MaksymBilenko/docker-oracle-xe-11g

After you install docker to your computer, you can use the following commands to create the database:

# Create a folder for data in your home folder or somewhere else
mkdir /home/sedran/mydb1

# Download the docker image
docker pull sath89/oracle-xe-11g

# Create and start a new container with oracle-xe running on it
docker run --name oracle11g_mydb1 -d -p 1522:1521 -p 49163:8080 -v /home/sedran/mydb1:/u01/app/oracle sath89/oracle-xe-11g

Then you can connect to this DB from localhost:1522/XE

To create a second database, execute the following commands:

mkdir /home/sedran/mydb2
docker run --name oracle11g_mydb2 -d -p 1523:1521 -p 49164:8080 -v /home/sedran/mydb2:/u01/app/oracle sath89/oracle-xe-11g

The new DB will listen to port 1523 on localhost.

Do not forget to assign different ports, names and data folders (volumes) to every container.


问:
Laravel, @lang and strtolower()
I'm trying to convert a string to lowercase like this:

```<code>@lang(strtolower('header.home'))
</code>```

This not working. Any Idea? Thx.

答:
try this :

```<code>{{ strtolower(__('header.home')) }}
</code>```

for more info :

You may retrieve lines from language files using the __ helper function. The __ method accepts the file and key of the translation string as its first argument. For example, let's retrieve the welcome translation string from the resources/lang/messages.php language file:

```<code>echo __('messages.welcome');

echo __('I love programming.');
</code>```

Of course if you are using the Blade templating engine, you may use the {{ }} syntax to echo the translation string or use the @lang directive:

```<code>{{ __('messages.welcome') }}

@lang('messages.welcome')
</code>```

If the specified translation string does not exist, the __ function will simply return the translation string key. So, using the example above, the __ function would return messages.welcome if the translation string does not exist.

Title: Laravel, @lang and strtolower()

Body:
I'm trying to convert a string to lowercase like this:

@lang(strtolower('header.home'))

This not working. Any Idea? Thx.

Body:
try this :

{{ strtolower(__('header.home')) }}

for more info :

You may retrieve lines from language files using the __ helper function. The __ method accepts the file and key of the translation string as its first argument. For example, let's retrieve the welcome translation string from the resources/lang/messages.php language file:

echo __('messages.welcome');

echo __('I love programming.');

Of course if you are using the Blade templating engine, you may use the {{ }} syntax to echo the translation string or use the @lang directive:

{{ __('messages.welcome') }}

@lang('messages.welcome')

If the specified translation string does not exist, the __ function will simply return the translation string key. So, using the example above, the __ function would return messages.welcome if the translation string does not exist.


问:
How to configure Jacoco with SonarQube and Maven in Jenkins

I Am trying to enable Sonarqube code coverage scan. I work on a Maven project in Eclipse and have already setup a successful Jenkins-build including Sonar-scan.

I already succeeded in using Jacoco locally; I added the Jacoco plugin to the pom.xml and executed jacoco:prepare-agent test jacoco:report via Run As-> Maven build.... After that call the html reports were located in target\site\jacoco and they seem to be correct.

Now I need to make it work in Jenkins but I don't know how to correctly configure the build. Currently the maven goal clean package -fae and an Invoke Standalone Sonar Analysis build step are executed.
 I found out that sonar.jacoco.reportPath needs do be set, but I don't know where to set it or where to call the jacoco:report target. Also I am unsure whether I need to add the jacoco plugin to jenkins as well, or if it is sufficient to do so in the maven project.

Any help is much appreciated, also please let me know if there is anything I can do to improve my question.

答:
I finally made it work. In case someone has similar issues I am posting my solution here:

In Jenkins the properties sonar.junit.reportsPath and sonar.jacoco.reportPath need to be configured. No additional goals have to be executed in Jenkins.

In the projects pom.xml one needs to specify

```<code>    <properties>
       <jacoco-maven-plugin.version>0.7.4.201502262128</jacoco-maven-plugin.version>
    </properties>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.jacoco</groupId>
                                    <artifactId>jacoco-maven-plugin</artifactId>
                                    <versionRange>(,0.7.4.201502262128]</versionRange>
                                    <goals>
                                        <goal>prepare-agent</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore></ignore>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco-maven-plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

The goal prepare-agent has to be executed, but it first generates a

Resource Path Location Type Plugin execution not covered by lifecycle configuration

To resolve that, the  pluginManagement block is needed, since it ignores the upcoming issues. Here it is evident to use versionRange and not just version, also this specific version is required, later versions are not working here.

Body:
I finally made it work. In case someone has similar issues I am posting my solution here:

In Jenkins the properties sonar.junit.reportsPath and sonar.jacoco.reportPath need to be configured. No additional goals have to be executed in Jenkins.

In the projects pom.xml one needs to specify

    <properties>
       <jacoco-maven-plugin.version>0.7.4.201502262128</jacoco-maven-plugin.version>
    </properties>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.jacoco</groupId>
                                    <artifactId>jacoco-maven-plugin</artifactId>
                                    <versionRange>(,0.7.4.201502262128]</versionRange>
                                    <goals>
                                        <goal>prepare-agent</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore></ignore>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco-maven-plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The goal prepare-agent has to be executed, but it first generates a

Resource Path Location Type Plugin execution not covered by lifecycle configuration

To resolve that, the  pluginManagement block is needed, since it ignores the upcoming issues. Here it is evident to use versionRange and not just version, also this specific version is required, later versions are not working here.


问:
Apache Airflow "greedy" DAG execution
Situation:
We have a DAG (daily ETL process) with 20 tasks. Some tasks are independent and most have a dependency structure.

Problem:
When an independent task fails, Airflow stops the whole DAG execution and marks it as failed.

Question:
Would it be possible to force Airflow to keep executing the DAG as long as all dependencies are satisfied? This way one failed independent task would not block the whole execution of all the other streams.

It's seems like such a trivial and fundamental problem, I was really surprised that nobody else has an issue with that behaviour. (Maybe I'm just missing something)

答:
You can set the trigger rules for each individual operarors.

All operators have a trigger_rule argument which defines the rule by which the generated task get triggered. The default value for trigger_rule is all_success and can be defined as “trigger this task when all directly upstream tasks have succeeded”. All other rules described here are based on direct parent tasks and are values that can be passed to any operator while creating tasks:

```<code>all_success: (default) all parents have succeeded
all_failed: all parents are in a failed or upstream_failed state
all_done: all parents are done with their execution
one_failed: fires as soon as at least one parent has failed, it does not wait for all parents to be done
one_success: fires as soon as at least one parent succeeds, it does not wait for all parents to be done
</code>```

Title: Apache Airflow "greedy" DAG execution

Body:
You can set the trigger rules for each individual operarors.

All operators have a trigger_rule argument which defines the rule by which the generated task get triggered. The default value for trigger_rule is all_success and can be defined as “trigger this task when all directly upstream tasks have succeeded”. All other rules described here are based on direct parent tasks and are values that can be passed to any operator while creating tasks:

all_success: (default) all parents have succeeded
all_failed: all parents are in a failed or upstream_failed state
all_done: all parents are done with their execution
one_failed: fires as soon as at least one parent has failed, it does not wait for all parents to be done
one_success: fires as soon as at least one parent succeeds, it does not wait for all parents to be done


问:
Predefined squareroot function without using sqrt() from math.h in C
Homework question:

Cygwin GNU GDB

Cygwin GNU GCC

Attempting to establish the length of the hypotenuse C from the square root of A power of 2 and B power of 2.

Example input:

Enter the length of two sides of a right-angled triangle: 2.25  8.33

Answer:

The length of the hypotenuse is: 8.628523

Question: when I specify the same input as above, the result is not the same - output is 19.84.9596

Full code below:

```<code>float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}

int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}
</code>```

OwnerDisplayName: Nefeli

LastEditorDisplayName: Nefeli

Body:
Homework question:

Cygwin GNU GDB

Cygwin GNU GCC

Attempting to establish the length of the hypotenuse C from the square root of A power of 2 and B power of 2.

Example input:

Enter the length of two sides of a right-angled triangle: 2.25  8.33

Answer:

The length of the hypotenuse is: 8.628523

Question: when I specify the same input as above, the result is not the same - output is 19.84.9596

Full code below:

float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}

int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}

Body: I make the answer 8.628522469, i.e. 8.628522.

OwnerDisplayName: gkrogers


问:
How to style open file dialog box in Silverlight
I am not an SL developer myself, but before I invest in it, I want to make sure I get its capabilities and limitations. My question is is it possible to style (i.e. change the UI of) an open file dialog box? It would be nice to see a sample if possible.</p>

答:
I don't think that you can do that. You have no chance to change the title, or preset a path either.
(http://msdn.microsoft.com/en-us/library/system.windows.controls.openfiledialog(v=vs.95).aspx, Is there anyway to change title of OpenFileDialog in Silverlight 3?)</p>