问:
Why does my Jest test of React propTypes break when using multiple unacceptable prop values?
In an answer to a different SO question about how to test propTypes in React using Jest, I proposed a solution that mocks console.error, something others have done before but which I thought could be improved. My solution, a function, is below. The example code below contains some arbitrary propTypes that are then tested. For each test, I expected the first sub-array of "acceptable values" to not cause the mock of console.error to have been called by React, but I expected each test prop value in the second sub-array of "unacceptable values" to cause the mock to have been called.

The testPropTypes Function

```<code>const testPropTypes = (component, propName, arraysOfTestValues, otherProps) => {
    console.error = jest.fn();
    const _test = (testValues, expectError) => {
        for (let propValue of testValues) {
            console.error.mockClear();
            React.createElement(component, {...otherProps, [propName]: propValue});
            expect(console.error).toHaveBeenCalledTimes(expectError ? 1 : 0);
        }
    };
    _test(arraysOfTestValues[0], false);
    _test(arraysOfTestValues[1], true);
};
</code>```

Example Code

MyComponent.js (just the propTypes):

```<code>MyComponent.propTypes = {
    myProp1: React.PropTypes.number,      // optional number
    myProp2: React.PropTypes.oneOfType([  // required number or array of numbers
        React.PropTypes.number,
        React.PropTypes.arrayOf(React.PropTypes.number)
    ]).isRequired
</code>```

MyComponent.test.js:

```<code>describe('MyComponent', () => {

    it('should accept an optional number for myProp1', () => {
        const testValues = [
            [0, null],                   // acceptable values
            ['', {}, [], Symbol(), true] // unacceptable values
        ];
        testPropTypes(MyComponent, 'myProp1', testValues, {myProp2: 123});
    });

    it('should require a number or an array of numbers for myProp2', () => {
        const testValues = [
            [0, [0]],                          // acceptable values
            ['', {}, [], Symbol(), true, null] // unacceptable values
        ];
        testPropTypes(MyComponent, 'myProp2', testValues);
    });
});
</code>```

The code seems to work fine in simple circumstances. However, the sub-array of unacceptable test prop values for the more complex propType, i.e. for myProp2, produces some funny results. The presence or absence of null (which tests for whether the prop is optional or required) makes no difference, i.e. it behaves properly all the time. However, the other test prop type values seem to interact with each other in some mysterious way. If a single non-null unacceptable test prop value is used, the test performs as expected. However, if more than one such non-null unacceptable test prop value is used, the test breaks, responding as if the second, third, etc. unacceptable types (again, other than null) are actually acceptable.

What's going on and how can I fix this?

答:
Here's a bit of detail on the why, to expand on Andrew Willems' detailed description of the conditions causing the problem.

Note that my explanation here applies to the prop-types library that Facebook extracted from React recently, specifically when checking props with the checkPropTypes function it exports.

The checkPropTypes.js module keeps mutable state in the form of an object called loggedTypeFailures on line 16:

```<code> var loggedTypeFailures = {};
</code>```

Lines 47-50 show how it is used and explain the thinking:

```<code>      if (error instanceof Error && !(error.message in loggedTypeFailures)) {
        // Only monitor this failure once because there tends to be a lot of the
        // same error.
        loggedTypeFailures[error.message] = true;
</code>```

When a propType check fails, the message is set as a key on loggedTypeFailures before logging the error, to track that it has already been logged. The next time a propType fails with the same message, the error.message in loggedTypeFailures check succeeds and logging is skipped.

Since loggedTypeFailures is private to the module, there is no way to access or reset it.

If you need to detect propType failures in a more robust way (eg., for unit tests), I published a tiny library that helps: check-prop-types. It checks props the same way as checkPropTypes.js, but returns the error instead of logging it.

Body:
In an answer to a different SO question about how to test propTypes in React using Jest, I proposed a solution that mocks console.error, something others have done before but which I thought could be improved. My solution, a function, is below. The example code below contains some arbitrary propTypes that are then tested. For each test, I expected the first sub-array of "acceptable values" to not cause the mock of console.error to have been called by React, but I expected each test prop value in the second sub-array of "unacceptable values" to cause the mock to have been called.

The testPropTypes Function

const testPropTypes = (component, propName, arraysOfTestValues, otherProps) => {
    console.error = jest.fn();
    const _test = (testValues, expectError) => {
        for (let propValue of testValues) {
            console.error.mockClear();
            React.createElement(component, {...otherProps, [propName]: propValue});
            expect(console.error).toHaveBeenCalledTimes(expectError ? 1 : 0);
        }
    };
    _test(arraysOfTestValues[0], false);
    _test(arraysOfTestValues[1], true);
};

Example Code

MyComponent.js (just the propTypes):

MyComponent.propTypes = {
    myProp1: React.PropTypes.number,      // optional number
    myProp2: React.PropTypes.oneOfType([  // required number or array of numbers
        React.PropTypes.number,
        React.PropTypes.arrayOf(React.PropTypes.number)
    ]).isRequired

MyComponent.test.js:

describe('MyComponent', () => {

    it('should accept an optional number for myProp1', () => {
        const testValues = [
            [0, null],                   // acceptable values
            ['', {}, [], Symbol(), true] // unacceptable values
        ];
        testPropTypes(MyComponent, 'myProp1', testValues, {myProp2: 123});
    });

    it('should require a number or an array of numbers for myProp2', () => {
        const testValues = [
            [0, [0]],                          // acceptable values
            ['', {}, [], Symbol(), true, null] // unacceptable values
        ];
        testPropTypes(MyComponent, 'myProp2', testValues);
    });
});

The code seems to work fine in simple circumstances. However, the sub-array of unacceptable test prop values for the more complex propType, i.e. for myProp2, produces some funny results. The presence or absence of null (which tests for whether the prop is optional or required) makes no difference, i.e. it behaves properly all the time. However, the other test prop type values seem to interact with each other in some mysterious way. If a single non-null unacceptable test prop value is used, the test performs as expected. However, if more than one such non-null unacceptable test prop value is used, the test breaks, responding as if the second, third, etc. unacceptable types (again, other than null) are actually acceptable.

What's going on and how can I fix this?

Body:
Here's a bit of detail on the why, to expand on Andrew Willems' detailed description of the conditions causing the problem.

Note that my explanation here applies to the prop-types library that Facebook extracted from React recently, specifically when checking props with the checkPropTypes function it exports.

The checkPropTypes.js module keeps mutable state in the form of an object called loggedTypeFailures on line 16:

 var loggedTypeFailures = {};

Lines 47-50 show how it is used and explain the thinking:

      if (error instanceof Error && !(error.message in loggedTypeFailures)) {
        // Only monitor this failure once because there tends to be a lot of the
        // same error.
        loggedTypeFailures[error.message] = true;

When a propType check fails, the message is set as a key on loggedTypeFailures before logging the error, to track that it has already been logged. The next time a propType fails with the same message, the error.message in loggedTypeFailures check succeeds and logging is skipped.

Since loggedTypeFailures is private to the module, there is no way to access or reset it.

If you need to detect propType failures in a more robust way (eg., for unit tests), I published a tiny library that helps: check-prop-types. It checks props the same way as checkPropTypes.js, but returns the error instead of logging it.


来源: stackexchange

问:
Using "generated strings" (stringWithFormat) as keys for NSDictionary
I would like to do something like this:

```<code>#define GETKEY (a) ([NSString stringWithFormat:@"%d",a])

NSMutableDictionary *mutableDictionay=[NSMutableDictionary dictionary];
//population of dictionary
[mutableDictionary setObject:anObject forKey:GETKEY(someIntValue)];
//... then retrive the object
[mutableDictionary getObjectForKey:GETKEY(someIntValue)];
</code>```

But I'm concerned the stringWithFormat method returns a different instance of NSString with the same value, I mean like having, 2 strings: "0" and another instance with value "0". I would like to know if this is a safe way to get and set the objects in the dictionary. If not, what other way could be the best way to "generate" a key object from an integer?

答: You should consider using NSNumber if expect all of them to be numbers but it will work with NSString also. The NSDictionary keys must conform to NSCopying protocol and keys are compared using the isEqual: selector.</p>

ContentLicense: CC BY-SA 2.5

Body:
I would like to do something like this:

#define GETKEY (a) ([NSString stringWithFormat:@"%d",a])

NSMutableDictionary *mutableDictionay=[NSMutableDictionary dictionary];
//population of dictionary
[mutableDictionary setObject:anObject forKey:GETKEY(someIntValue)];
//... then retrive the object
[mutableDictionary getObjectForKey:GETKEY(someIntValue)];

But I'm concerned the stringWithFormat method returns a different instance of NSString with the same value, I mean like having, 2 strings: "0" and another instance with value "0". I would like to know if this is a safe way to get and set the objects in the dictionary. If not, what other way could be the best way to "generate" a key object from an integer?


问:
Python socket 10048 error
I am learning network and for some reason I get an error with the bind line and I do not see why, help?</p>

```<code>Server_Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Server_Socket.bind(('127.0.0.1', 80))
Server_Socket.listen(10)
</code>```

答: In case someone comes across this error in the future, this exception is typically thrown in the event that another program is already bound to that port. Try changing the port from a popular port i.e(80,443,161..etc) to something above 1024 to be "safe" not to interfere with any other programs.</p>

ContentLicense: CC BY-SA 3.0

Title: Python socket 10048 error

Body:
I am learning network and for some reason I get an error with the bind line and I do not see why, help?

Server_Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Server_Socket.bind(('127.0.0.1', 80))
Server_Socket.listen(10)


问:
Group JSON by key
I have structured JSON data as below:

```<code>[
    {
        "Month": "Jan"
        "Year": 2015,
        "Count": 15
    },
    {
        "Month": "Feb"
        "Year": 2015,
        "Count": 5
    },
    {
        "Month": "Jan"
        "Year": 2016,
        "Count": 25
    },
        {
        "Month": "Feb"
        "Year": 2016,
        "Count": 50
    }
]
</code>```

I want to group the data using JavaScript to get the below output. Can someone help me with this?

```<code>[
    {
        "Month": "Jan"
        "Count_2015": 15,
        "Count_2016": 25
    },
    {
        "Month": "Feb"
        "Count_2015": 5,
        "Count_2016": 50
    }
]
</code>```

答:
```<code>var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var result = [];
[].forEach.call(months, function(month) {
  var monthObj = {"Month": month};
  result.push(monthObj);
});
let mi, year, keystr
for (var i=0; i< data.length; i++) {
  var obj = data[i];
  for (var key in obj) {
    if (!obj.hasOwnProperty(key)) continue;
    var value = obj[key];
    switch (key) {
      case "Month":
        mi = months.indexOf(value);
        break;
      case "Year":
        year = value;
        break;
      case "Count":
        keystr = "Count_" + year.toString();
        resObj = result[mi];
        resObj[keystr] = value;
        break;
    }
  }
}
console.log(result);
</code>```

Try it here

Title: Group JSON by key

Body:
I have structured JSON data as below:

[
    {
        "Month": "Jan"
        "Year": 2015,
        "Count": 15
    },
    {
        "Month": "Feb"
        "Year": 2015,
        "Count": 5
    },
    {
        "Month": "Jan"
        "Year": 2016,
        "Count": 25
    },
        {
        "Month": "Feb"
        "Year": 2016,
        "Count": 50
    }
]

I want to group the data using JavaScript to get the below output. Can someone help me with this?

[
    {
        "Month": "Jan"
        "Count_2015": 15,
        "Count_2016": 25
    },
    {
        "Month": "Feb"
        "Count_2015": 5,
        "Count_2016": 50
    }
]

Body:
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var result = [];
[].forEach.call(months, function(month) {
  var monthObj = {"Month": month};
  result.push(monthObj);
});
let mi, year, keystr
for (var i=0; i< data.length; i++) {
  var obj = data[i];
  for (var key in obj) {
    if (!obj.hasOwnProperty(key)) continue;
    var value = obj[key];
    switch (key) {
      case "Month":
        mi = months.indexOf(value);
        break;
      case "Year":
        year = value;
        break;
      case "Count":
        keystr = "Count_" + year.toString();
        resObj = result[mi];
        resObj[keystr] = value;
        break;
    }
  }
}
console.log(result);

Try it here


问:
Make a panel with values visible when I press a radiobutton
I have a uibuttongroup with radio buttons defined in it. I have uipanels defined with their corresponding properties. What I want to do is to be able to click one radio button and have one uipanel appear, and then click my other radio button to have the other uipanel appear. Here are snippets of my code:

```<code>operation_type_1 = uibuttongroup(S.Test, 'Title', 'Operation Type', 'position', [0 0.3 panel_w/2 0.15]);
uicontrol('Parent',operation_type_1, 'Style', 'radiobutton',...
               'String', 'invisible',...
               'position', [0 0 0 0], 'Tag', 'invisibutton');

uicontrol('Parent',operation_type_1,'Style','radiobutton',...
               'String', 'Time Operation',...
               'Position', 100*[0.1 flooring(3.5, 'tp') 1.2 0.15], 'Tag', 'timeop1');

uicontrol('Parent',operation_type_1,'Style','radiobutton',...
               'String', 'Volume Operation',...
               'Position', 100*[0.1 flooring(2.5, 'tp') 1.2 0.15], 'Tag', 'volumeop1');
</code>```

This defines my button group and the two radio buttons.

Then I have code which creates a volume panel:

As well as a Time Panel:

These are in the same position. What I want is to be able to click on the "Time Operation" radio button and have the time panel be visible, and when I click on the "Volume Operation" radio button, the volume panel is visible.

I've tried doing switch case statements. I don't get errors, but I don't get results either. For example, my case statements for the time and volume panels are:

```<code>switch str
    case 'timeop1'
    if U.Value; S.result_panel_time1.Visible = 'On';
    else S.result_panel_time1.Visible = 'Off';
    end

    case 'volumeop1'
    if U.Value; S.result_panel_volume1.Visible = 'On';
    else S.result_panel_volume1.Visible = 'Off';
end
</code>```

How do I get this to work? I'm not using GUIDE, just coding a MATLAB GUI.

UPDATE

I've tried implementing the callback suggested below, but I get a "Function definition is misplaced or improperly nested." error. I use the following function:

```<code>function button_callback(U, varargin{2})
    switch get(get(operation_type_1, 'SelectedObject'), 'Tag')
        case 'timeop1'
            if U.Value; S.result_panel_time1.Visible = 'On';
            else S.result_panel_time1.Visible = 'Off';
            end
        case 'volumeop1'
            if U.Value; S.result_panel_volume1.Visible = 'On';
            else S.result_panel_volume1.Visible = 'Off';
            end
    end
end
</code>```

And I've added the callbacks "...'callback', {@pb_call, S}" to my timeop1 and volumeop1. (Because all of the other function I have are in a .m file called pb_call.m). The function appears to be nested fine but the error points at the exact one.

答:
My partner ended up fixing it:

The callback was {callback, S} and S, U, and str were:

```<code>S = varargin{3}; %main figure handle
U = varargin{1}; %current uicontrol
str = char(U.String);
</code>```

The problem occurred in the radiobutton creation, since the result panels were being created after the radiobuttons could be triggered, thus nothing was made invisible/visible and an error would occur.

However, it would be highly convenient if callbacks could affect all GUI parts, not just previously defined ones. I've tried using guidata in the past, but I had to use other, less straighforward methods to accomplish my goals. I'll try using working samples and building upon those in the future, but currently I am working on another part of the project and will get back to that later.

But using either guidata/setappdata or something related would work here as well as my own solution, which is making sure that the objects you are trying to change are already defined before the button triggering the callback.

(He also posted this answer to where I asked this same question in MATLAB Answers.)

Body:
I have a uibuttongroup with radio buttons defined in it. I have uipanels defined with their corresponding properties. What I want to do is to be able to click one radio button and have one uipanel appear, and then click my other radio button to have the other uipanel appear. Here are snippets of my code:

operation_type_1 = uibuttongroup(S.Test, 'Title', 'Operation Type', 'position', [0 0.3 panel_w/2 0.15]);
uicontrol('Parent',operation_type_1, 'Style', 'radiobutton',...
               'String', 'invisible',...
               'position', [0 0 0 0], 'Tag', 'invisibutton');

uicontrol('Parent',operation_type_1,'Style','radiobutton',...
               'String', 'Time Operation',...
               'Position', 100*[0.1 flooring(3.5, 'tp') 1.2 0.15], 'Tag', 'timeop1');

uicontrol('Parent',operation_type_1,'Style','radiobutton',...
               'String', 'Volume Operation',...
               'Position', 100*[0.1 flooring(2.5, 'tp') 1.2 0.15], 'Tag', 'volumeop1');

This defines my button group and the two radio buttons.

Then I have code which creates a volume panel:

As well as a Time Panel:

These are in the same position. What I want is to be able to click on the "Time Operation" radio button and have the time panel be visible, and when I click on the "Volume Operation" radio button, the volume panel is visible.

I've tried doing switch case statements. I don't get errors, but I don't get results either. For example, my case statements for the time and volume panels are:

switch str
    case 'timeop1'
    if U.Value; S.result_panel_time1.Visible = 'On';
    else S.result_panel_time1.Visible = 'Off';
    end

    case 'volumeop1'
    if U.Value; S.result_panel_volume1.Visible = 'On';
    else S.result_panel_volume1.Visible = 'Off';
end

How do I get this to work? I'm not using GUIDE, just coding a MATLAB GUI.

UPDATE

I've tried implementing the callback suggested below, but I get a "Function definition is misplaced or improperly nested." error. I use the following function:

function button_callback(U, varargin{2})
    switch get(get(operation_type_1, 'SelectedObject'), 'Tag')
        case 'timeop1'
            if U.Value; S.result_panel_time1.Visible = 'On';
            else S.result_panel_time1.Visible = 'Off';
            end
        case 'volumeop1'
            if U.Value; S.result_panel_volume1.Visible = 'On';
            else S.result_panel_volume1.Visible = 'Off';
            end
    end
end

And I've added the callbacks "...'callback', {@pb_call, S}" to my timeop1 and volumeop1. (Because all of the other function I have are in a .m file called pb_call.m). The function appears to be nested fine but the error points at the exact one.

Body:
My partner ended up fixing it:

The callback was {callback, S} and S, U, and str were:

S = varargin{3}; %main figure handle
U = varargin{1}; %current uicontrol
str = char(U.String);

The problem occurred in the radiobutton creation, since the result panels were being created after the radiobuttons could be triggered, thus nothing was made invisible/visible and an error would occur.

However, it would be highly convenient if callbacks could affect all GUI parts, not just previously defined ones. I've tried using guidata in the past, but I had to use other, less straighforward methods to accomplish my goals. I'll try using working samples and building upon those in the future, but currently I am working on another part of the project and will get back to that later.

But using either guidata/setappdata or something related would work here as well as my own solution, which is making sure that the objects you are trying to change are already defined before the button triggering the callback.

(He also posted this answer to where I asked this same question in MATLAB Answers.)


问:
How to use single function to multiple classes?
I've got this following code:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('.sample1').click(function(){
            $('.dropdown-content').toggleClass('visible-dropdown');
        })
    })
</script>
</code>```

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

答:
You can edit your code to take multiple selectors.</p>

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('.sample1, .sample2, .sample3').click(function(){
            $('.dropdown-content').toggleClass('visible-dropdown');
        })
    })
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got this following code:

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

Body:
You can edit your code to take multiple selectors.

<script type="text/javascript">
    $(document).ready(function(){
        $('.sample1, .sample2, .sample3').click(function(){
            $('.dropdown-content').toggleClass('visible-dropdown');
        })
    })
</script>


问:
How do I prevent a JavasScript function from launching when the browser loads?
So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using document.getElementById("myButton"); but when I run console.log(document.getElementById("myButton")); in my browser console I get a Null result.

I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the document.getElementById... my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My  code is below

JSFiddle Example

```<code>            var el = document.getElementById("myButton");
            el.onclick = addUser("username", "email", onSuccess);

            function onSuccess(result){
               alert ('successful');
            }

            // Do not modify this function. Add user service wrapper.
            function addUser(username, email, callback) {
                var xhr = new XMLHttpRequest();
                var response;
                var success = (!!Math.round(Math.random()));

                if (!success){
                    response = JSON.stringify({
                        success: success,
                        error: "Oups, something went wrong!"
                    });
                } else {
                    response = JSON.stringify({
                        success: success,
                        user: {
                            username: username,
                            email: email
                        }
                    });
                }

                xhr.open("POST", "/echo/json/");
                xhr.onload = function () {
                        if (xhr.status === 200) {
                            callback(JSON.parse(xhr.responseText));
                    }
                }
                xhr.send("json=" + response);
            };
</code>```

答:
The thing that is going wrong is that you are calling addUser when you try to set the onClick listener. Try this instead.

var el = document.getElementById("myButton");
el.onclick = function() {
  var username = document.getElementById("username").value;
  var email = document.getElementById("email").value
  addUser(username, email, onSuccess)
}

function onSuccess(result){
   alert ('successful');
}

// Do not modify this function. Add user service wrapper.
function addUser(username, email, callback) {
    var xhr = new XMLHttpRequest();
    var response;
    var success = (!!Math.round(Math.random()));

    if (!success){
        response = JSON.stringify({
            success: success,
            error: "Oups, something went wrong!"
        });
    } else {
        response = JSON.stringify({
            success: success,
            user: {
                username: username,
                email: email
            }
        });
    }

    xhr.open("POST", "/echo/json/");
    xhr.onload = function () {
      if (xhr.status === 200) {
          callback(JSON.parse(xhr.responseText));
        }
    }
    xhr.send("json=" + response);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="email" name="email" placeholder="email">
<button id="myButton">add user</button>
<h2>Users:</h2>
<ul id="users"></ul></code>```

Body:
So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using document.getElementById("myButton"); but when I run console.log(document.getElementById("myButton")); in my browser console I get a Null result.

I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the document.getElementById... my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My  code is below

JSFiddle Example

            var el = document.getElementById("myButton");
            el.onclick = addUser("username", "email", onSuccess);

            function onSuccess(result){
               alert ('successful');
            }

            // Do not modify this function. Add user service wrapper.
            function addUser(username, email, callback) {
                var xhr = new XMLHttpRequest();
                var response;
                var success = (!!Math.round(Math.random()));

                if (!success){
                    response = JSON.stringify({
                        success: success,
                        error: "Oups, something went wrong!"
                    });
                } else {
                    response = JSON.stringify({
                        success: success,
                        user: {
                            username: username,
                            email: email
                        }
                    });
                }

                xhr.open("POST", "/echo/json/");
                xhr.onload = function () {
                        if (xhr.status === 200) {
                            callback(JSON.parse(xhr.responseText));
                    }
                }
                xhr.send("json=" + response);
            };

Body:
The thing that is going wrong is that you are calling addUser when you try to set the onClick listener. Try this instead.

var el = document.getElementById("myButton");
el.onclick = function() {
  var username = document.getElementById("username").value;
  var email = document.getElementById("email").value
  addUser(username, email, onSuccess)
}

function onSuccess(result){
   alert ('successful');
}

// Do not modify this function. Add user service wrapper.
function addUser(username, email, callback) {
    var xhr = new XMLHttpRequest();
    var response;
    var success = (!!Math.round(Math.random()));

    if (!success){
        response = JSON.stringify({
            success: success,
            error: "Oups, something went wrong!"
        });
    } else {
        response = JSON.stringify({
            success: success,
            user: {
                username: username,
                email: email
            }
        });
    }

    xhr.open("POST", "/echo/json/");
    xhr.onload = function () {
      if (xhr.status === 200) {
          callback(JSON.parse(xhr.responseText));
        }
    }
    xhr.send("json=" + response);
};

<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="email" name="email" placeholder="email">
<button id="myButton">add user</button>
<h2>Users:</h2>
<ul id="users"></ul>


问:
Is there a way to see the value of a variable as the program is running?
I'd like to see what value a variable is holding AS the program is running.

I remember Scott Hanselman blogging about something like a Variable Viewbox, but I can't seem to find the post.

I'd like to view the variable AS the program is running it's loop. Inside of Visual Studio.

答: Often when there is much data and the logic is difficult to trace..eg . Due to large loops and many variables, then I dump state to comma separated files.. and then inspect them in Excel.</p>

OwnerDisplayName: delete

LastEditorDisplayName: delete


问:
MxNet: label_shapes don't match names specified by label_names
I wrote a script to do the classification of a single input image using a model I trained with MxNet. To classify the incoming image I feedforward them in through network.

In short here is what I am doing:

```<code>symbol, arg_params, aux_params = mx.model.load_checkpoint('model-prefix', 42)
model = mx.mod.Module(symbol=symbol, context=mx.cpu())
model.bind(data_shapes=[('data', (1, 3, 224, 244))], for_training=False)
model.set_params(arg_params, aux_params)

# ... loading the image & resizing ...
# img is the image to classify as numpy array of shape (3, 244, 244)

Batch = namedtuple('Batch', ['data'])
self._model.forward(Batch(data=[mx.nd.array(img)]))
probabilities = self._model.get_outputs()[0].asnumpy()

print(str(probabilities))
</code>```

This works fine, except that I am getting the following warning

```<code>UserWarning: Data provided by label_shapes don't match names specified by label_names ([] vs. ['softmax_label'])
</code>```

What should I change to avoid getting this warning? It is not clear to me what the label_shapes and label_names parameters are meant for, and what I am expect to fill them with.

Note: I found some thread about them, but none enabled me to solve the problem. Similarly the MxNet documentation doesn't provide much details on what those parameters are and on how they are supposed to be filled.

答:
Set label_names=None and allow_missing=True. That should get rid of the warning.

```<code>model = mx.mod.Module(symbol=symbol, context=mx.cpu(), label_names=None)
...
model.set_params(arg_params, aux_params, allow_missing=True)
</code>```

If you are curious why the warning is printed in the first place,

Every module has associated label. When this model was trained, softmax_label was used as the label (most likely because the output layer was a softmax layer named 'softmax'). When the model was loaded from file, the module that was created had softmax_label as the module's label.

```<code>>>>print(model.label_names)
['softmax_label']
</code>```

model.bind is then called without providing label_shapes.

```<code>model.bind(data_shapes=[('data', (1, 3, 224, 244))], for_training=False)
</code>```

MXNet sees that the module has a label in it which was not provided during bind and complains about it - which is the warning message you see.

I think if bind is called with for_training=False, MXNet shouldn't complain about the missing label. I've created this issue: https://github.com/dmlc/mxnet/issues/6958

However, for this particular case where we load a model from disk, we can load it with None as the label so that MXNet doesn't later complain when bind doesn't provide label - which is what the suggested fix does.

Body:
I wrote a script to do the classification of a single input image using a model I trained with MxNet. To classify the incoming image I feedforward them in through network.

In short here is what I am doing:

symbol, arg_params, aux_params = mx.model.load_checkpoint('model-prefix', 42)
model = mx.mod.Module(symbol=symbol, context=mx.cpu())
model.bind(data_shapes=[('data', (1, 3, 224, 244))], for_training=False)
model.set_params(arg_params, aux_params)

# ... loading the image & resizing ...
# img is the image to classify as numpy array of shape (3, 244, 244)

Batch = namedtuple('Batch', ['data'])
self._model.forward(Batch(data=[mx.nd.array(img)]))
probabilities = self._model.get_outputs()[0].asnumpy()

print(str(probabilities))

This works fine, except that I am getting the following warning

UserWarning: Data provided by label_shapes don't match names specified by label_names ([] vs. ['softmax_label'])

What should I change to avoid getting this warning? It is not clear to me what the label_shapes and label_names parameters are meant for, and what I am expect to fill them with.

Note: I found some thread about them, but none enabled me to solve the problem. Similarly the MxNet documentation doesn't provide much details on what those parameters are and on how they are supposed to be filled.

Body:
Set label_names=None and allow_missing=True. That should get rid of the warning.

model = mx.mod.Module(symbol=symbol, context=mx.cpu(), label_names=None)
...
model.set_params(arg_params, aux_params, allow_missing=True)

If you are curious why the warning is printed in the first place,

Every module has associated label. When this model was trained, softmax_label was used as the label (most likely because the output layer was a softmax layer named 'softmax'). When the model was loaded from file, the module that was created had softmax_label as the module's label.

>>>print(model.label_names)
['softmax_label']

model.bind is then called without providing label_shapes.

model.bind(data_shapes=[('data', (1, 3, 224, 244))], for_training=False)

MXNet sees that the module has a label in it which was not provided during bind and complains about it - which is the warning message you see.

I think if bind is called with for_training=False, MXNet shouldn't complain about the missing label. I've created this issue: https://github.com/dmlc/mxnet/issues/6958

However, for this particular case where we load a model from disk, we can load it with None as the label so that MXNet doesn't later complain when bind doesn't provide label - which is what the suggested fix does.


问:
Send a json with a multiline string instead of \n
I have a string with \n as a join result:

```<code>my_var = ['name','phone','age'].join("\n")
</code>```

I will send this string in the body of a post as a Json:

```<code>def body
  { "str": my_var }
end
</code>```

I want to send the var in multiple lines instead of sending the \n like this:

```<code>"name\nphone\nage"
</code>```

EDIT:
I am sending this string joined with \n to another dev team as a json in the body of my post request to their uri. But they don't want to receive a string with \n and replace or translate there. They want to recieve in multiple lines.

答:
You can use different separator and then, on receive, separate lines from whole string based on that delimiter using

my_delimiter = '\n' or my_delimiter = ';'

lines = my_var.split(my_delimiter).

Or you could iterate over ['name','phone','age'] and add them as separate json elements.

If this doesn't help, then please clarify your question.

Body:
I have a string with \n as a join result:

my_var = ['name','phone','age'].join("\n")

I will send this string in the body of a post as a Json:

def body
  { "str": my_var }
end

I want to send the var in multiple lines instead of sending the \n like this:

"name\nphone\nage"

EDIT:
I am sending this string joined with \n to another dev team as a json in the body of my post request to their uri. But they don't want to receive a string with \n and replace or translate there. They want to recieve in multiple lines.


问:
How to set variable in mySQL
I have the following statement:

```<code>SELECT
    start_date,
    end_date,
    DATE(now()) BETWEEN start_date AND end_date should_be_live
FROM
    mytable
WHERE
    DATE(now()) BETWEEN start_date AND end_date should_be_live = 1
</code>```

Is there a way to set a variable should_be_live = the expression DATE(now()) BETWEEN start_date AND end_date. If so, how would I do this?

答:
If by "variable" you mean "column in the result set", then yes.  You are basically doing it:

```<code>SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable;
</code>```

If by "variable", you mean that you want to define a column in the select and then filter on it, you cannot do that with where (unless you use a subquery).  You can use having:

```<code>SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable
HAVING should_be_live = 1;
</code>```

This use of having is a MySQL extension.

Title: How to set variable in mySQL

Body:
I have the following statement:

SELECT
    start_date,
    end_date,
    DATE(now()) BETWEEN start_date AND end_date should_be_live
FROM
    mytable
WHERE
    DATE(now()) BETWEEN start_date AND end_date should_be_live = 1

Is there a way to set a variable should_be_live = the expression DATE(now()) BETWEEN start_date AND end_date. If so, how would I do this?

Body:
If by "variable" you mean "column in the result set", then yes.  You are basically doing it:

SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable;

If by "variable", you mean that you want to define a column in the select and then filter on it, you cannot do that with where (unless you use a subquery).  You can use having:

SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable
HAVING should_be_live = 1;

This use of having is a MySQL extension.


问:
redhawk fastfilter Designer
How do I access the fastfilter block filter designer? When I instantiate the fastfilter block in the chalkboard and change filter parameters nothing happens. Shouldn't it calculate the taps and update them in the "realFilterCoefficients" property?</p>

答: It doesn't look like the taps make their way out and into the properties. One reason why it may not be an easy feature to add is because the component can handle multiple streams and each stream could have a different sample rate. The sample rate is used when calculating the taps so each stream could have different taps.</p>

Title: redhawk fastfilter Designer


问:
*Right* outer join in LINQ
Is it safe to say that there is no such thing as a right outer join in LINQ?

I know to effectively create one, you'd just swap the tables in a left outer join.  But can you apply the DefaultIfEmpty() method to the table on the left side of the equijoin to make it a right outer join?

答: After extensive looking, I can find nothing referring to a right outer join.  The only syntax available for an outer join is a left outer join.</p>

Title: *Right* outer join in LINQ


问:
TYPO3 Extbase - The configuration file "ext_emconf.php" seems to be invalid
I try to upload my extension but I get Please check your uploaded extension "my_download_plugin". The configuration file "ext_emconf.php" seems to be invalid.
What is supposed to be wrong with this configuration file?

```<code><?php

/***************************************************************
 * Extension Manager/Repository config file for ext: "my_download_plugin"
 *
 * Auto generated by Extension Builder 2017-01-30
 *
 * Manual updates:
 * Only the data in the array - anything else is removed by next write.
 * "version" and "dependencies" must not be touched!
 ***************************************************************/

$EM_CONF[$_EXTKEY] = array(
    'title' => 'my_download_plugin',
    'description' => 'Downloadlist for my Donwloadcenter',
    'category' => 'plugin',
    'author' => 'Edward Black',
    'author_email' => 'my.name@mycompany.de',
    'state' => 'beta',
    'createDirs' => '',
    'uploadfolder' => false,
    'clearCacheOnLoad' => false,
    'version' => '2.0.0',
    'constraints' => array(
        'depends' => array(
            'typo3' => '6.2.0-6.3.0',
            'static_info_tables' => '6.3.9'
        ),
        'conflicts' => array(),
        'suggests' => array()
    )
);
</code>```

I was reading the official documentation but could not find anything wrong.

答: The TYPO3 version 6.3.0 does not exist. If you want to handle 6.2.x use 6.2.0-6.2.99

Body:
I try to upload my extension but I get Please check your uploaded extension "my_download_plugin". The configuration file "ext_emconf.php" seems to be invalid.
What is supposed to be wrong with this configuration file?

<?php

/***************************************************************
 * Extension Manager/Repository config file for ext: "my_download_plugin"
 *
 * Auto generated by Extension Builder 2017-01-30
 *
 * Manual updates:
 * Only the data in the array - anything else is removed by next write.
 * "version" and "dependencies" must not be touched!
 ***************************************************************/

$EM_CONF[$_EXTKEY] = array(
    'title' => 'my_download_plugin',
    'description' => 'Downloadlist for my Donwloadcenter',
    'category' => 'plugin',
    'author' => 'Edward Black',
    'author_email' => 'my.name@mycompany.de',
    'state' => 'beta',
    'createDirs' => '',
    'uploadfolder' => false,
    'clearCacheOnLoad' => false,
    'version' => '2.0.0',
    'constraints' => array(
        'depends' => array(
            'typo3' => '6.2.0-6.3.0',
            'static_info_tables' => '6.3.9'
        ),
        'conflicts' => array(),
        'suggests' => array()
    )
);

I was reading the official documentation but could not find anything wrong.


问:
Ignore JsonTypeInfo in rest controller
Hi I have a class with field configuration:

```<code>     @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "@type")
    @JsonSubTypes({
            @JsonSubTypes.Type(value = XYZ, name = "XYZ"),
            @JsonSubTypes.Type(value = ZYX, name = "ZYX")
    })
public class XZZ
</code>```

I need to receive in Rest Controller XZZ without field @type but be able to have it in ObjectMapper automatically.
I'm trying to avoid creating the same object, one to receive in restController and second to parse to JSON with @type. Of course XYZ and ZYX extends XZZ.

答:
Inside your XZZ class (or wherever the "@type" attribute exists), add the annotation:</p>

```<code>@JsonProperty(access = Access.WRITE_ONLY)
private String type;
</code>```

Title: Ignore JsonTypeInfo in rest controller

Body:
Hi I have a class with field configuration:

     @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "@type")
    @JsonSubTypes({
            @JsonSubTypes.Type(value = XYZ, name = "XYZ"),
            @JsonSubTypes.Type(value = ZYX, name = "ZYX")
    })
public class XZZ

I need to receive in Rest Controller XZZ without field @type but be able to have it in ObjectMapper automatically.
I'm trying to avoid creating the same object, one to receive in restController and second to parse to JSON with @type. Of course XYZ and ZYX extends XZZ.

Body:
Inside your XZZ class (or wherever the "@type" attribute exists), add the annotation:

@JsonProperty(access = Access.WRITE_ONLY)
private String type;


问:
Static route use
Using static routes is it possible to access a host with an IP address of 1.2.3.4 on port 4000 that is connect to rtrnode on a wlan network that has a public ip address of x.x.x.14 from a remote host (h1)?

h1 -------router-------INTERNET-------(public IP(x.x.14)) = rtrnode(1.2.3.3)---------destination(1.2.3.4)

答: NO: Unless:You tunnel. This way the foreign LAN is a hop from the LAN you are on according to the routers on both ends that handle the packetizing and perform the VPN. It is easiest to set this up using firewalls like : PFSense or the likes. This link explains, there are many more: http://www.makeuseof.com/tag/vpn-tunnel-set/. You cannot route across the Internet with static routes unless you have control over the routers that are routing. They run BGP and will direct your traffic to the valid IP you are incorrectly using in your private LAN.</p>

Title: Static route use


问:
Redshift pg_user table throws Invalid Operation error on JOIN
when I run the following query,

```<code>select * from stl_query q
join pg_user u on q.userid = u.usesysid
where u.usename = 'admin';
</code>```

I get the following error:

```<code>SQL Error [500310] [0A000]: [Amazon](500310) Invalid operation: Specified types or functions (one per INFO message) not supported on Redshift tables.;
</code>```

The query is run on the leader node. What am I doing wrong?

答:
pg_user is a Leader Node-Only Function and cannot be mixed with functions that are not Leader Node-Only.

From the documentation:

Some Amazon Redshift SQL functions are supported only on the leader
  node and are not supported on the compute nodes. A query that uses a
  leader-node function must execute exclusively on the leader node, not
  on the compute nodes, or it will return an error.

The documentation for each leader-node only function includes a note
  stating that the function will return an error if it references
  user-defined tables or Amazon Redshift system tables.

Source: http://docs.aws.amazon.com/redshift/latest/dg/c_SQL_functions_leader_node_only.html

As a work around in your scenario, you can generate a temp table with the subset of pg_user data that you need, then join to that temp table.

```<code>select usesysid
into temp table tmp_user
from pg_user
where usename = 'admin';

select * from stl_query q
inner join tmp_user u on q.userid = u.usesysid;
</code>```

Body:
when I run the following query,

select * from stl_query q
join pg_user u on q.userid = u.usesysid
where u.usename = 'admin';

I get the following error:

SQL Error [500310] [0A000]: [Amazon](500310) Invalid operation: Specified types or functions (one per INFO message) not supported on Redshift tables.;

The query is run on the leader node. What am I doing wrong?

Body:
pg_user is a Leader Node-Only Function and cannot be mixed with functions that are not Leader Node-Only.

From the documentation:

Some Amazon Redshift SQL functions are supported only on the leader
  node and are not supported on the compute nodes. A query that uses a
  leader-node function must execute exclusively on the leader node, not
  on the compute nodes, or it will return an error.

The documentation for each leader-node only function includes a note
  stating that the function will return an error if it references
  user-defined tables or Amazon Redshift system tables.

Source: http://docs.aws.amazon.com/redshift/latest/dg/c_SQL_functions_leader_node_only.html

As a work around in your scenario, you can generate a temp table with the subset of pg_user data that you need, then join to that temp table.

select usesysid
into temp table tmp_user
from pg_user
where usename = 'admin';

select * from stl_query q
inner join tmp_user u on q.userid = u.usesysid;


问:
Why does Android's onItemClick want a long for row Id?
For a listView, when you register an OnItemClickListener, the method you specify looks like this:

public abstract void onItemClick (AdapterView parent, View view, int position, long id)

The id corresponds to the row that the user clicked on.  My question is simply why is it a long and not an int?  When would you use it as a long?  I've been casting it to an int when I use it, so it makes me think that maybe I'm using it wrong.

答:
I think this comes to us straight from SQLite:

In SQLite, every row of every table
  has an 64-bit signed integer ROWID.
  The ROWID for each row is unique among
  all rows in the same table.

Given that, it seems natural that the Android APIs would specify 64 bits for the ID for a database row.


问:
Exporting each variable value in loop
I am trying to capture the changing variable '$server' everytime the parameters go through a foreach loop. To summarize, the $sever value is always changing, and I want to capture it and add it into a collective csv file

Thank you!

Here is the code main part of the code that I have.

```<code> function Convert-QueryToObjects
 {
   [CmdletBinding()]
   [Alias('QueryToObject')]
   [OutputType([PSCustomObject])]
   param
   (
    [Parameter(Mandatory = $false,
               ValueFromPipeline = $true,
               ValueFromPipelineByPropertyName = $true,
               Position = 0)]
    [Alias('ComputerName', 'Computer')]
    [string]
    $Name = $env:COMPUTERNAME
)

Process
{
    Write-Verbose "Running query.exe against $Name."
    $Users = query user /server:$Name 2>&1

    if ($Users -like "*No User exists*")
    {
        # Handle no user's found returned from query.
        # Returned: 'No User exists for *'
        Write-Error "There were no users found on $Name : $Users"
        Write-Verbose "There were no users found on $Name."
    }
    elseif ($Users -like "*Error*")
    {
        # Handle errored returned by query.
        # Returned: 'Error ...<message>...'
        Write-Error "There was an error running query against $Name : $Users"
        Write-Verbose "There was an error running query against $Name."
    }
    elseif ($Users -eq $null -and $ErrorActionPreference -eq 'SilentlyContinue')
    {
        # Handdle null output called by -ErrorAction.
        Write-Verbose "Error action has supressed output from query.exe. Results were null."
    }
    else
    {
        Write-Verbose "Users found on $Name. Converting output from text."

        # Conversion logic. Handles the fact that the sessionname column may be populated or not.
        $Users = $Users | ForEach-Object {
            (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
        } | ConvertFrom-Csv

        Write-Verbose "Generating output for $($Users.Count) users connected to $Name."

        # Output objects.
        foreach ($User in $Users)
        {
            Write-Verbose $User
            if ($VerbosePreference -eq 'Continue')
            {
                # Add '| Out-Host' if -Verbose is tripped.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                } | Out-Host
            }
            else
            {
                # Standard output.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                }
            }
        }
    }
}
}

$Servers = Get-Content 'H:\demo\computernames.txt'

foreach ($Server in $Servers)
{
if (-not( Test-Connection $Server -Count 1 -Quiet )) { continue }

if (-not( Convert-QueryToObjects $Server -ErrorAction SilentlyContinue)) {

      $server | Out-File 'H:\demo\session\run1.csv' -Append

    }
else
{
   Convert-QueryToObjects -Name $Server | select ComputerName, Username, Sessionstate, IdleTime, ID | Export-Csv 'H:\demo\session\run.csv' -NoTypeInformation
}
}
</code>```

答:
Not tested, but are you wanting to do something like this?</p>

```<code>Get-Content "H:\demo\computernames.txt" | ForEach-Object {
  $computerName = $_
  if ( Test-Connection $computerName -Count 1 -Quiet ) {
    Convert-QueryToObjects $computerName -ErrorAction SilentlyContinue
  }
  else {
    "$_ not pingable" | Out-File "H:\demo\session\notpingable.log" -Append
  }
} | Export-Csv "H:\demo\session\run.csv" -NoTypeInformation
</code>```

Title: Exporting each variable value in loop

Body:
I am trying to capture the changing variable '$server' everytime the parameters go through a foreach loop. To summarize, the $sever value is always changing, and I want to capture it and add it into a collective csv file

Thank you!

Here is the code main part of the code that I have.

 function Convert-QueryToObjects
 {
   [CmdletBinding()]
   [Alias('QueryToObject')]
   [OutputType([PSCustomObject])]
   param
   (
    [Parameter(Mandatory = $false,
               ValueFromPipeline = $true,
               ValueFromPipelineByPropertyName = $true,
               Position = 0)]
    [Alias('ComputerName', 'Computer')]
    [string]
    $Name = $env:COMPUTERNAME
)

Process
{
    Write-Verbose "Running query.exe against $Name."
    $Users = query user /server:$Name 2>&1

    if ($Users -like "*No User exists*")
    {
        # Handle no user's found returned from query.
        # Returned: 'No User exists for *'
        Write-Error "There were no users found on $Name : $Users"
        Write-Verbose "There were no users found on $Name."
    }
    elseif ($Users -like "*Error*")
    {
        # Handle errored returned by query.
        # Returned: 'Error ...<message>...'
        Write-Error "There was an error running query against $Name : $Users"
        Write-Verbose "There was an error running query against $Name."
    }
    elseif ($Users -eq $null -and $ErrorActionPreference -eq 'SilentlyContinue')
    {
        # Handdle null output called by -ErrorAction.
        Write-Verbose "Error action has supressed output from query.exe. Results were null."
    }
    else
    {
        Write-Verbose "Users found on $Name. Converting output from text."

        # Conversion logic. Handles the fact that the sessionname column may be populated or not.
        $Users = $Users | ForEach-Object {
            (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
        } | ConvertFrom-Csv

        Write-Verbose "Generating output for $($Users.Count) users connected to $Name."

        # Output objects.
        foreach ($User in $Users)
        {
            Write-Verbose $User
            if ($VerbosePreference -eq 'Continue')
            {
                # Add '| Out-Host' if -Verbose is tripped.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                } | Out-Host
            }
            else
            {
                # Standard output.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                }
            }
        }
    }
}
}

$Servers = Get-Content 'H:\demo\computernames.txt'

foreach ($Server in $Servers)
{
if (-not( Test-Connection $Server -Count 1 -Quiet )) { continue }

if (-not( Convert-QueryToObjects $Server -ErrorAction SilentlyContinue)) {

      $server | Out-File 'H:\demo\session\run1.csv' -Append

    }
else
{
   Convert-QueryToObjects -Name $Server | select ComputerName, Username, Sessionstate, IdleTime, ID | Export-Csv 'H:\demo\session\run.csv' -NoTypeInformation
}
}

Body:
Not tested, but are you wanting to do something like this?

Get-Content "H:\demo\computernames.txt" | ForEach-Object {
  $computerName = $_
  if ( Test-Connection $computerName -Count 1 -Quiet ) {
    Convert-QueryToObjects $computerName -ErrorAction SilentlyContinue
  }
  else {
    "$_ not pingable" | Out-File "H:\demo\session\notpingable.log" -Append
  }
} | Export-Csv "H:\demo\session\run.csv" -NoTypeInformation


问:
How to update date in table based on two criteria from a select
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like</p>

```<code>UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)
</code>```

答:
See if this helps...</p>

```<code>-- some test data...
IF OBJECT_ID('tempdb..#TableA', 'U') IS NOT NULL
DROP TABLE #TableA;

CREATE TABLE #TableA (
    UserID INT NOT NULL,
    PlanName VARCHAR(5) NOT NULL,
    SomeDate DATE NULL,
    PRIMARY KEY CLUSTERED (UserID)
    );

IF OBJECT_ID('tempdb..#TableB', 'U') IS NOT NULL
DROP TABLE #TableB;

CREATE TABLE #TableB (
    UserID INT NOT NULL,
    PlanName VARCHAR(5) NOT NULL,
    PRIMARY KEY CLUSTERED (UserID, PlanName)
    );

INSERT #TableA (UserID, PlanName) VALUES
    (1, 'aaa'), (2, 'aab'), (3, 'abb'),
    (4, 'aaa'), (5, 'aab'), (6, 'ccc');

INSERT #TableB (UserID, PlanName) VALUES
    (1, 'aaa'), (1, 'abb'), (1, 'bbb'),
    (2, 'aaa'), (2, 'abb'), (2, 'bbb'),
    (3, 'aaa'), (3, 'abb'), (3, 'bbb'),
    (4, 'aaa'), (4, 'abb'), (4, 'bbb'),
    (5, 'aaa'), (5, 'abb'), (5, 'bbb'),
    (6, 'aaa'), (6, 'abb'), (6, 'bbb');

--=========================================

-- check initial values...
SELECT * FROM #TableA ta;
SELECT * FROM #TableB tb;

-- written as a SELECT...
SELECT
    *
FROM
    #TableA ta
WHERE
    EXISTS (SELECT 1 FROM #TableB tb WHERE ta.UserID = tb.UserID AND ta.PlanName = tb.PlanName);

    -- written as an UPDATE...
UPDATE ta SET
    ta.SomeDate = GETDATE()
FROM
    #TableA ta
WHERE
    EXISTS (SELECT 1 FROM #TableB tb WHERE ta.UserID = tb.UserID AND ta.PlanName = tb.PlanName);

-- check updated values...
SELECT * FROM #TableA ta;
</code>```

Body:
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like

UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)

Body:
See if this helps...

-- some test data...
IF OBJECT_ID('tempdb..#TableA', 'U') IS NOT NULL
DROP TABLE #TableA;

CREATE TABLE #TableA (
    UserID INT NOT NULL,
    PlanName VARCHAR(5) NOT NULL,
    SomeDate DATE NULL,
    PRIMARY KEY CLUSTERED (UserID)
    );

IF OBJECT_ID('tempdb..#TableB', 'U') IS NOT NULL
DROP TABLE #TableB;

CREATE TABLE #TableB (
    UserID INT NOT NULL,
    PlanName VARCHAR(5) NOT NULL,
    PRIMARY KEY CLUSTERED (UserID, PlanName)
    );

INSERT #TableA (UserID, PlanName) VALUES
    (1, 'aaa'), (2, 'aab'), (3, 'abb'),
    (4, 'aaa'), (5, 'aab'), (6, 'ccc');

INSERT #TableB (UserID, PlanName) VALUES
    (1, 'aaa'), (1, 'abb'), (1, 'bbb'),
    (2, 'aaa'), (2, 'abb'), (2, 'bbb'),
    (3, 'aaa'), (3, 'abb'), (3, 'bbb'),
    (4, 'aaa'), (4, 'abb'), (4, 'bbb'),
    (5, 'aaa'), (5, 'abb'), (5, 'bbb'),
    (6, 'aaa'), (6, 'abb'), (6, 'bbb');

--=========================================

-- check initial values...
SELECT * FROM #TableA ta;
SELECT * FROM #TableB tb;

-- written as a SELECT...
SELECT
    *
FROM
    #TableA ta
WHERE
    EXISTS (SELECT 1 FROM #TableB tb WHERE ta.UserID = tb.UserID AND ta.PlanName = tb.PlanName);

    -- written as an UPDATE...
UPDATE ta SET
    ta.SomeDate = GETDATE()
FROM
    #TableA ta
WHERE
    EXISTS (SELECT 1 FROM #TableB tb WHERE ta.UserID = tb.UserID AND ta.PlanName = tb.PlanName);

-- check updated values...
SELECT * FROM #TableA ta;


问:
handle textview link click in my android app
I'm currently rendering HTML input in a TextView like so:

```<code>tv.setText(Html.fromHtml("<a href='test'>test</a>"));
</code>```

The HTML being displayed is provided to me via an external resource, so I cannot change things around as I will, but I can, of course, do some regex tampering with the HTML, to change the href value, say, to something else.

What I want is to be able to handle a link click directly from within the app, rather than having the link open a browser window. Is this achievable at all? I'm guessing it would be possible to set the protocol of the href-value to something like "myApp://", and then register something that would let my app handle that protocol. If this is indeed the best way, I'd like to know how that is done, but I'm hoping there's an easier way to just say, "when a link is clicked in this textview, I want to raise an event that receives the href value of the link as an input parameter"

答:
```<code>public static void setTextViewFromHtmlWithLinkClickable(TextView textView, String text) {
    Spanned result;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(text);
    }
    textView.setText(result);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
}
</code>```

Body:
I'm currently rendering HTML input in a TextView like so:

tv.setText(Html.fromHtml("test"));

The HTML being displayed is provided to me via an external resource, so I cannot change things around as I will, but I can, of course, do some regex tampering with the HTML, to change the href value, say, to something else.

What I want is to be able to handle a link click directly from within the app, rather than having the link open a browser window. Is this achievable at all? I'm guessing it would be possible to set the protocol of the href-value to something like "myApp://", and then register something that would let my app handle that protocol. If this is indeed the best way, I'd like to know how that is done, but I'm hoping there's an easier way to just say, "when a link is clicked in this textview, I want to raise an event that receives the href value of the link as an input parameter"


问:
How to map enums to integers implicitliy
I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java

```<code>public enum Packets {

    // Maps enums to integers 0-3
    PACKET_NONE = 0, PACKET_SYNC,
    PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,

    // Maps enums to integers 13-16
    PACKET_FILL = 13,  PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}
</code>```

I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).

答:
In Java you can assign values to Enum if that's what you are looking for. It will look like this:

```<code>public enum Packets {
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3);

    private int value;

    Packets(int value){
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}
</code>```

Now you can call enum like this to get it's value:

```<code>Packets.PACKET_SYNC.getValue(); //It will return 1
</code>```

Body:
I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java

public enum Packets {

    // Maps enums to integers 0-3
    PACKET_NONE = 0, PACKET_SYNC,
    PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,

    // Maps enums to integers 13-16
    PACKET_FILL = 13,  PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}

I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).

Body:
In Java you can assign values to Enum if that's what you are looking for. It will look like this:

public enum Packets {
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3);

    private int value;

    Packets(int value){
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}

Now you can call enum like this to get it's value:

Packets.PACKET_SYNC.getValue(); //It will return 1


问:
Is it possible to wrap table rows responsively?
Is it possible to wrap a table row and its contents (tds) so that the table stays responsive? For example:

```<code><table>
<tr>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
</tr>
<tr>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
</tr>
</table>
</code>```

Can those two rows of 5 become two rows of 4 and a row of 2 for some screen sizes, or three rows of 3 and one row of 1 for others, and so on?

Have tried floats and inline styling but the rows are always on the next line, and never flush next to one another so the td areas look seamless. I have no access to the html of the table structure, so I'm trying to target it with CSS or even Javascript/jQuery.

Any ideas?

答:
If you don't have an access to the table, you can re-render it according to the screen size.

You can try something like this:

function renderTable() {
  var myTable = $('#myTable');
  var content_var = ["content01", "content02",
                "content03", "content04",
                "content05", "content06",
                "content07", "content08",
                "content09", "content10"];
  var html_lgTable = `

       ${content_var[0]}
       ${content_var[1]}
       ${content_var[2]}
       ${content_var[3]}
       ${content_var[4]}

       ${content_var[5]}
       ${content_var[6]}
       ${content_var[7]}
       ${content_var[8]}
       ${content_var[9]}

`

  var html_mdTable = `

       ${content_var[0]}
       ${content_var[1]}
       ${content_var[2]}
       ${content_var[3]}

       ${content_var[4]}
       ${content_var[5]}
       ${content_var[6]}
       ${content_var[7]}

       ${content_var[8]}
       ${content_var[9]}

`

  var html_xsTable = `

       ${content_var[0]}
       ${content_var[1]}
       ${content_var[2]}

       ${content_var[3]}
       ${content_var[4]}
       ${content_var[5]}

       ${content_var[6]}
       ${content_var[7]}
       ${content_var[8]}

       ${content_var[9]}

`

  var windowW  = $(window).innerWidth();

  if (windowW < 500) {
    $('#myTable').html(html_xsTable);
  }
  else if ((windowW > 500) && (windowW < 900)) {
    $('#myTable').html(html_mdTable);
  }
  else $('#myTable').html(html_lgTable);
 }

$(document).ready(function() {
  renderTable();
  $(window).on("resize", function() {
       renderTable();
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  display: table;
  border: 1px solid black;
}

table td {
  border: 1px solid black;
  text-align: center;
}</code>```

```

Of course, content_var array should be parsed from original table.

Body:
Is it possible to wrap a table row and its contents (tds) so that the table stays responsive? For example:

Can those two rows of 5 become two rows of 4 and a row of 2 for some screen sizes, or three rows of 3 and one row of 1 for others, and so on?

Have tried floats and inline styling but the rows are always on the next line, and never flush next to one another so the td areas look seamless. I have no access to the html of the table structure, so I'm trying to target it with CSS or even Javascript/jQuery.

Any ideas?

Body:
If you don't have an access to the table, you can re-render it according to the screen size.

You can try something like this:

function renderTable() {
  var myTable = $('#myTable');
  var content_var = ["content01", "content02",
                "content03", "content04",
                "content05", "content06",
                "content07", "content08",
                "content09", "content10"];
  var html_lgTable = `
  <table>
    <tbody>
    <tr>
      <td> ${content_var[0]} </td>
      <td> ${content_var[1]} </td>
      <td> ${content_var[2]} </td>
      <td> ${content_var[3]} </td>
      <td> ${content_var[4]} </td>
    </tr>
     <tr>
      <td> ${content_var[5]} </td>
      <td> ${content_var[6]} </td>
      <td> ${content_var[7]} </td>
      <td> ${content_var[8]} </td>
      <td> ${content_var[9]} </td>
    </tr>
    </tbody>
  </table>`

  var html_mdTable = `
  <table>
    <tbody>
    <tr>
      <td> ${content_var[0]} </td>
      <td> ${content_var[1]} </td>
      <td> ${content_var[2]} </td>
      <td> ${content_var[3]} </td>
     </tr>
     <tr>
      <td> ${content_var[4]} </td>
      <td> ${content_var[5]} </td>
      <td> ${content_var[6]} </td>
      <td> ${content_var[7]} </td>
    </tr>
    <tr>
      <td colspan="2"> ${content_var[8]} </td>
      <td colspan="2"> ${content_var[9]} </td>
    </tr>
    </tbody>
  </table>`

  var html_xsTable = `
  <table>
    <tbody>
    <tr>
      <td> ${content_var[0]} </td>
      <td> ${content_var[1]} </td>
      <td> ${content_var[2]} </td>
     </tr>
     <tr>
      <td> ${content_var[3]} </td>
      <td> ${content_var[4]} </td>
      <td> ${content_var[5]} </td>
    </tr>
    <tr>
      <td> ${content_var[6]} </td>
      <td> ${content_var[7]} </td>
      <td> ${content_var[8]} </td>
    <tr>
      <td colspan="3"> ${content_var[9]} </td>
    </tr>
    </tbody>
  </table>`

  var windowW  = $(window).innerWidth();

  if (windowW < 500) {
    $('#myTable').html(html_xsTable);
  }
  else if ((windowW > 500) && (windowW < 900)) {
    $('#myTable').html(html_mdTable);
  }
  else $('#myTable').html(html_lgTable);
 }

$(document).ready(function() {
  renderTable();
  $(window).on("resize", function() {
       renderTable();
  })
});

table {
  display: table;
  border: 1px solid black;
}

table td {
  border: 1px solid black;
  text-align: center;
}

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
<table id="myTable">
</table>

Of course, content_var array should be parsed from original table.


问:
send data from ajax to controller codeigniter
I'm trying to send data from javascript to function in controller with ajax. But ajax wont send. I post my code below:

In javascript function

```<code>var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    }
});
</code>```

In controller

```<code>public function eventi()
{
    $day = $this->input->post('date');
    var_dump($day);
}
</code>```

答:
Try this. see if it works. Just using "type" instead of "method"

```<code>var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    type: 'POST',
    url: base_url + "Front_end_controller/eventi",
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    },
    error:function(result) {
      console.log(result);
    }
});
</code>```

And in your controler :

```<code>public function eventi()
{
    $day = $this->input->post('date');
    if(!empty($day))
    {
        echo $day;
    }
    else
    {
        echo "No Data";
    }
}
</code>```

Body:
I'm trying to send data from javascript to function in controller with ajax. But ajax wont send. I post my code below:

In javascript function

var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    }
});

In controller

public function eventi()
{
    $day = $this->input->post('date');
    var_dump($day);
}

Body:
Try this. see if it works. Just using "type" instead of "method"

var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    type: 'POST',
    url: base_url + "Front_end_controller/eventi",
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    },
    error:function(result) {
      console.log(result);
    }
});

And in your controler :

public function eventi()
{
    $day = $this->input->post('date');
    if(!empty($day))
    {
        echo $day;
    }
    else
    {
        echo "No Data";
    }
}


答:
No unfortunately, you will have to repeat the same expression DATE(now()) BETWEEN start_date AND end_date in your WHERE clause unless you are trying to access it in a outer query like

```<code>SELECT * FROM (
SELECT
    start_date,
    end_date,
    DATE(now()) BETWEEN start_date AND end_date as should_be_live
FROM mytable ) xxx
WHERE should_be_live = 1;
</code>```

Column alias are accessible only to GROUP BY, HAVING and ORDER BY clause and not to WHERE clause (that to it's a MySQL extension and not  standard SQL)

Title: How to set variable in mySQL

Body:
I have the following statement:

SELECT
    start_date,
    end_date,
    DATE(now()) BETWEEN start_date AND end_date should_be_live
FROM
    mytable
WHERE
    DATE(now()) BETWEEN start_date AND end_date should_be_live = 1

Is there a way to set a variable should_be_live = the expression DATE(now()) BETWEEN start_date AND end_date. If so, how would I do this?

Body:
No unfortunately, you will have to repeat the same expression DATE(now()) BETWEEN start_date AND end_date in your WHERE clause unless you are trying to access it in a outer query like

SELECT * FROM (
SELECT
    start_date,
    end_date,
    DATE(now()) BETWEEN start_date AND end_date as should_be_live
FROM mytable ) xxx
WHERE should_be_live = 1;

Column alias are accessible only to GROUP BY, HAVING and ORDER BY clause and not to WHERE clause (that to it's a MySQL extension and not  standard SQL)


问:
Selenium track network data transferred
Using the developer tools and network tab in chrome you are able to view track the quantity of data transfered.

I'm trying to find a way to do this programmatically using selenium.

I have tried adding up the transferSize in the Peformance.Resource entries (as described here: how to access Network panel on google chrome developer toools with selenium?.)

```<code>performance.clearResourceTimings();
  //Do Work
window.performance.getEntriesByType('resource');
</code>```

However this value is not accurate

Is this possible?

My current (inaccurate) code that totals the sizeTransfer figures

```<code> IWebDriver driver;

 /*Configure WebDriver*/

 IJavaScriptExecutor m_jse;
 m_jse = (IJavaScriptExecutor)m_driver;

 object Ents = m_jse.ExecuteScript("return window.performance.getEntriesByType('resource');");
 Type t = Ents.GetType();
 MethodInfo mGetCount = Ents.GetType().GetMethod("get_Count");
 int count = (int)mGetCount.Invoke(Ents, null);

  for(int i = 0; i < count; i++)
  {
      MethodInfo mi = Ents.GetType().GetMethod("get_Item");
      Dictionary<string, object> dict = (Dictionary<string, object>)mi.Invoke(Ents, new object[] { i });
      object Value;
      dict.TryGetValue("transferSize", out Value);
      string sSize = Value.ToString();
      size += Convert.ToDouble(sSize);
  }

  return size;
</code>```

答:
You are probably seeing inaccurate window.performance transferSize values because of CORS:

When CORS is in effect, many of the timing properties' values are returned as zero unless the server's access policy permits these values to be shared. This requires the server providing the resource to send the Timing-Allow-Origin HTTP response header with a value specifying the origin or origins which are allowed to get the restricted timestamp values.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/Using_the_Resource_Timing_API#Coping_with_CORS

HAR Export Trigger by Firebug might be a tool you'd want to consider. This Firefox-only extension will export all network/performance data into a .har file, which you can similarly parse:

```<code>...
"content": {
    "size": 33,
    "compression": 0,
    "mimeType": "text/html; charset=utf-8",
    "text": "PGh0bWw+PGhlYWQ+PC9oZWFkPjxib2R5Lz48L2h0bWw+XG4=",
    "encoding": "base64",
    "comment": ""
}
...
</code>```

Title: Selenium track network data transferred

Body:
Using the developer tools and network tab in chrome you are able to view track the quantity of data transfered.

I'm trying to find a way to do this programmatically using selenium.

I have tried adding up the transferSize in the Peformance.Resource entries (as described here: how to access Network panel on google chrome developer toools with selenium?.)

performance.clearResourceTimings();
  //Do Work
window.performance.getEntriesByType('resource');

However this value is not accurate

Is this possible?

My current (inaccurate) code that totals the sizeTransfer figures

 IWebDriver driver;

 /*Configure WebDriver*/

 IJavaScriptExecutor m_jse;
 m_jse = (IJavaScriptExecutor)m_driver;

 object Ents = m_jse.ExecuteScript("return window.performance.getEntriesByType('resource');");
 Type t = Ents.GetType();
 MethodInfo mGetCount = Ents.GetType().GetMethod("get_Count");
 int count = (int)mGetCount.Invoke(Ents, null);

  for(int i = 0; i < count; i++)
  {
      MethodInfo mi = Ents.GetType().GetMethod("get_Item");
      Dictionary<string, object> dict = (Dictionary<string, object>)mi.Invoke(Ents, new object[] { i });
      object Value;
      dict.TryGetValue("transferSize", out Value);
      string sSize = Value.ToString();
      size += Convert.ToDouble(sSize);
  }

  return size;

Body:
You are probably seeing inaccurate window.performance transferSize values because of CORS:

When CORS is in effect, many of the timing properties' values are returned as zero unless the server's access policy permits these values to be shared. This requires the server providing the resource to send the Timing-Allow-Origin HTTP response header with a value specifying the origin or origins which are allowed to get the restricted timestamp values.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/Using_the_Resource_Timing_API#Coping_with_CORS

HAR Export Trigger by Firebug might be a tool you'd want to consider. This Firefox-only extension will export all network/performance data into a .har file, which you can similarly parse:

...
"content": {
    "size": 33,
    "compression": 0,
    "mimeType": "text/html; charset=utf-8",
    "text": "PGh0bWw+PGhlYWQ+PC9oZWFkPjxib2R5Lz48L2h0bWw+XG4=",
    "encoding": "base64",
    "comment": ""
}
...


问:
center absolutely positioned  to absolutely positioned image
I try to make text that will be centered in the middle of the image, but the problem is that in my attempts I did not succeed to make it with resizing website. Any suggestions how to fix it and what I do wrong?

* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;margin:0}

.imageSlide-container {
    position: relative;
    margin: auto;
}
.imageSlide {
    position: absolute;
    width: 100%;
    height: auto;
    opacity: 0;
    z-index: 1;

    -webkit-transition: opacity 2.5s;
    -moz-transition: opacity 2.5s;
    -o-transition: opacity 2.5s;
    transition: opacity 2.5s;
}
.showing {
    opacity: 1;
    z-index: 2;
}

.prev, .next {
    z-index: 3;
    position: absolute;
    top: 50%;
    width: auto;
    cursor: pointer;
    color: red;
    /*margin-top: -22px;*/
    padding: 15px;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;

}
.next {
    right: 0;
    border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
}
@media only screen and (max-width: 300px) {
    .prev, .next,.text {font-size: 11px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="imageSlide-container">
    <img class="imageSlide showing" src="https://www.w3schools.com/howto/img_nature_wide.jpg">
    <img class="imageSlide" src="https://www.w3schools.com/howto/img_fjords_wide.jpg">
    <img class="imageSlide" src="https://www.w3schools.com/howto/img_mountains_wide.jpg">

    ❮
    ❯
</div></code>```

答:
I solved it with adding position: static to .showing, Because the image you see may not be set to position: absolute, so the code top: 50% in buttons can come from something.

* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;margin:0}

.imageSlide-container {
    position: relative;
    margin: auto;
}
.imageSlide {
    position: absolute;
    width: 100%;
    height: auto;
    opacity: 0;
    z-index: 1;

    -webkit-transition: opacity 2.5s;
    -moz-transition: opacity 2.5s;
    -o-transition: opacity 2.5s;
    transition: opacity 2.5s;
}
.showing {
    position: static;
    opacity: 1;
    z-index: 2;
}

.prev, .next {
    z-index: 3;
    position: absolute;
    top: 50%;
    width: auto;
    cursor: pointer;
    color: red;
    margin-top: -22px;
    padding: 15px;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;

}
.next {
    right: 0;
    border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
}
@media only screen and (max-width: 300px) {
    .prev, .next,.text {font-size: 11px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="imageSlide-container">
    <img class="imageSlide showing" src="https://www.w3schools.com/howto/img_nature_wide.jpg">
    <img class="imageSlide" src="https://www.w3schools.com/howto/img_fjords_wide.jpg">
    <img class="imageSlide" src="https://www.w3schools.com/howto/img_mountains_wide.jpg">

    ❮
    ❯
</div></code>```

Title: center absolutely positioned <a> to absolutely positioned image

Body:
I try to make text that will be centered in the middle of the image, but the problem is that in my attempts I did not succeed to make it with resizing website. Any suggestions how to fix it and what I do wrong?

* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;margin:0}

.imageSlide-container {
    position: relative;
    margin: auto;
}
.imageSlide {
    position: absolute;
    width: 100%;
    height: auto;
    opacity: 0;
    z-index: 1;

    -webkit-transition: opacity 2.5s;
    -moz-transition: opacity 2.5s;
    -o-transition: opacity 2.5s;
    transition: opacity 2.5s;
}
.showing {
    opacity: 1;
    z-index: 2;
}

.prev, .next {
    z-index: 3;
    position: absolute;
    top: 50%;
    width: auto;
    cursor: pointer;
    color: red;
    /*margin-top: -22px;*/
    padding: 15px;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;

}
.next {
    right: 0;
    border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
}
@media only screen and (max-width: 300px) {
    .prev, .next,.text {font-size: 11px}

    ❮
    ❯

Body:
I solved it with adding position: static to .showing, Because the image you see may not be set to position: absolute, so the code top: 50% in buttons can come from something.

* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;margin:0}

.imageSlide-container {
    position: relative;
    margin: auto;
}
.imageSlide {
    position: absolute;
    width: 100%;
    height: auto;
    opacity: 0;
    z-index: 1;

    -webkit-transition: opacity 2.5s;
    -moz-transition: opacity 2.5s;
    -o-transition: opacity 2.5s;
    transition: opacity 2.5s;
}
.showing {
    position: static;
    opacity: 1;
    z-index: 2;
}

.prev, .next {
    z-index: 3;
    position: absolute;
    top: 50%;
    width: auto;
    cursor: pointer;
    color: red;
    margin-top: -22px;
    padding: 15px;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;

}
.next {
    right: 0;
    border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
}
@media only screen and (max-width: 300px) {
    .prev, .next,.text {font-size: 11px}

<div class="imageSlide-container">
    <img class="imageSlide showing" src="https://www.w3schools.com/howto/img_nature_wide.jpg">
    <img class="imageSlide" src="https://www.w3schools.com/howto/img_fjords_wide.jpg">
    <img class="imageSlide" src="https://www.w3schools.com/howto/img_mountains_wide.jpg">

    <a class="prev" onclick="plusSlide-button(-1)">&#10094;</a>
    <a class="next" onclick="plusSlide-button(1)">&#10095;</a>
</div>


问:
On focus, how to place the caret after the last character in an already populated field in IE?
On focus, how to place the caret after the last character  in an already populated field in IE?</p>

答:
```<code>textareaname.scrollTop = textareaname.scrollHeight;
</code>```

Works for textareas

Nevermind, try this: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/

Body:
textareaname.scrollTop = textareaname.scrollHeight;

Works for textareas

Nevermind, try this: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/


问:
How to automatically update a SQL database
So I'm working with a professor who wants me to create a SQL Database containing information from csv files (from the New York City Department of Transportation). I've written program that takes the csv file and converts it into the appropriate sql commands. So my question is, how do i automate the database so that every 5 minutes or so a program downloads the new csv file, runs it through my csv-to-SQL command program, and then enters the output from my csv-to-SQL command program into terminal (what I use to interface with my SQL database)? Is there a specific language I should look into, I've seen people talk about cron?</p>

答:
cron is a reference to making a scheduled task under Unix; the Windows equivalent is to set up a task to run using a Task Scheduler.

I don't know that there's a pure SQL answer to your problem--probably the way I'd approach it is by writing a simple Import program in the language of your choice, compiling it down to an .EXE, then setting up a Task Scheduler command to run the program every 5 minutes. (Alternately, you could leave the app up all the time and simply let a timer execute every 5 minutes to trigger the import).


问:
How to check for duplicate 'ofstream' objects in a vector of shared pointers
In a practice project, I'm learning async/threading methodology as well as the concept for service type classes. I have a vector of shared pointers to ofstream objects, but am lost as to how to check for duplicates within that vector.

For clarification, I'm opting to have a single log file per module of my project, but in the event that two ofstream objects are added for the same file can cause mangling in outputs. I've tried a few different ways to compare between them, but I can't figure out the standard method of doing so. There also doesn't seem to be very much information on the subject, or perhaps I missed something basic in which I will slap myself for missing.

I know 'i' is accessing the objects in the vector, but cannot seem to get this to compile. Any and all help is greatly appreciated.

```<code>class LoggerService
{
public:
    ...
private:
    ...
    bool add_log_file(const std::string& file)
    {
        bool is_duplicate = false;
        for (int i : *ofstreams_) // <------ This block.
        {
            if (file.c_str() == i)
            {
                is_duplicate = true;
                break;
            }
        }

        if (!is_duplicate)
        {
            return false;
        }
        else
        {
            ofstreams_.push_back(std::make_shared<std::ofstream>(file.c_str()));
            return true;
        }
    }
    ...
    static std::vector<std::shared_ptr<std::ofstream>> ofstreams_;
    ...
}
</code>```

答: I doubt there is a standard way to get the path of an open ofstream. How about instead of a vector you have a map of file->ofstream. Or make your own class that contains path and ofstream and put those in the vector</p>

Body:
In a practice project, I'm learning async/threading methodology as well as the concept for service type classes. I have a vector of shared pointers to ofstream objects, but am lost as to how to check for duplicates within that vector.

For clarification, I'm opting to have a single log file per module of my project, but in the event that two ofstream objects are added for the same file can cause mangling in outputs. I've tried a few different ways to compare between them, but I can't figure out the standard method of doing so. There also doesn't seem to be very much information on the subject, or perhaps I missed something basic in which I will slap myself for missing.

I know 'i' is accessing the objects in the vector, but cannot seem to get this to compile. Any and all help is greatly appreciated.

class LoggerService
{
public:
    ...
private:
    ...
    bool add_log_file(const std::string& file)
    {
        bool is_duplicate = false;
        for (int i : *ofstreams_) // <------ This block.
        {
            if (file.c_str() == i)
            {
                is_duplicate = true;
                break;
            }
        }

        if (!is_duplicate)
        {
            return false;
        }
        else
        {
            ofstreams_.push_back(std::make_shared<std::ofstream>(file.c_str()));
            return true;
        }
    }
    ...
    static std::vector<std::shared_ptr<std::ofstream>> ofstreams_;
    ...
}


问:
Super expression must either be null or a function, not object
I get Super expression must either be null or a function, not object error when I run index.js

I see another post here with similar error message. But looks like that is related to react!

base.js

```<code>   export default class Base{
        constructor(title){
            console.log(title);
        }
    }
</code>```

Class1.js

```<code>import * as Base from './base';

export default class Class1 extends Base{
    constructor(title){
        super(title);
    }
}
</code>```

index.js

```<code>import * as Class1 from './class1';
'use strict';

function check() {
    var c = new Class1('from Index.js');
}

check();
</code>```

.babelrc

{
    "presets": [
        "es2015",
        "stage-1"
    ]
}

dependencies

```<code>dependencies": {
    "babel-cli": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-plugin-syntax-export-extensions": "^6.13.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-register": "^6.24.1"
  }
</code>```

Please help! Thanks in advance !

答:
You're doing namespace imports (* as …) that create namespace objects in your variables, which are not functions indeed like the error message says. You will want to import the default exports:

```<code>import Base from './base';
</code>```

and

```<code>import Class1 from './class1';
</code>```

Body:
I get Super expression must either be null or a function, not object error when I run index.js

I see another post here with similar error message. But looks like that is related to react!

base.js

   export default class Base{
        constructor(title){
            console.log(title);
        }
    }

Class1.js

import * as Base from './base';

export default class Class1 extends Base{
    constructor(title){
        super(title);
    }
}

index.js

import * as Class1 from './class1';
'use strict';

function check() {
    var c = new Class1('from Index.js');
}

check();

.babelrc

{
    "presets": [
        "es2015",
        "stage-1"
    ]
}

dependencies

dependencies": {
    "babel-cli": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-plugin-syntax-export-extensions": "^6.13.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-register": "^6.24.1"
  }

Please help! Thanks in advance !

Body:
You're doing namespace imports (* as …) that create namespace objects in your variables, which are not functions indeed like the error message says. You will want to import the default exports:

import Base from './base';

and

import Class1 from './class1';


问:
How to use single function to multiple classes?
I've got this following code:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('.sample1').click(function(){
            $('.dropdown-content').toggleClass('visible-dropdown');
        })
    })
</script>
</code>```

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

答:
You can just group the classes, separated by commas. Example : </p>

```<code>$('.sample1, .sample2, .sample3').click(function(){
</code>```

Body:
I've got this following code:

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

Body:
You can just group the classes, separated by commas. Example :

$('.sample1, .sample2, .sample3').click(function(){


问:
MySQL: Limiting result for WHERE IN list
Let's say there are millions of records in my_table.

Here is my query to extract rows with a specific name from list:

```<code>SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4')
</code>```

How do I limit the returned result per name1, name2, etc?
The following query would limit the whole result (to 100).

```<code>SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4') LIMIT 100
</code>```

I need to limit to 100 for each name.

答:
Try
SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4') FETCH FIRST 100 ROWS ONLY</p>

Body:
Let's say there are millions of records in my_table.

Here is my query to extract rows with a specific name from list:

SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4')

How do I limit the returned result per name1, name2, etc?
The following query would limit the whole result (to 100).

SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4') LIMIT 100

I need to limit to 100 for each name.