问:
Text-based game code not working?
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Here is my code:

```<code><!DOCTYPE html>
<html>
<head>
<title>game</title>
<style>
</style>
</head>
<body>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
/*var input;
var room;

function submitFunction() {
    alert("hello")
}
*/
</script>
<script type="text/javascript">
    var input;
    var room;
    room = "Main Enterence"

    $(document).ready(function () {
        $("#mainForm").submit(function() {
            input = document.getElementById("textInput").value;

            if (input == "east") {
                if (room == "Main Enterence") {
                    room = "Bedroom"
                    enterBedroom();
                }

            }
            if (input == "west") {

            }
            if (input == "north") {

            }
            if (input == "south") {

            }

        })
    })

function enterBedroom() {
    $( "#consoleOutput" ).append( "<p>Test</p>" );

}
</script>

<div id="consoleOutput">
    <p id="welcomeText"></p>
</div>

<form onsubmit="submitFunction()" id="mainForm">
    <input type="text" id="textInput">
    <input type="submit" name="sumbit">
</form>

</body>
</html>
</code>```

Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

答:
Error:

There are two functions invoked during submit of the form...

When you need page not to refresh then don't  use submit without preventing the default event...

Solution:

var input;
    var room;
    room = "Main Enterence";

        $("#mainForm").click(function() {
            input = document.getElementById("textInput").value;

            if (input == "east") {
                if (room == "Main Enterence") {
                    room = "Bedroom"
                    $("#consoleOutput").append( "
Test
" );
                }

            }
            if (input == "west") {

            }
            if (input == "north") {

            }
            if (input == "south") {

            }

        });
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="consoleOutput">
    <p id="welcomeText"></p>
</div>

<form id="mainForm">
    <input type="text" id="textInput">
    <input type="button" value="submit" name="submit">
</form></code>```

Title: Text-based game code not working?

Body:
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Here is my code:

<!DOCTYPE html>

<title>game</title>

<form onsubmit="submitFunction()" id="mainForm">
    <input type="text" id="textInput">
    <input type="submit" name="sumbit">
</form>

Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Body:
Error:

There are two functions invoked during submit of the form...

When you need page not to refresh then don't  use submit without preventing the default event...

Solution:

var input;
    var room;
    room = "Main Enterence";

        $("#mainForm").click(function() {
            input = document.getElementById("textInput").value;

            if (input == "east") {
                if (room == "Main Enterence") {
                    room = "Bedroom"
                    $("#consoleOutput").append( "<p>Test</p>" );
                }

            }
            if (input == "west") {

            }
            if (input == "north") {

            }
            if (input == "south") {

            }

        });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="consoleOutput">
    <p id="welcomeText"></p>
</div>

<form id="mainForm">
    <input type="text" id="textInput">
    <input type="button" value="submit" name="submit">
</form>


来源: stackexchange

问:
Box height is not as desired size in smaller devices- css
I'm facing an issue in matching the size of a  box to mobile(using bootstrap)
I have got 3 boxes, number 1 and 2 are images and number 3 has text,
and it looks like this

when I resize the screen to mobile size this is what happens(box number 3 is higher or in some devices shorter than box number 2, like here:error

I need it to look like that (box number 3 in the same height as 2):desired output

I tried to set max height and min hight to box3 but this is not the solution because it doesn't match to all the devices.

html:

```<code> <section id="carousel-section">

  <div class="container-fluid">

     <div class="row feature">
         <div class="col-lg-8 col-xl-8 col-md-12 col-xs-12 col-sm-12 ">
             <div class="carousel-margin">
<div id="myCarousel" class="carousel1 slide container-carousel" data-
 ride="carousel1">
  <!-- Indicators -->
 <ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
 </ol>

 <!-- Wrapper for slides -->
 <div class="carousel-inner">
<div class="item active">
  <img src="images/dragon_hunter_pic.png" alt="dragon_hunter_pic"
   id="mainImage1" >
</div>

 </div>

    </div>
         </div>
         </div>
            <div class="col-lg-4 col-xl-4 col-md-5 col-xs-5 col-sm-5 ">

       <div class="women-margin">
  <img src="images/women_3.png" alt="live" id="women-eyes1" >
            </div>
            </div>

  <div class="col-lg-4 col-xl-4 col-md-7 col-xs-7 col-sm-7 ">

      <div class="yellow-box">

      <h2 id="change_h2">THE DRAGON HUNTER</h2>
            <br/>
            <p id="change_p"> Lorem ipsum dolor sit amet, consectetur
       adipiscing elit, sed do eiusmod tempor incididunt ut labore et
        dolor aliqua. </p>

         </div>

      </div>

  </div>
 </div>

  </section>
</code>```

this is the problematic box, box number 3:

```<code>    <div class="yellow-box">
</code>```

css:

```<code>  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }
</code>```

this is box number 2:

```<code>  .women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }
</code>```

答:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example of Bootstrap 3 Nested Rows and Columns</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

```

Try this code.. for more info click here

ContentLicense: CC BY-SA 3.0

Body:
I'm facing an issue in matching the size of a  box to mobile(using bootstrap)
I have got 3 boxes, number 1 and 2 are images and number 3 has text,
and it looks like this

when I resize the screen to mobile size this is what happens(box number 3 is higher or in some devices shorter than box number 2, like here:error

I need it to look like that (box number 3 in the same height as 2):desired output

I tried to set max height and min hight to box3 but this is not the solution because it doesn't match to all the devices.

html:

THE DRAGON HUNTER

 Lorem ipsum dolor sit amet, consectetur
       adipiscing elit, sed do eiusmod tempor incididunt ut labore et
        dolor aliqua.

this is the problematic box, box number 3:

css:

  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }

this is box number 2:

  .women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }

Body:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example of Bootstrap 3 Nested Rows and Columns</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
 /* Some custom styles to beautify this example */
    .main-content{
  min-height: 330px;
        background: #dbdfe5;
    }
    .sidebar-content{
        min-height: 150px;
        margin-bottom: 30px;
        background: #b4bac0;
    }
</style>
</head>
<body>
 <!-- Open the output in a new blank tab (Click the arrow next to "Show Output" button) and resize the browser window to understand how the Bootstrap responsive grid system works. -->
 <div class="container">
        <div class="row">
            <div class="col-xs-12 col-lg-4">
                <div class="main-content"></div>
            </div>
            <div class="col-xs-6 col-lg-4">
                <!--Nested rows within a column-->

                        <div class="sidebar-content"></div></div>
                    <div class="col-xs-6 col-lg-4">
                        <div class="sidebar-content"></div>
                    </div>
                </div>
            </div>

</body>
</html>

Try this code.. for more info click here


问:
nodejs module not wowrking inside a function
i am having an issue with nodejs

the function bellow works fine

```<code>const process = require('detect-port');
port = 9090;
detect(port, (err, _port) => {
  if (err) {
    console.log(err);
  }else if (port == _port) {
   console.log("started");
   backgroundProcess();
  } else {
   console.log(`port: ${port} was occupied, try port: ${_port}`);
  }
});
</code>```

but does not work inside a function
i would like to know why and how to make it work

```<code>function lunchnd(){
const process = require('detect-port');
port = 9090;
detect(port, (err, _port) => {
  if (err) {
    console.log(err);
  }else if (port == _port) {
   console.log("started");
   backgroundProcess();
  } else {
   console.log(`port: ${port} was occupied, try port: ${_port}`);
  }
});
}

lunchnd();
</code>```

答:
In a few minutes, I found some implementations in Python including this one:
https://github.com/igobrilhante/simplex/blob/master/simplex.py

As any algorithm, there are no "secrets", you just have to implement each part of it. The easiest would probably be to start from a "pseudocode" perspective and write methods in the right spots. If your methods are placed in a sound order, then you can focus on implementing them one by one.

Of course, take a simple example that you've solved on paper to double check your work.

Body:
i am having an issue with nodejs

the function bellow works fine

const process = require('detect-port');
port = 9090;
detect(port, (err, _port) => {
  if (err) {
    console.log(err);
  }else if (port == _port) {
   console.log("started");
   backgroundProcess();
  } else {
   console.log(`port: ${port} was occupied, try port: ${_port}`);
  }
});

but does not work inside a function
i would like to know why and how to make it work

function lunchnd(){
const process = require('detect-port');
port = 9090;
detect(port, (err, _port) => {
  if (err) {
    console.log(err);
  }else if (port == _port) {
   console.log("started");
   backgroundProcess();
  } else {
   console.log(`port: ${port} was occupied, try port: ${_port}`);
  }
});
}

lunchnd();


问:
User information retrieval based download in Joomla
i am hosting a site in Joomla and we want to allow document downloads. however, we want the downloads only after user submits at least their email.

i searched and found that it could be possible to do this by means of user registration but is there a simpler way by means of a plugin that allows simple user email submission followed by download over full registration.

答:
You can try DocMan, which is a Joomla document management extension. The only issue is that this is a commercial, and it costs $99 for one website. But it is a solid extension.

Don't waste your time writing code to do what you want to do when an extension may do.


问:
jQuery load an image and swap by click
I have the following code on start to call the main image:

```<code>$(function () {
   var img = new Image();
   $(img).load(function () {
       //$(this).fadeOut('normal');
       $('#bg div table tr td').removeClass('loading').append(this);
       $(this).fadeIn();
   }).attr('src', 'images/home.jpg');
});
</code>```

Thats working so far. On click of an link i want to fade that one out and than load a second one in there. Somehow i cant get it to work... There are a lot of images that have to be loaded by clicking an element in the navigation, i´m not shure about the code. Any idea?

答:
This is probably a cleaner approach (sticking to jQuery)

```<code>$(function() {
    var $img = $('<img>', {
        src:    'images/home.jpg',
        load:   function() {
            $('#bg div table tr td').removeClass('loading').append(this);
            $(this).fadeIn('slow');
        },
        css: {
            display:  'none'
        }
    }).appendTo(document.body /* append wherever you need it */);

    $('a').bind('click', function() {
         $img.fadeOut('slow', function() {
            $img.attr('src', '/images/newimage.jpg');
         });
    });
});
</code>```

Demo: http://www.jsfiddle.net/AJcXd/

ContentLicense: CC BY-SA 2.5

Title: jQuery load an image and swap by click

Body:
I have the following code on start to call the main image:

$(function () {
   var img = new Image();
   $(img).load(function () {
       //$(this).fadeOut('normal');
       $('#bg div table tr td').removeClass('loading').append(this);
       $(this).fadeIn();
   }).attr('src', 'images/home.jpg');
});

Thats working so far. On click of an link i want to fade that one out and than load a second one in there. Somehow i cant get it to work... There are a lot of images that have to be loaded by clicking an element in the navigation, i´m not shure about the code. Any idea?

Body:
This is probably a cleaner approach (sticking to jQuery)

$(function() {
    var $img = $('<img>', {
        src:    'images/home.jpg',
        load:   function() {
            $('#bg div table tr td').removeClass('loading').append(this);
            $(this).fadeIn('slow');
        },
        css: {
            display:  'none'
        }
    }).appendTo(document.body /* append wherever you need it */);

    $('a').bind('click', function() {
         $img.fadeOut('slow', function() {
            $img.attr('src', '/images/newimage.jpg');
         });
    });
});

Demo: http://www.jsfiddle.net/AJcXd/


问:
Getting rid of the warning message - the proper way
I am working on a legacy pro* C/C++ code and migrated the project to Visual Studio 2015. When I compile the code in VS, it is giving me a below warning message at more than 100 places.

```<code>warning C4267: '=': conversion from 'size_t' to 'unsigned short', possible loss of data
</code>```

and the corresponding code is

```<code>stmt.len = strlen((char*)stmt.arr); // VARCHAR stmt[500];
</code>```

I was planning to change the above code to

```<code>stmt.len = static_cast<unsigned short>(strlen((char *)stmt.arr));
</code>```

this will just remove the warning message. But I have to modify in more than 100 places. Is there any way to get rid of this warning message may be using some sort of macro?
Please suggest.

Thanks

答:
It's the right way to use size_t consistently. Or, there do the casting that you though as an update.

A work around for C4267 warnings and how to disable them also suggested here is:

```<code>#pragma warning (disable : 4267)
</code>```

For the macro #define (only a sample)

```<code>#include <iostream>
#include <string.h>
#define strlen(x) static_cast<unsigned short>(strlen((char *)x))
//I tested with ((char *)x+1) and ((char *)x+2) for variation

using namespace std;

int main() {
    char stmt[] = "something";
    int len = strlen((char*)stmt); // VARCHAR stmt[500];
    cout << len;
    return 0;
}
</code>```

Test here with IDEONE

Body:
I am working on a legacy pro* C/C++ code and migrated the project to Visual Studio 2015. When I compile the code in VS, it is giving me a below warning message at more than 100 places.

warning C4267: '=': conversion from 'size_t' to 'unsigned short', possible loss of data

and the corresponding code is

stmt.len = strlen((char*)stmt.arr); // VARCHAR stmt[500];

I was planning to change the above code to

stmt.len = static_cast<unsigned short>(strlen((char *)stmt.arr));

this will just remove the warning message. But I have to modify in more than 100 places. Is there any way to get rid of this warning message may be using some sort of macro?
Please suggest.

Thanks

Body:
It's the right way to use size_t consistently. Or, there do the casting that you though as an update.

A work around for C4267 warnings and how to disable them also suggested here is:

#pragma warning (disable : 4267)

For the macro #define (only a sample)

#include <iostream>
#include <string.h>
#define strlen(x) static_cast<unsigned short>(strlen((char *)x))
//I tested with ((char *)x+1) and ((char *)x+2) for variation

using namespace std;

int main() {
    char stmt[] = "something";
    int len = strlen((char*)stmt); // VARCHAR stmt[500];
    cout << len;
    return 0;
}

Test here with IDEONE


问:
Java functional generics
ComputeIfAbsent method of Map has following declaration:

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction).

Why wasn't parameter declared as Function<K,V> when K and V types are not used anywhere else?

Now I understand that K and V are very important and they are part of the Map class declaration.

答:
Simple example:

```<code>Map<String,Object> myMap = ...
Function<Object,String> myFunc = Object::toString;
myMap.computeIfAbsent("42", myFunc);
</code>```

Is this acceptable?

Well, given the type of myFunc is Function<Object,String>, and we have a Map<String,Object>, which sounds like there is a problem. It certainly wouldn't compile if you only accepted Function<K,V>.

But when you look at it closer, there isn't anything wrong. Not only does the code demonstrably work, it's also easy to see why it works: "42" is an instance of String, which has a toString() method. That method returns a String, which is of course an Object. So of course it's fine.

And this "fine"-ness is what is expressed by Function<? super K, ? extends V>.

Title: Java functional generics

Body:
Simple example:

Map<String,Object> myMap = ...
Function<Object,String> myFunc = Object::toString;
myMap.computeIfAbsent("42", myFunc);

Is this acceptable?

Well, given the type of myFunc is Function<Object,String>, and we have a Map<String,Object>, which sounds like there is a problem. It certainly wouldn't compile if you only accepted Function<K,V>.

But when you look at it closer, there isn't anything wrong. Not only does the code demonstrably work, it's also easy to see why it works: "42" is an instance of String, which has a toString() method. That method returns a String, which is of course an Object. So of course it's fine.

And this "fine"-ness is what is expressed by Function<? super K, ? extends V>.


问:
Render JSON data using React
I have this JSON data I am trying to render as a list.

```<code>[{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]
</code>```

I am trying to display the data such that I pass a title of the data and the id's as parameters from Parent class to Child class and the latter prints the data as list.

```<code>export default class Parent extends Component {
  render() {
    return (
        <div>
        <Child
          title={"Group 1"}
          options={this.props.data.name}
        />
        </div>
    );
  }
}
</code>```

Here's my Child class:

```<code>export default class Child extends Component {
  render() {
    var data=this.props;
    var title=this.props.title;
    var name=this.props.name;
    return (
      <ul>
        <h4>{title}</h4>
        <div>{this.props.map(item=>
          <li>{name}</li>
        )}
        </div>
      </ul>
    );
  }
}
</code>```

What I don't understand is how to use map in the Child class to display data. I know that I shouldn't write this.props.map(item=>. I am new to React and would appreciate some help fixing this.

答:
You have a few issues with your code:

You need to pass your JSON object down from your Parent to your Child-component. If it's called data, then do:

```<code><Child
  title={"Group 1"}
  options={this.props.data}
/>
</code>```

I suggest using data instead of options to prevent confusion, but that's up to you. Also, you cannot pass this.props.data.name because this.props.data is an array of objects.

Now that options is an array, we can properly use map(). You were trying to use map() on this.props, which is incorrect. So try instead:

```<code><div>
  {this.props.map(item=>
    <li>{item.name}</li>
  )}
</div>
</code>```

Also,
 elements can only have
 as their direct children. You have placed
 and
 elements as its children. Instead wrap those inside an
 element.

Full demo:

const data = [
  {
    "id": "1",
    "name": "Bill"
  }, {
    "id": "2",
    "name": "Sarah"
  }
];

class Parent extends React.Component {
  render() {
    return (

        <Child
          title={"Group 1"}
          options={this.props.data}
        />

    );
  }
}

class Child extends React.Component {
  render() {
    var title = this.props.title;
    return (

{title}

              {this.props.options.map(item=>

{item.name}

              )}

    );
  }
}

ReactDOM.render(<Parent data={data} />, document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Title: Render JSON data using React

Body:
I have this JSON data I am trying to render as a list.

[{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]

I am trying to display the data such that I pass a title of the data and the id's as parameters from Parent class to Child class and the latter prints the data as list.

export default class Parent extends Component {
  render() {
    return (

        <Child
          title={"Group 1"}
          options={this.props.data.name}
        />

    );
  }
}

Here's my Child class:

export default class Child extends Component {
  render() {
    var data=this.props;
    var title=this.props.title;
    var name=this.props.name;
    return (

{title}

{this.props.map(item=>

{name}

        )}

    );
  }
}

What I don't understand is how to use map in the Child class to display data. I know that I shouldn't write this.props.map(item=>. I am new to React and would appreciate some help fixing this.

Body:
You have a few issues with your code:

You need to pass your JSON object down from your Parent to your Child-component. If it's called data, then do:

<Child
  title={"Group 1"}
  options={this.props.data}
/>

I suggest using data instead of options to prevent confusion, but that's up to you. Also, you cannot pass this.props.data.name because this.props.data is an array of objects.

Now that options is an array, we can properly use map(). You were trying to use map() on this.props, which is incorrect. So try instead:

<div>
  {this.props.map(item=>
    <li>{item.name}</li>
  )}
</div>

Also, <ul> elements can only have <li> as their direct children. You have placed <h4> and <div> elements as its children. Instead wrap those inside an <li> element.

Full demo:

const data = [
  {
    "id": "1",
    "name": "Bill"
  }, {
    "id": "2",
    "name": "Sarah"
  }
];

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child
          title={"Group 1"}
          options={this.props.data}
        />
      </div>
    );
  }
}

class Child extends React.Component {
  render() {
    var title = this.props.title;
    return (
      <div>
        <h4>{title}</h4>
        <ul>
          <li>
            <div>
              {this.props.options.map(item=>
                <li>{item.name}</li>
              )}
            </div>
          </li>
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<Parent data={data} />, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


答:
let's don't use map in the child... try this:

```<code>let data = [{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]
</code>```

user map in parent component:

```<code>export default class Parent extends Component {
  render() {
    return (
        <div>
        <div>Group 1</div>
        <ul>
          {data.map(item => <Child
            options={item}
          />)}
        </ul>
        </div>
    );
  }
}
</code>```

enhance the  child component :

```<code>export default class Child extends Component {
  render() {
    let {options:{name}} = this.props
    return (
      <li>{name}</li>
    );
  }
}
</code>```

Title: Render JSON data using React

Body:
let's don't use map in the child... try this:

let data = [{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]

user map in parent component:

export default class Parent extends Component {
  render() {
    return (
        <div>
        <div>Group 1</div>
        <ul>
          {data.map(item => <Child
            options={item}
          />)}
        </ul>
        </div>
    );
  }
}

enhance the  child component :

export default class Child extends Component {
  render() {
    let {options:{name}} = this.props
    return (
      <li>{name}</li>
    );
  }
}


问:
Add an X to the end of a div with pure CSS?
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag">category 2</span>
<span class="categoryTag">category 3</span></code>```

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

答:
Although having content in your css may work, I would recommend having an additional span instead because not all browsers support content. It's still totally up to you though.

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}
.close {
    color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1 <span class="close">x</span></span>
<span class="categoryTag">category 2 <span class="close">x</span></span>
<span class="categoryTag">category 3 <span class="close">x</span></span></code>```

Body:
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

category 1
category 2
category 3

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

Body:
Although having content in your css may work, I would recommend having an additional span instead because not all browsers support content. It's still totally up to you though.

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}
.close {
    color: red;
}

<span class="categoryTag">category 1 <span class="close">x</span></span>
<span class="categoryTag">category 2 <span class="close">x</span></span>
<span class="categoryTag">category 3 <span class="close">x</span></span>


问:
before_action except: PATCH
I'm defining some variables that I need for my header, into my application controller. But I would like to disable it for my AJAX requests. So I would like to know if it's possible to disable a before action for all the PATCH requests. Like on the example below

ApplicationController:

```<code>before_action :some_value, except: PATCH method

def some_value
  @main_group = current_user.groups.first
  @groups = current_user.groups - @main_group
end
</code>```

答:
To check that request is AJAX request, you can use request.xhr? method. See the Rails API doc

And to use it in before_action, you can write something like:

```<code>before_action :some_value, unless: -> { request.xhr? }
</code>```

Title: before_action except: PATCH

Body:
I'm defining some variables that I need for my header, into my application controller. But I would like to disable it for my AJAX requests. So I would like to know if it's possible to disable a before action for all the PATCH requests. Like on the example below

ApplicationController:

before_action :some_value, except: PATCH method

def some_value
  @main_group = current_user.groups.first
  @groups = current_user.groups - @main_group
end

Body:
To check that request is AJAX request, you can use request.xhr? method. See the Rails API doc

And to use it in before_action, you can write something like:

before_action :some_value, unless: -> { request.xhr? }


问:
How to return JSON by rendering razor syntax in to string
I am following the tutorial in which the instructor create a class for converting razor syntax to string which is right bellow .

```<code> public static string RazorToString(Controller controller , string viewName , object model = null)
        {
            controller.ViewData.Model = model;
            using(var sw = new StringWriter())
            {
                ViewEngineResult viewResult;
                viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }
</code>```

In the controller action he return the jSON like this.

```<code>return Json(new { success = true, html = RazorViewToString.RazorToString(this,"GetAll" ,), message = "submitted succesfully" }, JsonRequestBehavior.AllowGet);
</code>```

The GetALL is the action method which he passed , which is returning the list of records. which is right below.

```<code> public ActionResult GetAll()
        {
            using (DBModel db = new DBModel())
            {
                var list = db.Employees.ToList();
                return View(list);
            }
        }
</code>```

This above method is the difference I mean in that tutorial the instructor has separately created a method which is getting the list and in this action method he called that method.but in my implementation i returing the list directly as you can seen above.so in the third parameter of

```<code>RazorViewToString.RazorToString(this,"GetAll" ,)
</code>```

He passed that method which i not created , what i supposed to pass here ? and also if someone can describe the functionality above i will be thankful to him. #Peace

答:
The second parameter is not the method name,but the view name.The third parameter is the view model/model needed for that view.

Looks like your GetAll.cshtml view is strongly typed to a list of Employees. So you should be passing that as the model parameter value.

```<code>var employeeList = db.Employees.ToList();
return Json(new { success = true,
                  html = RazorToString(this, "GetAll",employeeList ),
                  message = "submitted succesfully" },JsonRequestBehavior.AllowGet);
</code>```

This will call the RazorToString method and inside the method we are manually executing the razor view engine and it will return a string which is the HTML markup produced by the view. We are then creating an anonymous object with 3 properties success, html and message and passing that to the Json method, which will convert it to corresponding json format.

Body:
I am following the tutorial in which the instructor create a class for converting razor syntax to string which is right bellow .

 public static string RazorToString(Controller controller , string viewName , object model = null)
        {
            controller.ViewData.Model = model;
            using(var sw = new StringWriter())
            {
                ViewEngineResult viewResult;
                viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }

In the controller action he return the jSON like this.

return Json(new { success = true, html = RazorViewToString.RazorToString(this,"GetAll" ,), message = "submitted succesfully" }, JsonRequestBehavior.AllowGet);

The GetALL is the action method which he passed , which is returning the list of records. which is right below.

 public ActionResult GetAll()
        {
            using (DBModel db = new DBModel())
            {
                var list = db.Employees.ToList();
                return View(list);
            }
        }

This above method is the difference I mean in that tutorial the instructor has separately created a method which is getting the list and in this action method he called that method.but in my implementation i returing the list directly as you can seen above.so in the third parameter of

RazorViewToString.RazorToString(this,"GetAll" ,)

He passed that method which i not created , what i supposed to pass here ? and also if someone can describe the functionality above i will be thankful to him. #Peace

Body:
The second parameter is not the method name,but the view name.The third parameter is the view model/model needed for that view.

Looks like your GetAll.cshtml view is strongly typed to a list of Employees. So you should be passing that as the model parameter value.

var employeeList = db.Employees.ToList();
return Json(new { success = true,
                  html = RazorToString(this, "GetAll",employeeList ),
                  message = "submitted succesfully" },JsonRequestBehavior.AllowGet);

This will call the RazorToString method and inside the method we are manually executing the razor view engine and it will return a string which is the HTML markup produced by the view. We are then creating an anonymous object with 3 properties success, html and message and passing that to the Json method, which will convert it to corresponding json format.


问:
How to get last records with conditions from SQLite?
I need to get last records from SQLite but with some conditions.. Let's say I have this table

```<code>id         course
1           math
2           english
3           math
4           english
5           chemistry
</code>```

and I need to return records of ids 3,4,5 because for math the id: 3 is the last(newest) record, for english the id: 4 is the last(newest) record and so on..

I don't know how to group them and then pick the newest record and so on..

答:
You seem to want:</p>

```<code>select max(id) as id, course
from t
group by course;
</code>```

Body:
I need to get last records from SQLite but with some conditions.. Let's say I have this table

id         course
1           math
2           english
3           math
4           english
5           chemistry

and I need to return records of ids 3,4,5 because for math the id: 3 is the last(newest) record, for english the id: 4 is the last(newest) record and so on..

I don't know how to group them and then pick the newest record and so on..

Body:
You seem to want:

select max(id) as id, course
from t
group by course;


问:
Get distinct values of all the columns for more than 50 tables
I have to get distinct values of all the columns for more than 50 tables in Teradata, is there any easy way to do that?

I don't want to keep on typing

```<code>select count(*), count(distinct A), count(distinct B), .......
from xyz;
</code>```

答: Instead of Distinct you may try GroupBy.

Body:
I have to get distinct values of all the columns for more than 50 tables in Teradata, is there any easy way to do that?

I don't want to keep on typing

select count(*), count(distinct A), count(distinct B), .......
from xyz;


问:
Onclick Confirm add Checkbox Length
This should be really simple, but I can't get it to work and I'm an absolute beginner with Javascript. I looked at various threads here.
 I'm working with a django template, on a simple link. I want to add an onclick confirmation message such as 'Trash (14) Projects? Are you sure?' where 14 is the number of checkboxes ready to submit in a form. Right now I have.

```<code><button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add projects to trash - Are you sure?')" >Remove / Add To Trash</button>
</code>```

Which of course doesn't have the number of projects to be deleted. I could add a script in the head to count the classes of checkboxes, but I want to know how I might execute javascript inside the confirm dialog itself? Such as...

```<code><button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add ($(":checkbox:checked").length) to trash - Are you sure?')" >Remove / Add To Trash</button>
</code>```

Which doesn't work, probably because the ":checkbox:checked" gets escaped inside the onclick " ".

Anyone point me in the right direction as to what is the 'usual' way to do this kind of thing...

答:
Use quotes wisely and use + to create a valid string

```<code><button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add (' + $(':checkbox:checked').length + ') to trash - Are you sure?')" >Remove / Add To Trash</button>
</code>```

I would recommend using unobtrusive event handler. Add a unique identifier, I have added submitbutton as CSS class

```<code><button type="submit" class="actionbutton submitbutton" name="delete" >Remove / Add To Trash</button>
</code>```

Bind event using Native Vanilla JS

```<code>document.querySelector('.submitbutton').addEventListener("click", function (event) {
    var msg = 'Add (' + document.querySelectorAll('[type=checkbox]:checked').length + ') to trash - Are you sure?';
    if (!confirm(msg)) {
        event.preventDefault();
    }
});
</code>```

jQuery

```<code>$('.submitbutton').on('click', function(){
    return confirm('Add (' + $(':checkbox:checked').length + ') to trash - Are you sure?')
});
</code>```

Title: Onclick Confirm add Checkbox Length

Body:
This should be really simple, but I can't get it to work and I'm an absolute beginner with Javascript. I looked at various threads here.
 I'm working with a django template, on a simple link. I want to add an onclick confirmation message such as 'Trash (14) Projects? Are you sure?' where 14 is the number of checkboxes ready to submit in a form. Right now I have.

<button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add projects to trash - Are you sure?')" >Remove / Add To Trash</button>

Which of course doesn't have the number of projects to be deleted. I could add a script in the head to count the classes of checkboxes, but I want to know how I might execute javascript inside the confirm dialog itself? Such as...

<button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add ($(":checkbox:checked").length) to trash - Are you sure?')" >Remove / Add To Trash</button>

Which doesn't work, probably because the ":checkbox:checked" gets escaped inside the onclick " ".

Anyone point me in the right direction as to what is the 'usual' way to do this kind of thing...

Body:
Use quotes wisely and use + to create a valid string

<button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add (' + $(':checkbox:checked').length + ') to trash - Are you sure?')" >Remove / Add To Trash</button>

I would recommend using unobtrusive event handler. Add a unique identifier, I have added submitbutton as CSS class

<button type="submit" class="actionbutton submitbutton" name="delete" >Remove / Add To Trash</button>

Bind event using Native Vanilla JS

document.querySelector('.submitbutton').addEventListener("click", function (event) {
    var msg = 'Add (' + document.querySelectorAll('[type=checkbox]:checked').length + ') to trash - Are you sure?';
    if (!confirm(msg)) {
        event.preventDefault();
    }
});

jQuery

$('.submitbutton').on('click', function(){
    return confirm('Add (' + $(':checkbox:checked').length + ') to trash - Are you sure?')
});


问:
Automation Testing using winium
If multiple elements have got the same name and there is no unique id for elements. How do we proceed automation testing using winium?

Is it possible to use clickable point coordinates for automation?

答:
If you know that the position of the element you're interested in will not change, then you can first get a list of all the elements that match the name you are identifying with. Iterate through the list and print out the coordinates. Then determine which one is the one you want and use those coordinates for clicking on the element. I believe (0,0) is the top left corner of the screen.

Sometimes I've found that I can identify an element with the same name as other elements by finding its parent or child elements. This will only work if the parent/child elements differ from the other elements that had the same name. It's annoying but sometimes I've had to find a unique child element, then get the parent element 2 levels above that, for example. Because that child element was the only unique identifier.

Title: Automation Testing using winium


问:
Xcode cannot find ProductModuleName-Swift.h
I'm attempting to import my "-Swift.h" file into one of my Objective-C .h files but xcode keeps telling me that the file doesn't exist

```<code>#import "Aesculus-Swift.h"
</code>```

If I command click on the file name it will take me to the generated header file so I know it exists. Why is xcode not able to find it?

答: When you encounter such situation, just find your kinda "ProductName-Swift.h" file by just cmnd+click on it (even if xcode shows warning about it is not found, the #import "Aesculus-Swift.h" string is still clickable) and then in opened code editor window choose context menu and "Show in Finder" item, then explicitly add it to your project.

Body:
I'm attempting to import my "-Swift.h" file into one of my Objective-C .h files but xcode keeps telling me that the file doesn't exist

#import "Aesculus-Swift.h"

If I command click on the file name it will take me to the generated header file so I know it exists. Why is xcode not able to find it?


问:
Extract Drupal encoded data using MySQL from Ubercart table
I am writing an integration piece between Drupal/Ubercart and a in-house admin system.

The customer uses Ubercart products with attributes (e.g. a Plaque, which can contain a name, a company, a registration date and month). When an order is placed, the values entered for the attributes are written to uc_order_products, where the data field contains the actual values entered by the user. As far as I can tell, this is the only place where product attributes values, as entered by an end user to place an order, is stored.

The encoded attribute values uses a format seen all over Drupal tables to encode objects:

```<code>a:3:{s:10:"attributes";a:4:{s:26:"Name (to appear on plaque)";a:1:{i:0;s:10:"Some
Namee";}s:7:"Company";a:1:{i:0;s:28:"Some Company Name Goes here_";}s:19:"Certification
Month";a:1:{i:0;s:0:"";}s:18:"Certification Year";a:1:
{i:0;s:4:"2011";}}s:9:"shippable";s:1:"1";s:6:"module";s:10:"uc_product";}
</code>```

And expanded, it looks like this:

```<code>a:3:
{
    s:10:"attributes";
    a:4:
        {
            s:26:"Name (to appear on plaque)";
            a:1:
                {
                    i:0;
                    s:10:"Some Namee";
                }
            s:7:"Company";
            a:1:
                {
                    i:0;
                    s:28:"Some Company Name Goes Herep";
                }
            s:19:"Certification Month";
            a:1:
                {
                    i:0;
                    s:0:"";
                }
            s:18:"Certification Year";
            a:1:
                {
                    i:0;
                    s:4:"2011";
                }
        }
    s:9:"shippable";
    s:1:"1";
    s:6:"module";
    s:10:"uc_product";
}
</code>```

I there a simple way to get to the individual field values within this text using SQL? I can write a SQL function to go look for specifics, but I'd like to know if someone knows of an existing MySQL approach (perhaps within Drupal) which would do this.

Thanks!

答:
Don't know if any built-in solution exists, but I ended up writing a SQL Function which takes as parameter text such as Name (to appear on plaque). The function then locates the text and extracts the succeeding { ... } block and from it retrieves the corresponding string value. Rough, but works in this case.

If someone has a better solution, I'd like to hear about it!

Body:
I am writing an integration piece between Drupal/Ubercart and a in-house admin system.

The customer uses Ubercart products with attributes (e.g. a Plaque, which can contain a name, a company, a registration date and month). When an order is placed, the values entered for the attributes are written to uc_order_products, where the data field contains the actual values entered by the user. As far as I can tell, this is the only place where product attributes values, as entered by an end user to place an order, is stored.

The encoded attribute values uses a format seen all over Drupal tables to encode objects:

a:3:{s:10:"attributes";a:4:{s:26:"Name (to appear on plaque)";a:1:{i:0;s:10:"Some
Namee";}s:7:"Company";a:1:{i:0;s:28:"Some Company Name Goes here_";}s:19:"Certification
Month";a:1:{i:0;s:0:"";}s:18:"Certification Year";a:1:
{i:0;s:4:"2011";}}s:9:"shippable";s:1:"1";s:6:"module";s:10:"uc_product";}

And expanded, it looks like this:

a:3:
{
    s:10:"attributes";
    a:4:
        {
            s:26:"Name (to appear on plaque)";
            a:1:
                {
                    i:0;
                    s:10:"Some Namee";
                }
            s:7:"Company";
            a:1:
                {
                    i:0;
                    s:28:"Some Company Name Goes Herep";
                }
            s:19:"Certification Month";
            a:1:
                {
                    i:0;
                    s:0:"";
                }
            s:18:"Certification Year";
            a:1:
                {
                    i:0;
                    s:4:"2011";
                }
        }
    s:9:"shippable";
    s:1:"1";
    s:6:"module";
    s:10:"uc_product";
}

I there a simple way to get to the individual field values within this text using SQL? I can write a SQL function to go look for specifics, but I'd like to know if someone knows of an existing MySQL approach (perhaps within Drupal) which would do this.

Thanks!


问:
Calling a external API class on Observer best practice
what are the good practice in magento on what im trying to do, basically i have a Class that sends some information to a external API, in my case is a invoice management system, so always that a order status is changed to complete i need to create a invoice on a external software. In my class i already have all the logic, but i not sure what is that best practice on magento of how i should do it.

For example is it OK using this example above on the Observer class.

```<code>include 'ApiName.class.php';

class Company_InvoiceSystemName_Model_Observer{

    public function createInvoice($observer) {
        $order = $observer->getEvent()->getOrder();
        $stateComplete = Mage_Sales_Model_Order::STATE_COMPLETE;
        if($order->getState() == $stateComplete && $order->getOrigData('state') != $stateComplete) {
            //Call Class API Methods for creating Invoice
            ...

        }
    }
}
</code>```

答:
this is common practice.

according to your method code it could observe sales_order_save_after event.

Body:
what are the good practice in magento on what im trying to do, basically i have a Class that sends some information to a external API, in my case is a invoice management system, so always that a order status is changed to complete i need to create a invoice on a external software. In my class i already have all the logic, but i not sure what is that best practice on magento of how i should do it.

For example is it OK using this example above on the Observer class.

include 'ApiName.class.php';

class Company_InvoiceSystemName_Model_Observer{

    public function createInvoice($observer) {
        $order = $observer->getEvent()->getOrder();
        $stateComplete = Mage_Sales_Model_Order::STATE_COMPLETE;
        if($order->getState() == $stateComplete && $order->getOrigData('state') != $stateComplete) {
            //Call Class API Methods for creating Invoice
            ...

        }
    }
}


问:
Trying to automate a process in console application
I am trying to get my console application to simulate dragging and dropping a file, so far I have had no luck.

The system throws a win32 exception stating it cannot find the file, since I know that is not really the problem I was hoping someone could shed some light on what might be causing this behavior.

I suspect it might be DEP. I can drag and drop the file and the process runs as expected, but I need to automate this.

I have created a filewatcher and am right now trying to figure out how to get the code to work, prior to making it a windows service.

But right now I am really stuck on this win32 error.

```<code>     public class Watcher
{
    public static void Main(string[] args)
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if (args.Length != 2)
        {

           // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");

            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch jpg files.
        watcher.Filter = "*.jpg";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        Process.Start(e.FullPath + "c:\\demo\\kr-pano\\mpr.bat");

}
</code>```

Visit the link to see the full win32 exception details.
Win32Exception

答: Apparently the issue is being caused because the filesystemwatcher is single threaded, and when I try to launch my new process it stops the old one from running. All I needed to do was stub out a new runpano function and call it from my code, its working now. </p>

Body:
I am trying to get my console application to simulate dragging and dropping a file, so far I have had no luck.

The system throws a win32 exception stating it cannot find the file, since I know that is not really the problem I was hoping someone could shed some light on what might be causing this behavior.

I suspect it might be DEP. I can drag and drop the file and the process runs as expected, but I need to automate this.

I have created a filewatcher and am right now trying to figure out how to get the code to work, prior to making it a windows service.

But right now I am really stuck on this win32 error.

     public class Watcher
{
    public static void Main(string[] args)
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if (args.Length != 2)
        {

           // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");

            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch jpg files.
        watcher.Filter = "*.jpg";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        Process.Start(e.FullPath + "c:\\demo\\kr-pano\\mpr.bat");

}

Visit the link to see the full win32 exception details.
Win32Exception


问:
explosion not spawning attached to parent gameobject
So I'm trying to get my vehicle to play an explosion when colliding with an enemy vehicle and have succeeded in making the explosion appear but when doing so it is cloned outside of the parent object and gets left behind when collision happens at a speed so the actual player car doesn't look like its exploding but instead travels past the explosion prefab. Any ideas on how to fix this would be much appreciated. Thanks

void OnTriggerEnter(Collider col)
{
    if (col.tag == "Enemy")
    {
        PlayExplosion();
    }
}

void PlayExplosion()
{
    GameObject explosion = (GameObject)Instantiate(ExplosionGo);
    //set the position of the explosion
    explosion.transform.position = transform.position;
}
```

答:
You need to either manually set the parent:

explosion.transform.parent = transform;
```

<p>Or supply a parent transform in the <code>Instantiate</code> parameters:</p>

<pre class="lang-c# prettyprint-override"><code>GameObject explosion = (GameObject)Instantiate(ExplosionGo, transform);
</code>```

Body:
You need to either manually set the parent:

explosion.transform.parent = transform;

Or supply a parent transform in the Instantiate parameters:

GameObject explosion = (GameObject)Instantiate(ExplosionGo, transform);


问:
Is there such a thing as a Fourier cipher, by another name?
I've created a type of alphabet cipher that is based on the concept of a Fourier transform, where each character is defined based on how distant it is (in the alphabet) from the preceding character:

```<code>function fourier_cipher($text) {

   $letters = array(1=>'a', 2=>'b', 3=>'c', 4=>'d', 5=>'e', 6=>'f', 7=>'g', 8=>'h', 9=>'i', 10=>'j', 11=>'k', 12=>'l', 13=>'m', 14=>'n', 15=>'o', 16=>'p', 17=>'q', 18=>'r', 19=>'s', 20=>'t', 21=>'u', 22=>'v', 23=>'w', 24=>'x', 25=>'y', 26=>'z');

   $chars = str_split($text);

   $prev_number = 0;
   $prev_difference = 0;

   for ($i=0; $i<count($chars); $i++) {
      $letter = $chars[$i];
      $number = array_search($letter,$letters);
      if ($number) {
         $difference = ($prev_difference > 13) ? 26 - abs($number - $prev_number) : abs($number - $prev_number);
         $code[$i] = $letters[$difference];
         $prev_number = $number;
         $prev_difference = $difference;
      }
      else {
         $code[$i] = $letter;
      }

   }

   return implode($code);

}
</code>```

One of the benefits of this type of cipher is that, unlike a Caesar cipher, it can't be broken using normal letter-frequency analysis, since the cipher-letter that represents each actual letter is not constant throughout.

For example:

```<code>$text = 'we hold these truths to be self evident';
echo fourier_cipher($text);
// outputs: wh cgch pnwln kbcalk ae mc nlgf aqmeaif
</code>```

I know very little about ciphers, so I'm assuming that this type of thing has been done before.

I'm curious: Does this type of cipher have a name -- and how easy is it to decipher, compared with other techniques?

答:
Looks more like Vigenere. At least to me. I'd try to break this with a Friedman Kappa test: find out the letter-gap frequencies related to how often they occure in the target-language. Still I don't see what this has to do with Fourier?

edit: see the comment

Body:
I've created a type of alphabet cipher that is based on the concept of a Fourier transform, where each character is defined based on how distant it is (in the alphabet) from the preceding character:

function fourier_cipher($text) {

   $letters = array(1=>'a', 2=>'b', 3=>'c', 4=>'d', 5=>'e', 6=>'f', 7=>'g', 8=>'h', 9=>'i', 10=>'j', 11=>'k', 12=>'l', 13=>'m', 14=>'n', 15=>'o', 16=>'p', 17=>'q', 18=>'r', 19=>'s', 20=>'t', 21=>'u', 22=>'v', 23=>'w', 24=>'x', 25=>'y', 26=>'z');

   $chars = str_split($text);

   $prev_number = 0;
   $prev_difference = 0;

   for ($i=0; $i<count($chars); $i++) {
      $letter = $chars[$i];
      $number = array_search($letter,$letters);
      if ($number) {
         $difference = ($prev_difference > 13) ? 26 - abs($number - $prev_number) : abs($number - $prev_number);
         $code[$i] = $letters[$difference];
         $prev_number = $number;
         $prev_difference = $difference;
      }
      else {
         $code[$i] = $letter;
      }

   }

   return implode($code);

}

One of the benefits of this type of cipher is that, unlike a Caesar cipher, it can't be broken using normal letter-frequency analysis, since the cipher-letter that represents each actual letter is not constant throughout.

For example:

$text = 'we hold these truths to be self evident';
echo fourier_cipher($text);
// outputs: wh cgch pnwln kbcalk ae mc nlgf aqmeaif

I know very little about ciphers, so I'm assuming that this type of thing has been done before.

I'm curious: Does this type of cipher have a name -- and how easy is it to decipher, compared with other techniques?


答:
You need to set explosion transform a child of your car transform/ Try this:

void PlayExplosion()
{
    GameObject explosion = (GameObject)Instantiate(ExplosionGo);
    explosion.transform.SetParent(transform, false);
}
```

Title: explosion not spawning attached to parent gameobject

Body:
So I'm trying to get my vehicle to play an explosion when colliding with an enemy vehicle and have succeeded in making the explosion appear but when doing so it is cloned outside of the parent object and gets left behind when collision happens at a speed so the actual player car doesn't look like its exploding but instead travels past the explosion prefab. Any ideas on how to fix this would be much appreciated. Thanks

void OnTriggerEnter(Collider col)
{
    if (col.tag == "Enemy")
    {
        PlayExplosion();
    }
}

void PlayExplosion()
{
    GameObject explosion = (GameObject)Instantiate(ExplosionGo);
    //set the position of the explosion
    explosion.transform.position = transform.position;
}


问:
Wait for query result of Bookshelf insert
Basically I need to wait the result of the insert query made with Bookshelf.js, because I need the id provided by the query to insert a row in my DB

I don't understand some aspects of the asynchronous behavior of Node and its components

So the problem is in this part of the code:

Insert Method Bookshelf

```<code>var new_timer = new Timer({
                titolo: title,
                time: timerVal,
                created: creation,
                ended: ended,
                id_owner: owner
            });
new_timer.save(null, {method: "insert"}).then(function(model){
    if(!model)
        return res.send({status: 400, url: "/add"});
    associateTag(model.id_timer, tags);
    return res.send({status: 200, url: "/"});
});
</code>```

functions used

```<code>var insertAssociation = function(timerID, tags) {
     return knex.table('timer_tag').insert({id_tmr: timerID, id_tg: tags.id_tag});
}

var associateTag = function(timerID, tags) {
    var id_tag;
    for(var i = 0; i < tags.length; i++){
        getTagByName(tags[i]).then(function(result) {
            console.log(result);
            insertAssociation(timerID, result[0]).then(function(k) {
                console.log(k);
            });
        });
    }
}

var getTagByName = function(name) {
    return knex.table('tags').select('id_tag').where('nome_tag', name);
}
</code>```

答:
Replace

```<code>for(var i = 0; i < tags.length; i++){
        getTagByName(tags[i]).then(function(result) {
            console.log(result);
            insertAssociation(timerID, result[0]).then(function(k) {
                console.log(k);
            });
        });
    }
</code>```

By

```<code>Promise.all(tags.map(x => getTagByName(x)
   .then((result) => insertAssociation(timerID, result[0]))))
</code>```

You were launching asynchronously several requests. What I do is using Promise.all in order to wait all of theses requests to finish.

EDIT: Full example

```<code>  new_timer.save(null, {
    method: 'insert',
  }).then((model) => {
    if (!model) {
      res.send({
         status: 400,
         url: '/add',
      });

      return;
    }

    associateTag(model.id_timer, tags)
      .then((allRets) => {
          console.log(allRets);

          res.send({
            status: 200,
            url: "/"
          });
      })
      .catch(e => {
        // error handling
      });
  })
  .catch(e => {
    // error handling
  });

  var associateTag = function (timerID, tags) {
    return Promise.all(tags.map(x => getTagByName(x)
      .then((result) => insertAssociation(timerID, result[0]))));
  }
</code>```

Body:
Basically I need to wait the result of the insert query made with Bookshelf.js, because I need the id provided by the query to insert a row in my DB

I don't understand some aspects of the asynchronous behavior of Node and its components

So the problem is in this part of the code:

Insert Method Bookshelf

var new_timer = new Timer({
                titolo: title,
                time: timerVal,
                created: creation,
                ended: ended,
                id_owner: owner
            });
new_timer.save(null, {method: "insert"}).then(function(model){
    if(!model)
        return res.send({status: 400, url: "/add"});
    associateTag(model.id_timer, tags);
    return res.send({status: 200, url: "/"});
});

functions used

var insertAssociation = function(timerID, tags) {
     return knex.table('timer_tag').insert({id_tmr: timerID, id_tg: tags.id_tag});
}

var associateTag = function(timerID, tags) {
    var id_tag;
    for(var i = 0; i < tags.length; i++){
        getTagByName(tags[i]).then(function(result) {
            console.log(result);
            insertAssociation(timerID, result[0]).then(function(k) {
                console.log(k);
            });
        });
    }
}

var getTagByName = function(name) {
    return knex.table('tags').select('id_tag').where('nome_tag', name);
}

Body:
Replace

for(var i = 0; i < tags.length; i++){
        getTagByName(tags[i]).then(function(result) {
            console.log(result);
            insertAssociation(timerID, result[0]).then(function(k) {
                console.log(k);
            });
        });
    }

By

Promise.all(tags.map(x => getTagByName(x)
   .then((result) => insertAssociation(timerID, result[0]))))

You were launching asynchronously several requests. What I do is using Promise.all in order to wait all of theses requests to finish.

EDIT: Full example

  new_timer.save(null, {
    method: 'insert',
  }).then((model) => {
    if (!model) {
      res.send({
         status: 400,
         url: '/add',
      });

      return;
    }

    associateTag(model.id_timer, tags)
      .then((allRets) => {
          console.log(allRets);

          res.send({
            status: 200,
            url: "/"
          });
      })
      .catch(e => {
        // error handling
      });
  })
  .catch(e => {
    // error handling
  });

  var associateTag = function (timerID, tags) {
    return Promise.all(tags.map(x => getTagByName(x)
      .then((result) => insertAssociation(timerID, result[0]))));
  }


问:
Memory leak with linkedHashMap
I have a memory leak in my web application, this memory leak due to linkedHashMap and WebappClassLoader.
 So I must know in my code if there is something make this memory leak. Unfortunately, I don't notice the reason for this memory leak.
  I search on google to know the possibility of having a memory leak with linkedHashMap but I don't have a solution.

 All I need to know more information about this case of this memory leak, how can I resolve it and the possibility of having a memory leak in my case.

答:
Generally, memory leaks happen when references to objects are not garbage collected. Can you post some of your code related to LinkedHashMap? You can use JVisual - shipped in the SDK - to find the class causing memory leak.

In WebappClassLoader, ThreadLocal is notorious for memory leaks.

Title: Memory leak with linkedHashMap


问:
Feedparser SAXParseException, bozo:1
I'm using feedparser in a script that's generally working for RSS URLs, but there's one URL that's giving me a headache: tabbforum.com/feed.atom

I get a SAXParseException('not well-formed (invalid token)',).

```<code>import feedparser

def read_from_feed(self, rss_url):
    feed = feedparser.parse(rss_url)
    for entry in feed.entries:
        print('do stuff')

>>>>feed
{'feed': {}, 'entries': [], 'bozo': 1, 'encoding': 'utf-8', 'version': '', 'bozo_exception': SAXParseException('not well-formed (invalid token)',), 'namespaces': {}}
</code>```

I'm thinking that there's something wrong with the xml(?). Has anybody had previous experiences and have been able to find a work-around? Or have an idea what the problem is?

答: Had a similar problem. In my case I forgot to put http:// in front of URL and feedparser was treating it not as a url, but as an RSS XML.

Title: Feedparser SAXParseException, bozo:1

Body:
I'm using feedparser in a script that's generally working for RSS URLs, but there's one URL that's giving me a headache: tabbforum.com/feed.atom

I get a SAXParseException('not well-formed (invalid token)',).

import feedparser

def read_from_feed(self, rss_url):
    feed = feedparser.parse(rss_url)
    for entry in feed.entries:
        print('do stuff')

>>>>feed
{'feed': {}, 'entries': [], 'bozo': 1, 'encoding': 'utf-8', 'version': '', 'bozo_exception': SAXParseException('not well-formed (invalid token)',), 'namespaces': {}}

I'm thinking that there's something wrong with the xml(?). Has anybody had previous experiences and have been able to find a work-around? Or have an idea what the problem is?


问:
Change page on button click ViewPager Android
UPDATES: Logcat has been added to the question
I actually want to change view ( from one fragment to other. ) on button Click i have tried many things but I am unable to do it. I have also wrote a CustomViewPager to stop changing pages on swiping the screen. it is working fine.

Here is my code:

MyFragment

```<code> public CustomViewPager mViewPager;
 public Button next;
 public static int count=0;

 public static final MyFragment newInstance(String message,ArrayList<String> a)

 {

   MyFragment f = new MyFragment();

   Bundle bdl = new Bundle(1);

   bdl.putString(EXTRA_MESSAGE, message);
   bdl.putStringArrayList(EXTRA_ARRAY, a);

   f.setArguments(bdl);

   return f;

 }

 @Override

 public View onCreateView(LayoutInflater inflater, ViewGroup container,

   Bundle savedInstanceState) {

   String message = getArguments().getString(EXTRA_MESSAGE);
   View v = inflater.inflate(R.layout.myfragment_layout, container, false);

   spinner = (Spinner)v.findViewById(R.id.spinoptions);
   answer = (EditText)v.findViewById(R.id.answer);
   next = (Button)v.findViewById(R.id.next);

   next.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        mViewPager.setCurrentItem(1, true);//getItem(-1) for previous

// it is not working

    }
});

   ArrayList<String> list = new ArrayList<String>();
    list.add("list 1");
    list.add("list 2");
    list.add("list 3");
    Builtprofile.q.get(0).getOptions();

        answer.setVisibility(View.INVISIBLE);
        spinner.setVisibility(View.VISIBLE);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Builtprofile.context,
        android.R.layout.simple_spinner_item,getArguments().getStringArrayList(EXTRA_ARRAY));
    dataAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
       spinner.setAdapter(dataAdapter);

   TextView messageTextView = (TextView)v.findViewById(R.id.textView);

   messageTextView.setText(message);

   return v;

 }
 private int getItem() {
       return mViewPager.getCurrentItem();
}
</code>```

Code for my PageAdapter

```<code>class MyPageAdapter extends FragmentPagerAdapter {

      private List<Fragment> fragments;

      public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {

        super(fm);

        this.fragments = fragments;

      }

      @Override

      public Fragment getItem(int position) {

        return this.fragments.get(position);

      }

      @Override

      public int getCount() {

        return this.fragments.size();

      }

    }
</code>```

Code for ActivityClass

```<code>  public List<Fragment> getFragments(){

      List<Fragment> fList = new ArrayList<Fragment>();

     for(i=0;i<q.size();i++)
     {
      fList.add(MyFragment.newInstance(q.get(i).getText(),q.get(i).getOptions()));

     }

      return fList;

    }

  public void fragmentopener()
  {
      List<Fragment> fragments = getFragments();

        pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);

        pager.setAdapter(pageAdapter);
  }
</code>```

Code for myCustomViewPager

```<code>public class CustomViewPager extends ViewPager {

    private boolean isPagingEnabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.isPagingEnabled = false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.isPagingEnabled) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.isPagingEnabled) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}
</code>```

LogCat:

```<code>04-07 15:55:53.254: E/AndroidRuntime(17379): FATAL EXCEPTION: main
04-07 15:55:53.254: E/AndroidRuntime(17379): java.lang.NullPointerException
04-07 15:55:53.254: E/AndroidRuntime(17379):    at adapters.MyFragment$1.onClick(MyFragment.java:71)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.view.View.performClick(View.java:3574)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.view.View$PerformClick.run(View.java:14293)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.os.Handler.handleCallback(Handler.java:605)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.os.Looper.loop(Looper.java:137)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.app.ActivityThread.main(ActivityThread.java:4448)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at java.lang.reflect.Method.invokeNative(Native Method)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at java.lang.reflect.Method.invoke(Method.java:511)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
This is how i do it        </p>

```<code>    if (viewPager.getCurrentItem() < 4) {
        viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
      }
</code>```

Body:
UPDATES: Logcat has been added to the question
I actually want to change view ( from one fragment to other. ) on button Click i have tried many things but I am unable to do it. I have also wrote a CustomViewPager to stop changing pages on swiping the screen. it is working fine.

Here is my code:

MyFragment

 public CustomViewPager mViewPager;
 public Button next;
 public static int count=0;

 public static final MyFragment newInstance(String message,ArrayList<String> a)

 {

   MyFragment f = new MyFragment();

   Bundle bdl = new Bundle(1);

   bdl.putString(EXTRA_MESSAGE, message);
   bdl.putStringArrayList(EXTRA_ARRAY, a);

   f.setArguments(bdl);

   return f;

 }

 @Override

 public View onCreateView(LayoutInflater inflater, ViewGroup container,

   Bundle savedInstanceState) {

   String message = getArguments().getString(EXTRA_MESSAGE);
   View v = inflater.inflate(R.layout.myfragment_layout, container, false);

   spinner = (Spinner)v.findViewById(R.id.spinoptions);
   answer = (EditText)v.findViewById(R.id.answer);
   next = (Button)v.findViewById(R.id.next);

   next.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        mViewPager.setCurrentItem(1, true);//getItem(-1) for previous

// it is not working

    }
});

   ArrayList<String> list = new ArrayList<String>();
    list.add("list 1");
    list.add("list 2");
    list.add("list 3");
    Builtprofile.q.get(0).getOptions();

        answer.setVisibility(View.INVISIBLE);
        spinner.setVisibility(View.VISIBLE);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Builtprofile.context,
        android.R.layout.simple_spinner_item,getArguments().getStringArrayList(EXTRA_ARRAY));
    dataAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
       spinner.setAdapter(dataAdapter);

   TextView messageTextView = (TextView)v.findViewById(R.id.textView);

   messageTextView.setText(message);

   return v;

 }
 private int getItem() {
       return mViewPager.getCurrentItem();
}

Code for my PageAdapter

class MyPageAdapter extends FragmentPagerAdapter {

      private List<Fragment> fragments;

      public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {

        super(fm);

        this.fragments = fragments;

      }

      @Override

      public Fragment getItem(int position) {

        return this.fragments.get(position);

      }

      @Override

      public int getCount() {

        return this.fragments.size();

      }

    }

Code for ActivityClass

  public List<Fragment> getFragments(){

      List<Fragment> fList = new ArrayList<Fragment>();

     for(i=0;i<q.size();i++)
     {
      fList.add(MyFragment.newInstance(q.get(i).getText(),q.get(i).getOptions()));

     }

      return fList;

    }

  public void fragmentopener()
  {
      List<Fragment> fragments = getFragments();

        pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);

        pager.setAdapter(pageAdapter);
  }

Code for myCustomViewPager

public class CustomViewPager extends ViewPager {

    private boolean isPagingEnabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.isPagingEnabled = false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.isPagingEnabled) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.isPagingEnabled) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}

LogCat:

04-07 15:55:53.254: E/AndroidRuntime(17379): FATAL EXCEPTION: main
04-07 15:55:53.254: E/AndroidRuntime(17379): java.lang.NullPointerException
04-07 15:55:53.254: E/AndroidRuntime(17379):    at adapters.MyFragment$1.onClick(MyFragment.java:71)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.view.View.performClick(View.java:3574)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.view.View$PerformClick.run(View.java:14293)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.os.Handler.handleCallback(Handler.java:605)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.os.Looper.loop(Looper.java:137)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at android.app.ActivityThread.main(ActivityThread.java:4448)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at java.lang.reflect.Method.invokeNative(Native Method)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at java.lang.reflect.Method.invoke(Method.java:511)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
04-07 15:55:53.254: E/AndroidRuntime(17379):    at dalvik.system.NativeStart.main(Native Method)

Body:
This is how i do it

    if (viewPager.getCurrentItem() < 4) {
        viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
      }


问:
how to display ToolTip in android?
I want to display the ToolTip(QuickAction View) when I am moving my cursor on the view. Can any one please give me the simple example for it? tooltip will only contains the text value.</p>

答:
Possibly using myView.setTooltipText(CharSequence) (from API-level 26) or TooltipCompat (prior to API-level 26) is an additonal option:

```<code>TooltipCompat.setTooltipText(myView, context.getString(R.string.myString));
</code>```

Documentation says:

Helper class used to emulate the behavior of {@link View#setTooltipText(CharSequence)} prior to API level 26.

Title: how to display ToolTip in android?

Body:
Possibly using myView.setTooltipText(CharSequence) (from API-level 26) or TooltipCompat (prior to API-level 26) is an additonal option:

TooltipCompat.setTooltipText(myView, context.getString(R.string.myString));

Documentation says:

Helper class used to emulate the behavior of {@link View#setTooltipText(CharSequence)} prior to API level 26.


问:
how to make a array copie for calculations in jQuery
I'm busy to make a html(canvas) version of "Conway's Game of life" (just for fun and learning) and i'm stuck at the point were i have to calculate the next generation.

The problem that i have is that i need a backup version from the old gen to make the new one and sinds im using a "2D" array for my drawing i tryed something like:

```<code>var game = []; //this is the original array in 2D
var calc = game.slice();
// here the code to edit "game" and draw using "game"
// here the code to calculate the next gen on "calc" using the info from "game"
game = calc.slice();
// draw using info on "game"
</code>```

but somehow this didn't work on me...

So is there a mistake that i make or do i have to use another solution for this?

Also i did find some info on ".slice" on here but or i need more info on this or i'm stupid...

Greetings...

答:
If you are doing a deep copy (multidimension) then you should go through each layer at a time and slice it.

```<code>var calc = game.map(function(x){
    return x.slice();
});
</code>```

If you plan on doing this more than once then just create a function for it:

```<code>function deepCopyArray(arr){
    return returnArray = arr.map(function(x){
        return x.slice();
    });
}

var calc = deepCopyArray(game);
</code>```

If you don't want to use map then you can also do it with just a for-loop:

```<code>var calc = [];

for(var i = 0; i < game.length; i++){
    calc[i] = game[i].slice();
}
</code>```

Body:
I'm busy to make a html(canvas) version of "Conway's Game of life" (just for fun and learning) and i'm stuck at the point were i have to calculate the next generation.

The problem that i have is that i need a backup version from the old gen to make the new one and sinds im using a "2D" array for my drawing i tryed something like:

var game = []; //this is the original array in 2D
var calc = game.slice();
// here the code to edit "game" and draw using "game"
// here the code to calculate the next gen on "calc" using the info from "game"
game = calc.slice();
// draw using info on "game"

but somehow this didn't work on me...

So is there a mistake that i make or do i have to use another solution for this?

Also i did find some info on ".slice" on here but or i need more info on this or i'm stupid...

Greetings...

Body:
If you are doing a deep copy (multidimension) then you should go through each layer at a time and slice it.

var calc = game.map(function(x){
    return x.slice();
});

If you plan on doing this more than once then just create a function for it:

function deepCopyArray(arr){
    return returnArray = arr.map(function(x){
        return x.slice();
    });
}

var calc = deepCopyArray(game);

If you don't want to use map then you can also do it with just a for-loop:

var calc = [];

for(var i = 0; i < game.length; i++){
    calc[i] = game[i].slice();
}


问:
Apply Validation Rule to ListView's ItemsSource property
I'd like to validate a ListView by checking if the ItemsSource contains an empty collection. Here's the XAML.

```<code><ListView x:Name="lstvItemsInGroup"
            <ListView.ItemsSource>
                <Binding Path="ItemsInGroup" Mode="OneWay" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:CollectionNotEmptyValidationRule ErrorMessage="You must select at least one item" />
                    </Binding.ValidationRules>
                </Binding>
            </ListView.ItemsSource>

        </ListView>
</code>```

Here's the ValidationRule.

```<code>public class CollectionNotEmptyValidationRule : ValidationRule
    {
        public string ErrorMessage
        { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        ValidationResult lResult = null;

        IEnumerable<object> lCollection = (IEnumerable<object>)value;
        if (lCollection == null || lCollection.Count() == 0)
        {
            lResult = new ValidationResult(false, ErrorMessage);
        }
        else
        {
            lResult = new ValidationResult(true, null);
        }

        return lResult;
    }
</code>```

I am forcing the validation upon loading the usercontrol with

```<code>lstvItemsInGroup.GetBindingExpression(ListView.ItemsSourceProperty).UpdateSource();
</code>```

But the ValidationRule isn't even called, I have a breakpoint in the first line and nothing.

Any clues?

Thank you.

答: Here http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.updatesource.aspx it is said that the UpdateSource method only updates the source if the binding is in TwoWay or OneWayToSource modes. So, try setting Mode=TwoWay on your binding.

Body:
I'd like to validate a ListView by checking if the ItemsSource contains an empty collection. Here's the XAML.

<ListView x:Name="lstvItemsInGroup"
            <ListView.ItemsSource>
                <Binding Path="ItemsInGroup" Mode="OneWay" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:CollectionNotEmptyValidationRule ErrorMessage="You must select at least one item" />
                    </Binding.ValidationRules>
                </Binding>
            </ListView.ItemsSource>

        </ListView>

Here's the ValidationRule.

public class CollectionNotEmptyValidationRule : ValidationRule
    {
        public string ErrorMessage
        { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        ValidationResult lResult = null;

        IEnumerable<object> lCollection = (IEnumerable<object>)value;
        if (lCollection == null || lCollection.Count() == 0)
        {
            lResult = new ValidationResult(false, ErrorMessage);
        }
        else
        {
            lResult = new ValidationResult(true, null);
        }

        return lResult;
    }

I am forcing the validation upon loading the usercontrol with

lstvItemsInGroup.GetBindingExpression(ListView.ItemsSourceProperty).UpdateSource();

But the ValidationRule isn't even called, I have a breakpoint in the first line and nothing.

Any clues?

Thank you.


问:
Failed to start firewalld on centos 7
I installed firewalld on my centos server but as I tried to start it I got this:

```<code>$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.
</code>```

here is the systemctl status:

```<code>sudo systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled)
   Active: failed (Result: exit-code) since پنجشنبه 2016-04-07 05:36:17 UTC; 9s ago
  Process: 929 ExecStart=/usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS (code=exited, status=1/FAILURE)
 Main PID: 929 (code=exited, status=1/FAILURE)

آوریل 07 05:36:17 server1.hamed1soleimani.ir systemd[1]: firewalld.service: main process exited, code=exited, status=1/FAILURE
آوریل 07 05:36:17 server1.hamed1soleimani.ir systemd[1]: Failed to start firewalld - dynamic firewall daemon.
آوریل 07 05:36:17 server1.hamed1soleimani.ir systemd[1]: Unit firewalld.service entered failed state.
</code>```

and firewall-cmd status:

```<code>sudo firewall-cmd --stat
Traceback (most recent call last):
  File "/bin/firewall-cmd", line 24, in <module>
    from gi.repository import GObject
  File "/usr/lib64/python2.7/site-packages/gi/__init__.py", line 37, in <module>
    from . import _gi
ImportError: /usr/lib64/python2.7/site-packages/gi/_gi.so: undefined symbol: g_type_check_instance_is_fundamentally_a
</code>```

I cant realize relation between firewalld and some gtk python extensions!

答:
I know that it is an old thread , But I was facing this problem and I just fixed it, Figured it will help someone in the nearby future.

I thought the problem was in my code or that I mis placed the file.

Well , sadly This file is corrupted (perhaps misplaced)

/usr/lib/python2.7/site-packages/gi/_gi.so or I think it has been compiled badly.

What you need is to Update Glib 2 since it will overwrite & fix it , You can do this using yum

Try yum update glib2

I tested the above using CentOS Linux release 7.1.1503 (Core)

Cheers

Title: Failed to start firewalld on centos 7

Body:
I installed firewalld on my centos server but as I tried to start it I got this:

$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.

here is the systemctl status:

sudo systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled)
   Active: failed (Result: exit-code) since پنجشنبه 2016-04-07 05:36:17 UTC; 9s ago
  Process: 929 ExecStart=/usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS (code=exited, status=1/FAILURE)
 Main PID: 929 (code=exited, status=1/FAILURE)

آوریل 07 05:36:17 server1.hamed1soleimani.ir systemd[1]: firewalld.service: main process exited, code=exited, status=1/FAILURE
آوریل 07 05:36:17 server1.hamed1soleimani.ir systemd[1]: Failed to start firewalld - dynamic firewall daemon.
آوریل 07 05:36:17 server1.hamed1soleimani.ir systemd[1]: Unit firewalld.service entered failed state.

and firewall-cmd status:

sudo firewall-cmd --stat
Traceback (most recent call last):
  File "/bin/firewall-cmd", line 24, in <module>
    from gi.repository import GObject
  File "/usr/lib64/python2.7/site-packages/gi/__init__.py", line 37, in <module>
    from . import _gi
ImportError: /usr/lib64/python2.7/site-packages/gi/_gi.so: undefined symbol: g_type_check_instance_is_fundamentally_a

I cant realize relation between firewalld and some gtk python extensions!


问:
Why I am receiving duplicate rows in following query , Table structure is attached
How to remove duplicate rows?

Query is->

```<code> SELECT       ps.Project_Brief_Description ,mscd.Brief_Description, Tbl_MilestoneCategory_Master.MileStoneCategory_Name, ps.AR_No_Perm, ptm.ProjectType_Name, mscd.Project_Id, mscd.MilestoneCategory_ID, mscd.MilestoneSubCategory_Id,
                         mscd.MeasurementUnit, mscd.TotalWorkMeasure, mscd.WorkMeasureCompletion, mscd.TaskStartDate, mscd.TaskEndDate, mscd.ActualStartDate, mscd.ActualEndDate, mscd.ReasonForDelay,
                         ps.Project_Id AS Expr1, ps.Executor_Dept_Id, ps.ProjectType_ID,ps.Project_Id, mscd.MilestoneCategory_ID
FROM            Tbl_Project_MilestoneSubCategoryDetails AS mscd INNER JOIN
                         Tbl_Project_Summary AS ps ON mscd.Project_Id = ps.Project_Id INNER JOIN
                         Tbl_Project_Budget AS pb ON ps.Project_Id = pb.Project_Id INNER JOIN
                         Tbl_ProjectType_Master AS ptm ON ps.ProjectType_ID = ptm.ProjectType_Id INNER JOIN
                         Tbl_MilestoneCategory_Master ON mscd.MilestoneCategory_ID = Tbl_MilestoneCategory_Master.MilestoneCategory_Id
</code>```

DataBase Structure snapshot

Kindly note that, table with alias mscd has no primary key

答:
You can use rank() here, and in the having clause you can only pick where rank =1.
This way you can exclude the duplicate rows. </p>

Body:
How to remove duplicate rows?

Query is->

 SELECT       ps.Project_Brief_Description ,mscd.Brief_Description, Tbl_MilestoneCategory_Master.MileStoneCategory_Name, ps.AR_No_Perm, ptm.ProjectType_Name, mscd.Project_Id, mscd.MilestoneCategory_ID, mscd.MilestoneSubCategory_Id,
                         mscd.MeasurementUnit, mscd.TotalWorkMeasure, mscd.WorkMeasureCompletion, mscd.TaskStartDate, mscd.TaskEndDate, mscd.ActualStartDate, mscd.ActualEndDate, mscd.ReasonForDelay,
                         ps.Project_Id AS Expr1, ps.Executor_Dept_Id, ps.ProjectType_ID,ps.Project_Id, mscd.MilestoneCategory_ID
FROM            Tbl_Project_MilestoneSubCategoryDetails AS mscd INNER JOIN
                         Tbl_Project_Summary AS ps ON mscd.Project_Id = ps.Project_Id INNER JOIN
                         Tbl_Project_Budget AS pb ON ps.Project_Id = pb.Project_Id INNER JOIN
                         Tbl_ProjectType_Master AS ptm ON ps.ProjectType_ID = ptm.ProjectType_Id INNER JOIN
                         Tbl_MilestoneCategory_Master ON mscd.MilestoneCategory_ID = Tbl_MilestoneCategory_Master.MilestoneCategory_Id

DataBase Structure snapshot

Kindly note that, table with alias mscd has no primary key


问:
rm -f fails for missing files when using "bash -e" as shell in GNU Make 4
I have a Makefile that looks as follows:

```<code>.ONESHELL:
SHELL = /bin/bash
.SHELLFLAGS = -e

clean:
    rm -f foo

.PHONY: clean
</code>```

foo doesn't exist. When I run this on Debian, GNU Make 4.1 I get this error:

```<code>rm -f foo
/bin/bash: rm -f foo: No such file or directory
Makefile:6: recipe for target 'clean' failed
make: *** [clean] Error 1
</code>```

When I run it on macOS, GNU Make 3.81 it works as expected. It makes no difference if I write -rm -f instead of rm -f.

Why do I get the error? Running bash -e -c "rm -f foo" ; echo $? in a shell prints 0 on both systems.

Am I missing something?

答:
The error message has to be read quite carefully:

```<code>/bin/bash: rm -f foo: No such file or directory
</code>```

This isn't a message from rm saying it can't find foo, it's a message from Bash telling it can't find the file rm -f foo (with the spaces in the filename).

With .SHELLFLAGS = -e, the shell gets what would equal the command line:

```<code>bash -e "rm -f foo"
</code>```

So it looks for a file rm -f foo to read commands from. You need to explicitly add the -c flag to tell it to take the argument itself as a command, i.e. .SHELLFLAGS = -ec, resulting in

```<code>bash -ec "rm -f foo"
</code>```

Not surprisingly, the default value for .SHELLFLAGS contains -c:

The argument(s) passed to the shell are taken from the variable .SHELLFLAGS. The default value of .SHELLFLAGS is -c normally, or -ec in POSIX-conforming mode.

Body:
I have a Makefile that looks as follows:

.ONESHELL:
SHELL = /bin/bash
.SHELLFLAGS = -e

clean:
    rm -f foo

.PHONY: clean

foo doesn't exist. When I run this on Debian, GNU Make 4.1 I get this error:

rm -f foo
/bin/bash: rm -f foo: No such file or directory
Makefile:6: recipe for target 'clean' failed
make: *** [clean] Error 1

When I run it on macOS, GNU Make 3.81 it works as expected. It makes no difference if I write -rm -f instead of rm -f.

Why do I get the error? Running bash -e -c "rm -f foo" ; echo $? in a shell prints 0 on both systems.

Am I missing something?

Body:
The error message has to be read quite carefully:

/bin/bash: rm -f foo: No such file or directory

This isn't a message from rm saying it can't find foo, it's a message from Bash telling it can't find the file rm -f foo (with the spaces in the filename).

With .SHELLFLAGS = -e, the shell gets what would equal the command line:

bash -e "rm -f foo"

So it looks for a file rm -f foo to read commands from. You need to explicitly add the -c flag to tell it to take the argument itself as a command, i.e. .SHELLFLAGS = -ec, resulting in

bash -ec "rm -f foo"

Not surprisingly, the default value for .SHELLFLAGS contains -c:

The argument(s) passed to the shell are taken from the variable .SHELLFLAGS. The default value of .SHELLFLAGS is -c normally, or -ec in POSIX-conforming mode.