问:
Dynamically construct jquery datatable with server side data
Based on the parameter , i would like to load the database table data into jquery datatable for CRUD operation . Please suggest me how to construct the table header based on the parameter.

```<code>(class name /attributes or table/columns )
Employee -id,firstname,lastname,email
Sports  - id ,sportname,count
Tropy   - id ,result.
</code>```

If the user select Employee from dropdown , i will pull the data from employee table and show it in datatable.

view Part given below

```<code>var table = $('#example').DataTable( {
        "sAjaxSource": "/restservice/employee",
        "sAjaxDataProp": "",
        "order": [[ 0, "asc" ]],
          "aoColumns": [
            { "mData": "id"},
            { "mData": "firstName"},
            { "mData": "lastName"},
            { "mData": "email"}
          ],
          "paging":false
        });
</code>```

Given below is Controller

```<code>@org.springframework.web.bind.annotation.RestController
public class RestController {

     @RequestMapping(path="/restservice/employee", method=RequestMethod.GET)
        public List<Employee> getEmployees()
        {

            List<Employee> employeesList = new ArrayList<Employee>();
            employeesList.add(new Employee(1,"khaja","sherif","khaja@gmail.com"));
            employeesList.add(new Employee(2,"bharathi","bar","bharathi@gmail.com"));
            employeesList.add(new Employee(3,"arun ","arun","arun@gmail.com"));
            employeesList.add(new Employee(4,"rajesh","bose","rajesh@gmail.com"));
            return employeesList;
        }
</code>```

Employee table contains 4 columns, so i have hardcoded 4 column in datatable.
Since sports and trophy contains 3 and 2 column respectively , how to construct the table header in datatable ?

答:
I am using terms expected for ver 1.10+. Some of yours is a bit older I think.

Not sure that I fully understand what you are trying to do but it sounds like you are displaying columns based on the data returned. try this:

```<code>    <script>
        $(document).ready(function () {
            $("#sel").on("change",
            function () {
                 setupTable($(this).val());
            })
        });
        function setupTable(selVal) {
            //Employee -id,firstname,lastname,email
            //Sports  - id ,sportname,count
            //Tropy   - id ,result.
            if ($.fn.DataTable.isDataTable('#example')) {
                $('#example').DataTable().destroy();
            }
            var cols = [{ 'data': 'id', 'title': 'ID' }];
            switch (selVal) {
                case "Employee":
                    cols.push({ 'data': 'firstname', 'title': 'First Name' });
                    cols.push({ 'data': 'lastname', 'title': 'Last Name' });
                    cols.push({ 'data': 'email', 'title': 'Email' });
                    break;
                case "Sports":
                    cols.push({ 'data': 'sportname', 'title': 'Sport Name' });
                    cols.push({ 'data': 'count', 'title': 'Count' });
                    break;

                case "Trophy":
                    cols.push({ 'data': 'result', 'title': 'Result' });
                    break;
                default:
                    alert("nothing selected");
                    break;
            }
            $("#example").html("");
            $("#example").DataTable({
                "columns": cols,
                "ajax": {url: "/restservice/" + selVal, dataSrc:""},
                "order": [[ 0, "asc" ]],
                "paging":false
            });
        }
    </script>

    <div>
        <select id="sel">
            <option value="0">Select Layout</option>
            <option value="Employee">id,firstname,lastname,email</option>
            <option value="Sports"> id ,sportname,count</option>
            <option value="Trophy">id ,result</option>
        </select>

</div>
    <div>
        <table id="example" class="display">
            <thead></thead>
            <tbody></tbody>
        </table>
    </div>
</code>```

Body:
Based on the parameter , i would like to load the database table data into jquery datatable for CRUD operation . Please suggest me how to construct the table header based on the parameter.

(class name /attributes or table/columns )
Employee -id,firstname,lastname,email
Sports  - id ,sportname,count
Tropy   - id ,result.

If the user select Employee from dropdown , i will pull the data from employee table and show it in datatable.

view Part given below

var table = $('#example').DataTable( {
        "sAjaxSource": "/restservice/employee",
        "sAjaxDataProp": "",
        "order": [[ 0, "asc" ]],
          "aoColumns": [
            { "mData": "id"},
            { "mData": "firstName"},
            { "mData": "lastName"},
            { "mData": "email"}
          ],
          "paging":false
        });

Given below is Controller

@org.springframework.web.bind.annotation.RestController
public class RestController {

     @RequestMapping(path="/restservice/employee", method=RequestMethod.GET)
        public List<Employee> getEmployees()
        {

            List<Employee> employeesList = new ArrayList<Employee>();
            employeesList.add(new Employee(1,"khaja","sherif","khaja@gmail.com"));
            employeesList.add(new Employee(2,"bharathi","bar","bharathi@gmail.com"));
            employeesList.add(new Employee(3,"arun ","arun","arun@gmail.com"));
            employeesList.add(new Employee(4,"rajesh","bose","rajesh@gmail.com"));
            return employeesList;
        }

Employee table contains 4 columns, so i have hardcoded 4 column in datatable.
Since sports and trophy contains 3 and 2 column respectively , how to construct the table header in datatable ?

Body:
I am using terms expected for ver 1.10+. Some of yours is a bit older I think.

Not sure that I fully understand what you are trying to do but it sounds like you are displaying columns based on the data returned. try this:

    <script>
        $(document).ready(function () {
            $("#sel").on("change",
            function () {
                 setupTable($(this).val());
            })
        });
        function setupTable(selVal) {
            //Employee -id,firstname,lastname,email
            //Sports  - id ,sportname,count
            //Tropy   - id ,result.
            if ($.fn.DataTable.isDataTable('#example')) {
                $('#example').DataTable().destroy();
            }
            var cols = [{ 'data': 'id', 'title': 'ID' }];
            switch (selVal) {
                case "Employee":
                    cols.push({ 'data': 'firstname', 'title': 'First Name' });
                    cols.push({ 'data': 'lastname', 'title': 'Last Name' });
                    cols.push({ 'data': 'email', 'title': 'Email' });
                    break;
                case "Sports":
                    cols.push({ 'data': 'sportname', 'title': 'Sport Name' });
                    cols.push({ 'data': 'count', 'title': 'Count' });
                    break;

                case "Trophy":
                    cols.push({ 'data': 'result', 'title': 'Result' });
                    break;
                default:
                    alert("nothing selected");
                    break;
            }
            $("#example").html("");
            $("#example").DataTable({
                "columns": cols,
                "ajax": {url: "/restservice/" + selVal, dataSrc:""},
                "order": [[ 0, "asc" ]],
                "paging":false
            });
        }
    </script>

    <div>
        <select id="sel">
            <option value="0">Select Layout</option>
            <option value="Employee">id,firstname,lastname,email</option>
            <option value="Sports"> id ,sportname,count</option>
            <option value="Trophy">id ,result</option>
        </select>

</div>
    <div>
        <table id="example" class="display">
            <thead></thead>
            <tbody></tbody>
        </table>
    </div>


来源: stackexchange

问:
Redirect to another page after a page with a pdf file displays for 5 minutes
please I'm having a hard time getting this to work. I'm fairly new to MVC.

So here is my challenge.
I have an actionResult in my controller that reads a pdf file and displays the pdf in a browser:`

```<code>public ActionResult ViewPdf(DocumentSearchInputModel searchInputModel)
        {
            var realPath =
                     "C:/Users/ionyejekwe/Documents/Visual Studio 2015/Projects/OnlineSearchLagos/OnlineSearchLagos/assets/img/gtb.pdf";
            var fileStream = new FileStream(realPath, FileMode.Open, FileAccess.Read);
            var fsResult = new FileStreamResult(fileStream, "application/pdf");
            return File(fsResult, "application/pdf");
        }`
</code>```

In a view called searchResult.cshtm, I have this
View pdf

which is supposed to call the pdf actionResult and render it to the browser.
It works perfectly fine. But I want to close the pdf page, after 5 minutes. I have tried many ways, but none seems to be working.
I tried using this ajax:`

```<code><script>
    $.ajax({
        url: '@Url.Action("ViewPdf", "Search")',
        contentType: "application/pdf; charset=utf-8",
        success: function() { alert('Success'); },
        error: function () { alert('A error'); }
    });

</script>`
</code>```

just to see if the ajax will get to the page, but the ajax code its not even getting to the pdf page, it's been triggered in the page where the pdf is being called. Please how do i get the pdf page to close or redirect to another page after 5 minutes.
I will really appreciate any help.

答:
Maybe try it with the window.open() function. It opens a new tab with the first parameter as its URL. I have no experience with ASP so I am not trying to get the URL of your PDF.

```<code>var newWindow = window.open("your_url_here");
setTimeout(function(){newWindow.close()}, 300000);
</code>```

what this will do is open a new tab with the PDF and close it after 300000ms = 5min.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
please I'm having a hard time getting this to work. I'm fairly new to MVC.

So here is my challenge.
I have an actionResult in my controller that reads a pdf file and displays the pdf in a browser:`

public ActionResult ViewPdf(DocumentSearchInputModel searchInputModel)
        {
            var realPath =
                     "C:/Users/ionyejekwe/Documents/Visual Studio 2015/Projects/OnlineSearchLagos/OnlineSearchLagos/assets/img/gtb.pdf";
            var fileStream = new FileStream(realPath, FileMode.Open, FileAccess.Read);
            var fsResult = new FileStreamResult(fileStream, "application/pdf");
            return File(fsResult, "application/pdf");
        }`

In a view called searchResult.cshtm, I have this
View pdf

which is supposed to call the pdf actionResult and render it to the browser.
It works perfectly fine. But I want to close the pdf page, after 5 minutes. I have tried many ways, but none seems to be working.
I tried using this ajax:`

`

just to see if the ajax will get to the page, but the ajax code its not even getting to the pdf page, it's been triggered in the page where the pdf is being called. Please how do i get the pdf page to close or redirect to another page after 5 minutes.
I will really appreciate any help.

Body:
Maybe try it with the window.open() function. It opens a new tab with the first parameter as its URL. I have no experience with ASP so I am not trying to get the URL of your PDF.

var newWindow = window.open("your_url_here");
setTimeout(function(){newWindow.close()}, 300000);

what this will do is open a new tab with the PDF and close it after 300000ms = 5min.

Hope this helps!


问:
full page background color angular
Try as I might I can't find a way to style the full page in Angular.  All my templates exist in their own tiny little world that is some kind of subset

```<code>html {
    background-color: lightblue;
}
</code>```

does not work.  I tried getting my template to fill the to the parent's height/width, but that also did not work.  It still only fills partially.  It almost hits the edges on the sides and top, but stops where the last div reaches toward the bottom.

```<code>.whatever {
    background-color: lightblue;
    width:100%;
    height:100%;
}
</code>```

答:
in projects generated with the angular-cli you should have a styles.css (scss if you chose sass on generating the project) directly in src/styles.css

if you add the following css to it, the background will be styled accordingly:

```<code>body {
    background-color: lightblue;
}
</code>```

good luck!

@edit:

the reason, you cannot style the body tag from within a component's css file is the shadow dom. the shadow dom ensures, that the styles are specific to the according component which most of the time is useful (if you want to use the same class name for different styling rules of different components)

the following page might clarify things a bit more for you:
https://angular.io/docs/ts/latest/guide/component-styles.html#!#special-selectors

Title: full page background color angular

Body:
Try as I might I can't find a way to style the full page in Angular.  All my templates exist in their own tiny little world that is some kind of subset

html {
    background-color: lightblue;
}

does not work.  I tried getting my template to fill the to the parent's height/width, but that also did not work.  It still only fills partially.  It almost hits the edges on the sides and top, but stops where the last div reaches toward the bottom.

.whatever {
    background-color: lightblue;
    width:100%;
    height:100%;
}

Body:
in projects generated with the angular-cli you should have a styles.css (scss if you chose sass on generating the project) directly in src/styles.css

if you add the following css to it, the background will be styled accordingly:

body {
    background-color: lightblue;
}

good luck!

@edit:

the reason, you cannot style the body tag from within a component's css file is the shadow dom. the shadow dom ensures, that the styles are specific to the according component which most of the time is useful (if you want to use the same class name for different styling rules of different components)

the following page might clarify things a bit more for you:
https://angular.io/docs/ts/latest/guide/component-styles.html#!#special-selectors


问:
p5.js - When to declare variables using var vs this.varName
I'm still figuring out how to use p5.js. In regular java you have to declare each variable using its data type, ex. int foo = 0.

In p5, I know you can just use var foo but you can also declare variables using this.foo. If someone could clarify when is the proper time to use var and when i can use this, that would be very helpful.

For example, if I want to declare a variable inside a method,  should i use var foo = thing or could I declare it using this.foo = thing? What should I use when declaring global variables or when referring to objects passed into methods?

Thanks!

答:
First of all, p5 is not a language, it is a Javascript library, you are coding in Javascript, not p5.

Coming to your question, if you want to use some function as a data type, similar to a class in java, and want all the "instances" of that to have their own different variables, you use this. If they are just variables you use in someway but don't need to be specific for each instance, or if the function is not a constructor function and is not to be used as a data type, you will just use var then.

Again, there is no class stuff in javascript, you will have to write what is called a constructor function in order to "simulate" a java class, but be aware that a constructor function should not return anything. Here is an example of car class in java:

```<code>class car {
  int speed = ___;
  String model = ___;
  static int numOfWheels = ___;
}
</code>```

This is what it will look like in javascript (a constructor function):

```<code>function car() {
  this.speed = ____;
  this.model = ____;
  var numOfWheels = ___;
}
</code>```

If you declare a variable without this, it can be roughly compared to a static variable in a java class in the sense that it will be constant among all the instances.

So basically, at least in most cases, you will use this.varName usually inside constructor functions, i.e., functions that you will use to construct objects.

What should I use when declaring global variables or when referring to objects passed into methods?

Global variables will almost always be var something = something. When referring to objects passed into functions, just use the dot notation to refer to its properties like passedObject.someProperty

I would recommend you to learn Javascript before jumping into p5 directly, here are some resources that I found useful when I started learning Javascript-

w3 School

JavaScript Info Website

TheNewBoston

Body:
First of all, p5 is not a language, it is a Javascript library, you are coding in Javascript, not p5.

Coming to your question, if you want to use some function as a data type, similar to a class in java, and want all the "instances" of that to have their own different variables, you use this. If they are just variables you use in someway but don't need to be specific for each instance, or if the function is not a constructor function and is not to be used as a data type, you will just use var then.

Again, there is no class stuff in javascript, you will have to write what is called a constructor function in order to "simulate" a java class, but be aware that a constructor function should not return anything. Here is an example of car class in java:

class car {
  int speed = ___;
  String model = ___;
  static int numOfWheels = ___;
}

This is what it will look like in javascript (a constructor function):

function car() {
  this.speed = ____;
  this.model = ____;
  var numOfWheels = ___;
}

If you declare a variable without this, it can be roughly compared to a static variable in a java class in the sense that it will be constant among all the instances.

So basically, at least in most cases, you will use this.varName usually inside constructor functions, i.e., functions that you will use to construct objects.

What should I use when declaring global variables or when referring to objects passed into methods?

Global variables will almost always be var something = something. When referring to objects passed into functions, just use the dot notation to refer to its properties like passedObject.someProperty

I would recommend you to learn Javascript before jumping into p5 directly, here are some resources that I found useful when I started learning Javascript-

w3 School

JavaScript Info Website

TheNewBoston


问:
Chart js data to start at zero
That's how I set the data:

```<code>    const data = {
        labels: ['February', 'March'],
        datasets: [
            {
                label: 'My First dataset',
                backgroundColor: 'rgba(255,99,132,0.2)',
                borderColor: 'rgba(255,99,132,1)',
                borderWidth: 1,
                hoverBackgroundColor: 'rgba(255,99,132,0.4)',
                hoverBorderColor: 'rgba(255,99,132,1)',
                data: [5, 9]
            }
        ]
    };
</code>```

But the first element sets the beginning of the axis:

But I want it to start from zero

adding the following doesn't help:

```<code>options: {
  scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}
</code>```

I couldn't find another setting to do that on the docs.

I'm using this btw: https://www.npmjs.com/package/react-chartjs-2

答:
Try Adding min to your options:

```<code>    var options = {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
            min: 0
          }
        }]
      }
    };
</code>```

Live Copepen: Chart.js Start at zero

Title: Chart js data to start at zero

Body:
That's how I set the data:

    const data = {
        labels: ['February', 'March'],
        datasets: [
            {
                label: 'My First dataset',
                backgroundColor: 'rgba(255,99,132,0.2)',
                borderColor: 'rgba(255,99,132,1)',
                borderWidth: 1,
                hoverBackgroundColor: 'rgba(255,99,132,0.4)',
                hoverBorderColor: 'rgba(255,99,132,1)',
                data: [5, 9]
            }
        ]
    };

But the first element sets the beginning of the axis:

But I want it to start from zero

adding the following doesn't help:

options: {
  scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

I couldn't find another setting to do that on the docs.

I'm using this btw: https://www.npmjs.com/package/react-chartjs-2

Body:
Try Adding min to your options:

    var options = {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
            min: 0
          }
        }]
      }
    };

Live Copepen: Chart.js Start at zero


问:
Mootools form submit & content change
I'd like to replace my_div's content after user clicks the submit button with the output that comes from my.php. I want to achieve this using mootools javascript library. How can I do this?

```<code>
<div id="my_div">
<form name="myform" action="http://www.domain.com/my.php" method="POST">
<br><br>
<input type="text" size="25" value="Enter your name here!">
<br><input type="submit" value="Send me your name!">
</div>
</code>```

Thanks for reading.

答: Actually, MooTools More has this Form.Request package which does exactly what you need.</p>

ContentLicense: CC BY-SA 2.5

Title: Mootools form submit & content change

Body:
I'd like to replace my_div's content after user clicks the submit button with the output that comes from my.php. I want to achieve this using mootools javascript library. How can I do this?

<form name="myform" action="http://www.domain.com/my.php" method="POST">

<input type="text" size="25" value="Enter your name here!">

<input type="submit" value="Send me your name!">

Thanks for reading.


问:
Row values as column headings
How can I make the following sql result:

Be rendered in a result set like this

```<code>| ID  | Chain Size      | Length  | Hook Type  | Shortening Grab |
|-----|-----------------|---------|------------|-----------------|
| 163 | 7mm (1.5 tonne) | 1 metre | C Hook     |  Yes            |
| 226 | 7mm (1.5 tonne) | 1 metre | C Hook     |  No             |
| 247 | 7mm (1.5 tonne) | 1 metre | Latch Hook |  No             |
</code>```

I know that the values in columns 2,4,6 and 8 (which I want to be headers) will be the same across all rows (but different depending on the initial query).

I believe the approach for what I want is through the use of PIVOT but really struggling to get the desired result.

Thanks

答:
Assuming your source data actually looks like this:

Static Pivot

```<code>Select *
From  YourTable
Pivot (max(attributeValue) For [attributeName] in ([Chain Size],[Length],[Hook Type],[Shortening Grab]) ) p
</code>```

Returns

Dynamic Approach

```<code>Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([attributeName]) From Yourtable  Order by 1 For XML Path('')),1,1,'')
Select  @SQL = '
Select *
From YourTable
Pivot (max(attributeValue) For [attributeName] in (' + @SQL + ') ) p'
Exec(@SQL);
</code>```

Returns

Notice, without an item for column sequence, you'll see that they are alphabetical.

Title: Row values as column headings

Body:
How can I make the following sql result:

Be rendered in a result set like this

| ID  | Chain Size      | Length  | Hook Type  | Shortening Grab |
|-----|-----------------|---------|------------|-----------------|
| 163 | 7mm (1.5 tonne) | 1 metre | C Hook     |  Yes            |
| 226 | 7mm (1.5 tonne) | 1 metre | C Hook     |  No             |
| 247 | 7mm (1.5 tonne) | 1 metre | Latch Hook |  No             |

I know that the values in columns 2,4,6 and 8 (which I want to be headers) will be the same across all rows (but different depending on the initial query).

I believe the approach for what I want is through the use of PIVOT but really struggling to get the desired result.

Thanks

Body:
Assuming your source data actually looks like this:

Static Pivot

Select *
From  YourTable
Pivot (max(attributeValue) For [attributeName] in ([Chain Size],[Length],[Hook Type],[Shortening Grab]) ) p

Returns

Dynamic Approach

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([attributeName]) From Yourtable  Order by 1 For XML Path('')),1,1,'')
Select  @SQL = '
Select *
From YourTable
Pivot (max(attributeValue) For [attributeName] in (' + @SQL + ') ) p'
Exec(@SQL);

Returns

Notice, without an item for column sequence, you'll see that they are alphabetical.


问:
Force closing when checking if the user is already logged in
When my application starts, it just force closes itself.

I've checked the logcat and this is the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean prefs.UserSession.isUserLoggedin()' on a null object reference

I don't see why this is happening tho since I'm a newbie on Android Development :(

This is my Authentication.java (this is the first activity/class that is gonna be opened when the application starts)

```<code>...
import prefs.UserInfo;
import prefs.UserSession;
...

public class Authentication extends AppCompatActivity {
    private UserSession session;
    private UserInfo userInfo;
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
       if(session.isUserLoggedin()){
            startActivity(new Intent(this, Mainpage.class));
            finish();
        }
    ...
</code>```

This is my UserSession.java (A class which handles the session)

```<code>...
import android.content.Context;
import android.content.SharedPreferences;

public class UserSession {
    ....
    private static final String KEY_IS_LOGGED_IN = "isloggedin";
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Context ctx;

    public UserSession(Context ctx) {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences(PREF_NAME, ctx.MODE_PRIVATE);
        editor = prefs.edit();
    }
    public void setLoggedin(boolean isLoggedin){
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedin);
        editor.apply();
    }
    public boolean isUserLoggedin(){return prefs.getBoolean(KEY_IS_LOGGED_IN, false);}
}
</code>```

答:
In your code you are using parameter as context of the activity.

```<code>public UserSession(Context ctx) {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences(PREF_NAME, ctx.MODE_PRIVATE);
        editor = prefs.edit();
    }
</code>```

So you should initialize your user session object with context.Without context you received null object reference

```<code>private UserSession session=new UserSession(this);
</code>```

Body:
When my application starts, it just force closes itself.

I've checked the logcat and this is the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean prefs.UserSession.isUserLoggedin()' on a null object reference

I don't see why this is happening tho since I'm a newbie on Android Development :(

This is my Authentication.java (this is the first activity/class that is gonna be opened when the application starts)

...
import prefs.UserInfo;
import prefs.UserSession;
...

public class Authentication extends AppCompatActivity {
    private UserSession session;
    private UserInfo userInfo;
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
       if(session.isUserLoggedin()){
            startActivity(new Intent(this, Mainpage.class));
            finish();
        }
    ...

This is my UserSession.java (A class which handles the session)

...
import android.content.Context;
import android.content.SharedPreferences;

public class UserSession {
    ....
    private static final String KEY_IS_LOGGED_IN = "isloggedin";
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Context ctx;

    public UserSession(Context ctx) {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences(PREF_NAME, ctx.MODE_PRIVATE);
        editor = prefs.edit();
    }
    public void setLoggedin(boolean isLoggedin){
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedin);
        editor.apply();
    }
    public boolean isUserLoggedin(){return prefs.getBoolean(KEY_IS_LOGGED_IN, false);}
}

Body:
In your code you are using parameter as context of the activity.

public UserSession(Context ctx) {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences(PREF_NAME, ctx.MODE_PRIVATE);
        editor = prefs.edit();
    }

So you should initialize your user session object with context.Without context you received null object reference

private UserSession session=new UserSession(this);


问:
How to log to terminal using scotty with Intellij (Haskell plugin)?
So I'm having something odd happen. Here's an illustrative code example:

```<code>main :: IO ()
main
 = do
     scotty 8000 $ do
       get "/" serve
 where
  serve :: ActionM ()
  serve = do
    liftIO $ print "I'm about to serve a request!"
</code>```

My message should print to the IntelliJ console whenever I type in "localhost:8000/", but it doesn't. Yet when I comment out the scotty stuff and just have:

```<code>main :: IO ()
main
 = do print "Hello World!"
</code>```

IntelliJ has no problem printing this out. What am I doing wrong? When I use the Windows command prompt to run the executable (e.g. ghc --make to create it, then running it), everything works fine - "I'm about to serve a request!" prints to the command prompt terminal everytime I Type in "localhost:8000/"

答:
Figured it out. Needed to make a logger as follows:

```<code> logger <- mkRequestLogger def {
   outputFormat = CustomOutputFormat (\_ _ _ _ -> "")
   }
</code>```

so that the resulting code would look like:

```<code>main :: IO ()
main
 = do
     logger <- mkRequestLogger def {
       outputFormat = CustomOutputFormat (\_ _ _ _ -> "")
       }
     scotty 8000 $ do
       middleware logger
       -- do stuff here
</code>```

The CustomOutputFormat ignores all other incoming information, focusing only on what you want to print to the console.

Body:
So I'm having something odd happen. Here's an illustrative code example:

main :: IO ()
main
 = do
     scotty 8000 $ do
       get "/" serve
 where
  serve :: ActionM ()
  serve = do
    liftIO $ print "I'm about to serve a request!"

My message should print to the IntelliJ console whenever I type in "localhost:8000/", but it doesn't. Yet when I comment out the scotty stuff and just have:

main :: IO ()
main
 = do print "Hello World!"

IntelliJ has no problem printing this out. What am I doing wrong? When I use the Windows command prompt to run the executable (e.g. ghc --make to create it, then running it), everything works fine - "I'm about to serve a request!" prints to the command prompt terminal everytime I Type in "localhost:8000/"

Body:
Figured it out. Needed to make a logger as follows:

 logger <- mkRequestLogger def {
   outputFormat = CustomOutputFormat (\_ _ _ _ -> "")
   }

so that the resulting code would look like:

main :: IO ()
main
 = do
     logger <- mkRequestLogger def {
       outputFormat = CustomOutputFormat (\_ _ _ _ -> "")
       }
     scotty 8000 $ do
       middleware logger
       -- do stuff here

The CustomOutputFormat ignores all other incoming information, focusing only on what you want to print to the console.


问:
Partial ordering of forwarding reference and normal reference with deduction guides
gcc 8.0.0 and clang 5.0.0 disagree on the behavior of this program:

```<code>#include <iostream>

template <typename T>
struct A {
    A(const T&) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
    A(T&&)      { std::cout << __PRETTY_FUNCTION__ << '\n'; }
};

template <typename U> A(U&&) -> A<double>;

int main() {
    int i = 0;
    const int ci = 0;

    A a1(0);  // both say A<double>
    A a2(i);  // both say A<double>
    A a3(ci); // gcc says A<int>, clang says A<double>
}
</code>```

gcc's behavior doesn't make sense to me - if the const T& overload is preferred to the U&& overload for lvalue const int, why isn't the T&& overload preferred to the U&& overload for rvalue int? clang's makes more sense to me (none of the functions is more specialized than the other, so deduction guide wins).

Who's right?

答:
We are in partial-ordering land again. The type of the synthesized function template parameters are

```<code>T&&      // #1: not a forwarding reference
const T& // #2
U&&      // #3: a forwarding reference
</code>```

The pre-partial ordering transformation strips away referenceness and after that the top-level cv-qualification, leaving us with a bare type in all three cases. It follows that in all three cases deduction succeeds in both directions. We are now left with [temp.deduct.partial]/9's tiebreaker:

If, for a given type, deduction succeeds in both directions (i.e., the
  types are identical after the transformations above) and both P and A
  were reference types (before being replaced with the type referred to
  above):

if the type from the argument template was an lvalue
  reference and the type from the parameter template was not, the
  parameter type is not considered to be at least as specialized as the
  argument type; otherwise,

if the type from the argument template
  is more cv-qualified than the type from the parameter template (as
  described above), the parameter type is not considered to be at least
  as specialized as the argument type.

For U&& vs T&&, neither rule applies and there's no ordering. For U&& vs const T&, however, the parameter type U&& is not considered to be at least as specialized as the argument type const T&, per the first bullet.

Partial ordering therefore finds #2 to be more specialized than #3, but finds #1 and #3 to be indistinguishable. GCC is correct.

That said, this may well be an oversight in the partial ordering rules. Class template deduction is the first time we have a "rvalue reference to cv-unqualified template parameter that isn't a forwarding reference" thing. Previously, in double-reference cases, forwarding references will always lose to non-forwarding rvalue references at the second bullet (because the only way you get non-forwarding rvalue references is if you have cv T&& for some non-empty cv).

Body:
gcc 8.0.0 and clang 5.0.0 disagree on the behavior of this program:

#include <iostream>

template <typename T>
struct A {
    A(const T&) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
    A(T&&)      { std::cout << __PRETTY_FUNCTION__ << '\n'; }
};

template <typename U> A(U&&) -> A<double>;

int main() {
    int i = 0;
    const int ci = 0;

    A a1(0);  // both say A<double>
    A a2(i);  // both say A<double>
    A a3(ci); // gcc says A<int>, clang says A<double>
}

gcc's behavior doesn't make sense to me - if the const T& overload is preferred to the U&& overload for lvalue const int, why isn't the T&& overload preferred to the U&& overload for rvalue int? clang's makes more sense to me (none of the functions is more specialized than the other, so deduction guide wins).

Who's right?

Body:
We are in partial-ordering land again. The type of the synthesized function template parameters are

T&&      // #1: not a forwarding reference
const T& // #2
U&&      // #3: a forwarding reference

The pre-partial ordering transformation strips away referenceness and after that the top-level cv-qualification, leaving us with a bare type in all three cases. It follows that in all three cases deduction succeeds in both directions. We are now left with [temp.deduct.partial]/9's tiebreaker:

If, for a given type, deduction succeeds in both directions (i.e., the
  types are identical after the transformations above) and both P and A
  were reference types (before being replaced with the type referred to
  above):

if the type from the argument template was an lvalue
  reference and the type from the parameter template was not, the
  parameter type is not considered to be at least as specialized as the
  argument type; otherwise,

if the type from the argument template
  is more cv-qualified than the type from the parameter template (as
  described above), the parameter type is not considered to be at least
  as specialized as the argument type.

For U&& vs T&&, neither rule applies and there's no ordering. For U&& vs const T&, however, the parameter type U&& is not considered to be at least as specialized as the argument type const T&, per the first bullet.

Partial ordering therefore finds #2 to be more specialized than #3, but finds #1 and #3 to be indistinguishable. GCC is correct.

That said, this may well be an oversight in the partial ordering rules. Class template deduction is the first time we have a "rvalue reference to cv-unqualified template parameter that isn't a forwarding reference" thing. Previously, in double-reference cases, forwarding references will always lose to non-forwarding rvalue references at the second bullet (because the only way you get non-forwarding rvalue references is if you have cv T&& for some non-empty cv).


问:
PHP script to make a dynamic image
I have a CMS that my freind built and I need to adjust one thing but I don't know how so please help me ...

this is my question :

I have an image in my home page , and I want the user to be able to click on this image and navigate to some website

now this website's link will be provided by the user in the CMS

I have added a textbox so that the user can write the link , and saved the link in mySQL database , but I don't know how to connect my image to this link I have ?!

Please help me

Title: PHP script to make a dynamic image

Body: <a href="<?= $encodedurl ?>"><img src="..." /></a>


问:
What is the most efficient way to reset the size of a shape after scaling in PaperJS
I am attempting to create a very simple beacon-like animation in Paper JS. The idea is that a circle starts off very small and totally opaque and then gets larger and more transparent until it disappears and the animation restarts.

I'm using scaling to make the image larger but resetting it to it's original size is becoming problematic and at the moment I have resorted to cloning a second circle to reset it rather than just working with a single shape, there has to be a simpler way of doing this.

I've create a jsFiddle to demonstrate my rough code so far, any help would be appreciated.

http://jsfiddle.net/colethecoder/Y3S9n/1

答:
Set item.applyMatrix = false if you don't want to persist transformations alongside item.

For example, the following code linearly (i.e. "additively") animates item.scaling:

```<code>var item = new Path.Rectangle({
    point: [75, 75],
    size: [5, 5],
    strokeColor: 'black',
    applyMatrix: false
});

function onFrame(event) {
    item.scaling += 0.1;
}
</code>```

Body:
Set item.applyMatrix = false if you don't want to persist transformations alongside item.

For example, the following code linearly (i.e. "additively") animates item.scaling:

var item = new Path.Rectangle({
    point: [75, 75],
    size: [5, 5],
    strokeColor: 'black',
    applyMatrix: false
});

function onFrame(event) {
    item.scaling += 0.1;
}


问:
TDD without local database?
When we develop a Rails application then we use a local database in our development environment, and make sure that our specs pass as part of TDD.

Is it a norm to not use a local database similar to Sqlite while doing TDD in Java? I have been told in-memory database(HSQL) is all that is needed for running unit and integration tests. Is this a standard practice being followed?

We use Sqlite in our Rails application for local development and for running our Rspecs. But my question is for Java development. We are working on rewritting a part of our application in Java. I have been told that you do not need any database for development if you write integration tests covering all functionality. And have been told that HSQL is sufficient for that. As I am used to having database for local development in Rails, I am wondering how you debug any issues later on? It is quite helpful to analyze any issues if we can replicate the data and scenario in local environment. How do you do same in Java/Spring if you do not use any database for development environment and rely completely on HSQL for testing?

答:
For me, I never use any databases including HSQLDB to write an unit-test.

I prefer to create some interfaces like as: *Repository. and let's the SUT communicate with it. and then I write some implementation class let them implement the interface which I have created. and the classes hierarchy looks like below:

```<code>          <<uses>>
  SUT  ---------------> Repository
                            ^
                            | <<implement>>
                            |
               |--------|--------|-------|
               |        |        |       |
              JPA    Hibernate  JDBC    .etc
</code>```

this approach is known as Separation of Concerns. the application domain is a concern, data accessing is another concern. following this approach result in many plug-compatible components and independent modules, such as: domain, jpa, jdbc, and .etc, but the important thing is that will make your test is more testable.

Then I use Test Doubles to mock/stub out its collaboration in unit-test to testing them are work together as expected. the pseudo-code like as below:

```<code>repo = mock(Repository.class);
SUT it = new SUT(repository);

when(repo.find(id)).thenReturn(entity);

assert it.exercise() == expectedResult;
assert it.currentState == expectedState;
</code>```

But you must write some integration test using database to testing each Repository implementation that operate on the third-party api. it is called by Martin: Test Isolation.

Title: TDD without local database?

Body:
For me, I never use any databases including HSQLDB to write an unit-test.

I prefer to create some interfaces like as: *Repository. and let's the SUT communicate with it. and then I write some implementation class let them implement the interface which I have created. and the classes hierarchy looks like below:

          <<uses>>
  SUT  ---------------> Repository
                            ^
                            | <<implement>>
                            |
               |--------|--------|-------|
               |        |        |       |
              JPA    Hibernate  JDBC    .etc

this approach is known as Separation of Concerns. the application domain is a concern, data accessing is another concern. following this approach result in many plug-compatible components and independent modules, such as: domain, jpa, jdbc, and .etc, but the important thing is that will make your test is more testable.

Then I use Test Doubles to mock/stub out its collaboration in unit-test to testing them are work together as expected. the pseudo-code like as below:

repo = mock(Repository.class);
SUT it = new SUT(repository);

when(repo.find(id)).thenReturn(entity);

assert it.exercise() == expectedResult;
assert it.currentState == expectedState;

But you must write some integration test using database to testing each Repository implementation that operate on the third-party api. it is called by Martin: Test Isolation.


问:
How do I get the .exe name of a C# console application?
I'm debugging "xiixtasks.exe", a C# console-mode application in VS2008.

I'm trying to get the version info from xiixtasks.exe.

When I try "Process.GetCurrentProcess()", it gives me the filename and version info for vshost.exe, NOT xiixtasks.exe:

```<code>  // WRONG: this gives me xiixtasks.vhost.exe, version 9.0.30729.1
  //        I *want* "xiixtasks.exe", version 1.0.0.1024
  System.Diagnostics.FileVersionInfo fi =
    System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo;
</code>```

What should I be doing instead?

Thank you in advance!

======================================================

Solution:

1) The initial problem was indeed the IDE's "vshost" wrapper.
   One workaround would have been to change the build settings.

2) Assembly.GetExecutingAssembly().CodeBase is an excellent solution - thank you!.
   It works inside and outside the debugger.

3) Unfortunately, when I tried calling it with a function that expected a normal file path (instead of a URI like GetExecutingAssembly()" gives you), it died with a "Uri formats are not supported" exception.

4) Final solution: call GetExecutingAssembly(), then Uri.LocalPath ():

```<code>...
else if (cmdArgs.cmd.Equals(CmdOptions.CMD_SHOW_VERSION))
{
    string codeBaseUri =
       Urifile.System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
    string codeBase =
        new Uri (codeBaseUri).LocalPath;
    string sVersion = Util.GetWindowsVersion(codeBase);
    System.Console.WriteLine ("version({0}): {1}: ",
        Util.Basename(codeBase), sVersion);
}
</code>```

Thank you once again, all!

答:
This would also get you name / version</p>

```<code>name: Assembly.GetExecutingAssembly().GetName().Name
version: = Assembly.GetExecutingAssembly().GetName().Version
</code>```

Body:
I'm debugging "xiixtasks.exe", a C# console-mode application in VS2008.

I'm trying to get the version info from xiixtasks.exe.

When I try "Process.GetCurrentProcess()", it gives me the filename and version info for vshost.exe, NOT xiixtasks.exe:

  // WRONG: this gives me xiixtasks.vhost.exe, version 9.0.30729.1
  //        I *want* "xiixtasks.exe", version 1.0.0.1024
  System.Diagnostics.FileVersionInfo fi =
    System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo;

What should I be doing instead?

Thank you in advance!

======================================================

Solution:

1) The initial problem was indeed the IDE's "vshost" wrapper.
   One workaround would have been to change the build settings.

2) Assembly.GetExecutingAssembly().CodeBase is an excellent solution - thank you!.
   It works inside and outside the debugger.

3) Unfortunately, when I tried calling it with a function that expected a normal file path (instead of a URI like GetExecutingAssembly()" gives you), it died with a "Uri formats are not supported" exception.

4) Final solution: call GetExecutingAssembly(), then Uri.LocalPath ():

...
else if (cmdArgs.cmd.Equals(CmdOptions.CMD_SHOW_VERSION))
{
    string codeBaseUri =
       Urifile.System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
    string codeBase =
        new Uri (codeBaseUri).LocalPath;
    string sVersion = Util.GetWindowsVersion(codeBase);
    System.Console.WriteLine ("version({0}): {1}: ",
        Util.Basename(codeBase), sVersion);
}

Thank you once again, all!

Body:
This would also get you name / version

name: Assembly.GetExecutingAssembly().GetName().Name
version: = Assembly.GetExecutingAssembly().GetName().Version


问:
Error: Uncaught TypeError: Cannot set property 'onclick' of null
Please help to solve the problem:
I want to modify the output of a picture through popup when I click.
There is a code (original):

```<code><div class="spproperty-floor-img">
<img alt="" src="<?php echo JUri::root() . $floor_plan['img']; ?>">
</div>
</code>```

Modified code with javascript,css and html+some php:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
}

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Style the Image Used to Trigger the Modal */
#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (Image) */
.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)}
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)}
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}</code>```

<img id="myImg" src="<?php echo JUri::root() . $floor_plan['img']; ?>" alt="">

×

     ```

Javascript returns error:
"Uncaught TypeError: Cannot set property 'onclick' of null

What's wrong here?
Thank you in advance for your help!

答:
You don't have an element with an id of img01.

```<code>var img = document.getElementById('myImg');
</code>```

Yes, i did'nt add it.
Now the code is:

```<code><div class="spproperty-floor-img">
  <img id="myImg" src="<?php echo JUri::root() . $floor_plan['img']; ?>" alt="">
  <div id="myModal" class="modal">
  <img class="modal-content" id="img01">
  <span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
  <div id="caption"></div>
  </div>
  </div>
</code>```

But still in the console error:
Uncaught TypeError: Cannot set property 'onclick' of null
at this line in javascript:

```<code>img.onclick = function(){
</code>```

Body:
Please help to solve the problem:
I want to modify the output of a picture through popup when I click.
There is a code (original):

<img alt="" src="<?php echo JUri::root() . $floor_plan['img']; ?>">

Modified code with javascript,css and html+some php:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
}

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

/* Style the Image Used to Trigger the Modal */
#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (Image) */
.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)}
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)}
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}

<img id="myImg" src="<?php echo JUri::root() . $floor_plan['img']; ?>" alt="">

×

Javascript returns error:
"Uncaught TypeError: Cannot set property 'onclick' of null

What's wrong here?
Thank you in advance for your help!

Body:
You don't have an element with an id of img01.

var img = document.getElementById('myImg');

Yes, i did'nt add it.
Now the code is:

<div class="spproperty-floor-img">
  <img id="myImg" src="<?php echo JUri::root() . $floor_plan['img']; ?>" alt="">
  <div id="myModal" class="modal">
  <img class="modal-content" id="img01">
  <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span>
  <div id="caption"></div>
  </div>
  </div>

But still in the console error:
Uncaught TypeError: Cannot set property 'onclick' of null
at this line in javascript:

img.onclick = function(){


问:
React event handling for complex hierarchy
I started a game project in ReactJS as a way to learn the framework and I'm stuck in a problem I have.

I am using react-hexgrid as my core component, it's based on hexagons. I have six <HexTile/> pieces consisting of two <Hexagon/> each and a <GameLayout/> board where I can drag&drop them.

The <HexTile/> has to be placed completely on the <GameLayout/>, I achieve this dropping an <Hexagon/> each time with a first variable indicating that's the first hex dropped. The problem is that I need the remaining <HexTile/>s to be blocked while the move is completed. I want to put the six <HexTile/> inside a <TileList/> but because the drag events listeners are binded to the <Hexagon/> components, I don't know how to tell the <TileList/> that a move is being done so it disables the other <HexTile/>s.

How can I make the <TileList/> listen the <HexTile/> drag events? <HexTile/> is based on <TilesLayout/> component here (the game itself takes this example as base):  https://github.com/Hellenic/react-hexgrid/tree/master/examples/drag-and-drop

答:
You could do something like:

```<code>class TileList extends Component {
  constructor(props){
    super(props)
    this.state = { isTileMoving: false }

    this.onDragStart = this.onDragStart.bind(this)
    this.onDragEnd = this.onDragEnd.bind(this)
  }

  onDragStart(evt, source) {
    this.setState({ isTileMoving: true })
  }

  onDragEnd(evt, source) {
    this.setState({ isTileMoving: false })
  }

  // ... Rest of your things

  render() {
    <div>
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
    </div>
}
</code>```

And in your Hexagon

```<code>class Hexagon extends Component {
  constructor(props){
    super(props)
    this.state = // Hexagon state
  }

  onDragStart(evt, source) {
    this.props.onDragStart(evt, source)
    // Rest of your drag
  }

  onDragEnd(evt, source) {
    this.props.onDragEnd(evt, source)
    // Rest of dragEnd
  }

  // ... Rest of your things

  render() {
    //whatever your render is
  }
}
</code>```

Body:
You could do something like:

class TileList extends Component {
  constructor(props){
    super(props)
    this.state = { isTileMoving: false }

    this.onDragStart = this.onDragStart.bind(this)
    this.onDragEnd = this.onDragEnd.bind(this)
  }

  onDragStart(evt, source) {
    this.setState({ isTileMoving: true })
  }

  onDragEnd(evt, source) {
    this.setState({ isTileMoving: false })
  }

  // ... Rest of your things

  render() {
    <div>
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
      <Hexagon onDragStart={this.onDragStart} onDragEnd={this.onDragEnd} />
    </div>
}

And in your Hexagon

class Hexagon extends Component {
  constructor(props){
    super(props)
    this.state = // Hexagon state
  }

  onDragStart(evt, source) {
    this.props.onDragStart(evt, source)
    // Rest of your drag
  }

  onDragEnd(evt, source) {
    this.props.onDragEnd(evt, source)
    // Rest of dragEnd
  }

  // ... Rest of your things

  render() {
    //whatever your render is
  }
}


问:
Adding Views Between Items in GridView
I have a scrollable GridView where the items have a decent amount of empty space between them. for some of the objects in the grid, I'd like to add arrow images leading from one to the other

For reference to what I mean, think of the World of Warcraft talent trees (http://calculators.iradei.eu/talents/mage). You'll see some of the talents have arrows leading from one item to the next.

The layout I'm dealing with just contains a gridview in a framelayout, nothing else

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="4"
        android:scrollbars="none"
        android:id="@+id/talent_tree_grid_view">
    </GridView>

</FrameLayout>
</code>```

I'm trying to add these ImageViews in code, as I don't think there is any way I could add this logic into the adapter for the GridView.

I've tried adding them as children of the parent FrameLayout, based on the x and y coords of the GridView items, and this works, but when scrolling the GridView, the arrows do not also scroll

I've also tried adding them directly as children of the GridView, but it does not support this behavior (it throws java.lang.UnsupportedOperationException)

Are there any ideas as to how I could add these imageviews between the gridview items?

答:
This sounds very similar to Romain Guy's "Shelves" app where a custom GridView is used and the background image of a bookshelf scrolls. Take a look at the project here. Source for the custom GridView can be found in the file ShelvesView.java in the source code. A quick intro from Guy Romain is here;

For the arrows, you may want to consider a 9-patch drawable.

I have investigated the above approach a little more and have a sample app based upon
Google's Hello GridView example.

Taking this example app, I have built a custom GridView (DogsGridView.java) and connected the photos across empty cells similar to your example of World of Warcraft talent trees. I just use simple lines, but the class can be modified to connect cells with arrows or another graphic.

Here is a quick video with connecting lines. Here is another with 9-patch arrows.

The project source can be found here.

Title: Adding Views Between Items in GridView

Body:
I have a scrollable GridView where the items have a decent amount of empty space between them. for some of the objects in the grid, I'd like to add arrow images leading from one to the other

For reference to what I mean, think of the World of Warcraft talent trees (http://calculators.iradei.eu/talents/mage). You'll see some of the talents have arrows leading from one item to the next.

The layout I'm dealing with just contains a gridview in a framelayout, nothing else

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="4"
        android:scrollbars="none"
        android:id="@+id/talent_tree_grid_view">
    </GridView>

</FrameLayout>

I'm trying to add these ImageViews in code, as I don't think there is any way I could add this logic into the adapter for the GridView.

I've tried adding them as children of the parent FrameLayout, based on the x and y coords of the GridView items, and this works, but when scrolling the GridView, the arrows do not also scroll

I've also tried adding them directly as children of the GridView, but it does not support this behavior (it throws java.lang.UnsupportedOperationException)

Are there any ideas as to how I could add these imageviews between the gridview items?


问:
android.widget.Toolbar home button color (NOT support/v7/AppCompat toolbar)
I'm struggling to set the color of the "hamburger" icon on my android.widget.Toolbar, also most of the answers I find online apply to the support/v7 toolbar, but I'm using android.widget.Toolbar.

this is what my code looks like:

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setActionBar(toolbar);
        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_closed);
        drawerLayout.addDrawerListener(drawerToggle);
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        drawerToggle.syncState();
</code>```

I would like to be able to style it in my styles.xml file, is it possible? I'm using material theme, this is my current styles.xml:

```<code><resources>
    <style
        name="AppTheme"
        parent="@android:style/Theme.Material.Light.NoActionBar">

        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColor">@color/textColor</item>
        <item name="iconColor">@color/iconColor</item>
    </style>

    <style
        name="SplashTheme"
        parent="AppTheme">

        <item name="android:windowBackground">@drawable/splash_screen</item>
    </style>
</resources>
</code>```

Thanks for your help.

答:
Try creating this style in your styles.xml

```<code><style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
</style>
</code>```

And then add it to you Applications theme like so:

```<code><item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</code>```

Body:
I'm struggling to set the color of the "hamburger" icon on my android.widget.Toolbar, also most of the answers I find online apply to the support/v7 toolbar, but I'm using android.widget.Toolbar.

this is what my code looks like:

Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setActionBar(toolbar);
        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_closed);
        drawerLayout.addDrawerListener(drawerToggle);
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        drawerToggle.syncState();

I would like to be able to style it in my styles.xml file, is it possible? I'm using material theme, this is my current styles.xml:

<resources>

</resources>

Thanks for your help.

Body:
Try creating this style in your styles.xml

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
</style>

And then add it to you Applications theme like so:

<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>


问:
Is there an effective tool to convert C# code to Java code?
Is there an effective tool to convert C# code to Java code?</p>

答:
Possibly you could use jni4net - opensource bridge instead ?
Or list of other options I know.</p>

OwnerDisplayName: joshjdevl


问:
Is it suitable to pass a click event to a submit handler?
I have a <form> that I want to submit by clicking an  because a library I use builds buttons using  tags rather than <button> or <input type='submit'>.

The form's onsubmit attribute is set by PHP via Laravel.

I have a script to handle the clicks on the , which works well for the page I'm building.  The submit handler for my page doesn't currently utilize the event.  But I want to make this generic.  Therein lies the question:

Is it ok to send the "click" event generated by an anchor to a form submit handler, or does it need a "form submit" event?

Here is my code:

```<code><form method="POST" action="somewhere" onsubmit="return form_sub()" id="myForm">...</form>

<a id='saveButton' href='#'>Save</a>

<script type='text/javascript'>
$(document).ready(function() {
    $('#saveButton').click(function (e) {
        e.preventDefault();
        var $f = $('#myForm');
        if ($f.prop('onsubmit')) {
            if ($f.prop('onsubmit')(e)) { // <-- there, that event, passed to a handler that might expect a different "type" of event?
                $f.submit();
            }
        } else {
            $f.submit();
        }
    });
});
</script>
</code>```

I'm also willing to entertain ideas that I've missed something and there's an easier way do this - some way to submit the form which includes/doesn't include a call to the submit handler based on whether or not the handler exists, which may also extend to handlers installed via .addEventListener.  I realize that $(form).submit() calls event handlers installed by $(form).submit(handler) but that is not the case for this question, and I want this code to cover handlers installed both ways.

答:
You could put an off screen input type="submit" or button type="submit" and trigger click on that so that user can still submit by keyboard and for screen readers/accessibility

function form_sub() {
  alert('Submiting');
  return false;
}
$(function() {
  $('#saveButton').click(function() {
    $('#submit-btn').click();
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#submit-btn {
  position: absolute;
  top: -999em;
  left: -999em
}</code>```

<form method="POST" action="somewhere" onsubmit="return form_sub()" id="myForm">

  Save
  <input id="submit-btn" type="submit" value="Submit">
</form>```

Ideally however it should be relatively easy to copy your library button styles to an input

Body:
I have a <form> that I want to submit by clicking an  because a library I use builds buttons using  tags rather than <button> or <input type='submit'>.

The form's onsubmit attribute is set by PHP via Laravel.

I have a script to handle the clicks on the , which works well for the page I'm building.  The submit handler for my page doesn't currently utilize the event.  But I want to make this generic.  Therein lies the question:

Is it ok to send the "click" event generated by an anchor to a form submit handler, or does it need a "form submit" event?

Here is my code:

<form method="POST" action="somewhere" onsubmit="return form_sub()" id="myForm">...</form>

Save

I'm also willing to entertain ideas that I've missed something and there's an easier way do this - some way to submit the form which includes/doesn't include a call to the submit handler based on whether or not the handler exists, which may also extend to handlers installed via .addEventListener.  I realize that $(form).submit() calls event handlers installed by $(form).submit(handler) but that is not the case for this question, and I want this code to cover handlers installed both ways.

Body:
You could put an off screen input type="submit" or button type="submit" and trigger click on that so that user can still submit by keyboard and for screen readers/accessibility

function form_sub() {
  alert('Submiting');
  return false;
}
$(function() {
  $('#saveButton').click(function() {
    $('#submit-btn').click();
  })
})

#submit-btn {
  position: absolute;
  top: -999em;
  left: -999em
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="somewhere" onsubmit="return form_sub()" id="myForm">

  <a id='saveButton' href='#'>Save</a>
  <input id="submit-btn" type="submit" value="Submit">
</form>

Ideally however it should be relatively easy to copy your library button styles to an input


问:
TFS 2017 - [ProjectName].setParameters.xml with powershell
I create a zip Package in my build then i deploy it to a diffrent machine i am pasing few Parameters in my parameters.xml

```<code><?xml version="1.0" encoding="utf-8"?>
 <parameters>
        <parameter name="WebSiteUserName" description="Please enter the username" defaultvalue="__WebSiteUserName__" tags="">
        <parameterentry kind="XmlFile" scope="\\web.config$" match="/configuration/connectionStrings/add[@key='WebSiteUserName']/@value">
        </parameterentry>
        </parameter>
        <parameter name="WebSiteUserPassword" description="Please enter the password" defaultvalue="__UserPassword__" tags="">
        <parameterentry kind="XmlFile" scope="\\web.config$" match="/configuration/connectionStrings/add[@key='WebSiteUserPassword']/@value">
        </parameterentry>
        </parameter>
        <parameter name="WebSiteDomain" description="Domiain" defaultvalue="__Domain__" tags="">
        <parameterentry kind="XmlFile" scope="\\web.config$" match="/configuration/appSettings/add[@key='WebSiteDomain']/@value">
    </parameterentry>
  </parameter>
</parameters>
    </parameters>
</code>```

Then i run a powershell script

```<code>param(
    [string]$paramsFilePath
)

Write-Verbose -Verbose "Entering script Replace-SetParameters.ps1"
Write-Verbose -Verbose ("Path to SetParametersFile: {0}" -f $paramsFilePath)

# get the environment variables
$vars = Get-ChildItem -path env:*

# read in the setParameters file
$contents = Get-Content -Path $paramsFilePath

# perform a regex replacement
$newContents = "";

$contents  | % {
    $line = $_
    if ($_ -match "__(\w+[\.\w+]*)__") {
        $setting = Get-ChildItem -path env:* | ? { $_.Name -eq $Matches[1]  }
        while ($setting) {
            Write-Verbose -Verbose ("Replacing key {0} with value from environment" -f $setting.Name)
            $line = $_ -replace "__(\w+[\.\w+]*)__", $setting.Value
        }
    }
    $newContents += $line + [Environment]::NewLine
}

Write-Verbose -Verbose "Overwriting SetParameters file with new values"
Set-Content $paramsFilePath -Value $newContents
Write-Verbose " Assigning Parameters"

Write-Verbose -Verbose "Exiting script Replace-SetParameters.ps1"
</code>```

It will go through the parameters file and replace the parameters token with the enviromental variable.

In my setParamaters.xml file The WebSiteUsername only gets changed

```<code><?xml version="1.0" encoding="utf-8"?>
<parameters>
  <setParameter name="IIS Web Application Name" value="Default Web Site/SomeWebsite" />
  <setParameter name="WebSiteUserName" value="username" />
  <setParameter name="WebSiteUserPassword" value="__UserPassword__" />
  <setParameter name="Web.config Connection String" value="SomeValueForConnection" />
</parameters>
</code>```

I dont know why this is happening. Any Thoughts?

答:
I think you want to get the password from a TFS release definition environment.

You can´t access hidden fields with

```<code>$vars = Get-ChildItem -path env:secretVariable
</code>```

There is a way but that´s only works in the context of a TFS VNext build or release extension.

In your case the only possibility of access is to set the variable as a script argument like this:

```<code>-paramsFilePath $(paramsFilePath) -password $(secretVariable)
</code>```

In your script add the parameter like

```<code>param(
   [string]$paramsFilePath,
   [string]$password
)
</code>```

Body:
I create a zip Package in my build then i deploy it to a diffrent machine i am pasing few Parameters in my parameters.xml

<?xml version="1.0" encoding="utf-8"?>
 <parameters>
        <parameter name="WebSiteUserName" description="Please enter the username" defaultvalue="__WebSiteUserName__" tags="">
        <parameterentry kind="XmlFile" scope="\\web.config$" match="/configuration/connectionStrings/add[@key='WebSiteUserName']/@value">
        </parameterentry>
        </parameter>
        <parameter name="WebSiteUserPassword" description="Please enter the password" defaultvalue="__UserPassword__" tags="">
        <parameterentry kind="XmlFile" scope="\\web.config$" match="/configuration/connectionStrings/add[@key='WebSiteUserPassword']/@value">
        </parameterentry>
        </parameter>
        <parameter name="WebSiteDomain" description="Domiain" defaultvalue="__Domain__" tags="">
        <parameterentry kind="XmlFile" scope="\\web.config$" match="/configuration/appSettings/add[@key='WebSiteDomain']/@value">
    </parameterentry>
  </parameter>
</parameters>
    </parameters>

Then i run a powershell script

param(
    [string]$paramsFilePath
)

Write-Verbose -Verbose "Entering script Replace-SetParameters.ps1"
Write-Verbose -Verbose ("Path to SetParametersFile: {0}" -f $paramsFilePath)

# get the environment variables
$vars = Get-ChildItem -path env:*

# read in the setParameters file
$contents = Get-Content -Path $paramsFilePath

# perform a regex replacement
$newContents = "";

$contents  | % {
    $line = $_
    if ($_ -match "__(\w+[\.\w+]*)__") {
        $setting = Get-ChildItem -path env:* | ? { $_.Name -eq $Matches[1]  }
        while ($setting) {
            Write-Verbose -Verbose ("Replacing key {0} with value from environment" -f $setting.Name)
            $line = $_ -replace "__(\w+[\.\w+]*)__", $setting.Value
        }
    }
    $newContents += $line + [Environment]::NewLine
}

Write-Verbose -Verbose "Overwriting SetParameters file with new values"
Set-Content $paramsFilePath -Value $newContents
Write-Verbose " Assigning Parameters"

Write-Verbose -Verbose "Exiting script Replace-SetParameters.ps1"

It will go through the parameters file and replace the parameters token with the enviromental variable.

In my setParamaters.xml file The WebSiteUsername only gets changed

<?xml version="1.0" encoding="utf-8"?>
<parameters>
  <setParameter name="IIS Web Application Name" value="Default Web Site/SomeWebsite" />
  <setParameter name="WebSiteUserName" value="username" />
  <setParameter name="WebSiteUserPassword" value="__UserPassword__" />
  <setParameter name="Web.config Connection String" value="SomeValueForConnection" />
</parameters>

I dont know why this is happening. Any Thoughts?

Body:
I think you want to get the password from a TFS release definition environment.

You can´t access hidden fields with

$vars = Get-ChildItem -path env:secretVariable

There is a way but that´s only works in the context of a TFS VNext build or release extension.

In your case the only possibility of access is to set the variable as a script argument like this:

-paramsFilePath $(paramsFilePath) -password $(secretVariable)

In your script add the parameter like

param(
   [string]$paramsFilePath,
   [string]$password
)


问:
Why is evaluation of this python code block disabled in emacs org mode?
In a python source block in org-mode, after hitting C-c C-c, emacs says

Evaluation of python source block is disabled

Could anyone explain why?

答:
Simon's answer is not right if the org-mode version is >= 9. Here is another question on the same problem.

The solution

```<code>cd .emacs.d
cd elpa
cd org-xxxx
rm *.elc
</code>```

Then, it's better to byte-recompile the directory of the org-xxxx. To do that, start emacs, then

```<code>C-0 M-x byte-recompile-directory RET ~/emacs.d/elpa/org-xxxx
</code>```

Details at here.

Update 1: EmacsWiki on compile file.

Body:
Simon's answer is not right if the org-mode version is >= 9. Here is another question on the same problem.

The solution

cd .emacs.d
cd elpa
cd org-xxxx
rm *.elc

Then, it's better to byte-recompile the directory of the org-xxxx. To do that, start emacs, then

C-0 M-x byte-recompile-directory RET ~/emacs.d/elpa/org-xxxx

Details at here.

Update 1: EmacsWiki on compile file.


问:
How can I configure Blessed 1.9.5 with Python in Ubuntu?
```<code>...pkg_resources.DistributionNotFound: The 'blessed==1.9.5'
distribution was not found and is required by awsebcli...
</code>```

Message above appear when I type eb when I check if I installed awsebcli correctly.

How can I install the blessed 1.9.5 correctly so I can install awsebcli?
Please help..

答:
I just had this issue occur with the latest AWS CLI tool. I fixed it via MaxNoe's suggestion to run:

pip install blessed

I put this prior to my AWS CLI tool install command in my script. The script looks like:

```<code>apt-get update
apt-get install python-dev
python -m pip install -U pip
pip install blessed
pip install awsebcli
</code>```

Body:
...pkg_resources.DistributionNotFound: The 'blessed==1.9.5'
distribution was not found and is required by awsebcli...

Message above appear when I type eb when I check if I installed awsebcli correctly.

How can I install the blessed 1.9.5 correctly so I can install awsebcli?
Please help..

Body:
I just had this issue occur with the latest AWS CLI tool. I fixed it via MaxNoe's suggestion to run:

pip install blessed

I put this prior to my AWS CLI tool install command in my script. The script looks like:

apt-get update
apt-get install python-dev
python -m pip install -U pip
pip install blessed
pip install awsebcli


问:
Showcase view in javascript application
I need to create step by step showcase in my ASP.NET MVC application like is done in Android by ShowcaseView (https://github.com/amlcurran/ShowcaseView).

Do you know any javascript framework which done something familiar?

答: showcaser is a Material Design inspired showcase view for the web. Demo here.

Title: Showcase view in javascript application


问:
How to change one array's values from another array?
```<code>String [] board = new String [9];
String [] sequence = new String [8];

sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];
</code>```

Say I was to make sequence[0]="XXO";

How could I take sequence[0] and change the the board points so that:

```<code>board[0]="X";
board[1]="X";
board[2]="O";
</code>```

I am trying to run this for loop and I have to initialize the board array  before the sequences part as I am printing it out to the screen and can't have the values be null.

```<code>for(int i = 0; i < 8; i++
{
    if(sequence[i].equals("X"+"X"+" "))
    {
        sequence[i] = "XXO";
    }
}
</code>```

答:
You generally shouldn't store the same data in different ways (the Don't Repeat Yourself principle), sometimes because it leads to a mess like this.

One correct way to do what you want is the following:

board[0] = String.valueOf(sequence[0].charAt(0));
board[1] = String.valueOf(sequence[0].charAt(1));
board[2] = String.valueOf(sequence[0].charAt(2));
```

Body:
String [] board = new String [9];
String [] sequence = new String [8];

sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];

Say I was to make sequence[0]="XXO";

How could I take sequence[0] and change the the board points so that:

board[0]="X";
board[1]="X";
board[2]="O";

I am trying to run this for loop and I have to initialize the board array  before the sequences part as I am printing it out to the screen and can't have the values be null.

for(int i = 0; i < 8; i++
{
    if(sequence[i].equals("X"+"X"+" "))
    {
        sequence[i] = "XXO";
    }
}


问:
SBT Coverage "exclude" used in Play application
I used the sbt-scoverage for our Play application.

I used the following config to exclude both Reverse and Routes generated file.

```<code>coverageExcludedPackages := ";Reverse.;Routes.;"
</code>```

However this can only exclude generated Reverse scala files and can't exclude Routes files. Even I use the following script, it does the same

```<code>coverageExcludedPackages := ";Routes.*;"
</code>```

Anyone knows what is the correct regex should be?

答:
As an improvement to @socom1880's answer, this worked for me by adding it to build.sbt

```<code>coverageExcludedPackages := "<empty>;Reverse.*;router\\.*"
</code>```

Body:
I used the sbt-scoverage for our Play application.

I used the following config to exclude both Reverse and Routes generated file.

coverageExcludedPackages := ";Reverse.;Routes.;"

However this can only exclude generated Reverse scala files and can't exclude Routes files. Even I use the following script, it does the same

coverageExcludedPackages := ";Routes.*;"

Anyone knows what is the correct regex should be?

Body:
As an improvement to @socom1880's answer, this worked for me by adding it to build.sbt

coverageExcludedPackages := "<empty>;Reverse.*;router\\.*"


问:
Javascript/Coffeescript append TypeError: is not a function
Why isn't working?

It works if I change variable msg for a string value.

Code:

```<code>console.log full_messages # Array [ "text to be displayed" ]
for msg in full_messages
  $('#error_explanation ul').append('<li>'+ msg +'</li>')
</code>```

Error message:

TypeError: msg is not a function

答:
Your problem is in your whitespace (or lack thereof):

```<code>'<li>'+ msg +'</li>'
</code>```

CoffeeScript thinks that the second + in that is a unary operator so the whole thing is interpreted as:

```<code>'<li>' + msg(+'</li>')
</code>```

If you put spaces on both sides of your binary operators:

```<code>'<li>' + msg + '</li>'
#     ^^^   ^^^
</code>```

then CoffeeScript does what you're expecting it to. Rule of Thumb: always put spaces on both sides of binary operators.

You could also use string interpolation:

```<code>"<li>#{msg}</li>"
</code>```

That becomes exactly the same JavaScript as '
' + msg + '
' but is (arguably) more readable and idiomatic.

Body:
Why isn't working?

It works if I change variable msg for a string value.

Code:

console.log full_messages # Array [ "text to be displayed" ]
for msg in full_messages
  $('#error_explanation ul').append('
'+ msg +'
')

Error message:

TypeError: msg is not a function

Body:
Your problem is in your whitespace (or lack thereof):

'<li>'+ msg +'</li>'

CoffeeScript thinks that the second + in that is a unary operator so the whole thing is interpreted as:

'<li>' + msg(+'</li>')

If you put spaces on both sides of your binary operators:

'<li>' + msg + '</li>'
#     ^^^   ^^^

then CoffeeScript does what you're expecting it to. Rule of Thumb: always put spaces on both sides of binary operators.

You could also use string interpolation:

"<li>#{msg}</li>"

That becomes exactly the same JavaScript as '<li>' + msg + '</li>' but is (arguably) more readable and idiomatic.


问:
Building a generic Camel/Docker image and apply different Camel routes when container starts
I've got a requirement to create some impostors/stubs/reflectors (pick your own term...) using Apache Camel. These stubs need to:

listen to a bunch of IBM MQ queues

for each queue:

grab messages off the queue when they appear

extract info from the message via simple XPath or regex extracts and construct a response via a template

wait some predefined period

send the response back on another queue

I'm no Camel expert, but I can work out how to do that much...

However, given there's going to be lots of these stubs and I want to use different subsets of these stubs in different circumstances, I want to build a generic Camel Docker image, and apply different sets of stubs to it when I start the Docker container.

If it helps clarify things further, I want to be able to store the stub definitions as uncompiled code (e.g. XML, Simple, whatever) in git repos - separate from the Docker image - and have the Docker/Camel container load those stub definitions via either volume mount/s or environment variables. Once the container starts, those stub images will persist till the container is killed off - I don't need to manipulate the stubs except when the container starts.

Key thing is that the Camel/Docker image has to be generic, not pre-built with a specific set of stub definitions.

I can handle the Docker side of things OK - what I can't work out is how to have Camel load the stub definitions when Camel starts (i.e. when the Docker container is created) rather than have the stubs loaded into e.g. a WAR at compile time.

Thanks for any help or suggestions

答:
It can be easy implemented using the following way:

Camel/Docker image has the main cmd to run camel routes from spring xml (you can use whatever logic you want like camel standalone or spring boot etc.)

Spring XML file is read from some location which is for example hardcoded inside Docker image (like /app/config.xml for example)

You will start docker container and map required spring XML file to the /app/config.xml

If you cannot map XML files to the running container then you can implement you own small boot part that will on startup read XML content from some env variable, store it into the temporary file and run same logic for starting spring using file context. In that case, you can run docker container and pass spring XML as an env. variable.


问:
How to implement a Complete Binary Tree using recursion without comparing the value of the node?
```<code>public void recurInsert(BinaryTree.Node root, BinaryTree.Node newNode, int height) {
    if (newNode == null) {
        System.out.println("InsertNode is empty, please create new one");
        return;
    }
    else{
        if (height == 1) {
            if (root == null)
                return;
            else if (root.leftChild == null) {
                root.leftChild = newNode;
                System.out.println("left" + newNode.data);
            }
            else {
                root.rightChild = newNode;
                System.out.println("right" + newNode.data);
            }
        }
        else{
            if (root.leftChild != null)
                recurInsert(root.leftChild, newNode, height-1);
            //else (root.rightChild != null)
            //    recurInsert(root.rightChild, newNode, height-1);
            if (root.rightChild != null)
                recurInsert(root.rightChild, newNode, height-1);
        }
    }
}
</code>```

This is the code I implemented, but it actually inserts two same nodes to make it balance. Can anyone help me to fix the bug or implement it in another way?

I just want to implement an insertion for a complete binary tree using recursion . Say inserting a node with a sequence A,B,C,D,E,F. It comes like root is A and its left child is B, and right child is C and B's children are D and E,and C's left child is F.

My code has bug but implemented this insertion to make the tree is binary complete tree. It comes like A's children are B and C. But B's children is D,E and C's children is D and E as well instead of F. So hope you guys can help me to fix the bug or to implement it in another way using recursion.

Fortunately. I've seen a similar question posted on Stack Overflow, but I want to implement it using recursion, not with additional data structure.

答:
```<code>//Node---
public class BinaryTreeNode<T> {
    private T data;
    private BinaryTreeNode<T> leftNode;
    private BinaryTreeNode<T> rightNode;

public BinaryTreeNode(T data) {
    this.data = data;
    this.leftNode = null;
    this.rightNode = null;
}

public T getData() {
    return data;
}

public void setData(T data) {
    this.data = data;
}

public BinaryTreeNode<T> getLeftNode() {
    return leftNode;
}

public void setLeftNode(BinaryTreeNode<T> leftNode) {
    this.leftNode = leftNode;
}

public BinaryTreeNode<T> getRightNode() {
    return rightNode;
}

public void setRightNode(BinaryTreeNode<T> rightNode) {
    this.rightNode = rightNode;
}
}

//Binary Tree---
public class BinaryTree<T> {
private BinaryTreeNode<T> rootNode;

public BinaryTreeNode<T> getRootNode() {
    return rootNode;
}

public void setRootNode(BinaryTreeNode<T> rootNode) {
    this.rootNode = rootNode;
}

public void insert(T data){
    this.setRootNode(insert(this.getRootNode(), data));
}

private BinaryTreeNode insert(BinaryTreeNode<T> node, T data){
    if(node == null){
        node = new BinaryTreeNode<>(data);
    }else{
        if(node.getLeftNode() == null){
            node.setLeftNode(insert(node.getLeftNode(), data));
        }else if(node.getRightNode() == null){
            node.setRightNode(insert(node.getRightNode(), data));
        } else{
            if(node.getLeftNode().getLeftNode() == null || node.getLeftNode().getRightNode() == null){
                insert(node.getLeftNode(), data);
            }else if(node.getRightNode().getLeftNode() == null || node.getRightNode().getRightNode() == null){
                insert(node.getRightNode(), data);
            }else{
                insert(node.getLeftNode(), data);
            }
        }
    }
    return node;
}
}
</code>```

Body:
public void recurInsert(BinaryTree.Node root, BinaryTree.Node newNode, int height) {
    if (newNode == null) {
        System.out.println("InsertNode is empty, please create new one");
        return;
    }
    else{
        if (height == 1) {
            if (root == null)
                return;
            else if (root.leftChild == null) {
                root.leftChild = newNode;
                System.out.println("left" + newNode.data);
            }
            else {
                root.rightChild = newNode;
                System.out.println("right" + newNode.data);
            }
        }
        else{
            if (root.leftChild != null)
                recurInsert(root.leftChild, newNode, height-1);
            //else (root.rightChild != null)
            //    recurInsert(root.rightChild, newNode, height-1);
            if (root.rightChild != null)
                recurInsert(root.rightChild, newNode, height-1);
        }
    }
}

This is the code I implemented, but it actually inserts two same nodes to make it balance. Can anyone help me to fix the bug or implement it in another way?

I just want to implement an insertion for a complete binary tree using recursion . Say inserting a node with a sequence A,B,C,D,E,F. It comes like root is A and its left child is B, and right child is C and B's children are D and E,and C's left child is F.

My code has bug but implemented this insertion to make the tree is binary complete tree. It comes like A's children are B and C. But B's children is D,E and C's children is D and E as well instead of F. So hope you guys can help me to fix the bug or to implement it in another way using recursion.

Fortunately. I've seen a similar question posted on Stack Overflow, but I want to implement it using recursion, not with additional data structure.


问:
Using first element of array or as is if object is not an array
Let's assume method a can return either an array or a single element

```<code>def a(n)
  if n == 0
    return '0'
  else
    return '1', '2'
  end
end

irb(main):008:0> a(0)
=> "0"
irb(main):009:0> a(1)
=> ["1", "2"]
</code>```

What would be the best "ruby" way to express the following:

```<code>irb(main):013:0> a(0).<???>.to_i
=> 0
irb(main):014:0> a(1).<???>.to_i
=> 1
</code>```

I'm looking for an elegant syntax to achieve the above. I obviously can implement a function what would do dynamic type inspection and would either return the first element of just the input variable as is..

Body:
Let's assume method a can return either an array or a single element

def a(n)
  if n == 0
    return '0'
  else
    return '1', '2'
  end
end

irb(main):008:0> a(0)
=> "0"
irb(main):009:0> a(1)
=> ["1", "2"]

What would be the best "ruby" way to express the following:

irb(main):013:0> a(0).<???>.to_i
=> 0
irb(main):014:0> a(1).<???>.to_i
=> 1

I'm looking for an elegant syntax to achieve the above. I obviously can implement a function what would do dynamic type inspection and would either return the first element of just the input variable as is..

Body:
def a(n)
  n.zero? ? '0' : '10', '20'
end

[*a(0)].first #=> "0"
[*a(7)].first #=> "10"