问:
Piping to same c program using stdin and stdout
Let's say I have an executable called myProgram that reads from an input file and writes to an output file. A command line for this program looks like this:

```<code>./myProgram -o outputfile inputfile
</code>```

The argument to the -o option specifies an output file name; if no such file exists then the program will create it.

What I was wondering is whether I can execute myProgram multiple times, piping the output of the one instance to the input of the next. For example,

```<code>./myProgram inputfile | ./myProgram -o outputfile
</code>```

Is it possible to achieve this and if so, what would I have to implement? exec calls and forking? just simple read and write calls?

答:
The short answer is: yes, you can do this.

However, your program should then read its input from stdin and write to stdout. This means, arguments as input or output file will no longer be necessary.

```<code>./myProgram < inputfile > outputfile
</code>```

or, to illustrate the chaining,

```<code>./myProgram < inputfile | ./myProgram > outputfile
</code>```

A widely spread combination is to read from stdin if no input file is specified and write to stdout if no outputfile or outputfile "-" is passed at the command line. This provides maximum flexibility.

Having said that, if it is sensible to chain multiple instances of the same program depends of course largely on what this program does. For example, for a sorting program this doesn't seem to make much sense of course ;)

Body:
Let's say I have an executable called myProgram that reads from an input file and writes to an output file. A command line for this program looks like this:

./myProgram -o outputfile inputfile

The argument to the -o option specifies an output file name; if no such file exists then the program will create it.

What I was wondering is whether I can execute myProgram multiple times, piping the output of the one instance to the input of the next. For example,

./myProgram inputfile | ./myProgram -o outputfile

Is it possible to achieve this and if so, what would I have to implement? exec calls and forking? just simple read and write calls?

Body:
The short answer is: yes, you can do this.

However, your program should then read its input from stdin and write to stdout. This means, arguments as input or output file will no longer be necessary.

./myProgram < inputfile > outputfile

or, to illustrate the chaining,

./myProgram < inputfile | ./myProgram > outputfile

A widely spread combination is to read from stdin if no input file is specified and write to stdout if no outputfile or outputfile "-" is passed at the command line. This provides maximum flexibility.

Having said that, if it is sensible to chain multiple instances of the same program depends of course largely on what this program does. For example, for a sorting program this doesn't seem to make much sense of course ;)


来源: stackexchange

问:
Get minX, maxX, minY, maxY from multidimensional array
I have an array like this

```<code>var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]
</code>```

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

```<code>var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}
</code>```

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

```<code>var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}
</code>```

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)```

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete

答:
This sorts the array and grabs the first and last elements for the smallest and largest objects.

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
];

my_array.sort(function(a, b){ return a[0] - b[0]; });
var minX = my_array[0];
var maxX = my_array[my_array.length - 1];
my_array.sort(function(a, b){ return a[1] - b[1]; });
var minY = my_array[0];
var maxY = my_array[my_array.length - 1];

console.log(JSON.stringify({
  minX: minX,
  maxX: maxX,
  minY: minY,
  maxY: maxY
}));```

ContentLicense: CC BY-SA 3.0

Body:
I have an array like this

var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete


问:
Injecting several Spring Beans of the same class using application.properties
I have a security test driven by Spring.  I want to create a set of test users (currentUser, anotherUser, adminUser, etc).  The credentials for the users will be stored in an application.properties like so:

```<code>test.currentUser.username=user1
test.currentUser.password=secret
test.adminUser.username=admin
test.adminUser.password=admin_password
...
</code>```

There is a class that can construct an object for a user.  It looks something like this:

```<code>@Component
public class UserObject{
  public UserObject(
    @Value("${test.currentUser.username}") String username,
    @Value("${test.currentUser.password}") String password){
    //Use username and password to do some authentication stuff
  }
}
</code>```

The client test class looks something like this:

```<code>public class TestClass{
  @Autowired
  public TestClass(UserObject userObject){
  }
}
</code>```

How can the classes above be altered such that several UserObjects are somehow injected by Spring (and get config values from the application.properties file)?

答:
Try something like this :

```<code>test:
   users:
       - user1,secret1
       - user2,secret2
</code>```

Would be transformed into these properties:

```<code>test.users[0]={user1, secret1}
test.users[1]={user2, secret2}

@ConfigurationProperties(prefix="test")
public class Config {

    private List<String[]> users= new ArrayList<String[]>();

    public List<String[]> getUsers() {
        return this.servers;
    }
}
</code>```

24.6.1 Loading YAML

I didn't try it but it should work.

Body:
I have a security test driven by Spring.  I want to create a set of test users (currentUser, anotherUser, adminUser, etc).  The credentials for the users will be stored in an application.properties like so:

test.currentUser.username=user1
test.currentUser.password=secret
test.adminUser.username=admin
test.adminUser.password=admin_password
...

There is a class that can construct an object for a user.  It looks something like this:

@Component
public class UserObject{
  public UserObject(
    @Value("${test.currentUser.username}") String username,
    @Value("${test.currentUser.password}") String password){
    //Use username and password to do some authentication stuff
  }
}

The client test class looks something like this:

public class TestClass{
  @Autowired
  public TestClass(UserObject userObject){
  }
}

How can the classes above be altered such that several UserObjects are somehow injected by Spring (and get config values from the application.properties file)?

Body:
Try something like this :

test:
   users:
       - user1,secret1
       - user2,secret2

Would be transformed into these properties:

test.users[0]={user1, secret1}
test.users[1]={user2, secret2}

@ConfigurationProperties(prefix="test")
public class Config {

    private List<String[]> users= new ArrayList<String[]>();

    public List<String[]> getUsers() {
        return this.servers;
    }
}

24.6.1 Loading YAML

I didn't try it but it should work.


问:
Uncaught ReferenceError: $ is not defined?
How come this code throws an

Uncaught ReferenceError: $ is not defined

when it was OK before?

$(document).ready(function() {
    $('#tabs > ul').tabs({ fx: { opacity: 'toggle' } });
    $('#featuredvid > ul').tabs();
});
```

<p>Results in tabs don't close anymore.</p>

<p>jQuery is referenced in the header:</p>

<pre class="lang-php prettyprint-override"><code><script language="JavaScript" type="text/javascript" src="<?php echo get_option('siteurl') ?>/js/sprinkle.js"></script>
<script language="JavaScript" type="text/javascript" src="<?php echo get_option('siteurl') ?>/js/jquery-1.2.6.min.js"></script>
<script language="JavaScript" type="text/javascript" src="<?php echo get_option('siteurl') ?>/js/jquery-ui-personalized-1.5.2.packed.js"></script>
</code>```

答:
I had the exact same problem and none of these solutions above helped.
however, I just linked the .css files after the .js files and the problem miraculously disappeared. Hope this helps.

Body:
How come this code throws an

Uncaught ReferenceError: $ is not defined

when it was OK before?

$(document).ready(function() {
    $('#tabs > ul').tabs({ fx: { opacity: 'toggle' } });
    $('#featuredvid > ul').tabs();
});

Results in tabs don't close anymore.

jQuery is referenced in the header:

ContentLicense: CC BY-SA 4.0


问:
How to identify objects that don't need new to be created?
Usually, an object needs to be created using:

```<code>Object object = new Object();
</code>```

However, this isn't the case for the String class.
Right now I'm using Firebase Database. Instead of using new, they use .getInstance(). So the question is, how can I know if I need to use new or not for creating an object?

Thanks in advance.

答:
There are 2 way in which you can instantiate a class.

Using the new keyword, by calling the public constructor: new MyClsss().

Without using new keyword. This case indicates that we are using either the Singleton or the Factory pattern. In a Singleton pattern, the name of the class used to get the object is the same as that of the class of the object. For example, Connection con = Connection.getInstance(); Therefore, in Firebase the pattern that is used is Factory pattern.

So, to actually know how to instantiate a class, first you need to read the Java documentation for that class. But for learning purposes, i strongly recommend you to read more about creating new objects in java and design paterns.

The factory method pattern is a way to encapsulate object creation in Java. Without a factory method, we would simply call the class's constructor directly, as mentioned above MyClsss myClsss = new MyClsss();. The constructors of the class are marked as private, so they cannot be called except from inside the class. The factory method is marked as static so that it can be called without creating an object of the class. So the object returned by the factory method is created basically inside that class.

Body:
Usually, an object needs to be created using:

Object object = new Object();

However, this isn't the case for the String class.
Right now I'm using Firebase Database. Instead of using new, they use .getInstance(). So the question is, how can I know if I need to use new or not for creating an object?

Thanks in advance.


问:
Drag and Drop files to diferent WxFilePicker controls
I'm creating a GUI where I need to drag and drop different files into different wxFilePicker controls.
Based on this example wxPython: Dragging a file into window to get file path I was able to get the filepath from one file into one filepicker or that same filepath for all filepickers with:

```<code>def updateText(self, text):
        """
        Write text to the wx control
        """
        self.m_filePicker1.SetPath(text)
        self.m_filePicker2.SetPath(text)
        self.m_filePicker3.SetPath(text)
</code>```

Although it worked as it would be expected that solution its not useful.

Do I need to create different panels for each wxfilepicker control or there is another way to solve this problem?

Thank you in advance

Ivo

Here's the code

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division

import wx
import wx.xrc

########################################################################
class MyFileDropTarget(wx.FileDropTarget):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, window):
        """Constructor"""
        wx.FileDropTarget.__init__(self)
        self.window = window

    #----------------------------------------------------------------------
    def OnDropFiles(self, x, y, filenames):
        """
        When files are dropped, write where they were dropped and then
        the file paths themselves
        """
        #self.window.SetInsertionPointEnd()
        self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
                              (len(filenames), x, y))
        print filenames
        for filepath in filenames:
            self.window.updateText(filepath + '\n')

class Test_Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(500, 164),
                          style=wx.TAB_TRAVERSAL)

        bSizer122 = wx.BoxSizer(wx.VERTICAL)

        sbSizer2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"Model"), wx.VERTICAL)

        bSizer3 = wx.BoxSizer(wx.VERTICAL)

        bSizer4 = wx.BoxSizer(wx.VERTICAL)

        bSizer10 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer12 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText1 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"Model File", wx.DefaultPosition,
                                           wx.Size(100, -1), wx.ALIGN_CENTRE)
        self.m_staticText1.Wrap(-1)
        bSizer12.Add(self.m_staticText1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer12, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer13 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker1 = wx.FilePickerCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"Select a file",
                                               u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer13.Add(self.m_filePicker1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer13, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        bSizer4.Add(bSizer10, 0, wx.EXPAND, 5)

        bSizer11 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer14 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText2 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"Data File", wx.DefaultPosition,
                                           wx.Size(100, -1), wx.ALIGN_CENTRE)
        self.m_staticText2.Wrap(-1)
        bSizer14.Add(self.m_staticText2, 1, wx.ALL, 5)

        bSizer11.Add(bSizer14, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer15 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker2 = wx.FilePickerCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"Select a file",
                                               u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer15.Add(self.m_filePicker2, 0, wx.ALL | wx.EXPAND, 5)

        bSizer11.Add(bSizer15, 1, wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer4.Add(bSizer11, 1, wx.EXPAND, 5)

        bSizer111 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer141 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText21 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"DoF Labels", wx.DefaultPosition,
                                            wx.Size(100, -1), wx.ALIGN_CENTRE)
        self.m_staticText21.Wrap(-1)
        bSizer141.Add(self.m_staticText21, 1, wx.ALL | wx.EXPAND, 5)

        bSizer111.Add(bSizer141, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer151 = wx.BoxSizer(wx.VERTICAL)

        file_drop_target = MyFileDropTarget(self)

        self.m_filePicker3 = wx.FilePickerCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"Select a file",
                                               u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer151.Add(self.m_filePicker3, 0, wx.ALL | wx.EXPAND, 5)

        bSizer111.Add(bSizer151, 1, wx.EXPAND, 5)

        bSizer4.Add(bSizer111, 0, wx.EXPAND, 5)

        bSizer3.Add(bSizer4, 0, wx.EXPAND, 5)

        sbSizer2.Add(bSizer3, 1, wx.EXPAND, 5)

        bSizer122.Add(sbSizer2, 0, wx.ALL | wx.EXPAND, 5)

        self.SetSizer(bSizer122)
        self.Layout()

        self.m_filePicker1.SetDropTarget(file_drop_target)

    def updateText(self, text):
        """
        Write text to the wx control
        """
        self.m_filePicker1.SetPath(text)

    def __del__(self):
        pass

class Test_Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)

        bSizer239 = wx.BoxSizer(wx.VERTICAL)

        self.m_panel8 = Test_Panel(self)#, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
        #self.m_panel8 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
        bSizer239.Add(self.m_panel8, 1, wx.EXPAND
                      , 5)

        self.SetSizer(bSizer239)
        self.Layout()

        self.Centre(wx.BOTH)

    def __del__(self):
        pass

if __name__ == "__main__":
    app = wx.App(redirect=False)
    frame = Test_Frame(None)
    app.SetTopWindow(frame)
    frame.Show(True)
    app.MainLoop()
</code>```

答:
Here's my solution for the problem:</p>

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wx
import wx.xrc

class MyFileDropTarget(wx.FileDropTarget):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, window):
        """Constructor"""
        wx.FileDropTarget.__init__(self)
        self.window = window

    #----------------------------------------------------------------------
    def OnDropFiles(self, x, y, filenames):
        """
        When files are dropped, write where they were dropped and then
        the file paths themselves
        """
        #self.window.SetInsertionPointEnd()
        self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
                              (len(filenames), x, y))
        # print filenames
        for filepath in filenames:
            # self.window.updateText(filepath + '\n')
            self.window.updateText(filepath)

class Model_Data(wx.Panel):
    def __init__(self, parent, label):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(-1, -1),
                          style=wx.TAB_TRAVERSAL)

        bSizer122 = wx.BoxSizer(wx.VERTICAL)

        bSizer3 = wx.BoxSizer(wx.VERTICAL)

        bSizer10 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer12 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText1 = wx.StaticText(self, wx.ID_ANY, label, wx.DefaultPosition, wx.Size(100, -1),
        #self.m_staticText1 = wx.StaticText(self, wx.ID_ANY, u"Model File", wx.DefaultPosition, wx.Size(100, -1),
                                           wx.ALIGN_CENTRE)
        self.m_staticText1.Wrap(-1)
        bSizer12.Add(self.m_staticText1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer12, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer13 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker1 = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*",
                                               wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer13.Add(self.m_filePicker1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer13, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        ##############################################
        file_drop_target = MyFileDropTarget(self)
        self.m_filePicker1.SetDropTarget(file_drop_target)
        ##############################################

        bSizer3.Add(bSizer10, 0, wx.EXPAND, 5)

        bSizer122.Add(bSizer3, 0, wx.EXPAND, 5)

        self.SetSizer(bSizer122)
        self.Layout()

    def updateText(self, text):
        """
        Write text to the wx control
        """
        self.m_filePicker1.SetPath(text)

    def __del__(self):
        pass

class Generic_Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(-1, -1),
                          style=wx.TAB_TRAVERSAL)

        bSizer122 = wx.BoxSizer(wx.VERTICAL)

        bSizer3 = wx.BoxSizer(wx.VERTICAL)

        bSizer10 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer12 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText1 = wx.StaticText(self, wx.ID_ANY, u"Model File", wx.DefaultPosition, wx.Size(100, -1),
                                           wx.ALIGN_CENTRE)
        self.m_staticText1.Wrap(-1)
        bSizer12.Add(self.m_staticText1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer12, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer13 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker1 = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*",
                                               wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer13.Add(self.m_filePicker1, 1, wx.ALL, 5)

        bSizer10.Add(bSizer13, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer3.Add(bSizer10, 1, wx.EXPAND, 5)

        bSizer122.Add(bSizer3, 1, wx.EXPAND, 5)

        self.SetSizer(bSizer122)
        self.Layout()
        bSizer122.Fit(self)

    def __del__(self):
        pass

class Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetBackgroundColour('LightGrey')

        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)

        bSizer239 = wx.BoxSizer(wx.VERTICAL)

        sbSizer8 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"Model "), wx.VERTICAL)

        self.m_panel1 = Model_Data(sbSizer8.GetStaticBox(),'Model File')

        sbSizer8.Add(self.m_panel1, 0, wx.EXPAND | wx.ALL, 5)

        self.m_panel2 = Model_Data(sbSizer8.GetStaticBox(),'Model Data')
        sbSizer8.Add(self.m_panel2, 0, wx.ALL | wx.EXPAND, 5)

        self.m_panel3 = Model_Data(sbSizer8.GetStaticBox(),'DoF Labels')
            # wx.Panel(sbSizer8.GetStaticBox(), wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
            #                      wx.TAB_TRAVERSAL)

        sbSizer8.Add(self.m_panel3, 0, wx.EXPAND | wx.ALL, 5)

        bSizer239.Add(sbSizer8, 1, wx.ALL | wx.EXPAND, 5)

        self.SetSizer(bSizer239)
        self.Layout()

        self.Centre(wx.BOTH)

    def __del__(self):
        pass

if __name__ == "__main__":
    app = wx.App(redirect=False)
    frame = Frame(None)
    app.SetTopWindow(frame)
    frame.Show(True)
    app.MainLoop()
</code>```

Body:
I'm creating a GUI where I need to drag and drop different files into different wxFilePicker controls.
Based on this example wxPython: Dragging a file into window to get file path I was able to get the filepath from one file into one filepicker or that same filepath for all filepickers with:

def updateText(self, text):
        """
        Write text to the wx control
        """
        self.m_filePicker1.SetPath(text)
        self.m_filePicker2.SetPath(text)
        self.m_filePicker3.SetPath(text)

Although it worked as it would be expected that solution its not useful.

Do I need to create different panels for each wxfilepicker control or there is another way to solve this problem?

Thank you in advance

Ivo

Here's the code

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division

import wx
import wx.xrc

########################################################################
class MyFileDropTarget(wx.FileDropTarget):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, window):
        """Constructor"""
        wx.FileDropTarget.__init__(self)
        self.window = window

    #----------------------------------------------------------------------
    def OnDropFiles(self, x, y, filenames):
        """
        When files are dropped, write where they were dropped and then
        the file paths themselves
        """
        #self.window.SetInsertionPointEnd()
        self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
                              (len(filenames), x, y))
        print filenames
        for filepath in filenames:
            self.window.updateText(filepath + '\n')

class Test_Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(500, 164),
                          style=wx.TAB_TRAVERSAL)

        bSizer122 = wx.BoxSizer(wx.VERTICAL)

        sbSizer2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"Model"), wx.VERTICAL)

        bSizer3 = wx.BoxSizer(wx.VERTICAL)

        bSizer4 = wx.BoxSizer(wx.VERTICAL)

        bSizer10 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer12 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText1 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"Model File", wx.DefaultPosition,
                                           wx.Size(100, -1), wx.ALIGN_CENTRE)
        self.m_staticText1.Wrap(-1)
        bSizer12.Add(self.m_staticText1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer12, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer13 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker1 = wx.FilePickerCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"Select a file",
                                               u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer13.Add(self.m_filePicker1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer13, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        bSizer4.Add(bSizer10, 0, wx.EXPAND, 5)

        bSizer11 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer14 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText2 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"Data File", wx.DefaultPosition,
                                           wx.Size(100, -1), wx.ALIGN_CENTRE)
        self.m_staticText2.Wrap(-1)
        bSizer14.Add(self.m_staticText2, 1, wx.ALL, 5)

        bSizer11.Add(bSizer14, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer15 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker2 = wx.FilePickerCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"Select a file",
                                               u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer15.Add(self.m_filePicker2, 0, wx.ALL | wx.EXPAND, 5)

        bSizer11.Add(bSizer15, 1, wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer4.Add(bSizer11, 1, wx.EXPAND, 5)

        bSizer111 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer141 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText21 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"DoF Labels", wx.DefaultPosition,
                                            wx.Size(100, -1), wx.ALIGN_CENTRE)
        self.m_staticText21.Wrap(-1)
        bSizer141.Add(self.m_staticText21, 1, wx.ALL | wx.EXPAND, 5)

        bSizer111.Add(bSizer141, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer151 = wx.BoxSizer(wx.VERTICAL)

        file_drop_target = MyFileDropTarget(self)

        self.m_filePicker3 = wx.FilePickerCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, u"Select a file",
                                               u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer151.Add(self.m_filePicker3, 0, wx.ALL | wx.EXPAND, 5)

        bSizer111.Add(bSizer151, 1, wx.EXPAND, 5)

        bSizer4.Add(bSizer111, 0, wx.EXPAND, 5)

        bSizer3.Add(bSizer4, 0, wx.EXPAND, 5)

        sbSizer2.Add(bSizer3, 1, wx.EXPAND, 5)

        bSizer122.Add(sbSizer2, 0, wx.ALL | wx.EXPAND, 5)

        self.SetSizer(bSizer122)
        self.Layout()

        self.m_filePicker1.SetDropTarget(file_drop_target)

    def updateText(self, text):
        """
        Write text to the wx control
        """
        self.m_filePicker1.SetPath(text)

    def __del__(self):
        pass

class Test_Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)

        bSizer239 = wx.BoxSizer(wx.VERTICAL)

        self.m_panel8 = Test_Panel(self)#, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
        #self.m_panel8 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
        bSizer239.Add(self.m_panel8, 1, wx.EXPAND
                      , 5)

        self.SetSizer(bSizer239)
        self.Layout()

        self.Centre(wx.BOTH)

    def __del__(self):
        pass

if __name__ == "__main__":
    app = wx.App(redirect=False)
    frame = Test_Frame(None)
    app.SetTopWindow(frame)
    frame.Show(True)
    app.MainLoop()

Body:
Here's my solution for the problem:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wx
import wx.xrc

class MyFileDropTarget(wx.FileDropTarget):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, window):
        """Constructor"""
        wx.FileDropTarget.__init__(self)
        self.window = window

    #----------------------------------------------------------------------
    def OnDropFiles(self, x, y, filenames):
        """
        When files are dropped, write where they were dropped and then
        the file paths themselves
        """
        #self.window.SetInsertionPointEnd()
        self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
                              (len(filenames), x, y))
        # print filenames
        for filepath in filenames:
            # self.window.updateText(filepath + '\n')
            self.window.updateText(filepath)

class Model_Data(wx.Panel):
    def __init__(self, parent, label):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(-1, -1),
                          style=wx.TAB_TRAVERSAL)

        bSizer122 = wx.BoxSizer(wx.VERTICAL)

        bSizer3 = wx.BoxSizer(wx.VERTICAL)

        bSizer10 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer12 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText1 = wx.StaticText(self, wx.ID_ANY, label, wx.DefaultPosition, wx.Size(100, -1),
        #self.m_staticText1 = wx.StaticText(self, wx.ID_ANY, u"Model File", wx.DefaultPosition, wx.Size(100, -1),
                                           wx.ALIGN_CENTRE)
        self.m_staticText1.Wrap(-1)
        bSizer12.Add(self.m_staticText1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer12, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer13 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker1 = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*",
                                               wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer13.Add(self.m_filePicker1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer13, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        ##############################################
        file_drop_target = MyFileDropTarget(self)
        self.m_filePicker1.SetDropTarget(file_drop_target)
        ##############################################

        bSizer3.Add(bSizer10, 0, wx.EXPAND, 5)

        bSizer122.Add(bSizer3, 0, wx.EXPAND, 5)

        self.SetSizer(bSizer122)
        self.Layout()

    def updateText(self, text):
        """
        Write text to the wx control
        """
        self.m_filePicker1.SetPath(text)

    def __del__(self):
        pass

class Generic_Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(-1, -1),
                          style=wx.TAB_TRAVERSAL)

        bSizer122 = wx.BoxSizer(wx.VERTICAL)

        bSizer3 = wx.BoxSizer(wx.VERTICAL)

        bSizer10 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer12 = wx.BoxSizer(wx.VERTICAL)

        self.m_staticText1 = wx.StaticText(self, wx.ID_ANY, u"Model File", wx.DefaultPosition, wx.Size(100, -1),
                                           wx.ALIGN_CENTRE)
        self.m_staticText1.Wrap(-1)
        bSizer12.Add(self.m_staticText1, 1, wx.ALL | wx.EXPAND, 5)

        bSizer10.Add(bSizer12, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer13 = wx.BoxSizer(wx.VERTICAL)

        self.m_filePicker1 = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*",
                                               wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE)
        bSizer13.Add(self.m_filePicker1, 1, wx.ALL, 5)

        bSizer10.Add(bSizer13, 0, wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer3.Add(bSizer10, 1, wx.EXPAND, 5)

        bSizer122.Add(bSizer3, 1, wx.EXPAND, 5)

        self.SetSizer(bSizer122)
        self.Layout()
        bSizer122.Fit(self)

    def __del__(self):
        pass

class Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetBackgroundColour('LightGrey')

        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)

        bSizer239 = wx.BoxSizer(wx.VERTICAL)

        sbSizer8 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"Model "), wx.VERTICAL)

        self.m_panel1 = Model_Data(sbSizer8.GetStaticBox(),'Model File')

        sbSizer8.Add(self.m_panel1, 0, wx.EXPAND | wx.ALL, 5)

        self.m_panel2 = Model_Data(sbSizer8.GetStaticBox(),'Model Data')
        sbSizer8.Add(self.m_panel2, 0, wx.ALL | wx.EXPAND, 5)

        self.m_panel3 = Model_Data(sbSizer8.GetStaticBox(),'DoF Labels')
            # wx.Panel(sbSizer8.GetStaticBox(), wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
            #                      wx.TAB_TRAVERSAL)

        sbSizer8.Add(self.m_panel3, 0, wx.EXPAND | wx.ALL, 5)

        bSizer239.Add(sbSizer8, 1, wx.ALL | wx.EXPAND, 5)

        self.SetSizer(bSizer239)
        self.Layout()

        self.Centre(wx.BOTH)

    def __del__(self):
        pass

if __name__ == "__main__":
    app = wx.App(redirect=False)
    frame = Frame(None)
    app.SetTopWindow(frame)
    frame.Show(True)
    app.MainLoop()


问:
How to traverse graph created using ConfiguredPlanFactory in JanusGraph?
I have set up a Janusgraph Cluster with Cassandra + ES. The cluster has been set up to support ConfiguredGraphFactory. Also, I am connecting the gremlin cluster remotely. I have set up a client and am able to create a graph using :

```<code>client.submit(String.format("ConfiguredGraphFactory.create(\"%s\")", graphName));
</code>```

However, I am not able to get the traversalSource of the graph created using the gremlin driver. Do I have to create raw gremlin queries and traverse the graph using client.submit or is there a way to get it through the gremlin driver using Emptygraph.Instance().

答:
To get the remote traversal reference, you need to pass in a variable name that is bound to your graph traversal. This binding is usually done as part of the "globals" in your startup script when you start the remote server (the start up script is configured to run as part of the gremlin-server.yaml).

There is currently no inherent way to dynamically bind a variable to  a graph or traversal reference, but I plan on fixing this at some point.

A short term fix is to bind your graph and traversal references to a method that will be variably defined, and then create some mechanism to change the variable dynamically.

To further explain a potential solution:

Update your server's startup script to bind g to something variable:

```<code>globals << [g : DynamicBindingTool.getBoundGraphTraversal()]
</code>```

Create DynamicBindingTool, which has to do two things:

A. Provide a way to setBoundGraph() which may look something like:

```<code>setBoundGraph(graphName) {
    this.boundGraph = ConfiguredGraphFactory.open(graphName);
}
</code>```

B. Provide a way to getBoundGraphTraversal() which may look something like:

```<code>getBoundGraphTraversal() {
    this.boundGraph.traversal();
}
</code>```

You can include these sorts of functions in your start-up script or perhaps even create a separate jar that you attach to your Gremlin Server.

Finally, I would like to note that the proposed example solution does not take into account a multi-node JanusGraph cluster, i.e. your notion of the current bound graph would not be shared across the JG nodes. To make this a multi-node solution, you can update the functions to define the bound graph on an external database or even piggybacked on a JanusGraph graph.

For example, something like this would be a multi-node safe implementation:

setBoundGraph(graphName) {
    def managementGraph = ConfiguredGraphFactory.open("managementGraph");
    managementGraph.traversal().V().has("boundGraph", true).remove();
    def v = managementGraph.addVertex();
    v.property("boundGraph", true);
    v.property("graph.graphname", graphName);
}
```

<p>and:</p>

<pre class="lang-scala prettyprint-override"><code>getBoundGraphTraversal() {
    def managementGraph = ConfiguredGraphFactory.open("managementGraph");
    def graphName = managementGraph.traversal().V().has("boundGraph", true).values("graph.graphname");
    return ConfiguredGraphFactory.open(graphName).traversal();
}
</code>```

EDIT:

Unfortunately, the above "short-term trick" will not work as the global bindings are evaluated once and stored in a Map for the duration of the sever life cycle. Please see here for more information and updates on fixes: https://issues.apache.org/jira/browse/TINKERPOP-1839.

Body:
I have set up a Janusgraph Cluster with Cassandra + ES. The cluster has been set up to support ConfiguredGraphFactory. Also, I am connecting the gremlin cluster remotely. I have set up a client and am able to create a graph using :

client.submit(String.format("ConfiguredGraphFactory.create(\"%s\")", graphName));

However, I am not able to get the traversalSource of the graph created using the gremlin driver. Do I have to create raw gremlin queries and traverse the graph using client.submit or is there a way to get it through the gremlin driver using Emptygraph.Instance().

Body:
To get the remote traversal reference, you need to pass in a variable name that is bound to your graph traversal. This binding is usually done as part of the "globals" in your startup script when you start the remote server (the start up script is configured to run as part of the gremlin-server.yaml).

There is currently no inherent way to dynamically bind a variable to  a graph or traversal reference, but I plan on fixing this at some point.

A short term fix is to bind your graph and traversal references to a method that will be variably defined, and then create some mechanism to change the variable dynamically.

To further explain a potential solution:

Update your server's startup script to bind g to something variable:

globals << [g : DynamicBindingTool.getBoundGraphTraversal()]

Create DynamicBindingTool, which has to do two things:

A. Provide a way to setBoundGraph() which may look something like:

setBoundGraph(graphName) {
    this.boundGraph = ConfiguredGraphFactory.open(graphName);
}

B. Provide a way to getBoundGraphTraversal() which may look something like:

getBoundGraphTraversal() {
    this.boundGraph.traversal();
}

You can include these sorts of functions in your start-up script or perhaps even create a separate jar that you attach to your Gremlin Server.

Finally, I would like to note that the proposed example solution does not take into account a multi-node JanusGraph cluster, i.e. your notion of the current bound graph would not be shared across the JG nodes. To make this a multi-node solution, you can update the functions to define the bound graph on an external database or even piggybacked on a JanusGraph graph.

For example, something like this would be a multi-node safe implementation:

setBoundGraph(graphName) {
    def managementGraph = ConfiguredGraphFactory.open("managementGraph");
    managementGraph.traversal().V().has("boundGraph", true).remove();
    def v = managementGraph.addVertex();
    v.property("boundGraph", true);
    v.property("graph.graphname", graphName);
}

and:

getBoundGraphTraversal() {
    def managementGraph = ConfiguredGraphFactory.open("managementGraph");
    def graphName = managementGraph.traversal().V().has("boundGraph", true).values("graph.graphname");
    return ConfiguredGraphFactory.open(graphName).traversal();
}

EDIT:

Unfortunately, the above "short-term trick" will not work as the global bindings are evaluated once and stored in a Map for the duration of the sever life cycle. Please see here for more information and updates on fixes: https://issues.apache.org/jira/browse/TINKERPOP-1839.


问:
Check if a value exists in an Array object in JavaScript or Angular
I want to check if a value exist in an array object. Example:

I have this array:

```<code>[
    {id: 1, name: 'foo'},
    {id: 2, name: 'bar'},
    {id: 3, name: 'test'}
]
</code>```

And I want check if id = 2 exists here.

答:
Try this:</p>
```<code>let idx = array.findIndex(elem => elem.id === 2)
if (idx !== -1){
    // Your element exists
}
</code>```

Body:
I want to check if a value exist in an array object. Example:

I have this array:

[
    {id: 1, name: 'foo'},
    {id: 2, name: 'bar'},
    {id: 3, name: 'test'}
]

And I want check if id = 2 exists here.

Body:
Try this:

let idx = array.findIndex(elem => elem.id === 2)
if (idx !== -1){
    // Your element exists
}


问:
Gitignore: am I supposed to commit changes?
The question may seem absurd but I have a doubt. I'm not a git expert but I've use it every day for 5 years via the command-line so I'm pretty used to it.

Here is the scenario I can't solve:

A valuable colleague of mine started a WordPress project. He commited every single file in the repo... bad idea.

I come on the project now, clone the project (so my index is super clean). I start by adding few entries in the .gitignore file and commit it. In these rules, i have added "wp-config.php", the regular WP config file, which will change on each instance (local/preprod/prod). Easy.

But then I change this specific file, with my local config:

```<code>me@myproject$ vi wp-config.php
me@myproject$ git st
On branch develop
Your branch is up-to-date with 'origin/develop'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

      modified:   wp-config.php

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Why is he doing that? Why isn't he ignoring my files?
After few reading, I saw that some fellows does a file deletion, like :

```<code>git rm -r --cached wp-config.php
</code>```

Sure we can do that but then we have to commit the file deletion, cause the index is spotting the file as deleted (not physically ofc).
Is it the standard way to ignore an existing file in a git repo?

Thanks for your helps.

Here is a copy of my .gitignore file:

```<code># Ignore all logs files.
*.log

# Ignore the instance-based configuration.
wp-config.php

# Ignore cache, backups and uploaded files.
wp-content/advanced-cache.php
wp-content/backup-db/
wp-content/backups/
wp-content/blogs.dir/
wp-content/cache/
wp-content/upgrade/
wp-content/uploads/
wp-content/wp-cache-config.php
wp-content/plugins/hello.php

# Ignore some site-based root files.
/.htaccess
/sitemap.xml
/sitemap.xml.gz

# Ignore editor files.
.idea

# Ignore OS generated files.
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
</code>```

答:
You need to git rm --cached path/to/file and commit. If you have a lot of files, you can run the following from the repository root to remove the ignored files from the index: git rm --cached $(git ls-files -i --exclude-from=.gitignore)

The second command retrieves the ignored files as processed by .gitignore and inserts those paths into the git rm --cached command. Note if you have  nested .gitignores in child directories, you point to that .gitignore file which will granularly clean up those individual directories.

The reason his files aren't deleted inherently is because .gitignore prevents automatically adding files matching patterns in the .gitignore file. It will not inherently remove files which are already tracked in the index.

Body:
The question may seem absurd but I have a doubt. I'm not a git expert but I've use it every day for 5 years via the command-line so I'm pretty used to it.

Here is the scenario I can't solve:

A valuable colleague of mine started a WordPress project. He commited every single file in the repo... bad idea.

I come on the project now, clone the project (so my index is super clean). I start by adding few entries in the .gitignore file and commit it. In these rules, i have added "wp-config.php", the regular WP config file, which will change on each instance (local/preprod/prod). Easy.

But then I change this specific file, with my local config:

me@myproject$ vi wp-config.php
me@myproject$ git st
On branch develop
Your branch is up-to-date with 'origin/develop'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

      modified:   wp-config.php

no changes added to commit (use "git add" and/or "git commit -a")

Why is he doing that? Why isn't he ignoring my files?
After few reading, I saw that some fellows does a file deletion, like :

git rm -r --cached wp-config.php

Sure we can do that but then we have to commit the file deletion, cause the index is spotting the file as deleted (not physically ofc).
Is it the standard way to ignore an existing file in a git repo?

Thanks for your helps.

Here is a copy of my .gitignore file:

# Ignore all logs files.
*.log

# Ignore the instance-based configuration.
wp-config.php

# Ignore cache, backups and uploaded files.
wp-content/advanced-cache.php
wp-content/backup-db/
wp-content/backups/
wp-content/blogs.dir/
wp-content/cache/
wp-content/upgrade/
wp-content/uploads/
wp-content/wp-cache-config.php
wp-content/plugins/hello.php

# Ignore some site-based root files.
/.htaccess
/sitemap.xml
/sitemap.xml.gz

# Ignore editor files.
.idea

# Ignore OS generated files.
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db


问:
org.openqa.selenium.StaleElementReferenceException: element is not attached to the page document while iterating through a List
I don't know why this error shows up . Need help to fix it . Website i am working on :"http://freevideolectures.com/Course/3680/Pentaho-BI" . In this site </p>

```<code>List<WebElement> cl = d.findElements(By.xpath("//ul[@class='lecture_menu']/li/a"));
System.out.println(cl.size());

for(int e=0 ; e<=cl.size()-1; e++) {
        cl.get(e).click();// i think the error shows up here, the loop runs for e=0 ,
        Thread.sleep(1000);
        String q = d.findElement(By.xpath(".//*[@id='cs-about']/div/div[2]/div[2]/span/a")).getAttribute("href");
        System.out.println(q);
}
</code>```

<p>The loop runs once for e=0 , i am getting the output for that . After this the error shows up . error: stale element reference: element is not attached to the page document.  Help Please .  </p>

答:
Here is the sample code which opens the WebBrowser with URL as http://freevideolectures.com/Course/3680/Pentaho-BI, browses through all the links By.xpath("//ul[@class='lecture_menu']/li/a"), opens each of them in a new Tab prints the href and closes the Tab :

```<code>    driver.get("http://freevideolectures.com/Course/3680/Pentaho-BI");
    List<WebElement> elementList = driver.findElements(By.xpath("//ul[@class='lecture_menu']//li/a"));
    ArrayList<String> hrefList = new ArrayList<String>();
    for(WebElement element:elementList)
        hrefList.add(element.getAttribute("href"));
    String firstTab =driver.getWindowHandle();
    for(String myhref:hrefList)
    {
        ((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", myhref);
        Set<String> windowHandles = driver.getWindowHandles();
        Iterator<String> itr = windowHandles.iterator();
        while(itr.hasNext())
        {
            String next_tab = itr.next();
            if(!firstTab.equalsIgnoreCase(next_tab))
            {
                driver.switchTo().window(next_tab);
                Thread.sleep(1000);
                String q = driver.findElement(By.xpath(".//*[@id='cs-about']/div/div[2]/div[2]/span/a")).getAttribute("href");
                System.out.println(q);
                driver.close();
                driver.switchTo().window(firstTab);
            }
        }

    }
</code>```

The Output on my Console is :

```<code>http://keepvid.com/?url=http://www.youtube.com/watch?v=nYI7A9giFzE
http://keepvid.com/?url=http://www.youtube.com/watch?v=YZz8tphl9o4
http://keepvid.com/?url=http://www.youtube.com/watch?v=Z9gSDaQQscE
http://keepvid.com/?url=http://www.youtube.com/watch?v=V0swWI9v-aY
http://keepvid.com/?url=http://www.youtube.com/watch?v=aooocfhp8Pw
http://keepvid.com/?url=http://www.youtube.com/watch?v=pOgWNdmo6Dw
http://keepvid.com/?url=http://www.youtube.com/watch?v=C-M0ESbGmCI
http://keepvid.com/?url=http://www.youtube.com/watch?v=43s93a3aY58
http://keepvid.com/?url=http://www.youtube.com/watch?v=ZzPMJSjQK_U
http://keepvid.com/?url=http://www.youtube.com/watch?v=KWJqbhunb9I
http://keepvid.com/?url=http://www.youtube.com/watch?v=XmcFx0wIKHo
http://keepvid.com/?url=http://www.youtube.com/watch?v=ouU5QwW3YwA
http://keepvid.com/?url=http://www.youtube.com/watch?v=GK-mzNIKyj8
http://keepvid.com/?url=http://www.youtube.com/watch?v=vcrqycyAFGQ
http://keepvid.com/?url=http://www.youtube.com/watch?v=EYLuGIzH9Uo
http://keepvid.com/?url=http://www.youtube.com/watch?v=J8NbYQaQiPo
http://keepvid.com/?url=http://www.youtube.com/watch?v=L6hLwjF45jI
http://keepvid.com/?url=http://www.youtube.com/watch?v=yazzgQ6g2-o
http://keepvid.com/?url=http://www.youtube.com/watch?v=kgO_eJsQVgE
http://keepvid.com/?url=http://www.youtube.com/watch?v=6bYwsbk7e3k
http://keepvid.com/?url=http://www.youtube.com/watch?v=MWRrqjZg4r4
http://keepvid.com/?url=http://www.youtube.com/watch?v=aviCystupUI
http://keepvid.com/?url=http://www.youtube.com/watch?v=CSZ7FDkxGDs
http://keepvid.com/?url=http://www.youtube.com/watch?v=iyEFAQIOrQg
http://keepvid.com/?url=http://www.youtube.com/watch?v=JqfB90OfHTI
http://keepvid.com/?url=http://www.youtube.com/watch?v=CJbb6hNX5wA
http://keepvid.com/?url=http://www.youtube.com/watch?v=8k4u9mdmfi4
</code>```

Body:
I don't know why this error shows up . Need help to fix it . Website i am working on :"http://freevideolectures.com/Course/3680/Pentaho-BI" . In this site

List<WebElement> cl = d.findElements(By.xpath("//ul[@class='lecture_menu']/li/a"));
System.out.println(cl.size());

for(int e=0 ; e<=cl.size()-1; e++) {
        cl.get(e).click();// i think the error shows up here, the loop runs for e=0 ,
        Thread.sleep(1000);
        String q = d.findElement(By.xpath(".//*[@id='cs-about']/div/div[2]/div[2]/span/a")).getAttribute("href");
        System.out.println(q);
}

The loop runs once for e=0 , i am getting the output for that . After this the error shows up . error: stale element reference: element is not attached to the page document.  Help Please .

Body:
Here is the sample code which opens the WebBrowser with URL as http://freevideolectures.com/Course/3680/Pentaho-BI, browses through all the links By.xpath("//ul[@class='lecture_menu']/li/a"), opens each of them in a new Tab prints the href and closes the Tab :

    driver.get("http://freevideolectures.com/Course/3680/Pentaho-BI");
    List<WebElement> elementList = driver.findElements(By.xpath("//ul[@class='lecture_menu']//li/a"));
    ArrayList<String> hrefList = new ArrayList<String>();
    for(WebElement element:elementList)
        hrefList.add(element.getAttribute("href"));
    String firstTab =driver.getWindowHandle();
    for(String myhref:hrefList)
    {
        ((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", myhref);
        Set<String> windowHandles = driver.getWindowHandles();
        Iterator<String> itr = windowHandles.iterator();
        while(itr.hasNext())
        {
            String next_tab = itr.next();
            if(!firstTab.equalsIgnoreCase(next_tab))
            {
                driver.switchTo().window(next_tab);
                Thread.sleep(1000);
                String q = driver.findElement(By.xpath(".//*[@id='cs-about']/div/div[2]/div[2]/span/a")).getAttribute("href");
                System.out.println(q);
                driver.close();
                driver.switchTo().window(firstTab);
            }
        }

    }

The Output on my Console is :

http://keepvid.com/?url=http://www.youtube.com/watch?v=nYI7A9giFzE
http://keepvid.com/?url=http://www.youtube.com/watch?v=YZz8tphl9o4
http://keepvid.com/?url=http://www.youtube.com/watch?v=Z9gSDaQQscE
http://keepvid.com/?url=http://www.youtube.com/watch?v=V0swWI9v-aY
http://keepvid.com/?url=http://www.youtube.com/watch?v=aooocfhp8Pw
http://keepvid.com/?url=http://www.youtube.com/watch?v=pOgWNdmo6Dw
http://keepvid.com/?url=http://www.youtube.com/watch?v=C-M0ESbGmCI
http://keepvid.com/?url=http://www.youtube.com/watch?v=43s93a3aY58
http://keepvid.com/?url=http://www.youtube.com/watch?v=ZzPMJSjQK_U
http://keepvid.com/?url=http://www.youtube.com/watch?v=KWJqbhunb9I
http://keepvid.com/?url=http://www.youtube.com/watch?v=XmcFx0wIKHo
http://keepvid.com/?url=http://www.youtube.com/watch?v=ouU5QwW3YwA
http://keepvid.com/?url=http://www.youtube.com/watch?v=GK-mzNIKyj8
http://keepvid.com/?url=http://www.youtube.com/watch?v=vcrqycyAFGQ
http://keepvid.com/?url=http://www.youtube.com/watch?v=EYLuGIzH9Uo
http://keepvid.com/?url=http://www.youtube.com/watch?v=J8NbYQaQiPo
http://keepvid.com/?url=http://www.youtube.com/watch?v=L6hLwjF45jI
http://keepvid.com/?url=http://www.youtube.com/watch?v=yazzgQ6g2-o
http://keepvid.com/?url=http://www.youtube.com/watch?v=kgO_eJsQVgE
http://keepvid.com/?url=http://www.youtube.com/watch?v=6bYwsbk7e3k
http://keepvid.com/?url=http://www.youtube.com/watch?v=MWRrqjZg4r4
http://keepvid.com/?url=http://www.youtube.com/watch?v=aviCystupUI
http://keepvid.com/?url=http://www.youtube.com/watch?v=CSZ7FDkxGDs
http://keepvid.com/?url=http://www.youtube.com/watch?v=iyEFAQIOrQg
http://keepvid.com/?url=http://www.youtube.com/watch?v=JqfB90OfHTI
http://keepvid.com/?url=http://www.youtube.com/watch?v=CJbb6hNX5wA
http://keepvid.com/?url=http://www.youtube.com/watch?v=8k4u9mdmfi4


问:
How can I update multiple items with a shared customer number on a sharepoint list with AJAX?
I am trying to update a sp list with the following javascript/ajax. It succeeds until it gets to the ajax function, which is where it fails. It says the ItemID is not defined, when it is defined as:

```<code>var ItemId=item.ID
</code>```

Any help appreciated.

```<code>  <script type="text/javascript">
    function updateMultipleListItems(){
        var listName="Address Validation";
        //CustomerNumber.val("16");
        var CustomerNumber="CustNum";
        $.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID&$filter=Cust_x0020_Number eq 17",

            type: "GET",
            headers: {
                "Accept": "application/json;odata=verbose",
            },
            success: function (data) {
                for (var i = 0; i < data.d.results.length; i++) {
                    var item = data.d.results[i];
                    alert("1");
                    var itemType = GetItemTypeForListName(listName);
                    alert("2");
                    var itemId = item.ID;
                    alert("3");
                    var item = {
                    "__metadata": {
                    "type": 'SP.Data.Address%20ValidationListItem'
                    },
                    "assign": "testinput"
                    };
                    alert("4");
                    $.ajax({
                        url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
                        type: "POST",
                        contentType: "application/json;odata=verbose",
                        data: JSON.stringify(item),
                        headers: {
                            "Accept": "application/json;odata=verbose",
                            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                            "X-HTTP-Method": "MERGE",
                            "If-Match": "*"
                        },
                        success: function (data) {
                            console.log('Update Success');
                            alert("Success");

                        },
            //          error: function(xhr, status, error) {
            //          var err = eval("(" + xhr.responseText + ")");
            //          alert(err.Message);
    //}
                    });

                }
            },
            error: function (data) {
                alert("Error");
            }
        });
    }
    function GetItemTypeForListName(name) {
        return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
    }
    </script>
</code>```

What I'm trying to do:

I am trying to update all records in a list where the cust_number (a column in the list) field is 17 so that assign (another column) = "testinput".

eg:

Cust Number| Assign

17         | testinput

1          |

17         | testinput

答:
I'm afraid you made a simple typo.

On a certain point in your code you declare the following:

```<code>var itemId = item.ID;
</code>```

Later on you try to acces that same variable

```<code>url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
</code>```

However itemId != ItemId

Javascript is case sensitive.

Body:
I am trying to update a sp list with the following javascript/ajax. It succeeds until it gets to the ajax function, which is where it fails. It says the ItemID is not defined, when it is defined as:

var ItemId=item.ID

Any help appreciated.

What I'm trying to do:

I am trying to update all records in a list where the cust_number (a column in the list) field is 17 so that assign (another column) = "testinput".

eg:

Cust Number| Assign

17         | testinput

1          |

17         | testinput

Body:
I'm afraid you made a simple typo.

On a certain point in your code you declare the following:

var itemId = item.ID;

Later on you try to acces that same variable

url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",

However itemId != ItemId

Javascript is case sensitive.


问:
symfony shortCodes bundle
i have used laravel shortcodes (https://github.com/webwizo/laravel-shortcodes) with success, it is a nice bundle.

the question is: is there any bundle like this for symfony 3.x?

what this essentially do is take formatted string like [myString] with some optional parameters like [myString param1="abc" param2="def" ...] from a rendered blade / twig and looks for a controller / function etc. to resolve "myString". it passes the params to the controller, and the whole [...] stuff is replaced with the returned output. and it is done recursivly, so the result may contain another [myString2 ...] and so on. this is very useful in CMS building.

does anyone know anything like this for symfony?

答:
There is a bundle that looks exactly what you are searching for:

https://github.com/mweimerskirch/MWShortcodeBundle

Title: symfony shortCodes bundle


问:
What to do with required, but empty, implementations?
I have a google map class

```<code>class MapActivity : FragmentActivity(), OnMapReadyCallback, LocationListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {
</code>```

However i only use a few of the required functions provided by the implementations.
All the unused methods i just place at the bottom of the class, like this:

```<code>override fun onConnected(p0: Bundle?) {
    checkLocationPermission()
    val mLocationProvider = FusedLocationProviderClient(this)

    mLocationProvider.lastLocation.addOnCompleteListener { task ->
        goToLocation(task.result.latitude, task.result.longitude)
    }

}

override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderEnabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderDisabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionSuspended(p0: Int) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionFailed(p0: ConnectionResult) {
    //To change body of created functions use File | Settings | File Templates.
}
</code>```

Is there a better way to dismiss of these unwanted required functions?

答:
No you can't do anything (except create another class as suggested...), this the typcal tradeoff of the Interface Segregation Principle.

Anyway if you need to listen for location change update use

```<code>import com.google.android.gms.location.LocationListener;
</code>```

that tell you to implement only

```<code>void onLocationChanged(Location var1);
</code>```

I also suggest you to use #region and collapse code on your editor to clean visually your class.

Hope it helps.

Body:
I have a google map class

class MapActivity : FragmentActivity(), OnMapReadyCallback, LocationListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

However i only use a few of the required functions provided by the implementations.
All the unused methods i just place at the bottom of the class, like this:

override fun onConnected(p0: Bundle?) {
    checkLocationPermission()
    val mLocationProvider = FusedLocationProviderClient(this)

    mLocationProvider.lastLocation.addOnCompleteListener { task ->
        goToLocation(task.result.latitude, task.result.longitude)
    }

}

override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderEnabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderDisabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionSuspended(p0: Int) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionFailed(p0: ConnectionResult) {
    //To change body of created functions use File | Settings | File Templates.
}

Is there a better way to dismiss of these unwanted required functions?

Body:
No you can't do anything (except create another class as suggested...), this the typcal tradeoff of the Interface Segregation Principle.

Anyway if you need to listen for location change update use

import com.google.android.gms.location.LocationListener;

that tell you to implement only

void onLocationChanged(Location var1);

I also suggest you to use #region and collapse code on your editor to clean visually your class.

Hope it helps.


问:
sqrt: ValueError: math domain error
I'm facing a problem with "distance ValueError: math domain error" when using sqrt function in python.

Here is my code:

```<code>from math import sqrt

def distance(x1,y1,x2,y2):
    x3 = x2-x1
    xFinal = x3^2
    y3 = y2-y1
    yFinal = y3^2
    final = xFinal + yFinal
    d = sqrt(final)
    return d
</code>```

答:
Your issue is that exponentiation in Python is done using a ** b and not a ^ b (^ is bitwise XOR) which causes final to be a negative value, which causes a domain error.

Your fixed code:

```<code>def distance(x1, y1, x2, y2):
     return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** .5 # to the .5th power equals sqrt
</code>```

ContentLicense: CC BY-SA 2.5

Title: sqrt: ValueError: math domain error

Body:
I'm facing a problem with "distance ValueError: math domain error" when using sqrt function in python.

Here is my code:

from math import sqrt

def distance(x1,y1,x2,y2):
    x3 = x2-x1
    xFinal = x3^2
    y3 = y2-y1
    yFinal = y3^2
    final = xFinal + yFinal
    d = sqrt(final)
    return d

Body:
Your issue is that exponentiation in Python is done using a ** b and not a ^ b (^ is bitwise XOR) which causes final to be a negative value, which causes a domain error.

Your fixed code:

def distance(x1, y1, x2, y2):
     return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** .5 # to the .5th power equals sqrt


问:
Flask & AJAX: Failed to load resource: the server responded with a status of 400 (BAD REQUEST)
I am making a Flask application for sending e-mails. It worked pretty fine until I decided to implement a little bit of AJAX for making it more interactive.

I constantly get 400 ERROR and I tried a lot of combinations, but noting worked.

Some people advised me that the problem is in CSRF token, but when I put @csrf.exempt decorator, it is still not working. Please help!

Here is the source code:

1) Flask:

```<code>from flask import Flask, render_template, url_for, redirect, request, jsonify
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail, Message
from flask_wtf.csrf import CSRFProtect
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import InputRequired, Email, Length, AnyOf, Regexp
from flask_wtf import FlaskForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '**********'

mail = Mail(app)
Bootstrap(app)
csrf = CSRFProtect(app)

class LoginForm(FlaskForm):
    email = StringField('Email *', _name='email', validators=[InputRequired(), Email(message='I don\'t like your email.')], render_kw={"placeholder": "Please enter your email"})
    password = PasswordField('Password *', _name='password', validators=[InputRequired(), Length(min=5, max=10), AnyOf(['secret', 'password'])], render_kw={"placeholder": "Please enter your password"})

app.config.update(
    DEBUG = True,
    # EMAIL SETTINGS
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = 465,
    MAIL_USE_SSL = True,
    MAIL_USERNAME = 'jakov.kusic92@gmail.com',
    MAIL_PASSWORD = '********'
)

@csrf.exempt
@app.route('/', methods=['GET', 'POST'])
def mailForm():
    form = LoginForm()
    return render_template('loginForm.html', form=form)

@csrf.exempt
@app.route('/process', methods=['POST'])
def process():

    emailInput = request.form['email']
    passwordInput = request.form['password']

    str = 'Hello'
    msg = Message(
        subject=str,
        sender='jakov.kusic92@gmail.com',
        recipients=['jakov.kusic@gmail.com']
    )
    msg.body = """
    NEW USER INFO:
    Email: {}
    Password: {}
    """.format(emailInput, passwordInput)

    if emailInput and passwordInput:
        # mail.send(msg)
        return jsonify({'firstname' : emailInput, 'lastname' : passwordInput})

    return jsonify({'error' : 'Missing data!'})

if __name__ == '__main__':
    app.run(debug=True)
</code>```

2) HTML:

```<code>{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}
WTForms
{% endblock %}

{% block head %}
    {{ super() }}
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    <script src="{{ url_for('static', filename='form.js') }}" type="text/javascript"></script>

{% endblock %}

{% block content %}
<div class="container">

    <br><br> <!-- br tags are here used for vertical alingment -->
    <div class="col-md-4 col-md-offset-4 col-sm-8 col-sm-offset-2">
        <div class="well">
            <br>
            <h1 class="text-center">Welcome to the database website</h1>
            <br>
            <h2>Please enter your data below:</h2>
            <form>
                <dl>
                    {{ wtf.quick_form(form)}}
                    <input type="submit" value="Login" class="btn btn-info">
                </dl>
            </form>
            <div class="row">
                <div class="col-md-12">
                    <p class="text-muted"><strong>*</strong> These fields are required.</p>
                </div>
            </div>
            <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
            <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
        </div>
    </div>
</div>
{% endblock %}
</code>```

3) JS:

```<code>$('form').on('submit', function(event) {

    $.ajax({
        data : {
            firstnameInput : $('#firstnameInput').val(),
            lastnameInput : $('#lastnameInput').val(),
            emailInput : $('#emailInput').val(),
            passwordInput : $('#passwordInput').val(),
            messageInput : $('#messageInput').val()
        },
        type : 'POST',
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        },
        url : '/process',
        dataType: "json",
        contentType: "application/json"
    })
    .done(function(data) {
        $('#successAlert').text(data.firstname + data.lastname).show();
        $('#errorAlert').hide();
    });

    event.preventDefault();

});
</code>```

THIS IS WHAT I GET ON CHROME DEV TOOLS:

答:
You send ajax request with the following payload to /process URL:

```<code>    data : {
        firstnameInput : $('#firstnameInput').val(),
        lastnameInput : $('#lastnameInput').val(),
        emailInput : $('#emailInput').val(),
        passwordInput : $('#passwordInput').val(),
        messageInput : $('#messageInput').val()
    }
</code>```

And you try to handle the following params in process route:

```<code>emailInput = request.form['email']
passwordInput = request.form['password']
</code>```

But you don't send email and password keys in ajax request payload, you send emailInput and passwordInput params, so that's why Flask responds to you with 400 status code - there are no such params in POST body you're trying to use in the route function.

Your code should be:

```<code>@app.route('/process/', methods=['POST'])
def process():

    emailInput = request.form['emailInput']
    passwordInput = request.form['passwordInput']
</code>```

That's it.

Also it's recommended to use "/" at the end of the url:

```<code>@app.route('/process/', methods=['POST'])
</code>```

to avoid 302 redirect to /process/ url that Flask does.

It's recommended also to use request.form.get('param') instead of request.form['param'] because .get() function returns None if there is no specified key in dict instead of raising exception.

Body:
I am making a Flask application for sending e-mails. It worked pretty fine until I decided to implement a little bit of AJAX for making it more interactive.

I constantly get 400 ERROR and I tried a lot of combinations, but noting worked.

Some people advised me that the problem is in CSRF token, but when I put @csrf.exempt decorator, it is still not working. Please help!

Here is the source code:

1) Flask:

from flask import Flask, render_template, url_for, redirect, request, jsonify
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail, Message
from flask_wtf.csrf import CSRFProtect
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import InputRequired, Email, Length, AnyOf, Regexp
from flask_wtf import FlaskForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '**********'

mail = Mail(app)
Bootstrap(app)
csrf = CSRFProtect(app)

class LoginForm(FlaskForm):
    email = StringField('Email *', _name='email', validators=[InputRequired(), Email(message='I don\'t like your email.')], render_kw={"placeholder": "Please enter your email"})
    password = PasswordField('Password *', _name='password', validators=[InputRequired(), Length(min=5, max=10), AnyOf(['secret', 'password'])], render_kw={"placeholder": "Please enter your password"})

app.config.update(
    DEBUG = True,
    # EMAIL SETTINGS
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = 465,
    MAIL_USE_SSL = True,
    MAIL_USERNAME = 'jakov.kusic92@gmail.com',
    MAIL_PASSWORD = '********'
)

@csrf.exempt
@app.route('/', methods=['GET', 'POST'])
def mailForm():
    form = LoginForm()
    return render_template('loginForm.html', form=form)

@csrf.exempt
@app.route('/process', methods=['POST'])
def process():

    emailInput = request.form['email']
    passwordInput = request.form['password']

    str = 'Hello'
    msg = Message(
        subject=str,
        sender='jakov.kusic92@gmail.com',
        recipients=['jakov.kusic@gmail.com']
    )
    msg.body = """
    NEW USER INFO:
    Email: {}
    Password: {}
    """.format(emailInput, passwordInput)

    if emailInput and passwordInput:
        # mail.send(msg)
        return jsonify({'firstname' : emailInput, 'lastname' : passwordInput})

    return jsonify({'error' : 'Missing data!'})

if __name__ == '__main__':
    app.run(debug=True)

2) HTML:

{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}
WTForms
{% endblock %}

{% block head %}
    {{ super() }}
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

{% endblock %}

{% block content %}

Welcome to the database website

Please enter your data below:

            <form>

                    {{ wtf.quick_form(form)}}
                    <input type="submit" value="Login" class="btn btn-info">

            </form>

* These fields are required.

{% endblock %}

3) JS:

$('form').on('submit', function(event) {

    $.ajax({
        data : {
            firstnameInput : $('#firstnameInput').val(),
            lastnameInput : $('#lastnameInput').val(),
            emailInput : $('#emailInput').val(),
            passwordInput : $('#passwordInput').val(),
            messageInput : $('#messageInput').val()
        },
        type : 'POST',
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        },
        url : '/process',
        dataType: "json",
        contentType: "application/json"
    })
    .done(function(data) {
        $('#successAlert').text(data.firstname + data.lastname).show();
        $('#errorAlert').hide();
    });

    event.preventDefault();

});

THIS IS WHAT I GET ON CHROME DEV TOOLS:

Body:
You send ajax request with the following payload to /process URL:

    data : {
        firstnameInput : $('#firstnameInput').val(),
        lastnameInput : $('#lastnameInput').val(),
        emailInput : $('#emailInput').val(),
        passwordInput : $('#passwordInput').val(),
        messageInput : $('#messageInput').val()
    }

And you try to handle the following params in process route:

emailInput = request.form['email']
passwordInput = request.form['password']

But you don't send email and password keys in ajax request payload, you send emailInput and passwordInput params, so that's why Flask responds to you with 400 status code - there are no such params in POST body you're trying to use in the route function.

Your code should be:

@app.route('/process/', methods=['POST'])
def process():

    emailInput = request.form['emailInput']
    passwordInput = request.form['passwordInput']

That's it.

Also it's recommended to use "/" at the end of the url:

@app.route('/process/', methods=['POST'])

to avoid 302 redirect to /process/ url that Flask does.

It's recommended also to use request.form.get('param') instead of request.form['param'] because .get() function returns None if there is no specified key in dict instead of raising exception.


问:
Immutable JS - get a value inside a nested map
I'm using immutableJS, React/Redux and I have this map and I need to get the values of actions, so it will be like -> allRetrospectivesMap -> id -> current_stage -> actions

I have this code and it works, but it's super ugly, is there a better way to do it?

```<code>    class UserActionItems extends Component {
      render() {
        const { retrospectives } = this.props
        const actions = flatten(
          Object.keys(immutableHelpers.toJS(retrospectives))
          .map(key => retrospectives.get(key))
          .map(retro => immutableHelpers.toJS(retro.getIn(['current_stage', 'actions'])))
        ).value()

    return (
       <div>
          <ActionsList
          actions={actions[0]}
          users={[]}
          />
       </div>
    )
  }
}

    const mapStateToProps = ({ allRetrospectivesMap }) => ({
      retrospectives: allRetrospectivesMap
    })
</code>```

Thanks!!! :)

答:
You can do this with a getIn() method from immutable js.

```<code>const id = getId() // you've id from somewhere
const actions= state.getIn(['allRetrospectivesMap', id, 'current_stage', 'actions']); // Note: state is your immutable data.
</code>```

Read more about it here

Body:
I'm using immutableJS, React/Redux and I have this map and I need to get the values of actions, so it will be like -> allRetrospectivesMap -> id -> current_stage -> actions

I have this code and it works, but it's super ugly, is there a better way to do it?

    class UserActionItems extends Component {
      render() {
        const { retrospectives } = this.props
        const actions = flatten(
          Object.keys(immutableHelpers.toJS(retrospectives))
          .map(key => retrospectives.get(key))
          .map(retro => immutableHelpers.toJS(retro.getIn(['current_stage', 'actions'])))
        ).value()

    return (

          <ActionsList
          actions={actions[0]}
          users={[]}
          />

    )
  }
}

    const mapStateToProps = ({ allRetrospectivesMap }) => ({
      retrospectives: allRetrospectivesMap
    })

Thanks!!! :)

Body:
You can do this with a getIn() method from immutable js.

const id = getId() // you've id from somewhere
const actions= state.getIn(['allRetrospectivesMap', id, 'current_stage', 'actions']); // Note: state is your immutable data.

Read more about it here


问:
ClassCastException causing app to stop
i'm having difficult to solve this, i already search through some similar problems, but i don't have experience this kind one,
from my logcat i found this:

```<code>Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.dot.analyticsdemo.DemoApp
                                                                                at com.example.dot.analyticsdemo.MainActivity.onCreate(MainActivity.java:23)
</code>```

and this is my MainActivity:

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DemoApp application = (DemoApp) getApplication();
        mTracker = application.getDefaultTracker();

        // starts a new session and notification to google analytics
        mTracker.send(new HitBuilders.ScreenViewBuilder()
                .setNewSession()
                .build());
    }
</code>```

which line 23 is: DemoApp application = (DemoApp) getApplication();

this is the DemoApp:

```<code>package com.example.dot.analyticsdemo;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

public class DemoApp extends Application {

    private Tracker mTracker;

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {

        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);

            // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
            mTracker = analytics.newTracker(R.xml.global_tracker);
            mTracker.enableExceptionReporting(true);
            mTracker.enableAutoActivityTracking(true);
        }

        return mTracker;
    }
}
</code>```

what is my mistake ?

答:
Did you declare application name in your manifest file ?</p>

```<code> <application
    android:name="[.path].DemoApp"
    .....
</code>```

Title: ClassCastException causing app to stop

Body:
i'm having difficult to solve this, i already search through some similar problems, but i don't have experience this kind one,
from my logcat i found this:

Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.dot.analyticsdemo.DemoApp
                                                                                at com.example.dot.analyticsdemo.MainActivity.onCreate(MainActivity.java:23)

and this is my MainActivity:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DemoApp application = (DemoApp) getApplication();
        mTracker = application.getDefaultTracker();

        // starts a new session and notification to google analytics
        mTracker.send(new HitBuilders.ScreenViewBuilder()
                .setNewSession()
                .build());
    }

which line 23 is: DemoApp application = (DemoApp) getApplication();

this is the DemoApp:

package com.example.dot.analyticsdemo;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

public class DemoApp extends Application {

    private Tracker mTracker;

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {

        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);

            // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
            mTracker = analytics.newTracker(R.xml.global_tracker);
            mTracker.enableExceptionReporting(true);
            mTracker.enableAutoActivityTracking(true);
        }

        return mTracker;
    }
}

what is my mistake ?

Body:
Did you declare application name in your manifest file ?

 <application
    android:name="[.path].DemoApp"
    .....


问:
Does the shoes gem support HTTPS requests?
I've been looking around on how to make HTTPS requests using the Shoes GUI builder and I'm getting the SSL_connnect connect error and I'm unsure of what to do about it.

I made a test app in this Gist

Here's the Error:

```<code>SSL_connect returned=1 errno=0 state=error: certificate verify failed
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:923:in `connect'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:923:in `block in connect'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/timeout.rb:73:in `timeout'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:923:in `connect'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:863:in `do_start'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:852:in `start'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:1375:in `request'
shoes.rb:17:in `request'
shoes.rb:54:in `block (3 levels) in <main>'
-e:1:in `call'
</code>```

答:
I figured it out. Updating the request to strip the token and setting the verify_mode to  OpenSSL::SSL::VERIFY_NONE fixed the problem.

```<code>token = Base64.encode64("#{user}:#{pass}").strip
uri = URI("https://example.com/")

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(uri.request_uri)
request["authorization"] = "Bearer #{token}"
request["Content-Type"] = "application/json"
response = http.request(request)

info(response.body)
response
</code>```

Body:
I've been looking around on how to make HTTPS requests using the Shoes GUI builder and I'm getting the SSL_connnect connect error and I'm unsure of what to do about it.

I made a test app in this Gist

Here's the Error:

SSL_connect returned=1 errno=0 state=error: certificate verify failed
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:923:in `connect'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:923:in `block in connect'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/timeout.rb:73:in `timeout'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:923:in `connect'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:863:in `do_start'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:852:in `start'
/Applications/Shoes.app/Contents/MacOS/lib/ruby/2.2.0/net/http.rb:1375:in `request'
shoes.rb:17:in `request'
shoes.rb:54:in `block (3 levels) in '
-e:1:in `call'

Body:
I figured it out. Updating the request to strip the token and setting the verify_mode to  OpenSSL::SSL::VERIFY_NONE fixed the problem.

token = Base64.encode64("#{user}:#{pass}").strip
uri = URI("https://example.com/")

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(uri.request_uri)
request["authorization"] = "Bearer #{token}"
request["Content-Type"] = "application/json"
response = http.request(request)

info(response.body)
response


问:
XSL namespaces and xsl:for-each
I'm currently stuck trying to use XSL to transform a XML document into HTML. The XML document uses namespaces and I don't really have too much experience with XSL let alone namespaces. Basically all I want to do is grab every instance of s:treatment and output this as a list. I've changed data so not to expose the website I'm doing this for. I'm using Classic ASP (can't update to ASP.NET) to transform the XML on the server, so the XSL has to be version 1 :(

Any help would be really appreciated here as I just can't figure out what's going wrong.

Here's the XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">a</title>
<id>a</id>
<rights type="text">© Crown Copyright 2009</rights>
<updated>2011-01-19T11:23:25Z</updated>
<category term="Service"/>
<author>
 <name>c</name>
<uri>http://www.meh.com</uri>
 <email>erwt</email>
 </author>
<complete xmlns="http://purl.org/syndication/history/1.0"/>
<entry>
 <id>http://meh.com/services</id>
 <title type="text">title</title>
 <updated>2010-06-18T19:52:12+01:00</updated>
 <link rel="self" title="title" href="meh"/>
 <link rel="alternate" title="title" href="id"/>
 <content type="application/xml">
 <s:service xmlns:s="http://syndication.nhschoices.nhs.uk/services">
  <s:type code="S">h</s:type>
  <s:deliverer>j</s:deliverer>
  <s:parent>k</s:parent>
  <s:treatments>
   <s:treatment>fissure</s:treatment>
   <s:treatment>fistula</s:treatment>
   <s:treatment>liver</s:treatment>
   <s:treatment>pancreas</s:treatment>
   <s:treatment>Cirrhosis</s:treatment>
     <s:treatment>Coeliac disease</s:treatment>
   <s:treatment>Crohn's disease</s:treatment>
    <s:treatment>Diagnostic endoscopy of the stomach</s:treatment>
   <s:treatment>Diverticular problems</s:treatment>
   <s:treatment>Gastrectomy</s:treatment>
   <s:treatment>Gastroenteritis</s:treatment>
   <s:treatment>Gastroenterology</s:treatment>
   <s:treatment>Gastroesophageal reflux disease(GORD)</s:treatment>
   <s:treatment>Hepatitis</s:treatment>
   <s:treatment>Hepatitis A</s:treatment>
   <s:treatment>Hepatitis B</s:treatment>
   <s:treatment>Hepatitis C</s:treatment>
   <s:treatment>Hernia hiatus</s:treatment>
   <s:treatment>Ileostomy</s:treatment>
   <s:treatment>Irritable bowel syndrome</s:treatment>
   <s:treatment>Liver disease (alcoholic)</s:treatment>
   <s:treatment>Obesity</s:treatment>
   <s:treatment>Pancreatitis</s:treatment>
   <s:treatment>Peptic ulcer</s:treatment>
   <s:treatment>Peritonitis</s:treatment>
   <s:treatment>Primary biliary cirrhosis</s:treatment>
   <s:treatment>Surgery for haemorrhoids</s:treatment>
   <s:treatment>Therapeutic endoscopy on the stomach</s:treatment>
   <s:treatment>Ulcerative colitis</s:treatment>
  </s:treatments>
  <s:phone>020 8</s:phone>
  <s:fax>020 8</s:fax>
  <s:email>jj</s:email>
  <s:website>oiyi</s:website>
 </s:service>
</content>
 </entry>
 </feed>
</code>```

As you can see it uses the Atom namespace, Purl syndication namespace and NHS Choices namespace only the NHS Choices namespace actually uses the prefix though, this is what is confusing me really. How would I declare the other namespaces and do I even need to?

Here's my XSL:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s="http://syndication.nhschoices.nhs.uk/services">
<ul>
<xsl:template match="/">

<xsl:for-each select="feed/entry/content/s:service/s:treatments/s:treatment">
<li><xsl:text></xsl:text></li>
</xsl:for-each>

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

This XSL was taken from the w3schools example so apologies if it's bare.

Any ideas what I need to do to make this work?

Thanks,
Colin

答:
First of all your XSLT is not valid at all (uloutside xsl:template is not valid XSL).

Further more as there is a default namespace on your feed tag you have also to define this in your xslt. You also better make usage of mathcing templates intead of for-each loops in CSLT.

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:s="http://syndication.nhschoices.nhs.uk/services"
  xmlns:a="http://www.w3.org/2005/Atom" exclude-result-prefixes="a s">

 <xsl:output method="html" indent="yes"/>

 <xsl:template match="/">
  <ul>
   <xsl:apply-templates
    select="a:feed/a:entry/a:content/s:service/s:treatments/s:treatment" />
  </ul>
 </xsl:template>

 <xsl:template match="s:treatment">
  <li>
   <xsl:value-of select="." />
  </li>
 </xsl:template>
</xsl:stylesheet>
</code>```

Title: XSL namespaces and xsl:for-each

Body:
I'm currently stuck trying to use XSL to transform a XML document into HTML. The XML document uses namespaces and I don't really have too much experience with XSL let alone namespaces. Basically all I want to do is grab every instance of s:treatment and output this as a list. I've changed data so not to expose the website I'm doing this for. I'm using Classic ASP (can't update to ASP.NET) to transform the XML on the server, so the XSL has to be version 1 :(

Any help would be really appreciated here as I just can't figure out what's going wrong.

Here's the XML:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">a</title>
<id>a</id>
<rights type="text">© Crown Copyright 2009</rights>
<updated>2011-01-19T11:23:25Z</updated>
<category term="Service"/>
<author>
 <name>c</name>
<uri>http://www.meh.com</uri>
 <email>erwt</email>
 </author>
<complete xmlns="http://purl.org/syndication/history/1.0"/>
<entry>
 <id>http://meh.com/services</id>
 <title type="text">title</title>
 <updated>2010-06-18T19:52:12+01:00</updated>
 <link rel="self" title="title" href="meh"/>
 <link rel="alternate" title="title" href="id"/>
 <content type="application/xml">
 <s:service xmlns:s="http://syndication.nhschoices.nhs.uk/services">
  <s:type code="S">h</s:type>
  <s:deliverer>j</s:deliverer>
  <s:parent>k</s:parent>
  <s:treatments>
   <s:treatment>fissure</s:treatment>
   <s:treatment>fistula</s:treatment>
   <s:treatment>liver</s:treatment>
   <s:treatment>pancreas</s:treatment>
   <s:treatment>Cirrhosis</s:treatment>
     <s:treatment>Coeliac disease</s:treatment>
   <s:treatment>Crohn's disease</s:treatment>
    <s:treatment>Diagnostic endoscopy of the stomach</s:treatment>
   <s:treatment>Diverticular problems</s:treatment>
   <s:treatment>Gastrectomy</s:treatment>
   <s:treatment>Gastroenteritis</s:treatment>
   <s:treatment>Gastroenterology</s:treatment>
   <s:treatment>Gastroesophageal reflux disease(GORD)</s:treatment>
   <s:treatment>Hepatitis</s:treatment>
   <s:treatment>Hepatitis A</s:treatment>
   <s:treatment>Hepatitis B</s:treatment>
   <s:treatment>Hepatitis C</s:treatment>
   <s:treatment>Hernia hiatus</s:treatment>
   <s:treatment>Ileostomy</s:treatment>
   <s:treatment>Irritable bowel syndrome</s:treatment>
   <s:treatment>Liver disease (alcoholic)</s:treatment>
   <s:treatment>Obesity</s:treatment>
   <s:treatment>Pancreatitis</s:treatment>
   <s:treatment>Peptic ulcer</s:treatment>
   <s:treatment>Peritonitis</s:treatment>
   <s:treatment>Primary biliary cirrhosis</s:treatment>
   <s:treatment>Surgery for haemorrhoids</s:treatment>
   <s:treatment>Therapeutic endoscopy on the stomach</s:treatment>
   <s:treatment>Ulcerative colitis</s:treatment>
  </s:treatments>
  <s:phone>020 8</s:phone>
  <s:fax>020 8</s:fax>
  <s:email>jj</s:email>
  <s:website>oiyi</s:website>
 </s:service>
</content>
 </entry>
 </feed>

As you can see it uses the Atom namespace, Purl syndication namespace and NHS Choices namespace only the NHS Choices namespace actually uses the prefix though, this is what is confusing me really. How would I declare the other namespaces and do I even need to?

Here's my XSL:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s="http://syndication.nhschoices.nhs.uk/services">

<xsl:template match="/">

<xsl:for-each select="feed/entry/content/s:service/s:treatments/s:treatment">

<xsl:text></xsl:text>

</xsl:for-each>

</xsl:template>

</xsl:stylesheet>

This XSL was taken from the w3schools example so apologies if it's bare.

Any ideas what I need to do to make this work?

Thanks,
Colin

Body:
First of all your XSLT is not valid at all (uloutside xsl:template is not valid XSL).

Further more as there is a default namespace on your feed tag you have also to define this in your xslt. You also better make usage of mathcing templates intead of for-each loops in CSLT.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:s="http://syndication.nhschoices.nhs.uk/services"
  xmlns:a="http://www.w3.org/2005/Atom" exclude-result-prefixes="a s">

 <xsl:output method="html" indent="yes"/>

 <xsl:template match="/">
  <ul>
   <xsl:apply-templates
    select="a:feed/a:entry/a:content/s:service/s:treatments/s:treatment" />
  </ul>
 </xsl:template>

 <xsl:template match="s:treatment">
  <li>
   <xsl:value-of select="." />
  </li>
 </xsl:template>
</xsl:stylesheet>


问:
Validation failed due to manually inserted value
Value of filename is being manually inserted using this

```<code><input type="file" ngf-select ng-model="file" name="file" id="file" onchange="document.getElementById('fileName').value = this.value.split('\\').pop().split('/').pop()" required>
</code>```

Filename is being injected into fileName field using the file a user chooses. Validation fails as it treats that field as still being empty until I at least insert one more character. What can I do to fix that?

This is the validation part

```<code><p ng-show="fileNameForm.fileNameInput.$error.required && fileNameForm.fileNameInput.$touched" class="help-block">File name is required.</p>
</code>```

And the actual text field

```<code><input name="fileNameInput" class="form-control" type="text" id="fileName" ng-model="document.fileName" ng-maxlength="255" required>
</code>```

答:
on change will not be evaluated if the model is changed programmatically and not by a change to the input value

you can use $scope.$watch to detect changes on ng-model

```<code>$scope.$watch('document.fileName', function(newValue, oldValue) {
  //if(newValue not valid)
  //    display validation error
});
</code>```

Body:
Value of filename is being manually inserted using this

<input type="file" ngf-select ng-model="file" name="file" id="file" onchange="document.getElementById('fileName').value = this.value.split('\\').pop().split('/').pop()" required>

Filename is being injected into fileName field using the file a user chooses. Validation fails as it treats that field as still being empty until I at least insert one more character. What can I do to fix that?

This is the validation part

File name is required.

And the actual text field

<input name="fileNameInput" class="form-control" type="text" id="fileName" ng-model="document.fileName" ng-maxlength="255" required>

Body:
on change will not be evaluated if the model is changed programmatically and not by a change to the input value

you can use $scope.$watch to detect changes on ng-model

$scope.$watch('document.fileName', function(newValue, oldValue) {
  //if(newValue not valid)
  //    display validation error
});