答:
As far as I'm concerned the following are working

```<code>response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,HEAD");
</code>```

Edit : (For spring cloud netflix and maybe others)

```<code>@Component
public class HeadersFilter implements Filter {
    @Override
    public void init(FilterConfig fc) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc) throws IOException, ServletException {
        if(servletResponse instanceof HttpServletResponse){
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            // here add the headers
        }
        fc.doFilter(servletRequest, servletResponse);
    }
    @Override
    public void destroy() {
    }
}
</code>```

Title: How to enable CORS on server-side code in java

Body:
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .

In-order to make server CORS enabled, We have done the below changes .

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml).
I don't have much knowledge on enabling CORS on server-side .
Please suggest how to proceed further .

Body:
As far as I'm concerned the following are working

response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,HEAD");

Edit : (For spring cloud netflix and maybe others)

@Component
public class HeadersFilter implements Filter {
    @Override
    public void init(FilterConfig fc) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc) throws IOException, ServletException {
        if(servletResponse instanceof HttpServletResponse){
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            // here add the headers
        }
        fc.doFilter(servletRequest, servletResponse);
    }
    @Override
    public void destroy() {
    }
}


来源: stackexchange

问:
Can't echo data from phpmyadmin
Am was already created form like this and working perfect but on last two forms not working, it displays warning-Undefined variable: reg_no and cost. Am trying to follow algorithm as previous forms but nothing happen. My goal is to update inserted data and here is my form

<!doctype html>

<meta charset="utf-8">
<title>Edit invoice</title>
<link rel="stylesheet"  href="box_style.css" />

<?php

include ("db_con.php");

if(isset($_GET['edit_invoice'])){

        $edit_i_id = $_GET['edit_invoice'];

        $select_invoice = "select * from invoice where i_id='$edit_i_id'";

        $run_query = mysqli_query($con, $select_invoice);

        while ($row_invoice=mysqli_fetch_array($run_query)){

  $i_id = $row_invoice['i_id'];
        $reg_no = $row_invoice['reg_no'];
        $cost = $row_invoice['cost'];

        }
    }

?>

<form action="" method="post" enctype="multipart/form-data" >

EDIT INVOICE:

  Registration Number:
  <input type="text" name="reg_no" id="reg_no" size="35" class="text" placeholder="Registration Number" value="<?php echo $reg_no; ?>" required=""/>

  Cost(Tshs):
  <input type="text" name="cost" id="cost" size="35" class="text" placeholder="Cost" value="<?php echo $cost; ?>" required=""/>

  <input type="submit" name="update" class="submit-button" value="SAVE CHANGES">

</form>

```

答:
if isset($_GET['edit_invoice']) is false, your $reg_no is not present in later script (where you want to echo it).

Put $reg_no above your isset($_GET...) check and set it null or empty string.

```<code>$reg_no = null;
if (isset($_GET['edit_invoice'])) {
   // your code...
}
</code>```

Edit: Do the same for $cost and $i_id ;)

PLEASE consider Tom Uddings comment with SQL injections!

ContentLicense: CC BY-SA 3.0

Title: Can't echo data from phpmyadmin

Body:
if isset($_GET['edit_invoice']) is false, your $reg_no is not present in later script (where you want to echo it).

Put $reg_no above your isset($_GET...) check and set it null or empty string.

$reg_no = null;
if (isset($_GET['edit_invoice'])) {
   // your code...
}

Edit: Do the same for $cost and $i_id ;)

PLEASE consider Tom Uddings comment with SQL injections!


问:
Using an svg file as the backgound for an angular app
I would like to use an svg file as the background for an angular app so that it scales along the rest when resized.
If I load it with:

```<code><span><ng-include src="'resources/svg/caricaFornoWB.svg'" /></ng-include></span>
</code>```

the svg is shown above the rest of the app. How may I show it in the background (possibly linking its objects to my own) instead?

答:
Use </p>

```<code><img src="resources/svg/caricaFornoWB.svg" />
</code>```

Body:
I would like to use an svg file as the background for an angular app so that it scales along the rest when resized.
If I load it with:

<ng-include src="'resources/svg/caricaFornoWB.svg'" /></ng-include>

the svg is shown above the rest of the app. How may I show it in the background (possibly linking its objects to my own) instead?

Body:
Use

<img src="resources/svg/caricaFornoWB.svg" />


问:
Which characters are valid in CSS class names/selectors?
What characters/symbols are allowed within the CSS class selectors?

I know that the following characters are invalid, but what characters are valid?

~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
```

答:
The complete regular expression is:

-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*
```

So all of your listed characters, except “-” and “_” are not allowed if used directly. But you can encode them using a backslash foo\~bar or using the Unicode notation foo\7E bar.

OwnerDisplayName: Darryl Hein

ContentLicense: CC BY-SA 4.0

Body:
The complete regular expression is:

-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*

So all of your listed characters, except “-” and “_” are not allowed if used directly. But you can encode them using a backslash foo\~bar or using the Unicode notation foo\7E bar.

OwnerDisplayName: Gumbo


问:
IF statement not being executed C# MVC
I have an MVC application, which has two areas - Administrator, and User. What I wanted to do, is on first login, the User will activate their account, agree to terms and conditions, etc. This application uses the asp membership api.

I have inserted an IF statement into the POST login action in the Account controller, however after debugging, it appears that this if statement is never executed. If someone could take a look at it I'd be very grateful. I have a feeling it could be something small I'm missing.

The login URL for the User is:

http://localhost:80/Account/LogOn?ReturnUrl=/User

The administrator URL is:

http://localhost:80/Account/LogOn?ReturnUrl=/Administrator

however both use the same login action in the account controller so hence the need to use an if statement to differentiate between the two.

Here is the code for the POST Logon action. The string returnUrl is "/User" not "User" which I discovered after debugging through the code.

```<code> [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        string url = returnUrl;

                        if (url == "/User")
                        {
                            ModelContainer ctn = new ModelContainer();

                            MyApp.Data.User p = ctn.Users.First(t => t.UserID == UserServices.CurrentUserId);

                            string status = p.AccountStatus;

                            if (status != "Active")
                            {
                                return RedirectToAction("contract", "Home");
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                        else
                            return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
</code>```

It just seems to skip after the else here:

```<code>if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        string url = returnUrl;
</code>```

and jumps right down to the final RedirectToAction.

I'd be very grateful if anyone could spot anything. If more info is needed just shout!

答: It doesn't - from your code, returnUrl will always contain a string, so it will run the first part of your conditional statement, and just return the redirect - it will never hit your first time user code.</p>

ContentLicense: CC BY-SA 2.5

Title: IF statement not being executed C# MVC

Body:
I have an MVC application, which has two areas - Administrator, and User. What I wanted to do, is on first login, the User will activate their account, agree to terms and conditions, etc. This application uses the asp membership api.

I have inserted an IF statement into the POST login action in the Account controller, however after debugging, it appears that this if statement is never executed. If someone could take a look at it I'd be very grateful. I have a feeling it could be something small I'm missing.

The login URL for the User is:

http://localhost:80/Account/LogOn?ReturnUrl=/User

The administrator URL is:

http://localhost:80/Account/LogOn?ReturnUrl=/Administrator

however both use the same login action in the account controller so hence the need to use an if statement to differentiate between the two.

Here is the code for the POST Logon action. The string returnUrl is "/User" not "User" which I discovered after debugging through the code.

 [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        string url = returnUrl;

                        if (url == "/User")
                        {
                            ModelContainer ctn = new ModelContainer();

                            MyApp.Data.User p = ctn.Users.First(t => t.UserID == UserServices.CurrentUserId);

                            string status = p.AccountStatus;

                            if (status != "Active")
                            {
                                return RedirectToAction("contract", "Home");
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                        else
                            return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

It just seems to skip after the else here:

if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        string url = returnUrl;

and jumps right down to the final RedirectToAction.

I'd be very grateful if anyone could spot anything. If more info is needed just shout!


问:
Asynchronous method has no availble extension methods, but resulting variable does have
I'm createing some methods in a standard repository class using MongoDB with c# and async methods and I've stumbled upon some strange behaviour.

In the end it's probably not strange at all, rather the problem lies in my own inexperience with async programming.

Consider this code:

```<code>public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id);

            return await model.FirstOrDefaultAsync();
        }
</code>```

Now that is totally fine, no compilation errors but I'm actually not sure its's correct calling await 2 times.

Now consider this code:

```<code>public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id).FirstOrDefaultAsync();

            return model;
        }
</code>```

Thats illegal according to the compiler. It's complaining about FirstOrDefaultAsync() not being an availble method to call. I would have to call .Result first to get access to .FirstOrDefaultAsync().

What is going on here?

答:
```<code>var model = await col.FindAsync(x => x.Id == id).FirstOrDefaultAsync();
</code>```

Should be:

```<code>var model = await (await col.FindAsync(x => x.Id == id)).FirstOrDefaultAsync();
</code>```

This is because FindAsync returns a Task object, which FirstOrDefaultAsync doesn't work for. Awaiting the operation yields the actual result.

This is one of the most annoying things with async/await IMO, as it requires parentheses or variables to hold the awaited result for further processing.

Body:
I'm createing some methods in a standard repository class using MongoDB with c# and async methods and I've stumbled upon some strange behaviour.

In the end it's probably not strange at all, rather the problem lies in my own inexperience with async programming.

Consider this code:

public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id);

            return await model.FirstOrDefaultAsync();
        }

Now that is totally fine, no compilation errors but I'm actually not sure its's correct calling await 2 times.

Now consider this code:

public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id).FirstOrDefaultAsync();

            return model;
        }

Thats illegal according to the compiler. It's complaining about FirstOrDefaultAsync() not being an availble method to call. I would have to call .Result first to get access to .FirstOrDefaultAsync().

What is going on here?

Body:
var model = await col.FindAsync(x => x.Id == id).FirstOrDefaultAsync();

Should be:

var model = await (await col.FindAsync(x => x.Id == id)).FirstOrDefaultAsync();

This is because FindAsync returns a Task object, which FirstOrDefaultAsync doesn't work for. Awaiting the operation yields the actual result.

This is one of the most annoying things with async/await IMO, as it requires parentheses or variables to hold the awaited result for further processing.


问:
A 5 points rating formula in SQL query
```<code>       RATING
[  id -  pid = rate]
[  1  -   1  -  5  ]
[  2  -   1  -  5  ]
[  3  -   1  -  4  ]
[  4  -   1  -  1  ]
[  5  -   1  -  1  ]

WHERE pid = 1;
$r5 = 10;
$r4 = 4;
$r3 = 0;
$r2 = 0;
$r1 = 2;
$tt = 16;
</code>```

from this table i'm trying to make this mathematical formula

```<code>($r5*5 + $r4*4 + $r3*3 + $r2*2 + $r1) / $tt
</code>```

instead of calling all the values into array and calculating it, How can i do inside the query itself? In which one is actually faster and the most efficient for the website?

答:
You can use the following solution:

```<code>SELECT pid,
    (((SUM(CASE WHEN rate = 5 THEN 5 ELSE 0 END) * 5) +
    (SUM(CASE WHEN rate = 4 THEN 4 ELSE 0 END) * 4) +
    (SUM(CASE WHEN rate = 3 THEN 3 ELSE 0 END) * 3) +
    (SUM(CASE WHEN rate = 2 THEN 2 ELSE 0 END) * 2) +
    (SUM(CASE WHEN rate = 1 THEN 1 ELSE 0 END) * 1)) / SUM(rate)) AS c_rate
FROM table_name
WHERE pid = 1
GROUP BY pid
</code>```

To format your output without rounding the result you can use TRUNCATE. You can also use ROUND if the result should be rounded and truncated.

solution using TRUNCATE:

```<code>SELECT pid,
    TRUNCATE((((SUM(CASE WHEN rate = 5 THEN 5 ELSE 0 END) * 5) +
    (SUM(CASE WHEN rate = 4 THEN 4 ELSE 0 END) * 4) +
    (SUM(CASE WHEN rate = 3 THEN 3 ELSE 0 END) * 3) +
    (SUM(CASE WHEN rate = 2 THEN 2 ELSE 0 END) * 2) +
    (SUM(CASE WHEN rate = 1 THEN 1 ELSE 0 END) * 1)) / SUM(rate)), 1) AS c_rate
FROM table_name
WHERE pid = 1
GROUP BY pid
</code>```

solution using ROUND:

```<code>SELECT pid,
    ROUND((((SUM(CASE WHEN rate = 5 THEN 5 ELSE 0 END) * 5) +
    (SUM(CASE WHEN rate = 4 THEN 4 ELSE 0 END) * 4) +
    (SUM(CASE WHEN rate = 3 THEN 3 ELSE 0 END) * 3) +
    (SUM(CASE WHEN rate = 2 THEN 2 ELSE 0 END) * 2) +
    (SUM(CASE WHEN rate = 1 THEN 1 ELSE 0 END) * 1)) / SUM(rate)), 1) AS c_rate
FROM table_name
WHERE pid = 1
GROUP BY pid
</code>```

Title: A 5 points rating formula in SQL query

Body:
       RATING
[  id -  pid = rate]
[  1  -   1  -  5  ]
[  2  -   1  -  5  ]
[  3  -   1  -  4  ]
[  4  -   1  -  1  ]
[  5  -   1  -  1  ]

WHERE pid = 1;
$r5 = 10;
$r4 = 4;
$r3 = 0;
$r2 = 0;
$r1 = 2;
$tt = 16;

from this table i'm trying to make this mathematical formula

($r5*5 + $r4*4 + $r3*3 + $r2*2 + $r1) / $tt

instead of calling all the values into array and calculating it, How can i do inside the query itself? In which one is actually faster and the most efficient for the website?

Body:
You can use the following solution:

SELECT pid,
    (((SUM(CASE WHEN rate = 5 THEN 5 ELSE 0 END) * 5) +
    (SUM(CASE WHEN rate = 4 THEN 4 ELSE 0 END) * 4) +
    (SUM(CASE WHEN rate = 3 THEN 3 ELSE 0 END) * 3) +
    (SUM(CASE WHEN rate = 2 THEN 2 ELSE 0 END) * 2) +
    (SUM(CASE WHEN rate = 1 THEN 1 ELSE 0 END) * 1)) / SUM(rate)) AS c_rate
FROM table_name
WHERE pid = 1
GROUP BY pid

To format your output without rounding the result you can use TRUNCATE. You can also use ROUND if the result should be rounded and truncated.

solution using TRUNCATE:

SELECT pid,
    TRUNCATE((((SUM(CASE WHEN rate = 5 THEN 5 ELSE 0 END) * 5) +
    (SUM(CASE WHEN rate = 4 THEN 4 ELSE 0 END) * 4) +
    (SUM(CASE WHEN rate = 3 THEN 3 ELSE 0 END) * 3) +
    (SUM(CASE WHEN rate = 2 THEN 2 ELSE 0 END) * 2) +
    (SUM(CASE WHEN rate = 1 THEN 1 ELSE 0 END) * 1)) / SUM(rate)), 1) AS c_rate
FROM table_name
WHERE pid = 1
GROUP BY pid

solution using ROUND:

SELECT pid,
    ROUND((((SUM(CASE WHEN rate = 5 THEN 5 ELSE 0 END) * 5) +
    (SUM(CASE WHEN rate = 4 THEN 4 ELSE 0 END) * 4) +
    (SUM(CASE WHEN rate = 3 THEN 3 ELSE 0 END) * 3) +
    (SUM(CASE WHEN rate = 2 THEN 2 ELSE 0 END) * 2) +
    (SUM(CASE WHEN rate = 1 THEN 1 ELSE 0 END) * 1)) / SUM(rate)), 1) AS c_rate
FROM table_name
WHERE pid = 1
GROUP BY pid


问:
What is a state of an object after it was moved-from via a reference to its base class?
Assume, there is a hierarchy of two classes:

```<code>class Base {};
class Foo: public Base {};
</code>```

Which are used like this:

```<code>Foo foo;
Base &base = foo;
Base moved = std::move(base);
</code>```

In what state is foo after such move? Does the Standard impose any requirements on limitations on such code?

答:
The standard does not make any such requirement on move constructors for C++ classes that are not a part of the standard library.  The library writer is free to do what they want.  For components that are a part of the standard library, the C++17 standard does say something (emphasis mine)

§ 20.5.5.15 Moved-from state of library types [lib.types.movedfrom]

Objects of types defined in the C++ standard library may be moved from (15.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

For classes in the standard library that are a part of an inheritance hierarchy, you would have to consult the documentation to see what happens when you try and move construct a base object from a base class rvalue reference a derived class object.  So if you could specify which class in particular you were worried about I could try and help more.

Not sure how relevant this is to your question, but regarding what would really happen in such a constructor.  Remember that the virtual function mechanism is disabled in constructors for the object that is going to be constructed,  but not for the referenced object.  In the following example

```<code>class Base {
public:
    virtual vector<int> extract_vector() { ... }

    // Move constructor can use virtual functions on the other object
    Base(Base&& other) {
        this->vec = other.extract_vector();
    }

private:
    std::vector<int> vec;
};

class Foo : public Base {
public:
    vector<int> extract_vector() override { ... }

private:
    // this does something ¯\\_(ツ)_/¯
    SpecialVectorAdaptor<std::vector<int>> vec;
};
</code>```

The virtual function extract_vector on other in the move constructor for Base will be called, and you can utilize virtual methods on the other object.  But you cannot use any such virtual methods on the class that is going to be constructed.

So long story short, the behavior of the code you have shown will depend strictly on the implementation of the classes in question.

Body:
Assume, there is a hierarchy of two classes:

class Base {};
class Foo: public Base {};

Which are used like this:

Foo foo;
Base &base = foo;
Base moved = std::move(base);

In what state is foo after such move? Does the Standard impose any requirements on limitations on such code?

Body:
The standard does not make any such requirement on move constructors for C++ classes that are not a part of the standard library.  The library writer is free to do what they want.  For components that are a part of the standard library, the C++17 standard does say something (emphasis mine)

§ 20.5.5.15 Moved-from state of library types [lib.types.movedfrom]

Objects of types defined in the C++ standard library may be moved from (15.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

For classes in the standard library that are a part of an inheritance hierarchy, you would have to consult the documentation to see what happens when you try and move construct a base object from a base class rvalue reference a derived class object.  So if you could specify which class in particular you were worried about I could try and help more.

Not sure how relevant this is to your question, but regarding what would really happen in such a constructor.  Remember that the virtual function mechanism is disabled in constructors for the object that is going to be constructed,  but not for the referenced object.  In the following example

class Base {
public:
    virtual vector<int> extract_vector() { ... }

    // Move constructor can use virtual functions on the other object
    Base(Base&& other) {
        this->vec = other.extract_vector();
    }

private:
    std::vector<int> vec;
};

class Foo : public Base {
public:
    vector<int> extract_vector() override { ... }

private:
    // this does something ¯\\_(ツ)_/¯
    SpecialVectorAdaptor<std::vector<int>> vec;
};

The virtual function extract_vector on other in the move constructor for Base will be called, and you can utilize virtual methods on the other object.  But you cannot use any such virtual methods on the class that is going to be constructed.

So long story short, the behavior of the code you have shown will depend strictly on the implementation of the classes in question.


问:
jQuery Datatables rowGroup
I'm using the jQuery datatables plugin with the rowGroup addon.

I need to use the 'startRender' function to display some information in the 'headline' of each group.

Links:

Datatables: https://datatables.net/

RowGroup Addon: https://datatables.net/extensions/rowgroup/examples/initialisation/startAndEndRender.html

But the problem is, that I cant read the row tr Id to get the needed data.

How can I access the row Id inside the startRender function to pass the data in the headline of the group?

Thats my jQuery rowGroup:

```<code>rowGroup: {
    dataSrc: 1,
    startRender: function ( rows, group ) {
        var kundenId = table.row( this ).index();
        var kundenDomainAnzahl = 1;
        var kundenMaxDomainAnzahl = 2;
        return group +' ( '+ kundenDomainAnzahl +' / '+ kundenMaxDomainAnzahl +' / '+ kundenId + ')';
    }
}
</code>```

And my table is filled by PHP vars,
but in general the rows looks like this:

```<code><tr id="number">
    <td>Name</td>
    <td>Type</td>
    <td>Age</td>
</tr>
</code>```

答:
startRender rows is actually a dataTables API holding the rows matching the group. So work directly on rows, no need for the general table API.

In order to get the
 id's, loop over rows and grab the id through nodes(). Example :

```<code>startRender: function ( rows, group ) {
  var ids = '';
  rows.every(function() {
    if (ids.length) ids+=', ';
    ids+=this.nodes().to$().attr('id');
  })
  return 'test id´s : ' + ids;
}
</code>```

Have jotted down this demo that more or less correspond to the issue you a facing -> http://jsfiddle.net/0x6m94ha/

Update. Using an array and join() in order to prevent duplicated ids :

```<code>startRender: function ( rows, group ) {
  var ids = [];
  rows.every(function() {
    var id = this.nodes().to$().attr('id');
    if (!~ids.indexOf(id)) ids.push(id);
  })
  return 'test id´s : '+ ids.join(', ');
}
</code>```

demo -> http://jsfiddle.net/0x6m94ha/1/

Title: jQuery Datatables rowGroup

Body:
I'm using the jQuery datatables plugin with the rowGroup addon.

I need to use the 'startRender' function to display some information in the 'headline' of each group.

Links:

Datatables: https://datatables.net/

RowGroup Addon: https://datatables.net/extensions/rowgroup/examples/initialisation/startAndEndRender.html

But the problem is, that I cant read the row tr Id to get the needed data.

How can I access the row Id inside the startRender function to pass the data in the headline of the group?

Thats my jQuery rowGroup:

rowGroup: {
    dataSrc: 1,
    startRender: function ( rows, group ) {
        var kundenId = table.row( this ).index();
        var kundenDomainAnzahl = 1;
        var kundenMaxDomainAnzahl = 2;
        return group +' ( '+ kundenDomainAnzahl +' / '+ kundenMaxDomainAnzahl +' / '+ kundenId + ')';
    }
}

And my table is filled by PHP vars,
but in general the rows looks like this:

    Name
    Type
    Age

Body:
startRender rows is actually a dataTables API holding the rows matching the group. So work directly on rows, no need for the general table API.

In order to get the <tr> id's, loop over rows and grab the id through nodes(). Example :

startRender: function ( rows, group ) {
  var ids = '';
  rows.every(function() {
    if (ids.length) ids+=', ';
    ids+=this.nodes().to$().attr('id');
  })
  return 'test id´s : ' + ids;
}

Have jotted down this demo that more or less correspond to the issue you a facing -> http://jsfiddle.net/0x6m94ha/

Update. Using an array and join() in order to prevent duplicated ids :

startRender: function ( rows, group ) {
  var ids = [];
  rows.every(function() {
    var id = this.nodes().to$().attr('id');
    if (!~ids.indexOf(id)) ids.push(id);
  })
  return 'test id´s : '+ ids.join(', ');
}

demo -> http://jsfiddle.net/0x6m94ha/1/


问:
Google NDB model validation
How does one validate the GAE's no sql "ndb" model in python ?

Is there a pattern for this. Lets say I have a model called BreadCrumb

```<code>class BreadCrumb_Ndb(ndb.Model):
    """ A model for building breadcrumbs on the site """
    item_prop = ndb.StringProperty()
    item_type = ndb.StringProperty()
    href = ndb.StringProperty()
</code>```

I want to validate the property href to ensure its of url format using regular expressions.

答:
If cross field validation is needed, then probably overriding put() is the quickest way.</p>

```<code>def put(self, *args, **kwargs):
    if self.start_date > self.end_date:
        raise Exception("start_date must be less than end_date")
    return super(BaseModel, self).put(*args, **kwargs)
</code>```

Title: Google NDB model validation

Body:
How does one validate the GAE's no sql "ndb" model in python ?

Is there a pattern for this. Lets say I have a model called BreadCrumb

class BreadCrumb_Ndb(ndb.Model):
    """ A model for building breadcrumbs on the site """
    item_prop = ndb.StringProperty()
    item_type = ndb.StringProperty()
    href = ndb.StringProperty()

I want to validate the property href to ensure its of url format using regular expressions.

Body:
If cross field validation is needed, then probably overriding put() is the quickest way.

def put(self, *args, **kwargs):
    if self.start_date > self.end_date:
        raise Exception("start_date must be less than end_date")
    return super(BaseModel, self).put(*args, **kwargs)


问:
How to enable CORS on server-side code in java
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .

In-order to make server CORS enabled, We have done the below changes .

```<code>import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}
</code>```

However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml).
I don't have much knowledge on enabling CORS on server-side .
Please suggest how to proceed further .

答:
For a JavaEE 7 App you need to register this class in the ResourceConfig by adding following class to your war.

```<code>@ApplicationPath( "/" )
public class ApplicationConfig
    extends ResourceConfig {

   public ApplicationConfig() {
       register( new CORSFilter() );
   }

}
</code>```

Maybe you also need to increase the priority of your Filter by adding the following class level annotation:

```<code>@Provider
@Priority( Priorities.HEADER_DECORATOR)
public class CORSFilter implements ContainerResponseFilter {
...
}
</code>```

Body:
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .

In-order to make server CORS enabled, We have done the below changes .

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml).
I don't have much knowledge on enabling CORS on server-side .
Please suggest how to proceed further .

Body:
For a JavaEE 7 App you need to register this class in the ResourceConfig by adding following class to your war.

@ApplicationPath( "/" )
public class ApplicationConfig
    extends ResourceConfig {

   public ApplicationConfig() {
       register( new CORSFilter() );
   }

}

Maybe you also need to increase the priority of your Filter by adding the following class level annotation:

@Provider
@Priority( Priorities.HEADER_DECORATOR)
public class CORSFilter implements ContainerResponseFilter {
...
}


答:
This will not go further than the if case when returnUrl == "/User" or any other value

```<code>if (!String.IsNullOrEmpty(returnUrl))
{
    return Redirect(returnUrl);
}
</code>```

If not is null or empty, and if returnUrl == "/User", this is true since "/User" is not null and it is not empty.

and your second part will always be null or empty:

```<code>string url = returnUrl;

if (url == "/User")
{
</code>```

so this will "appear" like something isn't working.

My suggestion would be to return the "true" case first in an if/ else for clarity:

```<code>if (string.IsNullOrEmpty(returnUrl))
{
    // do the default cases
}
else
{
    // redirect to returnUrl
}
</code>```

Title: IF statement not being executed C# MVC

Body:
This will not go further than the if case when returnUrl == "/User" or any other value

if (!String.IsNullOrEmpty(returnUrl))
{
    return Redirect(returnUrl);
}

If not is null or empty, and if returnUrl == "/User", this is true since "/User" is not null and it is not empty.

and your second part will always be null or empty:

string url = returnUrl;

if (url == "/User")
{

so this will "appear" like something isn't working.

My suggestion would be to return the "true" case first in an if/ else for clarity:

if (string.IsNullOrEmpty(returnUrl))
{
    // do the default cases
}
else
{
    // redirect to returnUrl
}


问:
Replace contents in a file in only specific lines
I have a sample use case, where i want to replace "glob" with "url" in only some limited lines in the file. The rest of the file need not be replaced.

```<code>/publishfarm
        {
        # client headers which should be passed through to the render instances
        # (feature supported since dispatcher build 2.6.3.5222)
        /clientheaders
          {
                $include "clientheaders.any"
          }
        # hostname globbing for farm selection (virtual domain addressing)
        /virtualhosts
          {
                $include "publish-vhosts.any"
          }
        # the load will be balanced among these render instances
        /renders
          {
          $include "publish-renders.any"
          }
        # only handle the requests in the following acl. default is 'none'
        # the glob pattern is matched against the first request line
        /filter
          {
          # deny everything and allow specific entries
          /0001 { /type "deny"  /glob "*" }

          # open consoles
        #    /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
        #    /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

          # allow non-public content directories
        #    /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
        #    /0022 { /type "allow" /glob "* /bin/*"    }

        #    /0024 { /type "allow" /glob "* /libs/*"   }
        #    /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

        #    /0026 { /type "allow" /glob "* /home/*"   }
        #    /0027 { /type "allow" /glob "* /tmp/*"    }
        #    /0028 { /type "allow" /glob "* /var/*"    }

          /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

          # enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
      /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
      /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
      /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
      /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg

      # enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*" }  # enable personalization
      /0063 { /type "allow" /glob "POST /content/[.]*.commerce.cart.json" }  # allow POSTs to update the shopping cart

          # deny content grabbing
          /0081 { /type "deny"  /glob "GET *.infinity.json*" }
          /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
          /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
          /0084 { /type "deny"  /glob "GET *.docview.json*"  }
          /0085 { /type "deny"  /glob "GET *.docview.xml*"   }
          /0086 { /type "deny"  /glob "GET *.*[0-9].json*"   }
          /0087 { /type "deny"  /glob "GET *.feed.xml*"      }
        #    /0088 { /type "allow" /glob "GET *.1.json*"        }  # allow one-level json requests
</code>```

I want to replace glob by url in only these blocks and not for the entire file.
The contents which i want to be replaced are

```<code>      # enable specific mime types in non-public content directories
  /0041 { /type "allow" /glob "* *.css *"   }  # enable css
  /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
  /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
  /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
  /0045 { /type "allow" /glob "* *.png *"   }  # enable png
  /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
  /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
  /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
  /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
  /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
  /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg
</code>```

Now the catch here is the line numbers are not fixed. How can i accomplish this in ansible.

I used to do this :41,51s/glob/url in this file opening in vim and then note the start and the end line. But as i said these line numbers keep on changing.

答:
I was able to do this with the following command:

```<code># ansible 127.0.0.1 -m replace -a "path='/my/path/test_file' regexp='W*(/glob)\W*(.*)W*(css)W*(.*)css$' replace='url \"* *.css *\"   }  # enable css'"
</code>```

The W*(/glob)\W*(.*)W*(css)W*(.*)css$ regex matches everything between "glob" and the end of the line if it ends with "css".

That should translate into this inside a task file:

```<code>- replace:
  path: /my/path/test_file
  regexp: 'W*(/glob)\W*(.*)W*(css)W*(.*)css$'
  replace: 'url \"* *.css *\"   }  # enable css''
</code>```

The disadvantage of this method is that you would either need a replace block for each of the css, gifs, icos, javascript, etc.

So, a better approach would be to use with_items and handle the extension and comment upon we're doing the match on like so:

```<code>- hosts: myhostgroup
  tasks:
    - replace:
        path: /my/path/test_file
        regexp: 'W*(/glob)\W*(.*)W*({{ item.extension }})W*(.*){{ item.comment }}$'
        replace: 'url "* *.{{ item.extension }} *"   }  # enable {{ item.comment }}'
      with_items:
        - { extension: 'css', comment: 'css' }
        - { extension: 'gif', comment: 'gifs' }
        - { extension: 'ico', comment: 'icos' }
        - { extension: 'js', comment: 'javascript' }
        - { extension: 'png', comment: 'png' }
        - { extension: 'swf', comment: 'flash' }
        - { extension: 'svg', comment: 'SVG' }
        - { extension: 'woff', comment: 'woff' }
        - { extension: 'ttf', comment: 'ttf' }
        - { extension: 'eot', comment: 'eot' }
        - { extension: 'jpg', comment: 'jpg' }
</code>```

I am sure the regex could be improved, but this worked for my test on your file.

Body:
I have a sample use case, where i want to replace "glob" with "url" in only some limited lines in the file. The rest of the file need not be replaced.

/publishfarm
        {
        # client headers which should be passed through to the render instances
        # (feature supported since dispatcher build 2.6.3.5222)
        /clientheaders
          {
                $include "clientheaders.any"
          }
        # hostname globbing for farm selection (virtual domain addressing)
        /virtualhosts
          {
                $include "publish-vhosts.any"
          }
        # the load will be balanced among these render instances
        /renders
          {
          $include "publish-renders.any"
          }
        # only handle the requests in the following acl. default is 'none'
        # the glob pattern is matched against the first request line
        /filter
          {
          # deny everything and allow specific entries
          /0001 { /type "deny"  /glob "*" }

          # open consoles
        #    /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
        #    /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

          # allow non-public content directories
        #    /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
        #    /0022 { /type "allow" /glob "* /bin/*"    }

        #    /0024 { /type "allow" /glob "* /libs/*"   }
        #    /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

        #    /0026 { /type "allow" /glob "* /home/*"   }
        #    /0027 { /type "allow" /glob "* /tmp/*"    }
        #    /0028 { /type "allow" /glob "* /var/*"    }

          /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

          # enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
      /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
      /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
      /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
      /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg

      # enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*" }  # enable personalization
      /0063 { /type "allow" /glob "POST /content/[.]*.commerce.cart.json" }  # allow POSTs to update the shopping cart

          # deny content grabbing
          /0081 { /type "deny"  /glob "GET *.infinity.json*" }
          /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
          /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
          /0084 { /type "deny"  /glob "GET *.docview.json*"  }
          /0085 { /type "deny"  /glob "GET *.docview.xml*"   }
          /0086 { /type "deny"  /glob "GET *.*[0-9].json*"   }
          /0087 { /type "deny"  /glob "GET *.feed.xml*"      }
        #    /0088 { /type "allow" /glob "GET *.1.json*"        }  # allow one-level json requests

I want to replace glob by url in only these blocks and not for the entire file.
The contents which i want to be replaced are

      # enable specific mime types in non-public content directories
  /0041 { /type "allow" /glob "* *.css *"   }  # enable css
  /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
  /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
  /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
  /0045 { /type "allow" /glob "* *.png *"   }  # enable png
  /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
  /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
  /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
  /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
  /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
  /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg

Now the catch here is the line numbers are not fixed. How can i accomplish this in ansible.

I used to do this :41,51s/glob/url in this file opening in vim and then note the start and the end line. But as i said these line numbers keep on changing.

Body:
I was able to do this with the following command:

# ansible 127.0.0.1 -m replace -a "path='/my/path/test_file' regexp='W*(/glob)\W*(.*)W*(css)W*(.*)css$' replace='url \"* *.css *\"   }  # enable css'"

The W*(/glob)\W*(.*)W*(css)W*(.*)css$ regex matches everything between "glob" and the end of the line if it ends with "css".

That should translate into this inside a task file:

- replace:
  path: /my/path/test_file
  regexp: 'W*(/glob)\W*(.*)W*(css)W*(.*)css$'
  replace: 'url \"* *.css *\"   }  # enable css''

The disadvantage of this method is that you would either need a replace block for each of the css, gifs, icos, javascript, etc.

So, a better approach would be to use with_items and handle the extension and comment upon we're doing the match on like so:

- hosts: myhostgroup
  tasks:
    - replace:
        path: /my/path/test_file
        regexp: 'W*(/glob)\W*(.*)W*({{ item.extension }})W*(.*){{ item.comment }}$'
        replace: 'url "* *.{{ item.extension }} *"   }  # enable {{ item.comment }}'
      with_items:
        - { extension: 'css', comment: 'css' }
        - { extension: 'gif', comment: 'gifs' }
        - { extension: 'ico', comment: 'icos' }
        - { extension: 'js', comment: 'javascript' }
        - { extension: 'png', comment: 'png' }
        - { extension: 'swf', comment: 'flash' }
        - { extension: 'svg', comment: 'SVG' }
        - { extension: 'woff', comment: 'woff' }
        - { extension: 'ttf', comment: 'ttf' }
        - { extension: 'eot', comment: 'eot' }
        - { extension: 'jpg', comment: 'jpg' }

I am sure the regex could be improved, but this worked for my test on your file.


问:
Async post request and assigning returned data
So I am learning AngularJS and I am trying to replace my not-so-pretty method of getting data from a webservice and realtime assinging it to a variable that is binded using ng-repeat. The thing I want to achieve mostly is to have asynchronous call. I can't use it now because AJAX is returning data after data is returned to a scope variable.

My current code looks like this:

```<code>var app = angular.module("Listt", []);

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            $scope.results = getListt();
            loadingAnimationStop();
        };

        function getListt() {
            var returnData;
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    returnData = JSON.parse(data);
                }
            });
            return returnData;
        }
    }
);
</code>```

And in HTML I indicate search function by using ng-click

```<code><button ng-click="searchListt()">Search</button>
</code>```

答:
Why you cany directly call searchlist function and take variable. I think it will work.</p>

```<code>$scope.results=[];

$scope.searchListt = function () {

           loadingAnimationStart();
           $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                     $scope.results = JSON.parse(data);
                     loadingAnimationStop();
                }

            });
           loadingAnimationStop();
        }
</code>```

Body:
So I am learning AngularJS and I am trying to replace my not-so-pretty method of getting data from a webservice and realtime assinging it to a variable that is binded using ng-repeat. The thing I want to achieve mostly is to have asynchronous call. I can't use it now because AJAX is returning data after data is returned to a scope variable.

My current code looks like this:

var app = angular.module("Listt", []);

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            $scope.results = getListt();
            loadingAnimationStop();
        };

        function getListt() {
            var returnData;
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    returnData = JSON.parse(data);
                }
            });
            return returnData;
        }
    }
);

And in HTML I indicate search function by using ng-click

<button ng-click="searchListt()">Search</button>

Body:
Why you cany directly call searchlist function and take variable. I think it will work.

$scope.results=[];

$scope.searchListt = function () {

           loadingAnimationStart();
           $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                     $scope.results = JSON.parse(data);
                     loadingAnimationStop();
                }

            });
           loadingAnimationStop();
        }


问:
Installed MAMP on windows & loaded wordpress but have get HTTP ERROR 500
What I have done:

Apache Port set to 9000

Location of wordpress folder is C:\MAMP\htdocs.
Folder is called wordpress

Went to phpMyAdmin and created DB

Went to wp-config-sample.php and updated DB = wpTest, username & password = 'root'

changed wp-config-sample.php to wp-config.php

Servers are started.

What displays in chrome browser OK:

```<code>http://localhost:9000/MAMP/
http://localhost:9000/wordpress/readme.html
</code>```

http://localhost:9000/wordpress/ gives the error in browser:

```<code>This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500
</code>```

I am therefore unable to set up wordpress.

One thing I have noticed is that MAMP and htdocs folder properties when read only is unchecked and applied and I open it again then read only is checked again.
I have given all users full control in security settings.

Thanks

答:
the unzipping program I used to extract the wordpress files did not unzip correctly and the files within the folders wp-admin, wp-content, wp-includes were displayed but not the folders themselves. Several times I downloaded & unzipped the wordpress files and all with the same results.
I changed the unzipping programming and the folders were correctly unzipped.
In the past I have had an unzipping program fail to extract a file but never extract the files incorrectly like this before.
Initially without the folders the path to load certain files was incorrect and they couldn't be found and hence the error:

```<code>This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500
</code>```

Body:
What I have done:

Apache Port set to 9000

Location of wordpress folder is C:\MAMP\htdocs.
Folder is called wordpress

Went to phpMyAdmin and created DB

Went to wp-config-sample.php and updated DB = wpTest, username & password = 'root'

changed wp-config-sample.php to wp-config.php

Servers are started.

What displays in chrome browser OK:

http://localhost:9000/MAMP/
http://localhost:9000/wordpress/readme.html

http://localhost:9000/wordpress/ gives the error in browser:

This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500

I am therefore unable to set up wordpress.

One thing I have noticed is that MAMP and htdocs folder properties when read only is unchecked and applied and I open it again then read only is checked again.
I have given all users full control in security settings.

Thanks

Body:
the unzipping program I used to extract the wordpress files did not unzip correctly and the files within the folders wp-admin, wp-content, wp-includes were displayed but not the folders themselves. Several times I downloaded & unzipped the wordpress files and all with the same results.
I changed the unzipping programming and the folders were correctly unzipped.
In the past I have had an unzipping program fail to extract a file but never extract the files incorrectly like this before.
Initially without the folders the path to load certain files was incorrect and they couldn't be found and hence the error:

This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500


问:
Stubbing file tests in shUnit2
I am using shUnit2 to do unit testing in Bash shell scripts.

I have code like this:

```<code>if [ ! -x /usr/local/rvm/bin/rvm ]; then
  ...
fi
</code>```

etc

I want to write unit tests to test this code, but to do that I need to stub out the behaviour of Bash file tests.

One way I could do this would be to refactor as:

```<code>if ! test -x /usr/local/rvm/bin/rvm; then
  ...
fi
</code>```

Then I can stub out the test built-in using something like:

```<code>test() {
  case "$*" in
  "-x /usr/local/rvm/bin/rvm")
    false
    ;;
  esac
}
</code>```

Creating the files that are expected during setUp might be an option sometimes, but obviously not always.

Or, I could refactor to move file tests inside custom functions, e.g.

```<code>rvm_installed() {
  [ -x /usr/local/rvm/bin/rvm ]
}
</code>```

Then I can stub this function in my tests.

Is there any way to test this code without refactoring it though?

答:
What @janos said is correct, but it breaks shUnit2 if something like [ is stubbed.

I raised a pull request that was merged to fix this problem in the way @janos suggested in the comments. This fix will hopefully be released eventually in shUnit2 2.1.7.

In the mean time the options are:

1) Use the patched version above.

2) See also suggestions about how to use a wrapper file in this example here: https://github.com/zofrex/bourne-shell-unit-testing

Title: Stubbing file tests in shUnit2

Body:
I am using shUnit2 to do unit testing in Bash shell scripts.

I have code like this:

if [ ! -x /usr/local/rvm/bin/rvm ]; then
  ...
fi

etc

I want to write unit tests to test this code, but to do that I need to stub out the behaviour of Bash file tests.

One way I could do this would be to refactor as:

if ! test -x /usr/local/rvm/bin/rvm; then
  ...
fi

Then I can stub out the test built-in using something like:

test() {
  case "$*" in
  "-x /usr/local/rvm/bin/rvm")
    false
    ;;
  esac
}

Creating the files that are expected during setUp might be an option sometimes, but obviously not always.

Or, I could refactor to move file tests inside custom functions, e.g.

rvm_installed() {
  [ -x /usr/local/rvm/bin/rvm ]
}

Then I can stub this function in my tests.

Is there any way to test this code without refactoring it though?


问:
Sessions and storing objects
If return an object from the session (HttpContext.Current.Session) to a private member of the objects type and then modify it, e.g. you rename an attribute or add something to the objects internal list member. Are those changes persisted if on another page you request the same object from the session...will it be updated with the values updated on the previous page. In other words is the object persisted, or do you have to re-save the object back to the session once you change anything on every page. Any help is much appreciated. Thanks</p>

答:
Although you could have tested this for yourself very easily, the answer is yes - the object will be persisted!

The objects stored in the Session dictionary are stored by reference so what this means is that if you change the object's internal properties or structure (i.e. if you store a List<> object and add or remove items) those changes will be preserved.

That being said, if you store a value type such as an Int32 or a Boolean, then if you change the value you need to specifically set it to the Session.

Title: Sessions and storing objects


问:
Filter JSON data in TextField
Version that I use:

```<code>psycopg2==2.6.2
django=1.10.5
postgres=9.3
</code>```

I want to store JSON data to the database using Django, but I can't use JSONField() because it needs jsonb type that only present in PostgreSQL >=9.4.

My Django model is as follows:

```<code>class Inspection(models.Model):
    data = models.TextField(null=False, blank=False)
</code>```

In the data field I want to store JSON data.

The data is as follows:

Record1:

```<code>{
  "url": "some_url",
  "user": [
    {
      "id": "1",
      "email": "myemail@hotmail.com",
      "first_name": "My_First_Name",
      "last_name": "My_Last_Name"
    }
  ]
}
</code>```

Record2:

```<code>{
      "url": "some_url",
      "user": [
        {
          "id": "2",
          "email": "myemail_2@hotmail.com",
          "first_name": "My_First_Name_2",
          "last_name": "My_Last_Name_2"
        }
      ]
    }
</code>```

Can I filter on user id?

答:
```<code>id = 1
Inspection.objects.filter(data__icontains='"id": "{}"'.format(id))
</code>```

try with above and use space after colon (:) symbol.

Title: Filter JSON data in TextField

Body:
Version that I use:

psycopg2==2.6.2
django=1.10.5
postgres=9.3

I want to store JSON data to the database using Django, but I can't use JSONField() because it needs jsonb type that only present in PostgreSQL >=9.4.

My Django model is as follows:

class Inspection(models.Model):
    data = models.TextField(null=False, blank=False)

In the data field I want to store JSON data.

The data is as follows:

Record1:

{
  "url": "some_url",
  "user": [
    {
      "id": "1",
      "email": "myemail@hotmail.com",
      "first_name": "My_First_Name",
      "last_name": "My_Last_Name"
    }
  ]
}

Record2:

{
      "url": "some_url",
      "user": [
        {
          "id": "2",
          "email": "myemail_2@hotmail.com",
          "first_name": "My_First_Name_2",
          "last_name": "My_Last_Name_2"
        }
      ]
    }

Can I filter on user id?

Body:
id = 1
Inspection.objects.filter(data__icontains='"id": "{}"'.format(id))

try with above and use space after colon (:) symbol.


问:
restrict 1 word as case sensitive and other as case insensitive in python regex | (pipe)
I got the meaning of | (pipe special character) in regex, Python.
It matches either 1st or 2nd.

ex : a|b  Matches either a or b.

My question:
What if I want to match is a with case sensitive  and b with case insensitive in above example?

ex:

```<code>s = "Welcome to PuNe, Maharashtra"

result1 = re.search("punnee|MaHaRaShTrA",s)
result2 = re.search("pune|maharashtra",s)
result3 = re.search("PuNe|MaHaRaShTrA",s)
result4 = re.search("P|MaHaRaShTrA",s)
</code>```

I want to search Pune in the way I have written in above statement s i.e PuNe. But I have to search Maharashtra by ignoring case. How can I search 1 word with case sensitive and other with case insensitive? So that, result1, result2, result3, result4 will give not null value.

I tried:

```<code>result1 = re.search("pune|MaHaRaShTrA",s1, re.IGNORECASE)
</code>```

But this ignores the cases for both the words.

How can I restrict 1 word as case sensitive and other as case insensitive?

答:
In Python 3.6 and later, you may use the inline modifier groups:

```<code>>>> s = "Welcome to PuNe, Maharashtra"
>>> print(re.findall(r"PuNe|(?i:MaHaRaShTrA)",s))
['PuNe', 'Maharashtra']
</code>```

See the relevant Python re documentation:

(?aiLmsux-imsx:...)
   (Zero or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x', optionally followed by '-' followed by one or more letters from the 'i', 'm', 's', 'x'.) The letters set or remove the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode matching), and re.X (verbose), for the part of the expression. (The flags are described in Module Contents.)

The letters 'a', 'L' and 'u' are mutually exclusive when used as inline flags, so they can’t be combined or follow '-'. Instead, when one of them appears in an inline group, it overrides the matching mode in the enclosing group. In Unicode patterns (?a:...) switches to ASCII-only matching, and (?u:...) switches to Unicode matching (default). In byte pattern (?L:...) switches to locale depending matching, and (?a:...) switches to ASCII-only matching (default). This override is only in effect for the narrow inline group, and the
  original matching mode is restored outside of the group.

  New in version 3.6.

 Changed in version 3.7: The letters
  'a', 'L' and 'u' also can be used in a group.

Unfortunately, Python re versions before 3.6 did not support these groups, nor did they support alternating on and off inline modifiers.

If you can use PyPi regex module, you may use a (?i:...) construct:

```<code>import regex
s = "Welcome to PuNe, Maharashtra"
print(regex.findall(r"PuNe|(?i:MaHaRaShTrA)",s))
</code>```

See the online Python demo.

Body:
I got the meaning of | (pipe special character) in regex, Python.
It matches either 1st or 2nd.

ex : a|b  Matches either a or b.

My question:
What if I want to match is a with case sensitive  and b with case insensitive in above example?

ex:

s = "Welcome to PuNe, Maharashtra"

result1 = re.search("punnee|MaHaRaShTrA",s)
result2 = re.search("pune|maharashtra",s)
result3 = re.search("PuNe|MaHaRaShTrA",s)
result4 = re.search("P|MaHaRaShTrA",s)

I want to search Pune in the way I have written in above statement s i.e PuNe. But I have to search Maharashtra by ignoring case. How can I search 1 word with case sensitive and other with case insensitive? So that, result1, result2, result3, result4 will give not null value.

I tried:

result1 = re.search("pune|MaHaRaShTrA",s1, re.IGNORECASE)

But this ignores the cases for both the words.

How can I restrict 1 word as case sensitive and other as case insensitive?

Body:
In Python 3.6 and later, you may use the inline modifier groups:

>>> s = "Welcome to PuNe, Maharashtra"
>>> print(re.findall(r"PuNe|(?i:MaHaRaShTrA)",s))
['PuNe', 'Maharashtra']

See the relevant Python re documentation:

(?aiLmsux-imsx:...)
   (Zero or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x', optionally followed by '-' followed by one or more letters from the 'i', 'm', 's', 'x'.) The letters set or remove the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode matching), and re.X (verbose), for the part of the expression. (The flags are described in Module Contents.)

The letters 'a', 'L' and 'u' are mutually exclusive when used as inline flags, so they can’t be combined or follow '-'. Instead, when one of them appears in an inline group, it overrides the matching mode in the enclosing group. In Unicode patterns (?a:...) switches to ASCII-only matching, and (?u:...) switches to Unicode matching (default). In byte pattern (?L:...) switches to locale depending matching, and (?a:...) switches to ASCII-only matching (default). This override is only in effect for the narrow inline group, and the
  original matching mode is restored outside of the group.

  New in version 3.6.

 Changed in version 3.7: The letters
  'a', 'L' and 'u' also can be used in a group.

Unfortunately, Python re versions before 3.6 did not support these groups, nor did they support alternating on and off inline modifiers.

If you can use PyPi regex module, you may use a (?i:...) construct:

import regex
s = "Welcome to PuNe, Maharashtra"
print(regex.findall(r"PuNe|(?i:MaHaRaShTrA)",s))

See the online Python demo.


问:
Calculating Euler's Number to nth digit in javascript
How to calculate Euler's Number to nth digit in JavaScript?

```<code>e   =   1/0! + 1/1! + 1/2! + ...
    =   2.7182818284590...to nth digit  (base 10)
</code>```

Below code returns only number to 16 decimal point and accuracy is depend upon to the number of iterations/or number passed to function.

Code

```<code>function calcE(n) {
  let euler, itr;
  euler = 0
  itr = Number(n)
    for (var i = 0; i < itr+1; i++) {
      let fact = factorial(i)
      euler += 1/fact
    }
  return euler;
}
</code>```

Demo: miniwebtool

答:
Found a solution by using npm decimal.js package to handle big decimal.

Euler

```<code>function euler(n) {
  let zero = new Decimal(0);
  let one = new Decimal(1);
  let rval;

  for (let i = 0; i <= n; i++) {
    let fval = factorial(i);
    let invert = one.dividedBy(fval)
    zero = zero.plus(invert)
  }
  rval = zero.toFixed(Number(n))
  return rval;
}

function factorial(n) {
  var i = 2,
    r = new Decimal(1);
  for (; i <= n; r = r.times(i++));
  return r;
}
</code>```

Still not able to compute very large values. An Suggestions?

Body:
How to calculate Euler's Number to nth digit in JavaScript?

e   =   1/0! + 1/1! + 1/2! + ...
    =   2.7182818284590...to nth digit  (base 10)

Below code returns only number to 16 decimal point and accuracy is depend upon to the number of iterations/or number passed to function.

Code

function calcE(n) {
  let euler, itr;
  euler = 0
  itr = Number(n)
    for (var i = 0; i < itr+1; i++) {
      let fact = factorial(i)
      euler += 1/fact
    }
  return euler;
}

Demo: miniwebtool

Body:
Found a solution by using npm decimal.js package to handle big decimal.

Euler

function euler(n) {
  let zero = new Decimal(0);
  let one = new Decimal(1);
  let rval;

  for (let i = 0; i <= n; i++) {
    let fval = factorial(i);
    let invert = one.dividedBy(fval)
    zero = zero.plus(invert)
  }
  rval = zero.toFixed(Number(n))
  return rval;
}

function factorial(n) {
  var i = 2,
    r = new Decimal(1);
  for (; i <= n; r = r.times(i++));
  return r;
}

Still not able to compute very large values. An Suggestions?


问:
Detect overlapping date ranges from the same table
I have a table with the following data

```<code>PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010  31/01/2010  S
03    05/01/2010  06/01/2010  A
</code>```

And want to get the following results

```<code>PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
03    05/01/2010  06/01/2010  A
</code>```

Any ideas on where to start? A lot of the reading I've done suggests I need to create entries and for each day and join on matching days, is this the only way?

答:
```<code>select A.*
from MyTable A
inner join MyTable B
on (B.start <= A.end)
and (B.end >= A.start)
</code>```

or something like that (assuming dates are not nullable and equal dates count as an overlap).

Body:
I have a table with the following data

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010  31/01/2010  S
03    05/01/2010  06/01/2010  A

And want to get the following results

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
03    05/01/2010  06/01/2010  A

Any ideas on where to start? A lot of the reading I've done suggests I need to create entries and for each day and join on matching days, is this the only way?

Body:
select A.*
from MyTable A
inner join MyTable B
on (B.start <= A.end)
and (B.end >= A.start)

or something like that (assuming dates are not nullable and equal dates count as an overlap).


问:
Angular animation with *ngFor
I have I list of items and I want to trigger state for one item at a time.
http://plnkr.co/edit/WGLbs2gl7zSxGymOSm0y?p=preview

When clicking I want only clicked item to get the state and if state is 'closed' it should not show.

import { Http } from '@angular/http';
import {
  animate,
  Component,
  keyframes,
  state,
  style,
  transition,
  trigger,
} from '@angular/core';

@Component({
  selector: 'card-overview-example',
  templateUrl: 'card-overview-example.html',
  animations: [
    trigger('state', [
      state('open',
        style({
          opacity: 1
        })),
      transition('* => open', [
        animate(200, keyframes([
          style({
            opacity: 1
          }),
        ])),
      ]),
      state('closed',
        style({
          opacity: 0
        })
      ),
    ])
  ]
})
export class CardOverviewExample {
  items = [];
  state;
  constructor(private http: Http) {
   this.getData().subscribe(items => this.items = items.results);
  }
  getData() {
    return this.http.get(`https://swapi.co/api/people/?format=json`)
    .map((res:Response) => res.json());
  }
  showDetails(item) {
    // this.state = (this.state === 'open' ? 'closed' : 'open');
    this.state = (this.state === 'open' ? 'closed' : 'open');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><md-card *ngFor="let item of items">
  <md-card-title (click)="showDetails()">{{item.name}}</md-card-title>
  <md-card-content [@state]="closed">state = {{state}}
    <p>{{item.hair_color}}</p>
    <p>{{item.skin_color}}</p>
    <p>{{item.eye_color}}</p>
  </md-card-content>
</md-card></code>```

答:
More or less figured it out by passing the item and having state on items... http://plnkr.co/edit/QhArVlfFGIsXjx5QSLcX?p=preview

```<code>(click)="showDetails(item)"
</code>```

Hope it helps someone else :)

Title: Angular animation with *ngFor

Body:
I have I list of items and I want to trigger state for one item at a time.
http://plnkr.co/edit/WGLbs2gl7zSxGymOSm0y?p=preview

When clicking I want only clicked item to get the state and if state is 'closed' it should not show.

import { Http } from '@angular/http';
import {
  animate,
  Component,
  keyframes,
  state,
  style,
  transition,
  trigger,
} from '@angular/core';

@Component({
  selector: 'card-overview-example',
  templateUrl: 'card-overview-example.html',
  animations: [
    trigger('state', [
      state('open',
        style({
          opacity: 1
        })),
      transition('* => open', [
        animate(200, keyframes([
          style({
            opacity: 1
          }),
        ])),
      ]),
      state('closed',
        style({
          opacity: 0
        })
      ),
    ])
  ]
})
export class CardOverviewExample {
  items = [];
  state;
  constructor(private http: Http) {
   this.getData().subscribe(items => this.items = items.results);
  }
  getData() {
    return this.http.get(`https://swapi.co/api/people/?format=json`)
    .map((res:Response) => res.json());
  }
  showDetails(item) {
    // this.state = (this.state === 'open' ? 'closed' : 'open');
    this.state = (this.state === 'open' ? 'closed' : 'open');
  }
}

<md-card *ngFor="let item of items">
  <md-card-title (click)="showDetails()">{{item.name}}</md-card-title>
  <md-card-content [@state]="closed">state = {{state}}

{{item.hair_color}}

{{item.skin_color}}

{{item.eye_color}}

  </md-card-content>
</md-card>

Body:
More or less figured it out by passing the item and having state on items... http://plnkr.co/edit/QhArVlfFGIsXjx5QSLcX?p=preview

(click)="showDetails(item)"

Hope it helps someone else :)


问:
Cannot sign in to Google in JavaFX WebView
I cannot sign in to Google in JavaFX WebView. The page doesn't load when I click the 'Next' button.

Other logins on different websites work fine.

Here is an example you can run:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class App extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        WebView browser = new WebView();

        WebEngine webEngine = browser.getEngine();

        webEngine.load("https://calendar.google.com");

        StackPane root = new StackPane();
        root.getChildren().add(browser);

        primaryStage.setScene(new Scene(root, 600, 600));
        primaryStage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}
</code>```

Screenshot here

答:
Short Version:

Add the following line to your main method, before you load the page:

```<code>System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
</code>```

Long Version:

My first instinct was that JavaScript wasn't working, but I tested dummy emails and correctly got the error:

Couldn't find your Google Account

So it seemed like some JavaScript was working, but not the part which enabled the user to continue to enter their password. I added the following listener to listen for console errors, which I found here:

```<code>com.sun.javafx.webkit.WebConsoleListener.setDefaultListener(
    (webView, message, lineNumber, sourceId) ->
        System.out.println("Console: [" + sourceId + ":" + lineNumber + "] " + message)
);
</code>```

This resulted in the following error:

Console: [null:0] XMLHttpRequest cannot load
  https://ssl.gstatic.com/accounts/static/_/js/blahblahblah

  Origin https://accounts.google.com is not allowed by
  Access-Control-Allow-Origin.

This is a security feature called Same-Origin Policy. It's designed to stop pages being able to load scripts from potentially malicious third-party websites.

I searched for "Same Origin Policy JavaFX" and found the following question which will solve your problem.

The full application with both the fix and the additional logging is:

```<code>public class CalendarController extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        WebView browser = new WebView();

        WebEngine webEngine = browser.getEngine();

        com.sun.javafx.webkit.WebConsoleListener.setDefaultListener(
            (webView, message, lineNumber, sourceId)-> System.out.println("Console: [" + sourceId + ":" + lineNumber + "] " + message)
        );

        webEngine.load("http://calendar.google.com");

        StackPane root = new StackPane();
        root.getChildren().add(browser);

        primaryStage.setScene(new Scene(root, 600, 600));
        primaryStage.show();
    }

    public static void main(String[] args)
    {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        launch(args);
    }
}
</code>```

Body:
I cannot sign in to Google in JavaFX WebView. The page doesn't load when I click the 'Next' button.

Other logins on different websites work fine.

Here is an example you can run:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class App extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        WebView browser = new WebView();

        WebEngine webEngine = browser.getEngine();

        webEngine.load("https://calendar.google.com");

        StackPane root = new StackPane();
        root.getChildren().add(browser);

        primaryStage.setScene(new Scene(root, 600, 600));
        primaryStage.show();
    }

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

Screenshot here

Body:
Short Version:

Add the following line to your main method, before you load the page:

System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

Long Version:

My first instinct was that JavaScript wasn't working, but I tested dummy emails and correctly got the error:

Couldn't find your Google Account

So it seemed like some JavaScript was working, but not the part which enabled the user to continue to enter their password. I added the following listener to listen for console errors, which I found here:

com.sun.javafx.webkit.WebConsoleListener.setDefaultListener(
    (webView, message, lineNumber, sourceId) ->
        System.out.println("Console: [" + sourceId + ":" + lineNumber + "] " + message)
);

This resulted in the following error:

Console: [null:0] XMLHttpRequest cannot load
  https://ssl.gstatic.com/accounts/static/_/js/blahblahblah

  Origin https://accounts.google.com is not allowed by
  Access-Control-Allow-Origin.

This is a security feature called Same-Origin Policy. It's designed to stop pages being able to load scripts from potentially malicious third-party websites.

I searched for "Same Origin Policy JavaFX" and found the following question which will solve your problem.

The full application with both the fix and the additional logging is:

public class CalendarController extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        WebView browser = new WebView();

        WebEngine webEngine = browser.getEngine();

        com.sun.javafx.webkit.WebConsoleListener.setDefaultListener(
            (webView, message, lineNumber, sourceId)-> System.out.println("Console: [" + sourceId + ":" + lineNumber + "] " + message)
        );

        webEngine.load("http://calendar.google.com");

        StackPane root = new StackPane();
        root.getChildren().add(browser);

        primaryStage.setScene(new Scene(root, 600, 600));
        primaryStage.show();
    }

    public static void main(String[] args)
    {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        launch(args);
    }
}


问:
Inline initialization of two-dimensional typed array in IronPython
I have a question about typed array initialization in IronPython. I want to initialize inline typed two-dimensional array in IronPython.

In IronPython I discovered how to initialize simple typed array:

```<code>pythonTypedArray = Array[int]([0, 1, 2, 3, 4])
</code>```

and how to initialize typed array of arrays:

```<code>pythonTypedArrayOfArrays = Array[Array[int]]([Array[int]([0, 1]), Array[int]([2, 3])])
</code>```

For example, in C# I can do like so:

```<code>int[,] twoDimensionalArray = new int[,] { {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9} };
</code>```

Can I initialize inline two-dimensional typed array in IronPython? If no, what is the best way to initialize two-dimensional typed array in IronPython?

答:
So, you need a matrix. In Python it can be achieved by doing this:

```<code>matrix = [[0 for x in range(w)] for y in range(h)]
</code>```

Or using numpy (you can install it by running pip install numpy):

```<code>>>> import numpy
>>> numpy.zeros((4, 4))
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
</code>```

In numpy, generating a matrix with random numbers is as simple as:

```<code>>>> import numpy as np
>>> np.random.rand(2,3)
array([[ 0.22568268,  0.0053246 ,  0.41282024],
       [ 0.68824936,  0.68086462,  0.6854153 ]])
</code>```

IMO, whenever you want matrices, you want to use numpy because it has some nice methods which really help you process them.

//EDIT: Since you added more context, in IronPython you can create an array of arrays by doing:

```<code>array = Array[Array[int]]( ( (1,2), (3,4) ) )
</code>```

or you can create multidimensional arrays is to use Array.CreateInstance passing type as a first argument followed by dimension sizes:

```<code>array = Array.CreateInstance(int, 2, 3)
</code>```

You can always read the docs when you need more information

Body:
I have a question about typed array initialization in IronPython. I want to initialize inline typed two-dimensional array in IronPython.

In IronPython I discovered how to initialize simple typed array:

pythonTypedArray = Array[int]([0, 1, 2, 3, 4])

and how to initialize typed array of arrays:

pythonTypedArrayOfArrays = Array[Array[int]]([Array[int]([0, 1]), Array[int]([2, 3])])

For example, in C# I can do like so:

int[,] twoDimensionalArray = new int[,] { {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9} };

Can I initialize inline two-dimensional typed array in IronPython? If no, what is the best way to initialize two-dimensional typed array in IronPython?

Body:
So, you need a matrix. In Python it can be achieved by doing this:

matrix = [[0 for x in range(w)] for y in range(h)]

Or using numpy (you can install it by running pip install numpy):

>>> import numpy
>>> numpy.zeros((4, 4))
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

In numpy, generating a matrix with random numbers is as simple as:

>>> import numpy as np
>>> np.random.rand(2,3)
array([[ 0.22568268,  0.0053246 ,  0.41282024],
       [ 0.68824936,  0.68086462,  0.6854153 ]])

IMO, whenever you want matrices, you want to use numpy because it has some nice methods which really help you process them.

//EDIT: Since you added more context, in IronPython you can create an array of arrays by doing:

array = Array[Array[int]]( ( (1,2), (3,4) ) )

or you can create multidimensional arrays is to use Array.CreateInstance passing type as a first argument followed by dimension sizes:

array = Array.CreateInstance(int, 2, 3)

You can always read the docs when you need more information


问:
Location of public class method 'new' of 'Class'
Ruby's Class class lists two methods named 'new':

Class::new is a public class method

Class#new is a public instance method

But when I do:

```<code>Class.methods(false)
#=> []
</code>```

which is supposed to list singleton methods (which I am assuming what class methods are), I get an empty array. Why is this so? Where is Class::new defined?

答:
tl;dr summary:

Why is this so?

Because it's not a singleton method.

Where is Class::new defined?

It isn't. The call Class.new is just calling Class#new (since Class is an instance of itself). The documentation for Foo::new is actually the documentation for Foo#initialize for any class Foo, including Class itself.

If you want to know something about Ruby, it is often a good idea to ask her herself:

```<code>new_method = Class.method(:new)
#=> #<Method: Class#new (defined in Class at core/alpha.rb:90)>
</code>```

The Object#method method returns a Method object representing the method. (Methods aren't objects in Ruby themselves, but you can get a reflective proxy object that represents a method.)

You can ask a Method where it is defined using the Method#owner method:

```<code>new_method.owner
#=> Class
</code>```

As you can see, new is defined in Class and not in Class's singleton class.

You can also ask a Method about the location of its Ruby source code using the Method#source_location method:

```<code>new_method.source_location
#=> ['core/alpha.rb', 90]
</code>```

What this tells us is that Class#new is defined in the file core/alpha.rb on line 90:

```<code>def new(*args)
  obj = allocate()

  Rubinius.asm(args, obj) do |args, obj|
    run obj
    run args
    push_block
    send_with_splat :initialize, 0, true
    # no pop here, as .asm blocks imply a pop as they're not
    # allowed to leak a stack value
  end

  obj
end
</code>```

The method is partially implemented in bytecode for performance reasons, but it is basically just:

```<code>class Class
  def new(*args, &block)
    obj = allocate

    obj.__send__(:initialize, *args, &block) # because initialize is private
    #obj.initialize(*args, &block)

    obj
  end
end
</code>```

Now, you might ask yourself: why is there an entry for Class::new in the RDoc documentation, if that method doesn't exist? Well, RDoc knows about the relationship between #initialize which is the method you define but usually don't call directly and Class#new which is the method you call but usually don't define, and it will document #initialize as ::new if it exists.

So, what we really want to look at, is Class#initialize:

```<code>initialize_method = Class.method(:initialize)
#=> #<Method: Class#initialize (defined in Class at core/class.rb:15)>

initialize_method.owner
#=> Class

initialize_method.source_location
#=> ['core/class.rb', 15]
</code>```

This is the source:

```<code>def initialize(sclass=Object, name=nil, under=nil)
  raise TypeError, "already initialized class" if @instance_type
  raise TypeError, "can't make subclass of Class" if Class.equal?(sclass)

  set_superclass sclass

  # Things (rails) depend on the fact that a normal class is in the constant
  # table and have a name BEFORE inherited is run.
  under.const_set name, self if under

  if sclass
    Rubinius.privately do
      sclass.inherited self
    end
  end
  super()
end
private :initialize
</code>```

Class#initialize essentially does three things:

set the superclass

optionally assign the class to a constant to give it a name

call the Class#inherited hook method of the superclass

If you want to know what the relationships between some of the core classes that magically spring into existence at the beginning are, you can take a look at the initialization code of some Ruby execution engines, e.g.

Rubinius: VM::bootstrap_class in machine/ontology.cpp

JRuby: org.jruby.Ruby.initRoot in core/src/main/java/org/jruby/Ruby.java

IronRuby: the initial classes are generated by a program, the generator is in the directory Src/ClassInitGenerator

MRuby: mrb_init_class in src/class.c

Note: depending on what Ruby implementation you use, obviously the places where those methods are defined and how exactly they are defined may vary.

Body:
Ruby's Class class lists two methods named 'new':

Class::new is a public class method

Class#new is a public instance method

But when I do:

Class.methods(false)
#=> []

which is supposed to list singleton methods (which I am assuming what class methods are), I get an empty array. Why is this so? Where is Class::new defined?

Body:
tl;dr summary:

Why is this so?

Because it's not a singleton method.

Where is Class::new defined?

It isn't. The call Class.new is just calling Class#new (since Class is an instance of itself). The documentation for Foo::new is actually the documentation for Foo#initialize for any class Foo, including Class itself.

If you want to know something about Ruby, it is often a good idea to ask her herself:

new_method = Class.method(:new)
#=> #<Method: Class#new (defined in Class at core/alpha.rb:90)>

The Object#method method returns a Method object representing the method. (Methods aren't objects in Ruby themselves, but you can get a reflective proxy object that represents a method.)

You can ask a Method where it is defined using the Method#owner method:

new_method.owner
#=> Class

As you can see, new is defined in Class and not in Class's singleton class.

You can also ask a Method about the location of its Ruby source code using the Method#source_location method:

new_method.source_location
#=> ['core/alpha.rb', 90]

What this tells us is that Class#new is defined in the file core/alpha.rb on line 90:

def new(*args)
  obj = allocate()

  Rubinius.asm(args, obj) do |args, obj|
    run obj
    run args
    push_block
    send_with_splat :initialize, 0, true
    # no pop here, as .asm blocks imply a pop as they're not
    # allowed to leak a stack value
  end

  obj
end

The method is partially implemented in bytecode for performance reasons, but it is basically just:

class Class
  def new(*args, &block)
    obj = allocate

    obj.__send__(:initialize, *args, &block) # because initialize is private
    #obj.initialize(*args, &block)

    obj
  end
end

Now, you might ask yourself: why is there an entry for Class::new in the RDoc documentation, if that method doesn't exist? Well, RDoc knows about the relationship between #initialize which is the method you define but usually don't call directly and Class#new which is the method you call but usually don't define, and it will document #initialize as ::new if it exists.

So, what we really want to look at, is Class#initialize:

initialize_method = Class.method(:initialize)
#=> #<Method: Class#initialize (defined in Class at core/class.rb:15)>

initialize_method.owner
#=> Class

initialize_method.source_location
#=> ['core/class.rb', 15]

This is the source:

def initialize(sclass=Object, name=nil, under=nil)
  raise TypeError, "already initialized class" if @instance_type
  raise TypeError, "can't make subclass of Class" if Class.equal?(sclass)

  set_superclass sclass

  # Things (rails) depend on the fact that a normal class is in the constant
  # table and have a name BEFORE inherited is run.
  under.const_set name, self if under

  if sclass
    Rubinius.privately do
      sclass.inherited self
    end
  end
  super()
end
private :initialize

Class#initialize essentially does three things:

set the superclass

optionally assign the class to a constant to give it a name

call the Class#inherited hook method of the superclass

If you want to know what the relationships between some of the core classes that magically spring into existence at the beginning are, you can take a look at the initialization code of some Ruby execution engines, e.g.

Rubinius: VM::bootstrap_class in machine/ontology.cpp

JRuby: org.jruby.Ruby.initRoot in core/src/main/java/org/jruby/Ruby.java

IronRuby: the initial classes are generated by a program, the generator is in the directory Src/ClassInitGenerator

MRuby: mrb_init_class in src/class.c

Note: depending on what Ruby implementation you use, obviously the places where those methods are defined and how exactly they are defined may vary.


问:
Simulate "drag & drop" with Windows
How i can simulate "drag & drop" file with Windows Arguments on "object line" Object line in red rectangle (image example)</p>

答:
The shortcut properties dialog does not support drag & drop (neither files nor text as far as I can tell).

You could use UI Automation to change the text but just modifying the shortcut .lnk file is a better option.

From a scripting language you can set TargetPath and Arguments on a WshShortcut object or use the IShellLink interface in a real application.

Title: Simulate "drag & drop" with Windows