问:
Phantom colon appearing in Tumblr Theme
I'm having a first crack at a custom Tumblr theme and I've begun to encounter a phantom colon. I've traced its origin to the overlay div but I can't delete it as the caption is served from Tumblr.

This is the code in question:

```<code><div class="leftcolumn">

       <div class="item"><img src="{PhotoURL-500}">

       <div class="overlay"> {block:Caption}{Caption}{/block:Caption}</div>  </div>

       </div>
</code>```

and if you squint you can make out the offending colon beneath the bottom left corner of the image (in the orange):

colon on web page

Any help would be greatly appreciated

答:
I would suggest making the text invisible:

```<code>.leftcolumn .overlay {
   color: transparent;
}
</code>```

Or you could even make the text shrink:

```<code>.leftcolumn .overlay {
   font-size: 0
}
</code>```

Title: Phantom colon appearing in Tumblr Theme

Body:
I'm having a first crack at a custom Tumblr theme and I've begun to encounter a phantom colon. I've traced its origin to the overlay div but I can't delete it as the caption is served from Tumblr.

This is the code in question:

 {block:Caption}{Caption}{/block:Caption}

and if you squint you can make out the offending colon beneath the bottom left corner of the image (in the orange):

colon on web page

Any help would be greatly appreciated

Body:
I would suggest making the text invisible:

.leftcolumn .overlay {
   color: transparent;
}

Or you could even make the text shrink:

.leftcolumn .overlay {
   font-size: 0
}


来源: stackexchange

问:
Why instantiate a new list before recursion call?
```<code>public void dfsSearch (TreeNode root, List<String> curr, List<List<String>> res) {
        curr.add(String.valueOf(root.val));
        // a leaf node has been reached
        if (root.left == null && root.right == null) {
            res.add(curr);
            return;
        }
        if (root.left != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.left, temp, res);
        }
        if (root.right != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.right, temp, res);
        }
    }
</code>```

The code above is a a method using dfs to find all the paths from root to leaves in a binary tree, and my question is, in the two lines above the recursive call, why do I need to instantiate a new list and pass this temp list (temp) to the recursive call, why can't I just use the curr (the argument in the function)?

答:
Imagine this is your binary tree

```<code>     1
   2    3
  4 5
</code>```

Let's say you didn't use temp. Then you would recurse down the left side of the binary tree, meaning curr would add 1,2,and 4. Because lists are mutable, their values are saved in recursive calls, even when you pop from the recursive stack. So after adding 4 to curr, you will go back to node 2, go to the right, and add 5. Thus curr will contain 1,2,4,5 instead of what you want, 1,2,4 and 1,2,5.

ContentLicense: CC BY-SA 3.0

Body:
public void dfsSearch (TreeNode root, List<String> curr, List<List<String>> res) {
        curr.add(String.valueOf(root.val));
        // a leaf node has been reached
        if (root.left == null && root.right == null) {
            res.add(curr);
            return;
        }
        if (root.left != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.left, temp, res);
        }
        if (root.right != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.right, temp, res);
        }
    }

The code above is a a method using dfs to find all the paths from root to leaves in a binary tree, and my question is, in the two lines above the recursive call, why do I need to instantiate a new list and pass this temp list (temp) to the recursive call, why can't I just use the curr (the argument in the function)?

Body:
Imagine this is your binary tree

     1
   2    3
  4 5

Let's say you didn't use temp. Then you would recurse down the left side of the binary tree, meaning curr would add 1,2,and 4. Because lists are mutable, their values are saved in recursive calls, even when you pop from the recursive stack. So after adding 4 to curr, you will go back to node 2, go to the right, and add 5. Thus curr will contain 1,2,4,5 instead of what you want, 1,2,4 and 1,2,5.


问:
Extra column/field on IdentityUserRoles table using Identity 2 and Entity Framework 6
I'm using a custom implementation of the IdentityUser class in my project.

The problem is that Entity Framework adds an extra column in the table IdentityUserRoles, mapping the child class Id as a constraint.

 I know that EF is probably getting confused on figuring how to map the relationship with this new class, I just don't know why and how to solve it. I've been searching the web about this EF behavior, but couldn't find a solution yet.

Here are some screenshots that summarize the problem:

答:
I've found the same issue. There is a much simpler solution. You should explicitly define the relation on the IdentityUserRole configuration.

E.g.:

```<code>public class UserRoleConfiguration : EntityTypeConfiguration<UserRole>
{
    public UserRoleConfiguration()
    {
        HasKey(x => new {x.UserId, x.RoleId});
        HasRequired(x => x.User).WithMany(x => x.Roles).WillCascadeOnDelete();
    }
}
</code>```

Body:
I've found the same issue. There is a much simpler solution. You should explicitly define the relation on the IdentityUserRole configuration.

E.g.:

public class UserRoleConfiguration : EntityTypeConfiguration<UserRole>
{
    public UserRoleConfiguration()
    {
        HasKey(x => new {x.UserId, x.RoleId});
        HasRequired(x => x.User).WithMany(x => x.Roles).WillCascadeOnDelete();
    }
}


问:
How to deal with jQuery bootgrid request data in MVC
I'm having some issues with implementing a jQuery bootgrid using ASP.Net MVC. I can't implement the sorting, searching, pagination etc. functionality.

This is what I have in my controller:

```<code>public JsonResult IndexJson(BootgridRequestData model)
{
    var contacts = (from x in db.ContactSet
                    select new
                    {
                        x.AccountId,
                        x.FirstName,
                        x.LastName,
                        x.FullName,
                        x.JobTitle,
                        x.ParentCustomerId,
                        x.EMailAddress1,
                        x.Telephone1,
                        x.MobilePhone,
                        x.Fax,
                        x.GenderCode,
                        x.BirthDate
                    }).ToList();

    // This tResult throws a Non-invocable member cannot be used like a method error.
    var tResult = BootgridResponseData<JsonResult>() {
        current = model.current,
        rowCount = model.rowCount,
        rows = contacts,
        total = contacts.Count
    };

    return Json(tResult, JsonRequestBehavior.AllowGet);
}
</code>```

Then I have the following helper classes:

```<code>public class BootgridRequestData
{
    public int current { get; set; }
    public string rowCount { get; set; }
    public string searchPhrase { get; set; }
    public IEnumerable<SortData> sortItems { get; set; }
}

public class BootgridResponseData<T> where T : class
{
    public int current { get; set; } //? current page
    public int rowCount { get; set; } //? rows per page
    public IEnumerable<T> rows { get; set; } //? items
    public int total { get; set; } //? total rows for whole query
}

public class SortData
{
    public string Field { get; set; } //? Field Name
    public string Type { get; set; } //? ASC or DESC
}
</code>```

I'm not really too sure where to go from here. Any advice?

答:
The template T needs to be the same object type of your list.

```<code>public class BootgridResponseData<T> where T : class
{
    public int current { get; set; } //? current page
    public int rowCount { get; set; } //? rows per page
    public IEnumerable<T> rows { get; set; } //? items
    public int total { get; set; } //? total rows for whole query
}
</code>```

In your case your list its being generated as List<object>. It would be nice if you create a new type like(im assuming all the ids are strings, adapt it at your needs, Guid, int etc):

```<code>public class Contact
{
    public string AccountId {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string FullName {get; set;}
    public string JobTitle {get; set;}
    public string ParentCustomerId {get; set;}
    public string EMailAddress1 {get; set;}
    public string Telephone1 {get; set;}
    public string MobilePhone {get; set;}
    public string Fax {get; set;}
    public string GenderCode {get; set;}
    public DateTime BirthDate {get; set;}
}
</code>```

and Instead of this

```<code>select new
{
    x.AccountId,
    x.FirstName,
    x.LastName,
    x.FullName,
    x.JobTitle,
    x.ParentCustomerId,
    x.EMailAddress1,
    x.Telephone1,
    x.MobilePhone,
    x.Fax,
    x.GenderCode,
    x.BirthDate
}
</code>```

i would put this

```<code>select new Contact
{
    AccountId = x.AccountId,
    FirstName = x.FirstName,
    LastName = x.LastName,
    FullName = x.FullName,
    JobTitle = x.JobTitle,
    ParentCustomerId = x.ParentCustomerId,
    EMailAddress1 = x.EMailAddress1,
    Telephone1 = x.Telephone1,
    MobilePhone = x.MobilePhone,
    Fax = x.Fax,
    GenderCode = x.GenderCode,
    BirthDate = x.BirthDate
 }
</code>```

and your return will be like this, because your contacts are now of the type List<Contact>

```<code>var tResult = new
          BootgridResponseData<List<Contact>>()
          {
              current = model.current,
              rowCount = model.rowCount,
              rows = contacts,
              total = contacts.Count
          };
</code>```

In the front end, don't forget to put the table headers.

```<code><table id="grid-data" class="table table-condensed table-hover table-striped">
    <thead>
        <tr>
            <th data-column-id="AccountId">Account ID</th>
            <th data-column-id="FirstName">First Name</th>
            <th data-column-id="LastName">Last Name</th>
            (...) and so on
        </tr>
    </thead>
</table>
</code>```

The grid JavaScript in the front end will look like, depending if your function is a web GET or POST, your ajax settings may change.

```<code>$("#grid-data").bootgrid({
    ajax: true,
    ajaxSettings: {
    method: "GET",
    cache: false
}
    url: "<your_mvc_controller_url>"
});
</code>```

Take a look at bootgrid official page examples

Body:
I'm having some issues with implementing a jQuery bootgrid using ASP.Net MVC. I can't implement the sorting, searching, pagination etc. functionality.

This is what I have in my controller:

public JsonResult IndexJson(BootgridRequestData model)
{
    var contacts = (from x in db.ContactSet
                    select new
                    {
                        x.AccountId,
                        x.FirstName,
                        x.LastName,
                        x.FullName,
                        x.JobTitle,
                        x.ParentCustomerId,
                        x.EMailAddress1,
                        x.Telephone1,
                        x.MobilePhone,
                        x.Fax,
                        x.GenderCode,
                        x.BirthDate
                    }).ToList();

    // This tResult throws a Non-invocable member cannot be used like a method error.
    var tResult = BootgridResponseData<JsonResult>() {
        current = model.current,
        rowCount = model.rowCount,
        rows = contacts,
        total = contacts.Count
    };

    return Json(tResult, JsonRequestBehavior.AllowGet);
}

Then I have the following helper classes:

public class BootgridRequestData
{
    public int current { get; set; }
    public string rowCount { get; set; }
    public string searchPhrase { get; set; }
    public IEnumerable<SortData> sortItems { get; set; }
}

public class BootgridResponseData<T> where T : class
{
    public int current { get; set; } //? current page
    public int rowCount { get; set; } //? rows per page
    public IEnumerable<T> rows { get; set; } //? items
    public int total { get; set; } //? total rows for whole query
}

public class SortData
{
    public string Field { get; set; } //? Field Name
    public string Type { get; set; } //? ASC or DESC
}

I'm not really too sure where to go from here. Any advice?

Body:
The template T needs to be the same object type of your list.

public class BootgridResponseData<T> where T : class
{
    public int current { get; set; } //? current page
    public int rowCount { get; set; } //? rows per page
    public IEnumerable<T> rows { get; set; } //? items
    public int total { get; set; } //? total rows for whole query
}

In your case your list its being generated as List<object>. It would be nice if you create a new type like(im assuming all the ids are strings, adapt it at your needs, Guid, int etc):

public class Contact
{
    public string AccountId {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string FullName {get; set;}
    public string JobTitle {get; set;}
    public string ParentCustomerId {get; set;}
    public string EMailAddress1 {get; set;}
    public string Telephone1 {get; set;}
    public string MobilePhone {get; set;}
    public string Fax {get; set;}
    public string GenderCode {get; set;}
    public DateTime BirthDate {get; set;}
}

and Instead of this

select new
{
    x.AccountId,
    x.FirstName,
    x.LastName,
    x.FullName,
    x.JobTitle,
    x.ParentCustomerId,
    x.EMailAddress1,
    x.Telephone1,
    x.MobilePhone,
    x.Fax,
    x.GenderCode,
    x.BirthDate
}

i would put this

select new Contact
{
    AccountId = x.AccountId,
    FirstName = x.FirstName,
    LastName = x.LastName,
    FullName = x.FullName,
    JobTitle = x.JobTitle,
    ParentCustomerId = x.ParentCustomerId,
    EMailAddress1 = x.EMailAddress1,
    Telephone1 = x.Telephone1,
    MobilePhone = x.MobilePhone,
    Fax = x.Fax,
    GenderCode = x.GenderCode,
    BirthDate = x.BirthDate
 }

and your return will be like this, because your contacts are now of the type List<Contact>

var tResult = new
          BootgridResponseData<List<Contact>>()
          {
              current = model.current,
              rowCount = model.rowCount,
              rows = contacts,
              total = contacts.Count
          };

In the front end, don't forget to put the table headers.

<table id="grid-data" class="table table-condensed table-hover table-striped">
    <thead>
        <tr>
            <th data-column-id="AccountId">Account ID</th>
            <th data-column-id="FirstName">First Name</th>
            <th data-column-id="LastName">Last Name</th>
            (...) and so on
        </tr>
    </thead>
</table>

The grid JavaScript in the front end will look like, depending if your function is a web GET or POST, your ajax settings may change.

$("#grid-data").bootgrid({
    ajax: true,
    ajaxSettings: {
    method: "GET",
    cache: false
}
    url: "<your_mvc_controller_url>"
});

Take a look at bootgrid official page examples


问:
I have URL rewriting in my asp.net web solution how can I set startup url for non existent URL in VS2010?
I have URL rewriting in my asp.net web solution defined how can I set startup url for non existent page URL in VS2010.</p>

答:
For the web project, open the Properties page.

Go to the Web tab.

Select Start URL for the Start Action and enter the full URL that you want to use.

ContentLicense: CC BY-SA 2.5


问:
what is the easiest and efficient way to read elements from an XML using nodejs?
How do I easily and efficiently read a complex xml and get all values based on element names?

For an example for the following xml, how do I get only num_bedrooms and price element values?

http://api.zoopla.co.uk/api/v1/property_listings.xml?api_key=rau64t8asw384ypskf4qgt29&postcode=ST5&listing_status=sale&page_size=100&page_number=1

Thanks

答:
Once you convert xml to json, things will be easy.
I know a good tool to do this: xml2js.

A issue with it is that it always set arrays even there is only one object. Don't know if they have solution for this. If not, you can use this code to fix it:

```<code>var cleanXML = function(xml){
var keys = Object.keys(xml),
    o = 0, k = keys.length,
    node, value, singulars,
    l = -1, i = -1, s = -1, e = -1,
    isInt = /^-?\s*\d+$/,
    isDig = /^(-?\s*\d*\.?\d*)$/,
    radix = 10;

for (; o < k; ++o) {
    node = keys[o];

    if (xml[node] instanceof Array && xml[node].length === 1) {
        xml[node] = xml[node][0];
    }

    if (xml[node] instanceof Object) {
        value = Object.keys(xml[node]);

        if (value.length === 1) {
            l = node.length;

            singulars = [
                node.substring(0, l - 1),
                node.substring(0, l - 3) + "y"
            ];

            i = singulars.indexOf(value[0]);

            if (i !== -1) {
                xml[node] = xml[node][singulars[i]];
            }
        }
    }

    if (typeof(xml[node]) === "object") {
        xml[node] = cleanXML(xml[node]);
    }

    if (typeof(xml[node]) === "string") {
        value = xml[node].trim();

        if (value.match(isDig)) {
            if (value.match(isInt)) {
                if (Math.abs(parseInt(value, radix)) <= (2 ^ 53 - 1)) {
                    xml[node] = parseInt(value, radix);
                }
            }else {
                l = value.length;

                if (l <= 15) {
                    xml[node] = parseFloat(value);
                }else {
                    for (i = 0, s = -1, e = -1; i < l && e - s <= 15; ++i) {
                        if (value.charAt(i) > 0) {
                            if (s === -1) {
                                s = i;
                            }else {
                                e = i;
                            }
                        }
                    }

                    if (e - s <= 15) {
                        xml[node] = parseFloat(value);
                    }
                }
            }
        }
    }
}
return xml;
};
</code>```

Body:
Once you convert xml to json, things will be easy.
I know a good tool to do this: xml2js.

A issue with it is that it always set arrays even there is only one object. Don't know if they have solution for this. If not, you can use this code to fix it:

var cleanXML = function(xml){
var keys = Object.keys(xml),
    o = 0, k = keys.length,
    node, value, singulars,
    l = -1, i = -1, s = -1, e = -1,
    isInt = /^-?\s*\d+$/,
    isDig = /^(-?\s*\d*\.?\d*)$/,
    radix = 10;

for (; o < k; ++o) {
    node = keys[o];

    if (xml[node] instanceof Array && xml[node].length === 1) {
        xml[node] = xml[node][0];
    }

    if (xml[node] instanceof Object) {
        value = Object.keys(xml[node]);

        if (value.length === 1) {
            l = node.length;

            singulars = [
                node.substring(0, l - 1),
                node.substring(0, l - 3) + "y"
            ];

            i = singulars.indexOf(value[0]);

            if (i !== -1) {
                xml[node] = xml[node][singulars[i]];
            }
        }
    }

    if (typeof(xml[node]) === "object") {
        xml[node] = cleanXML(xml[node]);
    }

    if (typeof(xml[node]) === "string") {
        value = xml[node].trim();

        if (value.match(isDig)) {
            if (value.match(isInt)) {
                if (Math.abs(parseInt(value, radix)) <= (2 ^ 53 - 1)) {
                    xml[node] = parseInt(value, radix);
                }
            }else {
                l = value.length;

                if (l <= 15) {
                    xml[node] = parseFloat(value);
                }else {
                    for (i = 0, s = -1, e = -1; i < l && e - s <= 15; ++i) {
                        if (value.charAt(i) > 0) {
                            if (s === -1) {
                                s = i;
                            }else {
                                e = i;
                            }
                        }
                    }

                    if (e - s <= 15) {
                        xml[node] = parseFloat(value);
                    }
                }
            }
        }
    }
}
return xml;
};


问:
python matplotlib make everything bold
Well , I am making some plots and wants to make everything in bold font. I can can use weight="bold" to make bold font of label to ticks. Can also use the prop={'weight':'bold'} to make the legends lines bold, but I can't make the legend title bold. So, 1st question is there a way to make the legend title bold?

2nd,I tried to used matplotlib latex support to make the title bold, that did it but if I use rc('text', usetex=True) I cant use weight=bold and have to use \textbf{} everytime, also how do I make the ticks bold in this way.

3rd , If I use latex support then the font changes that I don't like. How do use the normal matplotlib font with using latex?

答:
You should be able to pass parameters into the plt.legend using the prop argument

```<code>legend_prop = {'weight':'bold'}
plt.plot(x, y, label='some label')
plt.legend(prop=legend_prop)
</code>```

This would give you bold labels. Is this not what you're looking for?

Title: python matplotlib make everything bold

Body:
You should be able to pass parameters into the plt.legend using the prop argument

legend_prop = {'weight':'bold'}
plt.plot(x, y, label='some label')
plt.legend(prop=legend_prop)

This would give you bold labels. Is this not what you're looking for?


问:
elisp search-forward with regexp and spec. chars return nil
emacs 25.1

I have string:

```<code><p>more complex non Q and A HTML code here.</p><table class="waffle" cellspacing="0" cellpadding="0"><thead><tr><th
</code>```

And if use in emacs regexp-builder with the next regexp: "
"

it's success found text:

```<code><table class="waffle" cellspacing="0" cellpadding="0">
</code>```

OK. But when I use same regexp in elisp by function search-forward nothing found (return nil)

```<code>      (setq test-start-point (search-forward "<table .*?>" nil t))
</code>```

test-start-point = nil.

Why?

答: search-forward searches exact matches.  In your case, you want to search a regular expression pattern, so you want to use re-search-forward instead.

Body:
emacs 25.1

I have string:

more complex non Q and A HTML code here.

<th

And if use in emacs regexp-builder with the next regexp: "
"

it's success found text:

OK. But when I use same regexp in elisp by function search-forward nothing found (return nil)

      (setq test-start-point (search-forward "
" nil t))

test-start-point = nil.

Why?


问:
Mule WSDL Connector
I use version 3.8 (3.8.3) .
I basically want to host my wsdl in a different location other than http://{serviceurl}?wsdl like http://{serviceurl}/my-great-service.wsdl

At the following mule doc
https://docs.mulesoft.com/mule-user-guide/v/3.8/wsdl-connectors

it says that you can specify the _wsdlLocation_ property of the CXF endpoint as follows

```<code><endpoint address="wsdl-cxf:http://localhost:8080/book/services/BookService?method=getBooks">
   <properties>
      <property name="wsdlLocation" value="file:///c:/BookService.wsdl"/>
   </properties>
</endpoint>
</code>```

But where to put this in the mule xml ?

To the root of the file <mule> here  </mule> or to <flow> here </flow> or to the <cxf:proxy-service> here </cxf:proxy-service>

The mule documentation is so limited and lock of examples.

答:
Any reason why you are using the cxf connector instead of the web service consumer?

https://docs.mulesoft.com/mule-user-guide/v/3.8/web-service-consumer

All the global configuration elements are specified after the <mule> tag and before the <flow> elements.

Example with web service consumer below:

```<code><mule ......>
    <ws:consumer-config name="Web_Service_Consumer" service="ServiceService"
    port="ServicePort" serviceAddress="addresUrl"
    wsdlLocation="wsdl location" doc:name="Web Service Consumer"/>

    <flow>...</flow>
</mule>
</code>```

If for any reason you want to use the cxf connector, is the same but using the cxf connector

Title: Mule WSDL Connector

Body:
I use version 3.8 (3.8.3) .
I basically want to host my wsdl in a different location other than http://{serviceurl}?wsdl like http://{serviceurl}/my-great-service.wsdl

At the following mule doc
https://docs.mulesoft.com/mule-user-guide/v/3.8/wsdl-connectors

it says that you can specify the _wsdlLocation_ property of the CXF endpoint as follows

<endpoint address="wsdl-cxf:http://localhost:8080/book/services/BookService?method=getBooks">
   <properties>
      <property name="wsdlLocation" value="file:///c:/BookService.wsdl"/>
   </properties>
</endpoint>

But where to put this in the mule xml ?

To the root of the file <mule> here  </mule> or to <flow> here </flow> or to the <cxf:proxy-service> here </cxf:proxy-service>

The mule documentation is so limited and lock of examples.

Body:
Any reason why you are using the cxf connector instead of the web service consumer?

https://docs.mulesoft.com/mule-user-guide/v/3.8/web-service-consumer

All the global configuration elements are specified after the <mule> tag and before the <flow> elements.

Example with web service consumer below:

<mule ......>
    <ws:consumer-config name="Web_Service_Consumer" service="ServiceService"
    port="ServicePort" serviceAddress="addresUrl"
    wsdlLocation="wsdl location" doc:name="Web Service Consumer"/>

    <flow>...</flow>
</mule>

If for any reason you want to use the cxf connector, is the same but using the cxf connector


问:
Issue on downloading Hadoopizer
I want to work with the framework hadoopizer but i can't find the hadoopizer.jar , could you please suggest me where i can find it </p>

<p>here is the github site : https://github.com/genouest/hadoopizer/tree/v1.0
They tell me to download hadoopizer from here https://github.com/genouest/hadoopizer/downloads but the hadoopizer bin is not found </p>

答:
As BinaryNerd above suggested, the link is broken but you can clone the source and build the jar. I was able to do so via the following steps using git and ant. I knew to use ant since it is referenced in the build.xml file found in the repository.

```<code>git clone https://github.com/genouest/hadoopizer.git
cd hadoopizer
</code>```

Here I had to make a change to build.xml. I converted the line:

```<code><fileset dir="bin"/>
</code>```

to:

```<code><fileset dir="src"/>
</code>```

Finally, we run any by calling

```<code>ant create_run_jar
</code>```

Now, if you look in the newly created distrib directory, you'll see hadoopizer.jar

Title: Issue on downloading Hadoopizer

Body:
I want to work with the framework hadoopizer but i can't find the hadoopizer.jar , could you please suggest me where i can find it

here is the github site : https://github.com/genouest/hadoopizer/tree/v1.0
They tell me to download hadoopizer from here https://github.com/genouest/hadoopizer/downloads but the hadoopizer bin is not found

Body:
As BinaryNerd above suggested, the link is broken but you can clone the source and build the jar. I was able to do so via the following steps using git and ant. I knew to use ant since it is referenced in the build.xml file found in the repository.

git clone https://github.com/genouest/hadoopizer.git
cd hadoopizer

Here I had to make a change to build.xml. I converted the line:

<fileset dir="bin"/>

to:

<fileset dir="src"/>

Finally, we run any by calling

ant create_run_jar

Now, if you look in the newly created distrib directory, you'll see hadoopizer.jar


问:
What do you use the Android Terminal Emulator for?
Why is there a terminal emulator in the Android App Market?</p>

答:
As above - it's for shell access, once you have root.

I've mainly just used it for browsing the file structure to get a better idea of where everything sits.


问:
Remove newline in textarea generated by HAML / Form Builder
I have a very simple Rails form.:

```<code>= form_for @object :remote => true do |form|
   = form.text_area :text, :class => 'form-control'
</code>```

For a new object, with a nil text attribute, this generates:

<textarea class="form-control" name="object[text]" id="object_text">    </textarea>

The blank space in that is a newline:

```<code>(byebug) form.text_area :text, :class => 'form-control'
"<textarea class=\"form-control\" name=\"user_deactivation[reason_text]\" id=\"user_deactivation_reason_text\">\n</textarea>"
</code>```

I strip out the leading and trailing spaces on save, so data wise, its not a big deal, but when the user clicks on this field, it appears indented.

Relevant software versions:

Rails 5.02

haml-4.0.7

The text area is in a bootstrap 3 dialog

Why is this newline being generated and how can I stop it?

答:
You can use the '~' operator, which is like the '=' operator, but automatically runs find_and_preserve on the output.

Like this:

   = form_for @object :remote => true do |form|
     ~ form.text_area :text, :class => 'form-control'

Body:
I have a very simple Rails form.:

= form_for @object :remote => true do |form|
   = form.text_area :text, :class => 'form-control'

For a new object, with a nil text attribute, this generates:

<textarea class="form-control" name="object[text]" id="object_text">    </textarea>

The blank space in that is a newline:

(byebug) form.text_area :text, :class => 'form-control'
"<textarea class=\"form-control\" name=\"user_deactivation[reason_text]\" id=\"user_deactivation_reason_text\">\n</textarea>"

I strip out the leading and trailing spaces on save, so data wise, its not a big deal, but when the user clicks on this field, it appears indented.

Relevant software versions:

Rails 5.02

haml-4.0.7

The text area is in a bootstrap 3 dialog

Why is this newline being generated and how can I stop it?


问:
Is there a way to tell if ReactElement renders "null"?
In my JSX, I have a case of a conditional rendering logic - when element A renders something (it's render() function returns something other than null), then also render element B, just above the element A.

Code example (simplified) would look like this:

```<code>function render() {
    let elemA = (<ElementA someProp={this.someVar} />);

    if (elemA.isNull()) {
        return (
            <div>
                { ...someElements }
            </div>
        );
    }

    return (
        <div>
            { ...someElements }
            <ElementB />
            { elemA }
        </div>
    );
}
</code>```

So my question is - Is there any way to have the elemA.isNull() check?

答:
So I ran into a situation where I was stuck having to do this, here is a way that works (though the hackiness might make you cry).

Should only be used as a last resort because it really is a total hack and you'll take a ~0-20ms performance hit depending on component complexity.
(Provider is there assuming you're using redux and your component depends on your redux state):

```<code>import { renderToStaticMarkup } from 'react-dom/server';
import { Provider } from 'react-redux';
import store from 'pathToYourReduxStoreInstance';

export default function isRenderingNull(componentInstance) {
  return !renderToStaticMarkup(
    <Provider store={store}>
      {componentInstance}
    </Provider>
  )
}
</code>```

Body:
In my JSX, I have a case of a conditional rendering logic - when element A renders something (it's render() function returns something other than null), then also render element B, just above the element A.

Code example (simplified) would look like this:

function render() {
    let elemA = (<ElementA someProp={this.someVar} />);

    if (elemA.isNull()) {
        return (

                { ...someElements }

        );
    }

    return (

            { ...someElements }
            <ElementB />
            { elemA }

    );
}

So my question is - Is there any way to have the elemA.isNull() check?

Body:
So I ran into a situation where I was stuck having to do this, here is a way that works (though the hackiness might make you cry).

Should only be used as a last resort because it really is a total hack and you'll take a ~0-20ms performance hit depending on component complexity.
(Provider is there assuming you're using redux and your component depends on your redux state):

import { renderToStaticMarkup } from 'react-dom/server';
import { Provider } from 'react-redux';
import store from 'pathToYourReduxStoreInstance';

export default function isRenderingNull(componentInstance) {
  return !renderToStaticMarkup(
    <Provider store={store}>
      {componentInstance}
    </Provider>
  )
}


问:
return separate values from an array in json
I have an instance variable @seats in a controller having value as follows (I checked the value using a byebug breakpoint)

```<code>#<Programmability::Response:0x007fdae0bb84e8 @return_code=0, @outputs=[[2, 4]], @table=#<Programmability::Table:0x007fdae0bb8538 @rows=nil, @columns=["column1", "column2"]>>
</code>```

How do i display the following in JSON

```<code>column1: 2
column2: 4
</code>```

I have the following line in JSON which returns output: [[2, 4]]

```<code>json.output        @seats.blank? ? nil : @seats.outputs
</code>```

答:
```<code>@seats.outputs.flatten.each_with_index do |val,index|
  puts "column#{index+1}: #{val}"
end
</code>```

Body:
I have an instance variable @seats in a controller having value as follows (I checked the value using a byebug breakpoint)

#<Programmability::Response:0x007fdae0bb84e8 @return_code=0, @outputs=[[2, 4]], @table=#<Programmability::Table:0x007fdae0bb8538 @rows=nil, @columns=["column1", "column2"]>>

How do i display the following in JSON

column1: 2
column2: 4

I have the following line in JSON which returns output: [[2, 4]]

json.output        @seats.blank? ? nil : @seats.outputs


问:
Jquery change src of audio and play on keydown
I have the following code that's working except for case 78 (letter N).  When this key is pressed the audio starts to play but then stops.  The other keys play the new audio file. I think the problem might have something to do with the keydown being pressed when the src file is being changed.  Here's a working fiddle:  keysounds</p>

```<code><!DOCTYPE html>

<html>
<head>
   <script
      type        = "text/javascript"
      src         = "https://code.jquery.com/jquery-3.2.1.min.js"
      integrity   = "sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin = "anonymous">
   </script>
   <script>
   /*global $ */
      $(function() {
         var playing;
         $(document).on("keydown", function(key) {
           playing = undefined;
           switch(parseInt(key.which, 10)) {
              case 68:
                 playing = $("#sound0").get(0);
                 break;
              case 78:
                 playing = $("#sound0").get(0);
                 $("#sound0").attr("src",'sound2.mp3');
                 break;
              case 79:
                 playing = $("#sound0").get(0);
                 break;
              case 83:
                 playing = $("#sound0").get(0);
                 break;
              case 85:
                 playing = $("#sound0").get(0);
                 break;
           };

           if(playing){
              playing.play();
           }

         }).on("keyup", function() {
            if(playing){
               playing.pause();
               playing.currentTime=0;
              playing = undefined;
            }
         });
      });
   </script>
   <style>
       div{
           text-align:center;
           margin-top:50%;
       }
       span{
           border-style:double;
           margin:.4%;
       }
   </style>
   <title>Keys</title>
</head>
<body>
    <div>
        <span>S</span>
        <span>O</span>
        <span>U</span>
        <span>N</span>
        <span>D</span>
        <span>S</span>
    </div>
    <audio  id="sound0" src="sound0.wav" ></audio>
</body>
</html>
</code>```

答:
You change the src attribute AFTER having it getted in the playing variable.

It should work if you just inverse two lines, like this:

```<code>case 78:
   $("#sound0").attr("src",'sound2.mp3');
   playing = $("#sound0").get(0);
   break;
</code>```

You should also reset the original audio source for next iterations.

EDIT

The use of a "flag" to determine if the key is held avoids the keydown event to trigger your script too often... and to let the music play.

```<code>/*global $ */
$(function() {
  var playing;
  var keyHeld=false;        // Flag!

  $(document).on("keydown", function(key) {
    if(!keyHeld){
      keyHeld=true;

      // Reset to original sound
      $("#sound0").attr("src",'http://www.sailwbob.com/sound0.wav');

      switch(parseInt(key.which, 10)) {
        case 68:
          playing = $("#sound0").get(0);
          break;
        case 78:
          $("#sound0").attr("src",'http://www.sailwbob.com/sound2.mp3');
          playing = $("#sound0").get(0);
          break;
        case 79:
          playing = $("#sound0").get(0);
          break;
        case 83:
          playing = $("#sound0").get(0);
          break;
        case 85:
          playing = $("#sound0").get(0);
          break;
        default:
          $("#sound0").attr("src",'');          // On other key, Play nothing!
          playing = $("#sound0").get(0);
                                    };

      if($("#sound0").attr("src")!=""){
        playing.play();
      }
    }
  }).on("keyup", function() {
    if(playing){
      playing.pause();
      playing.currentTime=0;
      keyHeld=false;
    }
  });
});
</code>```

Here is your Fiddle updated

Body:
I have the following code that's working except for case 78 (letter N).  When this key is pressed the audio starts to play but then stops.  The other keys play the new audio file. I think the problem might have something to do with the keydown being pressed when the src file is being changed.  Here's a working fiddle:  keysounds

<!DOCTYPE html>

   <title>Keys</title>

        S
        O
        U
        N
        D
        S

    <audio  id="sound0" src="sound0.wav" ></audio>

Body:
You change the src attribute AFTER having it getted in the playing variable.

It should work if you just inverse two lines, like this:

case 78:
   $("#sound0").attr("src",'sound2.mp3');
   playing = $("#sound0").get(0);
   break;

You should also reset the original audio source for next iterations.

EDIT

The use of a "flag" to determine if the key is held avoids the keydown event to trigger your script too often... and to let the music play.

/*global $ */
$(function() {
  var playing;
  var keyHeld=false;        // Flag!

  $(document).on("keydown", function(key) {
    if(!keyHeld){
      keyHeld=true;

      // Reset to original sound
      $("#sound0").attr("src",'http://www.sailwbob.com/sound0.wav');

      switch(parseInt(key.which, 10)) {
        case 68:
          playing = $("#sound0").get(0);
          break;
        case 78:
          $("#sound0").attr("src",'http://www.sailwbob.com/sound2.mp3');
          playing = $("#sound0").get(0);
          break;
        case 79:
          playing = $("#sound0").get(0);
          break;
        case 83:
          playing = $("#sound0").get(0);
          break;
        case 85:
          playing = $("#sound0").get(0);
          break;
        default:
          $("#sound0").attr("src",'');          // On other key, Play nothing!
          playing = $("#sound0").get(0);
                                    };

      if($("#sound0").attr("src")!=""){
        playing.play();
      }
    }
  }).on("keyup", function() {
    if(playing){
      playing.pause();
      playing.currentTime=0;
      keyHeld=false;
    }
  });
});

Here is your Fiddle updated


问:
Ansible: use host address of hosts.ini in playbook
I have to do a POST request with ansible.

My hosts.ini file is:

```<code>[workers]
worker1 ansible_host=111.111.111.111
worker2 ansible_host=222.222.222.222
</code>```

The url I have to connect to needs the ip address of worker1, so I wrote my playbook as:

```<code>- hosts: worker1

  tasks:
  - name: inizialize worker
    uri:
      url: "http://{{ worker1 }}:8080/xxx/yyy"
      method: POST
      user: admin
      password: password
      force_basic_auth: yes
      return_content: yes
      body: "field=myfield"
</code>```

But running it, I get:

the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'worker1' is undefined

Where is the problem?

答:
You don't have a variable named worker1 defined.

If you wanted to replace the value with 111.111.111.111, you should use magic variables:

```<code>url: "http://{{ hostvars['worker1']['ansible_host'] }}:8080/xxx/yyy"
</code>```

but considering your whole play, you might as well wanted:

```<code>url: "http://{{ ansible_host }}:8080/xxx/yyy"
</code>```

Mind that your inventory file defines a host group named workers and your play refers to a host group named worker1 -- this makes no sense altogether.

Body:
I have to do a POST request with ansible.

My hosts.ini file is:

[workers]
worker1 ansible_host=111.111.111.111
worker2 ansible_host=222.222.222.222

The url I have to connect to needs the ip address of worker1, so I wrote my playbook as:

- hosts: worker1

  tasks:
  - name: inizialize worker
    uri:
      url: "http://{{ worker1 }}:8080/xxx/yyy"
      method: POST
      user: admin
      password: password
      force_basic_auth: yes
      return_content: yes
      body: "field=myfield"

But running it, I get:

the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'worker1' is undefined

Where is the problem?

Body:
You don't have a variable named worker1 defined.

If you wanted to replace the value with 111.111.111.111, you should use magic variables:

url: "http://{{ hostvars['worker1']['ansible_host'] }}:8080/xxx/yyy"

but considering your whole play, you might as well wanted:

url: "http://{{ ansible_host }}:8080/xxx/yyy"

Mind that your inventory file defines a host group named workers and your play refers to a host group named worker1 -- this makes no sense altogether.


问:
Pandas fill missing values in dataframe from another dataframe
I cannot find a pandas function (which I had seen before) to substitute the NaN's in a dataframe with values from another dataframe (assuming a common index which can be specified). Any help?</p>

答:
DataFrame.combine_first() answers this question exactly.

However, sometimes you want to fill/replace/overwrite some of the non-missing (non-NaN) values of DataFrame A with values from DataFrame B. That question brought me to this page, and the solution is DataFrame.mask()

```<code>A = B.mask(condition, A)
</code>```

When condition is true, the values from A will be used, otherwise B's values will be used.

For example, you could solve the OP's original question with mask such that when an element from A is non-NaN, use it, otherwise use the corresponding element from B.

But using DataFrame.mask() you could replace the values of A that fail to meet arbitrary criteria (less than zero? more than 100?) with values from B. So mask is more flexible, and overkill for this problem, but I thought it was worthy of mention (I needed it to solve my problem).

It's also important to note that B could be a numpy array instead of a DataFrame. DataFrame.combine_first() requires that B be a DataFrame, but DataFrame.mask() just requires that B's is an NDFrame and its dimensions match A's dimensions.

Body:
DataFrame.combine_first() answers this question exactly.

However, sometimes you want to fill/replace/overwrite some of the non-missing (non-NaN) values of DataFrame A with values from DataFrame B. That question brought me to this page, and the solution is DataFrame.mask()

A = B.mask(condition, A)

When condition is true, the values from A will be used, otherwise B's values will be used.

For example, you could solve the OP's original question with mask such that when an element from A is non-NaN, use it, otherwise use the corresponding element from B.

But using DataFrame.mask() you could replace the values of A that fail to meet arbitrary criteria (less than zero? more than 100?) with values from B. So mask is more flexible, and overkill for this problem, but I thought it was worthy of mention (I needed it to solve my problem).

It's also important to note that B could be a numpy array instead of a DataFrame. DataFrame.combine_first() requires that B be a DataFrame, but DataFrame.mask() just requires that B's is an NDFrame and its dimensions match A's dimensions.


问:
How to pass multiple values to a stored procedure
I have an Excel worksheet with a dropdown data validation box where the user can select from a list of integer values to determine a department or the word "ALL" to get all departments.  I'm passing that cell's value to a stored procedure using SQL. In the SQL, I have WHERE Department=@Dept.

If I'm only going to allow one department choice, this works fine, but I want to also allow for all departments.

Are there any ideas on how to make that work?  Does it take some sort of trick with the IN operator or something else?

答:
Use a CASE statement, so if it's "ALL" you can pass back the Department field. If it's anything else pass the value you sent in:

```<code>Where Department = CASE @input WHEN 'ALL' Then Department ELSE @input END
</code>```

Body:
Use a CASE statement, so if it's "ALL" you can pass back the Department field. If it's anything else pass the value you sent in:

Where Department = CASE @input WHEN 'ALL' Then Department ELSE @input END


问:
Is it possible to retrieve data from a 3rd party App by my own Android app?
I'm too much of an android novice to comprehend the more detailed postings wrt this topic on stackoverflow, so I hope I can ask this simple yes/no question instead.
I have my own flashcard android app and (due to lack of translation APIs, a different story ...) I thought I could utilized a 3rd party dictionary app I have installed on my phone (this is just for me, not for productation, so no concern about how this scales to other phones/envs).
So it sounds like it might be possible to launch the 3rd party app from my app, but it doesn't sound possible to retrieve data from the 3rd party app and consume it in my own i.e. I would have to know the source code of the 3rd party app to understand intent and activity names (and its manifest ?)

So here's the naive/simple question, is it possible to simply launch the app, navigate to the page/activity I'm interested in (since I assume I can't jump directly to it since I don't know the details) and 'swipe/parse' the output of that app and return to my app ?

答: As far as i understand from your question you want to get data from another app? Yes you can use server to retrieve and send data between apps.</p>


问:
Overriding methods in a class extension constrained to a protocol in swift
I am trying to add default implementations to UIViewController touches began to all controllers conforming to a protocol through a protocol extension. There the touch would be sent to a custom view all controllers implementing this protocol have.

Here's the initial state:

```<code>protocol WithView {
    var insideView: UIView! { get }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 2 */
}
</code>```

What I'd like to accomplish is a situation where all the UIViewControllers forwarded the touches to the insideView without specifying so for every controller the same way. Something like this:

```<code>protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController where Self: WithView {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}
</code>```

But this does not compile, saying 'Trailing where clause for extension of non-generic type UIViewController'

I tried to define it the other way around, like so:

```<code>extension WithView where Self: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}
</code>```

and while the extension is properly formatted, the compiler complains, as it cannot 'override' things in a protocol extension.

What I'd like is a class extension constrained to a protocol, such as I can override this methods and not being forced to copy-paste code inside all my controllers implementing this protocol.

Edit: as per proposed solutions

I also came up with this solution:

```<code>protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController {
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let viewSelf = (self as? WithView) else {
            super.touchesBegan(touches, with: event)
            return
        }
        viewSelf.insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}
</code>```

It does what I want, but it feels a bit messy though, because then all the UIViewControllers would intherit this behavior, and would override its code, checking if they implement the protocol.

答:
You can define your own superclass for all view controllers and check if self conforms to the particular protocol (WithView in your case) to decide if you should forward touch events to any other view.

```<code>class MyViewController: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let selfWithView = self as? WithView {
            selfWithView.insideView.touchesBegan(touches, with: event)
        } else {
            super.touchesBegan(touches, with: event)
        }
    }
}
</code>```

This is more flexible approach, you don't have to store insideView property in every view controller subclass.

Body:
I am trying to add default implementations to UIViewController touches began to all controllers conforming to a protocol through a protocol extension. There the touch would be sent to a custom view all controllers implementing this protocol have.

Here's the initial state:

protocol WithView {
    var insideView: UIView! { get }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 2 */
}

What I'd like to accomplish is a situation where all the UIViewControllers forwarded the touches to the insideView without specifying so for every controller the same way. Something like this:

protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController where Self: WithView {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}

But this does not compile, saying 'Trailing where clause for extension of non-generic type UIViewController'

I tried to define it the other way around, like so:

extension WithView where Self: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

and while the extension is properly formatted, the compiler complains, as it cannot 'override' things in a protocol extension.

What I'd like is a class extension constrained to a protocol, such as I can override this methods and not being forced to copy-paste code inside all my controllers implementing this protocol.

Edit: as per proposed solutions

I also came up with this solution:

protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController {
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let viewSelf = (self as? WithView) else {
            super.touchesBegan(touches, with: event)
            return
        }
        viewSelf.insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}

It does what I want, but it feels a bit messy though, because then all the UIViewControllers would intherit this behavior, and would override its code, checking if they implement the protocol.

Body:
You can define your own superclass for all view controllers and check if self conforms to the particular protocol (WithView in your case) to decide if you should forward touch events to any other view.

class MyViewController: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let selfWithView = self as? WithView {
            selfWithView.insideView.touchesBegan(touches, with: event)
        } else {
            super.touchesBegan(touches, with: event)
        }
    }
}

This is more flexible approach, you don't have to store insideView property in every view controller subclass.


问:
Using Django Rest Framework, is it possible to get results internally on server within Django?
I have a complex DRF ViewSet that supports paging, filtering, sorting, etc. that backends a grid view.  To build an "export" capability, I need to be able to take the same querystring that my endpoint uses, such as:

?obj_id=129&ordering=latitude&city__icontains=nap

And be able to, in Django, send that string into DRF somehow and get the fully-modified queryset after all the view's filters, sorts, etc are applied (the same way as the GET did).  I could use the fully-rendered json response or some interim filter-applied queryset.  Is it possible to use DRF in this way?

答:
You should write a CSV renderer for your viewset and get that content-type to export the CSV.
There's even one already available.</p>


问:
Reversing order of divs depending on width
I'm currently working on a menu consisting of two parts (see image). On mobile, I'd like to show these menu items stacked from top to bottom, but starting with the bottom menu and ending with the top menu. Is there any (clean) way to do this with CSS or will I have to create two menus and show the correct one depending on page width?

EDIT: To clarify, the image is just to show an example of what I mean. I'm wondering in a more general sense if it's possible to somehow reverse the divs in CSS (without absolute positioning etc).

EDIT 2: Apologies for not adding any code. Here's a small pen that shows the situation: https://codepen.io/anon/pen/GWwrMW

```<code><div class="nav">
  <ul class="nav__top">
    <li>Sub Item 1</li>
    <li>Sub Item 2</li>
  </ul>
  <ul class="nav__primary">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
</div>

.nav__top,
.nav__primary {
  list-style: none;
  margin: 0 0 20px 0;
  text-align: right;
  li {
    display: inline-block;
    padding: 10px;
    background-color: #ccc;
  }
}
</code>```

On mobile, I want the sub items to be displayed underneath the main items.

答:
If you want responsive nav bar you have to use media queries. Something like this

```<code>@media screen and (max-width: 600px){
    ul.topnav li {float: none;}}
</code>```

This will work if your menu was built by list.

Body:
I'm currently working on a menu consisting of two parts (see image). On mobile, I'd like to show these menu items stacked from top to bottom, but starting with the bottom menu and ending with the top menu. Is there any (clean) way to do this with CSS or will I have to create two menus and show the correct one depending on page width?

EDIT: To clarify, the image is just to show an example of what I mean. I'm wondering in a more general sense if it's possible to somehow reverse the divs in CSS (without absolute positioning etc).

EDIT 2: Apologies for not adding any code. Here's a small pen that shows the situation: https://codepen.io/anon/pen/GWwrMW

Sub Item 1

Sub Item 2

Item 1

Item 2

Item 3

Item 4

.nav__top,
.nav__primary {
  list-style: none;
  margin: 0 0 20px 0;
  text-align: right;
  li {
    display: inline-block;
    padding: 10px;
    background-color: #ccc;
  }
}

On mobile, I want the sub items to be displayed underneath the main items.

Body:
If you want responsive nav bar you have to use media queries. Something like this

@media screen and (max-width: 600px){
    ul.topnav li {float: none;}}

This will work if your menu was built by list.


问:
Why there is no data race?
I am reading  Bjarne's FAQ on Memory Model, here is a quote

So, C++11 guarantees that no such problems occur for "separate memory locations.'' More precisely: A memory location cannot be safely accessed by two threads without some form of locking unless they are both read accesses. Note that different bitfields within a single word are not separate memory locations, so don't share structs with bitfields among threads without some form of locking. Apart from that caveat, the C++ memory model is simply "as everyone would expect.''

However, it is not always easy to think straight about low-level concurrency issues. Consider:

start with x==0 and y==0

if (x) y = 1;   // Thread 1

if (y) x = 1;  // Thread 2

Is there a problem here? More precisely, is there a data race? (No there isn't).

My question is, why there is no data race? It is obvious to me that there apparently is a data race since thread 1 is a writer for y while thread 2 is a reader for y, and similarly for x.

答: x and y are 0 and therefore the code behind the if will not be executed and there will be no write and therefore there can be no data race.

Title: Why there is no data race?


问:
android studio surround find results with if statement
Is there a way of surrounding search results in android studio with a predefined if statement?

Like every Log.d line

```<code>Log.d("foo","bar");
</code>```

surrounded with an if statement? Or any other statment.

```<code>if(BuildConfig.DEBUG){
    Log.d("foo","bar");
}
</code>```

答:
Yes, you can do this with regex replacement.

Press Ctrl+Shift+R

In the options tab, make sure the regex checkbox is selected and scope is Whole project.

Text to find:

```<code>(Log\.d.*\;)
</code>```

Replace with:

```<code>if(BuildConfig.DEBUG){$1}
</code>```

Body:
Is there a way of surrounding search results in android studio with a predefined if statement?

Like every Log.d line

Log.d("foo","bar");

surrounded with an if statement? Or any other statment.

if(BuildConfig.DEBUG){
    Log.d("foo","bar");
}

Body:
Yes, you can do this with regex replacement.

Press Ctrl+Shift+R

In the options tab, make sure the regex checkbox is selected and scope is Whole project.

Text to find:

(Log\.d.*\;)

Replace with:

if(BuildConfig.DEBUG){$1}


问:
Java Maze from a file
i got a maze from a file i try to make this Write a class Exercise4 with a program that reads such a maze file into a two-dimensional boolean array. Then display the array on the console with one line for each row. Represent array elements using blank-symbols and #-symbols so that the console output has the same format as the maze file, see the example above.

```<code>    package assignmentce152;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;
    import java.io.FileNotFoundException;
/**
 * Created by ak on 29/03/2017.
 */
public class Exercise4 {
    public static void main(String[] args) throws IOException {
        Mazes();
    }
        private static char[][] maze = null;
        private static int rows = 0;
        private static int cols = 0;
        private static int xStart = 0;
        private static int yStart = 0;

        public static void Mazes() throws IOException {
            File mazefile = new File("C:/Users/IdeaProjects/Assignment152/data/maze21.txt");
            BufferedReader reader = new BufferedReader(new FileReader(mazefile));

           Scanner lineOfFile = new Scanner(reader.readLine());

            rows = lineOfFile.nextInt(); //get the number of rows of the maze

            cols = lineOfFile.nextInt(); // get the number of columns of the maze
            maze = new char[rows][cols]; //create a char array of the proper size

            //For loops to iterate the rows and col to find the start/enterance of the maze as it pertains to the first char in the row
            for (int y = 0; y < cols; y++) {
                lineOfFile = new Scanner(reader.readLine());
                for (int x = 0; x < rows; x++) {
                    char start = lineOfFile.next().charAt(0);
                    maze[x][y] = start;

                    //statement to set the starting coorinates for the maze
                    if (start == '.') {
                        xStart = x;
                        yStart = y;
                    }

                }
            }

        }
    }
</code>```

how ever i got these ERROR what should i change ? Anything i think will be helpful

```<code>Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at assignmentce152.Exercise4.Mazes(Exercise4.java:28)
at assignmentce152.Exercise4.main(Exercise4.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

答:
It seems your program tries to read two integers from the scanner and does not find two integers there.

Let me guess: the following line is wrong.

```<code>       Scanner lineOfFile = new Scanner(reader.readLine());
</code>```

readLine() reads the first line of your file. From this line you create a scanner object that could be used for parsing the line. If, for instance, your two numbers are on the first two lines of your file, it will never get to them both and will throw an InputMismatchException.

Instead you can try discarding the reader and just creating your scanner as

```<code>       Scanner lineOfFile = new Scanner(mazefile);
</code>```

This will allow your scanner to read the entire text file rather than only the first line.

If this doesn’t solve your problem, I believe you need to edit your question and add a sample of how your file looks.

Title: Java Maze from a file

Body:
i got a maze from a file i try to make this Write a class Exercise4 with a program that reads such a maze file into a two-dimensional boolean array. Then display the array on the console with one line for each row. Represent array elements using blank-symbols and #-symbols so that the console output has the same format as the maze file, see the example above.

    package assignmentce152;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;
    import java.io.FileNotFoundException;
/**
 * Created by ak on 29/03/2017.
 */
public class Exercise4 {
    public static void main(String[] args) throws IOException {
        Mazes();
    }
        private static char[][] maze = null;
        private static int rows = 0;
        private static int cols = 0;
        private static int xStart = 0;
        private static int yStart = 0;

        public static void Mazes() throws IOException {
            File mazefile = new File("C:/Users/IdeaProjects/Assignment152/data/maze21.txt");
            BufferedReader reader = new BufferedReader(new FileReader(mazefile));

           Scanner lineOfFile = new Scanner(reader.readLine());

            rows = lineOfFile.nextInt(); //get the number of rows of the maze

            cols = lineOfFile.nextInt(); // get the number of columns of the maze
            maze = new char[rows][cols]; //create a char array of the proper size

            //For loops to iterate the rows and col to find the start/enterance of the maze as it pertains to the first char in the row
            for (int y = 0; y < cols; y++) {
                lineOfFile = new Scanner(reader.readLine());
                for (int x = 0; x < rows; x++) {
                    char start = lineOfFile.next().charAt(0);
                    maze[x][y] = start;

                    //statement to set the starting coorinates for the maze
                    if (start == '.') {
                        xStart = x;
                        yStart = y;
                    }

                }
            }

        }
    }

how ever i got these ERROR what should i change ? Anything i think will be helpful

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at assignmentce152.Exercise4.Mazes(Exercise4.java:28)
at assignmentce152.Exercise4.main(Exercise4.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Body:
It seems your program tries to read two integers from the scanner and does not find two integers there.

Let me guess: the following line is wrong.

       Scanner lineOfFile = new Scanner(reader.readLine());

readLine() reads the first line of your file. From this line you create a scanner object that could be used for parsing the line. If, for instance, your two numbers are on the first two lines of your file, it will never get to them both and will throw an InputMismatchException.

Instead you can try discarding the reader and just creating your scanner as

       Scanner lineOfFile = new Scanner(mazefile);

This will allow your scanner to read the entire text file rather than only the first line.

If this doesn’t solve your problem, I believe you need to edit your question and add a sample of how your file looks.


问:
CKEditor Link input not working in modal
I've got a project in which I use a modal with a form and a ckeditor and the Link input doesn't work.

Here's a fiddle that recreates this problem:

http://jsfiddle.net/8t882a2s/3/

And the code of this example.

HTML:

```<code>        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                        <h4 class="modal-title" contenteditable="true" id="myModalLabel">Modal title</h4>
                    </div>
                    <div id="bodyModal" contenteditable="true" class="modal-body">
                        ...
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>

 <button type="button" class="btn btn-default navbar-btn  margin-right-button-nav" data-toggle="modal" data-target="#myModal"><span class="glyphicon glyphicon-new-window"></span> Edit Modal</button>
</code>```

JS:

```<code>CKEDITOR.disableAutoInline = true;

$(document).ready(function() {
    $('#myModal').on('shown.bs.modal', function () {
        CKEDITOR.inline('myModalLabel');
        CKEDITOR.inline('bodyModal');
    })
});
</code>```

This isn't exactly my code but the bug is the same. If you click in the modal and then try do add a Link you can't write the url in the input field.

Thanks :)

答:
lots of answers around the internet suggested multiple ways for fixes,
this worked for me, for a bootstrap 4 project:

```<code>$.fn.modal.Constructor.prototype._enforceFocus = function() {
                var $modalElement = this.$element;
                $(document).on('focusin.modal',function(e) {
                    if ($modalElement.length > 0 && $modalElement[0] !== e.target
                        && !$modalElement.has(e.target).length
                        && $(e.target).parentsUntil('*[role="dialog"]').length === 0) {
                        $modalElement.focus();
                    }
                });
            };
</code>```

if your running on bootstrap 3, then override $.fn.modal.Constructor.prototype.enforceFocus insdead.

Body:
I've got a project in which I use a modal with a form and a ckeditor and the Link input doesn't work.

Here's a fiddle that recreates this problem:

http://jsfiddle.net/8t882a2s/3/

And the code of this example.

HTML:

                        <button type="button" class="close" data-dismiss="modal">×Close</button>

Modal title

                        ...

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>

 <button type="button" class="btn btn-default navbar-btn  margin-right-button-nav" data-toggle="modal" data-target="#myModal"> Edit Modal</button>

JS:

CKEDITOR.disableAutoInline = true;

$(document).ready(function() {
    $('#myModal').on('shown.bs.modal', function () {
        CKEDITOR.inline('myModalLabel');
        CKEDITOR.inline('bodyModal');
    })
});

This isn't exactly my code but the bug is the same. If you click in the modal and then try do add a Link you can't write the url in the input field.

Thanks :)

Body:
lots of answers around the internet suggested multiple ways for fixes,
this worked for me, for a bootstrap 4 project:

$.fn.modal.Constructor.prototype._enforceFocus = function() {
                var $modalElement = this.$element;
                $(document).on('focusin.modal',function(e) {
                    if ($modalElement.length > 0 && $modalElement[0] !== e.target
                        && !$modalElement.has(e.target).length
                        && $(e.target).parentsUntil('*[role="dialog"]').length === 0) {
                        $modalElement.focus();
                    }
                });
            };

if your running on bootstrap 3, then override $.fn.modal.Constructor.prototype.enforceFocus insdead.

ContentLicense: CC BY-SA 4.0


答:
The critical point is:

start with x==0 and y==0

Since both variables are set to 0 when it starts, the if tests will fail, and assignments will never occur. So both threads are only reading the variables, never writing them.

Title: Why there is no data race?

Body:
I am reading  Bjarne's FAQ on Memory Model, here is a quote

So, C++11 guarantees that no such problems occur for "separate memory locations.'' More precisely: A memory location cannot be safely accessed by two threads without some form of locking unless they are both read accesses. Note that different bitfields within a single word are not separate memory locations, so don't share structs with bitfields among threads without some form of locking. Apart from that caveat, the C++ memory model is simply "as everyone would expect.''

However, it is not always easy to think straight about low-level concurrency issues. Consider:

start with x==0 and y==0

if (x) y = 1;   // Thread 1

if (y) x = 1;  // Thread 2

Is there a problem here? More precisely, is there a data race? (No there isn't).

My question is, why there is no data race? It is obvious to me that there apparently is a data race since thread 1 is a writer for y while thread 2 is a reader for y, and similarly for x.


问:
boost asio multithreaded tcp server with synchronous I/O on a given thread
Basically, what I'm trying to achieve is to implement a generic multithreaded TCP server that can handle arbitrary requests for usage by 2 different servers with slightly different needs.

My requirements are:

A request cannot begin to be processed until an entire initial request has been received. (Essentially, I have a request header of a fixed size that among other things, includes the size of the entire request).

Handling a request may result in multiple response messages to the requesting client. I.E., normally, requests can be handled in a single response, but at times, in response to long running database transactions, I need to ping back to the client, letting them know that I'm still working and to not time out the connection.

To achieve this, I've been following fairly closely the HTTP server example #2 from boost v1.44. In general, the example has worked for simple cases. What I've noticed is that when I scale up to handling multiple requests concurrently, the changes I've made have somehow resulted in all request being handled serially, by a single thread. Obviously, I'm doing something wrong.

I cannot post the entirety of the actual code I'm using, due to employer restrictions, but suffice it to say, I've kept the async calls to accept new connections, but have replaced the async read/writes with synchronous calls. If there are specific pieces that you think you need to see, I can see what I can do.

Essentially, what I'm looking for are pointers in how to use boost::asio for a multithreaded TCP server where individual connections are handled by a single thread with synchronous I/O. Again, keep in mind, my abstraction is based upon the http server example #2 (one io_service per CPU), but I am flexible to altern

答:
Some diagnostics: can you print the value of io_service_pool_.get_io_service() before using it in the following code?

```<code>// from server.cpp
void server::handle_accept(const boost::system::error_code& e)
{
  if (!e)
  {
    new_connection_->start();
    new_connection_.reset(new connection(
          io_service_pool_.get_io_service(), request_handler_));
    acceptor_.async_accept(new_connection_->socket(),
        boost::bind(&server::handle_accept, this,
          boost::asio::placeholders::error));
  }
}
</code>```

You'll need to store it in a temporary before passing it to new_connection_.reset(); that is, don't call get_io_service() twice for this test.

We first must make sure you're getting a new io_service.

Body:
Some diagnostics: can you print the value of io_service_pool_.get_io_service() before using it in the following code?

// from server.cpp
void server::handle_accept(const boost::system::error_code& e)
{
  if (!e)
  {
    new_connection_->start();
    new_connection_.reset(new connection(
          io_service_pool_.get_io_service(), request_handler_));
    acceptor_.async_accept(new_connection_->socket(),
        boost::bind(&server::handle_accept, this,
          boost::asio::placeholders::error));
  }
}

You'll need to store it in a temporary before passing it to new_connection_.reset(); that is, don't call get_io_service() twice for this test.

We first must make sure you're getting a new io_service.


问:
Scope's eval returns undefined in an AngularJS directive
Background:
I'm trying to run a callback when something inside the code of a directive in AngularJS happen.

Pertinent code:

HTML:

```<code><img-cropper onselect="updateAvatarData" x="100" y="100" src="{{tempAvatar}}" id="avatarCropper"/>
</code>```

Controller:

```<code>$scope.updateAvatarData = function(c){
    alert("¡¡¡Funciona!!!!");
};
</code>```

Directive:

```<code><<more code up here>>

link: function(scope,element, attr) {
  scope.wsId = attr.id+'WS';
  scope.pvId = attr.id+'preview';
  scope.x = attr.x;
  scope.y = attr.y;
  scope.aspectRatio = scope.x/scope.y;
  scope.previewStyle = "width:"+scope.x+"px;height:"+scope.y+"px;overflow:hidden;";
  scope.onSelectFn = scope.$eval(attr.onselect);

<<more code down here>>
</code>```

The problem is in that last line "scope.onSelectFn = scope.$eval(attr.onselect);". That "scope.$eval(attr.onselect);" returns 'undefined'. The attr.onselect works fine, it returns the name of the function typed on the 'onselect' attribute.

I have made others directives with functions passed via attibutes with no problem, but am unable to find what I am doing wrong here.

Thanks in advance

答:
By default, $eval only evaluates the given expression against the current scope.  You can pass in a different data object to evaluate against, and in your case it is the parent scope.  You should call it like this:

```<code>scope.onSelectFn = scope.$eval(attr.onselect, scope.$parent);
</code>```

See the documentation here

Body:
Background:
I'm trying to run a callback when something inside the code of a directive in AngularJS happen.

Pertinent code:

HTML:

Controller:

$scope.updateAvatarData = function(c){
    alert("¡¡¡Funciona!!!!");
};

Directive:

<<more code up here>>

link: function(scope,element, attr) {
  scope.wsId = attr.id+'WS';
  scope.pvId = attr.id+'preview';
  scope.x = attr.x;
  scope.y = attr.y;
  scope.aspectRatio = scope.x/scope.y;
  scope.previewStyle = "width:"+scope.x+"px;height:"+scope.y+"px;overflow:hidden;";
  scope.onSelectFn = scope.$eval(attr.onselect);

<<more code down here>>

The problem is in that last line "scope.onSelectFn = scope.$eval(attr.onselect);". That "scope.$eval(attr.onselect);" returns 'undefined'. The attr.onselect works fine, it returns the name of the function typed on the 'onselect' attribute.

I have made others directives with functions passed via attibutes with no problem, but am unable to find what I am doing wrong here.

Thanks in advance

Body:
By default, $eval only evaluates the given expression against the current scope.  You can pass in a different data object to evaluate against, and in your case it is the parent scope.  You should call it like this:

scope.onSelectFn = scope.$eval(attr.onselect, scope.$parent);

See the documentation here


问:
How find all usage (using emacs) some elisp function in all *.el files in Emacs?
Emacs ver. 25.1.1

All emacs source files are in folder: ...\emacs\share\emacs\25.1\lisp\

Suppose I open in emacs file url.el. In this file has function url-retrieve.
How I can found (using emacs) what another *.el files use this function?

Thanks.

答:
You want to use xref-find-references (new in Emacs-25), which by default is bound to M-?.

It is meant to be generic, so it should work not only in Elisp, but in any major mode which provides support for xref.


问:
How to load CommonJS module in Titanium project correctly?
I'm working with Atom and Titanium SDK 6.0.1.GA, Alloy 1.9.8 and targeting Android API 22, I created a CommonJS module in the Resources folder but when I try to run my app I get the following error:

In ti:/module.js:303,2

Message: Uncaught Error: Requested module not found: contactClient

Source:    throw new Error("Requested module not found: " + request);

V8Exception: Exception occurred at ti:/module.js:303: Uncaught Error: Requested module not found: contactClient

The code inside the module is this:

```<code>function getClient(path, successCallback, errorCallback){
  var client = Ti.Network.createHTTPClient({
    onload : successCallback,
    onerror : errorCallback
  });
  client.open('GET', 'http://10.0.12.138:8284/' + path);
  client.send();
}

function getContacts(successCallback, errorCallback){
  getClient('contacts', successCallback, errorCallback);
}

exports.getContacts = getContacts;
</code>```

The path to my module is Resources/contactClient.js and I try to load it in my index.js like this:

```<code>var contactsClient = require('contactClient');
</code>```

I checked the documentation for CommonJS modules and according to it this shouldn't be a problem.

Am I doing something wrong? I'm placing the js file inside the Resources folder, is it another path?

答:
The issue was that I was placing the module inside the Resources folder, when appearently the CommonJS modules must be placed inside a lib folder inside the app folder.

So an Alloy projects with CommonJS modules must have the following structure:

```<code>root
  -> app
      -> lib
      -> controllers
      -> views
      -> styles
      -> models
</code>```

Body:
I'm working with Atom and Titanium SDK 6.0.1.GA, Alloy 1.9.8 and targeting Android API 22, I created a CommonJS module in the Resources folder but when I try to run my app I get the following error:

In ti:/module.js:303,2

Message: Uncaught Error: Requested module not found: contactClient

Source:    throw new Error("Requested module not found: " + request);

V8Exception: Exception occurred at ti:/module.js:303: Uncaught Error: Requested module not found: contactClient

The code inside the module is this:

function getClient(path, successCallback, errorCallback){
  var client = Ti.Network.createHTTPClient({
    onload : successCallback,
    onerror : errorCallback
  });
  client.open('GET', 'http://10.0.12.138:8284/' + path);
  client.send();
}

function getContacts(successCallback, errorCallback){
  getClient('contacts', successCallback, errorCallback);
}

exports.getContacts = getContacts;

The path to my module is Resources/contactClient.js and I try to load it in my index.js like this:

var contactsClient = require('contactClient');

I checked the documentation for CommonJS modules and according to it this shouldn't be a problem.

Am I doing something wrong? I'm placing the js file inside the Resources folder, is it another path?

Body:
The issue was that I was placing the module inside the Resources folder, when appearently the CommonJS modules must be placed inside a lib folder inside the app folder.

So an Alloy projects with CommonJS modules must have the following structure:

root
  -> app
      -> lib
      -> controllers
      -> views
      -> styles
      -> models


问:
How to use generics to return child type from a parent method to support builder pattern
I am trying to support a builder pattern with inheritance, to allow chaining setters from parent and child class with no issue. For this I need the parent class to know to return back the child type to keep all methods exposed for chaining.

Here is a sample of code I wrote following this article which I think should work, But as you'll see, the first example using a1 works fine, but if I change the order of the setters, the last setter is not recognized.

Problem is: once I call a method from the parent class, it will return itself as a type and not the child, even thought T is defined as the child type.

```<code>public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        A a1 = new B<>().setAge(0).setId(0).setName("name"); //Works fine
        A a2 = new B<>().setAge(0).setName("name").setId(0); //setId is not found

    }

    static class A<T extends A> {
        private String mpName;

        T setName(String name) {
            mpName = name;
            return (T) this;
        }
    }

    static class B<T extends B> extends A<T> {
        private int mpAge;
        private int mpId;

        T setAge(int age) {
            mpAge = age;
            return (T) this;
        }

        T setId(int id) {
            mpId = id;
            return (T) this;
        }
    }
}
</code>```

答:
You should change you classes definitions as following:

```<code>static class A<T extends A<T>>
static class B<T extends B<T>> extends A<T>
</code>```

java.lang.Enum uses the same declaration. You can find explanation why it's required in this post.

Body:
I am trying to support a builder pattern with inheritance, to allow chaining setters from parent and child class with no issue. For this I need the parent class to know to return back the child type to keep all methods exposed for chaining.

Here is a sample of code I wrote following this article which I think should work, But as you'll see, the first example using a1 works fine, but if I change the order of the setters, the last setter is not recognized.

Problem is: once I call a method from the parent class, it will return itself as a type and not the child, even thought T is defined as the child type.

public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        A a1 = new B<>().setAge(0).setId(0).setName("name"); //Works fine
        A a2 = new B<>().setAge(0).setName("name").setId(0); //setId is not found

    }

    static class A<T extends A> {
        private String mpName;

        T setName(String name) {
            mpName = name;
            return (T) this;
        }
    }

    static class B<T extends B> extends A<T> {
        private int mpAge;
        private int mpId;

        T setAge(int age) {
            mpAge = age;
            return (T) this;
        }

        T setId(int id) {
            mpId = id;
            return (T) this;
        }
    }
}

Body:
You should change you classes definitions as following:

static class A<T extends A<T>>
static class B<T extends B<T>> extends A<T>

java.lang.Enum uses the same declaration. You can find explanation why it's required in this post.


问:
Change text button action of picker
My question is simple but I do not know if it is possible to do

how i change text button (Done)?

My picture of Picker

it is for Xamarin Forms.

答:
Is doable but there is not an easy way to do it. If you check here the done button is private in the PickerRenderer as well as the Toolbar object containing it which means none of them are exposed from outside the renderer.

You could however take this renderer as base and create a custom renderer where you can expose a property for the "Done" button text.

Title: Change text button action of picker


问:
Getting java.lang.ClassNotFoundException: SessionFactory when I try to deploy the war
I am trying to deploy war on TC server using STS. I am able to build the project without any dependency issues. But once I try to add the war to the server , I get the following error:

```<code>[2017-03-29 09:27:14,303] ERROR [ContextLoader]Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ApplConfigService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configManager': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserAuthentication': Injection of resource dependencies failed; nested exception is java.lang.NoClassDefFoundError: SessionFactory
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Troubleshooting steps I tried:

I made sure the war that was built had all the necessary jars under WEB_INF/lib

Tried adding the jars to buildpath

Made sure maven dependencies are added under Preferences->Deployment Assembly

Cleaned the server several times

Forced maven to download all the jars again

Did Maven install from command line to make sure the wars are building properly

Tried deploying the war manually into tomcat/STS and starting the server on command line. It starts without this error but gives 404 for the application URL.

Tried STS and Eclipse

For some reason it is not able to find the Hibernate jars from the server. I have tried most of the solutions I came across for this error on Stack overflow but it doesn't go away.

Any insights on this will be greatly appreciated!

答:
The issue was with IDE. I copied the WEB-INF folder from target folder of the project and pasted it the folder in server path overriding the WEB-INF present there:

Server path location

I am able to start the server now with no issues

Body:
I am trying to deploy war on TC server using STS. I am able to build the project without any dependency issues. But once I try to add the war to the server , I get the following error:

[2017-03-29 09:27:14,303] ERROR [ContextLoader]Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ApplConfigService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configManager': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserAuthentication': Injection of resource dependencies failed; nested exception is java.lang.NoClassDefFoundError: SessionFactory
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Troubleshooting steps I tried:

I made sure the war that was built had all the necessary jars under WEB_INF/lib

Tried adding the jars to buildpath

Made sure maven dependencies are added under Preferences->Deployment Assembly

Cleaned the server several times

Forced maven to download all the jars again

Did Maven install from command line to make sure the wars are building properly

Tried deploying the war manually into tomcat/STS and starting the server on command line. It starts without this error but gives 404 for the application URL.

Tried STS and Eclipse

For some reason it is not able to find the Hibernate jars from the server. I have tried most of the solutions I came across for this error on Stack overflow but it doesn't go away.

Any insights on this will be greatly appreciated!