问:
Java: Convert byte to integer
I need to convert 2 byte array ( byte[2] ) to integer value in java.  How can I do that?</p>

答:
Well, each byte is an integer in the range -128..127, so you need a way to map a pair of integers to a single integer.  There are many ways of doing that, depending on what you have encoded in the pair of bytes.  The most common will be storing a 16-bit signed integer as a pair of bytes.  Converting that back to an integer depends on whether you store it big-endian form:

```<code>(byte_array[0]<<8) + (byte_array[1] & 0xff)
</code>```

or little endian:

```<code>(byte_array[1]<<8) + (byte_array[0] & 0xff)
</code>```

Title: Java: Convert byte to integer

Body:
Well, each byte is an integer in the range -128..127, so you need a way to map a pair of integers to a single integer.  There are many ways of doing that, depending on what you have encoded in the pair of bytes.  The most common will be storing a 16-bit signed integer as a pair of bytes.  Converting that back to an integer depends on whether you store it big-endian form:

(byte_array[0]<<8) + (byte_array[1] & 0xff)

or little endian:

(byte_array[1]<<8) + (byte_array[0] & 0xff)


来源: stackexchange

问:
How to deal with multiple hierarchy on same dimension table with different leaf node in RPD - OBIEE 11g
I have to create two hierarchies

```<code> 1.) Year-Quarter
 2.) Year-Month, on the same dimension table.
</code>```

As we know,  when we create multiple hierarchies the leaf node should be same in both the hierarchies, in that case guide me how to deal with different leaf nodes on the same dimension table?

答: Different logical dimension tables.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have to create two hierarchies

 1.) Year-Quarter
 2.) Year-Month, on the same dimension table.

As we know,  when we create multiple hierarchies the leaf node should be same in both the hierarchies, in that case guide me how to deal with different leaf nodes on the same dimension table?

Body: Different logical dimension tables.


问:
Count number of ways to climb a ladder with a twist
I am aware of this question.

Question:

A ladder has n steps. One can climb the ladder using any combination of steps of 1 or steps of 2. How many possible ways are there for one to climb the ladder?

However, how will this number change if some of the stairs are broken?

PS: This is not homework.

答:
I believe this constraint simplifies the problem.

If there are two or more consecutive broken steps, the answer is zero.

If there is a broken step, then the climber must land on the step previous to it. So without loss of generality you can remove that step and the one previous to it from the puzzle.

Then you perform the calculation on the, in general, shorter ladder as per the linked question.

(Alternatively view the broken step / one before it as subdividing the problem into separate ladders. Perform the calculation for each one separately and multiply the results.)


问:
How to find the diameter of objects using image processing in Python?
Given an image with some irregular objects in it, I want to find their individual diameter.

Thanks to this answer, I know how to identify the objects. However, is it possible to measure the maximum diameter of the objects shown in the image?

I have looked into the scipy-ndimage documentation and haven't found a dedicated function.

Code for object identification:

```<code>import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt

# generate some lowpass-filtered noise as a test image
gen = np.random.RandomState(0)
img = gen.poisson(2, size=(512, 512))
img = ndimage.gaussian_filter(img.astype(np.double), (30, 30))
img -= img.min()
img /= img.max()

# use a boolean condition to find where pixel values are > 0.75
blobs = img > 0.75

# label connected regions that satisfy this condition
labels, nlabels = ndimage.label(blobs)

# find their centres of mass. in this case I'm weighting by the pixel values in
# `img`, but you could also pass the boolean values in `blobs` to compute the
# unweighted centroids.
r, c = np.vstack(ndimage.center_of_mass(img, labels, np.arange(nlabels) + 1)).T

# find their distances from the top-left corner
d = np.sqrt(r*r + c*c)

# plot
fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))
ax[0].imshow(img)
ax[1].hold(True)
ax[1].imshow(np.ma.masked_array(labels, ~blobs), cmap=plt.cm.rainbow)
for ri, ci, di in zip(r, c, d):
    ax[1].annotate('', xy=(0, 0), xytext=(ci, ri),
                   arrowprops={'arrowstyle':'<-', 'shrinkA':0})
    ax[1].annotate('d=%.1f' % di, xy=(ci, ri),  xytext=(0, -5),
                   textcoords='offset points', ha='center', va='top',
                   fontsize='x-large')
for aa in ax.flat:
    aa.set_axis_off()
fig.tight_layout()
plt.show()
</code>```

Image:

答:
I would propose using a distance transform.  So once you've got your labeled image you do:

```<code>dt = ndimage.distance_transform_edt(blobs)
slices = ndimage.find_objects(input=labels)
radii = [np.amax(dt[s]) for s in slices]
</code>```

This gives the largest inscribed circle (or sphere in 3D).  The find_objects function is quite handy.  It returns a list of Python slice objects, which you can use to index into the image at the specific locations containing the blobs.  These slices can of course be used to index into the distance transform image. Thus the largest value of the distance transform inside the slice is the radius you're looking for.

There is one potential gothcha of the above code: the slice is a square (or cubic) section so might contain small pieces of other blobs if they are close together.  You can get around this with a bit more complicated logic as follows:

```<code>radii = [np.amax(dt[slices[i]]*(labels[slices[i]] == (i+1))) for i in range(nlabels)]
</code>```

The above version of the list comprehension masks the distance transform with the blob that is supposed to be indexed by the slice, thereby removing any unwanted interference from neighboring blobs.

Body:
Given an image with some irregular objects in it, I want to find their individual diameter.

Thanks to this answer, I know how to identify the objects. However, is it possible to measure the maximum diameter of the objects shown in the image?

I have looked into the scipy-ndimage documentation and haven't found a dedicated function.

Code for object identification:

import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt

# generate some lowpass-filtered noise as a test image
gen = np.random.RandomState(0)
img = gen.poisson(2, size=(512, 512))
img = ndimage.gaussian_filter(img.astype(np.double), (30, 30))
img -= img.min()
img /= img.max()

# use a boolean condition to find where pixel values are > 0.75
blobs = img > 0.75

# label connected regions that satisfy this condition
labels, nlabels = ndimage.label(blobs)

# find their centres of mass. in this case I'm weighting by the pixel values in
# `img`, but you could also pass the boolean values in `blobs` to compute the
# unweighted centroids.
r, c = np.vstack(ndimage.center_of_mass(img, labels, np.arange(nlabels) + 1)).T

# find their distances from the top-left corner
d = np.sqrt(r*r + c*c)

# plot
fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))
ax[0].imshow(img)
ax[1].hold(True)
ax[1].imshow(np.ma.masked_array(labels, ~blobs), cmap=plt.cm.rainbow)
for ri, ci, di in zip(r, c, d):
    ax[1].annotate('', xy=(0, 0), xytext=(ci, ri),
                   arrowprops={'arrowstyle':'<-', 'shrinkA':0})
    ax[1].annotate('d=%.1f' % di, xy=(ci, ri),  xytext=(0, -5),
                   textcoords='offset points', ha='center', va='top',
                   fontsize='x-large')
for aa in ax.flat:
    aa.set_axis_off()
fig.tight_layout()
plt.show()

Image:

Body:
I would propose using a distance transform.  So once you've got your labeled image you do:

dt = ndimage.distance_transform_edt(blobs)
slices = ndimage.find_objects(input=labels)
radii = [np.amax(dt[s]) for s in slices]

This gives the largest inscribed circle (or sphere in 3D).  The find_objects function is quite handy.  It returns a list of Python slice objects, which you can use to index into the image at the specific locations containing the blobs.  These slices can of course be used to index into the distance transform image. Thus the largest value of the distance transform inside the slice is the radius you're looking for.

There is one potential gothcha of the above code: the slice is a square (or cubic) section so might contain small pieces of other blobs if they are close together.  You can get around this with a bit more complicated logic as follows:

radii = [np.amax(dt[slices[i]]*(labels[slices[i]] == (i+1))) for i in range(nlabels)]

The above version of the list comprehension masks the distance transform with the blob that is supposed to be indexed by the slice, thereby removing any unwanted interference from neighboring blobs.


问:
Regex match if string contains "if" and "&"
I need to implement a regex to check if a string contains a "if" and "&".
for example:

if a & b // regex should to match here

for a & b // regex not should to match here

I have tried, this regex (if|&), but in this case will be considerate if the string contains if OR ampersand...

答:
Note: This answer assumes that a and b are words, that is, only containing the characters [a-zA-Z0-9_]. If this is not what you want, replace \w+ in the examples below appropriately.

```<code>if\s+(\w+)\s*&\s*(\w+)
</code>```

matches the following:

```<code>if a & b
if foo&bar
</code>```

Broken down:

Match the word if

Look for at least one whitespace character

Match (and capture) a word

Match 0 or more whitespace characters

Match the & character

Match 0 or more whitespace characters

Match (and capture) a word

Body:
Note: This answer assumes that a and b are words, that is, only containing the characters [a-zA-Z0-9_]. If this is not what you want, replace \w+ in the examples below appropriately.

if\s+(\w+)\s*&\s*(\w+)

matches the following:

if a & b
if foo&bar

Broken down:

Match the word if

Look for at least one whitespace character

Match (and capture) a word

Match 0 or more whitespace characters

Match the & character

Match 0 or more whitespace characters

Match (and capture) a word


问:
Regex not working in Java while working otherwise
I made a regular expression: https://regex101.com/r/ToCwrE/2/

All it should do, is get out the function's parameters. I am trying with capture groups to achieve this.

[\s]*javascript:[\s]*m\((-?\d+)[\s]*,[\s]*(-?\d+)[\s]*,[\s]{0,}encodeURIComponent\(\'([^\']+)*\'\)[\s]*,[\s]*(-?\d+)\)[\s]*

Tried it on:

```<code>javascript:m(53009,2,encodeURIComponent('7711T'), 22)
javascript:m(52992,2,encodeURIComponent('3013'), 2)
javascript:m(10440,2,encodeURIComponent('F Series'), 11)
javascript:m(53022,2,encodeURIComponent('C 12045'), 85)
javascript:m(53045,2,encodeURIComponent('Prox 8441'), 16)
javascript:m(26016,2,encodeURIComponent('Vard   asd .ious'), 22)
</code>```

Using the site regex101 and a few similar ones, it correctly returns the matched groups. However when I am trying to use it in Java, it simply won't match the capture groups and only returns the whole text.

If I copy paste it with IDEA, It automatically gets escaped (replaces \ to \):

```<code>Pattern pattern = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
Matcher m = pattern.matcher("javascript:m(53022,2,encodeURIComponent('Cr 12045'), 85)");
List<String> groups = new ArrayList<>();
while (m.find()) {
    groups.add(m.group());
}
groups;
</code>```

What am I missing? How should the regex be converted to get it working in Java?

答:
The regex is matching correctly, it's just how you reference each group using m.group(). The following should help:

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaTest {

    public static void main(String[] args) {

        Pattern pattern = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
        Matcher m = pattern.matcher("javascript:m(53009,2,encodeURIComponent('7711T'), 22)");
        if (m.find()) {
            for (int i=1 ; i <= m.groupCount() ; i++) {
                System.out.println(m.group(i));
            }
        }
    }
}
</code>```

Provides the output:

```<code>53009
2
7711T
22
</code>```

Body:
I made a regular expression: https://regex101.com/r/ToCwrE/2/

All it should do, is get out the function's parameters. I am trying with capture groups to achieve this.

[\s]*javascript:[\s]*m\((-?\d+)[\s]*,[\s]*(-?\d+)[\s]*,[\s]{0,}encodeURIComponent\(\'([^\']+)*\'\)[\s]*,[\s]*(-?\d+)\)[\s]*

Tried it on:

javascript:m(53009,2,encodeURIComponent('7711T'), 22)
javascript:m(52992,2,encodeURIComponent('3013'), 2)
javascript:m(10440,2,encodeURIComponent('F Series'), 11)
javascript:m(53022,2,encodeURIComponent('C 12045'), 85)
javascript:m(53045,2,encodeURIComponent('Prox 8441'), 16)
javascript:m(26016,2,encodeURIComponent('Vard   asd .ious'), 22)

Using the site regex101 and a few similar ones, it correctly returns the matched groups. However when I am trying to use it in Java, it simply won't match the capture groups and only returns the whole text.

If I copy paste it with IDEA, It automatically gets escaped (replaces \ to \):

Pattern pattern = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
Matcher m = pattern.matcher("javascript:m(53022,2,encodeURIComponent('Cr 12045'), 85)");
List<String> groups = new ArrayList<>();
while (m.find()) {
    groups.add(m.group());
}
groups;

What am I missing? How should the regex be converted to get it working in Java?

Body:
The regex is matching correctly, it's just how you reference each group using m.group(). The following should help:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaTest {

    public static void main(String[] args) {

        Pattern pattern = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
        Matcher m = pattern.matcher("javascript:m(53009,2,encodeURIComponent('7711T'), 22)");
        if (m.find()) {
            for (int i=1 ; i <= m.groupCount() ; i++) {
                System.out.println(m.group(i));
            }
        }
    }
}

Provides the output:

53009
2
7711T
22


问:
Single ASP.net site with Multiple Instances & web.configs
We have a legacy ASP.net powered site running on a IIS server, the site was developed by a central team and is used by multiple customers.  Each customer however has their own copy of the site's aspx files plus a web.config file. This is causing problems as changes made by well meaning support engineers to the copies of the source aspx files are not being folded back into the central source, so our code base is diverging.  Our current folder structure looks something like:
OurApp/Source aspx & default web.config

Customer1/Source aspx & web.config

Customer2/Source aspx & web.config

Customer3/Source aspx & web.config

Customer4/Source aspx & web.config

...

This is something I'd like to change to each customer having just a customised web.config file and all the customers sharing a common set of source files. So something like:
OurApp/Source aspx & default web.config

Customer1/web.config

Customer2/web.config

Customer3/web.config

Customer4/web.config

...

So my question is, how do I set this up?  I'm new to ASP.net and IIS as I usually use php and apache at home but we use ASP.net and ISS here at work.

Source control is used and I intend to retrain the support engineers but is there any way to avoid having multiple copies of the source aspx files?  I hate that sort of duplication!

答:
I am implementing this as we speak.

In the main web.config, I have 1 item per installation.  It points me toward the custom config file I built for each client (and toward the custom masterpage, css, images, etc).

Using WebConfigurationManager.OpenWebConfiguration, I open the new webconfigs in their subdirectories.  I determine which one to use by using System.Web.HttpContext.Current.Request.Url.OriginalString, and determining the uRL that called me.  Based on that URL, I know which web.config to use.

From that point forward the clients all use the same codebase.  They have their own databases too.

The idea of having to update 30-40 installations when we make an update scares the death out of me.  We do not want to support 30-40 codebases, so there won't be customization beyond the master page, css, and images.

I wrote a custom class lib that knows how to switch to the proper webconfig, and read the custom section I built with all our settings.

The only issue I have now is the FormsAuthentication Cookie.  I need to be able to switch that as well.  Unfortunately, the property for the name is read only

OwnerDisplayName: Danielb

ContentLicense: CC BY-SA 2.5


问:
How to append to appended element through JQuery?
My question is related more to why is this happening, not to knowing how to solve it.

I want to firstly append a
 to a div and then an  to the
.

I have the following jQuery code:

```<code>$('.patches').empty();
for(i=0;i<patches.length;i++){
    $('.patches').append($('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }));
    $('#li'+patches[i].name).append($('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    }));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}
</code>```

The
 is appended but the  isn't, why isn't this working?

EDIT: I have modified the code as follows and it works perfectly:

```<code>$('.patches').empty();
for(i=0;i<patches.length;i++){
    var listItem=$('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    });
    $('.patches').append(listItem);
    var aItem=$('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    });
    listItem.append(aItem);
    listItem.append('<p>Version : '+patches[i].version+' Author : '+patches[i].author+'</p>');
}
</code>```

This version is almost the same as the previous one, I am just using variables. I would still like to know why the previous version of the code was not working. Could someone explain this?

答:
You can create a link element and wrap it in a li tag, then append it to the list.

See following please:

$(document).ready(function(){
  let patches = [
    {name: "test1", downloadUrl: "/url1", version: 1, author: "Alessandro"},
    {name: "test2", downloadUrl: "/url2", version: 2, author: "Alessandro"}];
  $('.patches').empty();
  for(i=0;i<patches.length;i++){
      let link = $('',{
          href:patches[i].downloadUrl,
          text: 'Version : '+patches[i].version+' Author : '+patches[i].author,
          id:'a'+patches[i].name
      }).wrap("

").parent();
      $('.patches').append($(link, {
          id:'li'+ patches[i].name,
          class: 'list-group-item'
      }));
  }
});

$("#btnAdd").click(function(){
  $("#atest2").append(";\tSome new information");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAdd">Add something to second element</button>
<ol class="patches"/></code>```

If you want to refer to a specific link element you could use its id, like:

```<code>$("#atest2").append(";\tSome new information");
</code>```

I hope it helps you, bye.

Body:
My question is related more to why is this happening, not to knowing how to solve it.

I want to firstly append a
 to a div and then an  to the
.

I have the following jQuery code:

$('.patches').empty();
for(i=0;i<patches.length;i++){
    $('.patches').append($('
', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }));
    $('#li'+patches[i].name).append($('',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    }));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}

The
 is appended but the  isn't, why isn't this working?

EDIT: I have modified the code as follows and it works perfectly:

$('.patches').empty();
for(i=0;i<patches.length;i++){
    var listItem=$('
', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    });
    $('.patches').append(listItem);
    var aItem=$('',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    });
    listItem.append(aItem);
    listItem.append('
Version : '+patches[i].version+' Author : '+patches[i].author+'
');
}

This version is almost the same as the previous one, I am just using variables. I would still like to know why the previous version of the code was not working. Could someone explain this?

Body:
You can create a link element and wrap it in a li tag, then append it to the list.

See following please:

$(document).ready(function(){
  let patches = [
    {name: "test1", downloadUrl: "/url1", version: 1, author: "Alessandro"},
    {name: "test2", downloadUrl: "/url2", version: 2, author: "Alessandro"}];
  $('.patches').empty();
  for(i=0;i<patches.length;i++){
      let link = $('<a>',{
          href:patches[i].downloadUrl,
          text: 'Version : '+patches[i].version+' Author : '+patches[i].author,
          id:'a'+patches[i].name
      }).wrap("<li></li>").parent();
      $('.patches').append($(link, {
          id:'li'+ patches[i].name,
          class: 'list-group-item'
      }));
  }
});

$("#btnAdd").click(function(){
  $("#atest2").append(";\tSome new information");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAdd">Add something to second element</button>
<ol class="patches"/>

If you want to refer to a specific link element you could use its id, like:

$("#atest2").append(";\tSome new information");

I hope it helps you, bye.


问:
Want ajax multiple file upload on my button click event
Here is my .aspx page code

```<code> <form id="form1" runat="server">
    <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>
    <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
        Width="400px" OnUploadComplete="OnUploadComplete" Mode="Auto" />
    <asp:Button ID="abc" runat="server" Text="Button" OnClientClick="$('.ajax__fileupload_uploadbutton').trigger('click');" OnClick="abc_Click" />
</form>
</code>```

.aspx.cs code is

```<code> protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string fileName = Path.GetFileName(e.FileName);
        AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
    }
    protected void abc_Click(object sender, EventArgs e)
    {
    // need file upload on this click and also need to store some outer data in this click event
    }
</code>```

How can I achieve ajax multiple file upload on my own button click event as I need to upload multiple file and also other some data on this button click

I have placed control html and the .cs code which is working well and is uploading multiple images with event OnUploadComplete but I need to upload images on abc_Click event so that on single click I can upload images as well as I can save data too

答:
So I assume all is working well except that you wish to trigger the upload when some other button (that is probably in other part of your HTML markup) You can simply add a button on the same page:</p>

```<code><input type="button" value="Custom Upload Button"
    onClick="$('.ajax__fileupload_uploadbutton').trigger('click');
        return false;" />
</code>```

Body:
Here is my .aspx page code

 <form id="form1" runat="server">
    <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>
    <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
        Width="400px" OnUploadComplete="OnUploadComplete" Mode="Auto" />
    <asp:Button ID="abc" runat="server" Text="Button" OnClientClick="$('.ajax__fileupload_uploadbutton').trigger('click');" OnClick="abc_Click" />
</form>

.aspx.cs code is

 protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string fileName = Path.GetFileName(e.FileName);
        AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
    }
    protected void abc_Click(object sender, EventArgs e)
    {
    // need file upload on this click and also need to store some outer data in this click event
    }

How can I achieve ajax multiple file upload on my own button click event as I need to upload multiple file and also other some data on this button click

I have placed control html and the .cs code which is working well and is uploading multiple images with event OnUploadComplete but I need to upload images on abc_Click event so that on single click I can upload images as well as I can save data too

Body:
So I assume all is working well except that you wish to trigger the upload when some other button (that is probably in other part of your HTML markup) You can simply add a button on the same page:

<input type="button" value="Custom Upload Button"
    onClick="$('.ajax__fileupload_uploadbutton').trigger('click');
        return false;" />


问:
How to get child user stories from parent (using filter in snapshotstore) using the sdk api js
Using the REST API I can simply use the following link to get all child stories for a specific object:

How can I get the same result using the Rally SDK Api JS (without Rest)?
Is there a filter that can be used to get the same results in a (snapshot)store?

答:
There are quite a few examples of how to do this in JavaScript in the help manuals. When you are logged in to Agile Central, click on your avatar and go to Help. In the search box enter "SDK".

One of the entries returned should be titled "Agile Central App SDK 2.1 Docs". Click on that and then click on "Examples" or "Guides"

Children are considered a "Collection" in the documentation.

 There is a section on handling Collections under "Working with WSAPI" in the guides.


答:
Here is a method with data.table using aggregation, a two dimensional shift, apply, and a join.

```<code>library(data.table)
dt[dt[, .(mx=max(value)), by=c("Name", "year")
      ][, .(year,
            max_val=apply(matrix(unlist(shift(mx, 1:2)), ncol=2), 1, max, na.rm=TRUE)),
        by=Name],
    on=c("Name", "year")][is.infinite(max_val), max_val := NA][]
</code>```

The first line calculates the maximum value by year and name. The second line, for each name, the year and using apply the maximum of the two lagged years (using shift(mx, 1:2)) are returned, dropping NA values. This results in warnings for every line that has 2 NA values, and a -Inf is returned in that place. I had to manually convert the output of shift into a matrix, in order to feed it to apply, which is not ideal. The resulting data.table is joined onto the original using name and year as IDs. Finally, the -Inf values are replaced with NA in the final line and the result printed with [].

This returns

```<code>    Name year value max_value max_val
 1:    A 2012    22        NA      NA
 2:    A 2012    99        NA      NA
 3:    A 2013    12        99      99
 4:    A 2014     1        99      99
 5:    A 2015    23        12      12
 6:    A 2016    40        23      23
 7:    A 2017    12        40      40
 8:    B 2012    12        NA      NA
 9:    B 2013    33        12      12
10:    B 2013    40        12      12
11:    B 2014    NA        40      40
12:    B 2015    20        40      40
13:    B 2016    20        20      20
</code>```

data

```<code>dt <-
structure(list(Name = c("A", "A", "A", "A", "A", "A", "A", "B",
"B", "B", "B", "B", "B"), year = c(2012L, 2012L, 2013L, 2014L,
2015L, 2016L, 2017L, 2012L, 2013L, 2013L, 2014L, 2015L, 2016L
), value = c(22L, 99L, 12L, 1L, 23L, 40L, 12L, 12L, 33L, 40L,
NA, 20L, 20L), max_value = c(NA, NA, 99L, 99L, 12L, 23L, 40L,
NA, 12L, 12L, 40L, 40L, 20L)), .Names = c("Name", "year", "value",
"max_value"), row.names = c(NA, -13L), class = c("data.table",
"data.frame"))
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get previous two years max value in R

Body:
Hi I have data frame as

How to create column max_value with max from last 2 years max value

dt <-
structure(list(Name = c("A", "A", "A", "A", "A", "A", "A", "B",
"B", "B", "B", "B", "B"), year = c(2012L, 2012L, 2013L, 2014L,
2015L, 2016L, 2017L, 2012L, 2013L, 2013L, 2014L, 2015L, 2016L
), value = c(22L, 99L, 12L, 1L, 23L, 40L, 12L, 12L, 33L, 40L,
NA, 20L, 20L), max_value = c(NA, NA, 99L, 99L, 12L, 23L, 40L,
NA, 12L, 12L, 40L, 40L, 20L)), .Names = c("Name", "year", "value",
"max_value"), row.names = c(NA, -13L), class = c("data.table",
"data.frame"))

Name   year   value   *max_value*
A      2012    22        NA
A      2012    99        NA
A      2013    12        99
A      2014    01        99
A      2015    23        12
A      2016    40        23
A      2017    12        40
B      2012    12        NA
B      2013    33        12
B      2013    40        12
B      2014    NA        40
B      2015    20        40
B      2016    20        20

Thanks in advance

Body:
Here is a method with data.table using aggregation, a two dimensional shift, apply, and a join.

library(data.table)
dt[dt[, .(mx=max(value)), by=c("Name", "year")
      ][, .(year,
            max_val=apply(matrix(unlist(shift(mx, 1:2)), ncol=2), 1, max, na.rm=TRUE)),
        by=Name],
    on=c("Name", "year")][is.infinite(max_val), max_val := NA][]

The first line calculates the maximum value by year and name. The second line, for each name, the year and using apply the maximum of the two lagged years (using shift(mx, 1:2)) are returned, dropping NA values. This results in warnings for every line that has 2 NA values, and a -Inf is returned in that place. I had to manually convert the output of shift into a matrix, in order to feed it to apply, which is not ideal. The resulting data.table is joined onto the original using name and year as IDs. Finally, the -Inf values are replaced with NA in the final line and the result printed with [].

This returns

    Name year value max_value max_val
 1:    A 2012    22        NA      NA
 2:    A 2012    99        NA      NA
 3:    A 2013    12        99      99
 4:    A 2014     1        99      99
 5:    A 2015    23        12      12
 6:    A 2016    40        23      23
 7:    A 2017    12        40      40
 8:    B 2012    12        NA      NA
 9:    B 2013    33        12      12
10:    B 2013    40        12      12
11:    B 2014    NA        40      40
12:    B 2015    20        40      40
13:    B 2016    20        20      20

data

dt <-
structure(list(Name = c("A", "A", "A", "A", "A", "A", "A", "B",
"B", "B", "B", "B", "B"), year = c(2012L, 2012L, 2013L, 2014L,
2015L, 2016L, 2017L, 2012L, 2013L, 2013L, 2014L, 2015L, 2016L
), value = c(22L, 99L, 12L, 1L, 23L, 40L, 12L, 12L, 33L, 40L,
NA, 20L, 20L), max_value = c(NA, NA, 99L, 99L, 12L, 23L, 40L,
NA, 12L, 12L, 40L, 40L, 20L)), .Names = c("Name", "year", "value",
"max_value"), row.names = c(NA, -13L), class = c("data.table",
"data.frame"))


问:
MySQL syntax error, underscore
Executing this query

```<code>INSERT INTO classes(  '_fkUserID',  'date',  'time' )
VALUES (

'1',  '2017-07-04',  '8:15'
)
</code>```

gives me the following error

```<code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''_fkUserID', 'date', 'time') VALUES ('1', '2017-07-04', '8:15')' at line 1
</code>```

I'm assuming the error has something to do with parsing the underscore, but I can't manage to find a way around it.

答: Try removing the single quotes and use back tick symbol instead (</p>

Title: MySQL syntax error, underscore

Body:
Executing this query

INSERT INTO classes(  '_fkUserID',  'date',  'time' )
VALUES (

'1',  '2017-07-04',  '8:15'
)

gives me the following error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''_fkUserID', 'date', 'time') VALUES ('1', '2017-07-04', '8:15')' at line 1

I'm assuming the error has something to do with parsing the underscore, but I can't manage to find a way around it.


问:
How to import external template in vue js?
I am beginner to vue js, not sure i am asking correct or not.

I want to make following type of structure for my Laravel 5.3 - Vue Js App.

my-vue.js

```<code> Vue.component('my-component', {
        template: 'template from Catgory.Vue'
 })

 new Vue({
    el: '#example'
 })
</code>```

Category.vue

```<code><template>
    <div>
        // some code goes here
    </div>
</template>
</code>```

index.blade.php

```<code><div id="example">
   <my-component></my-component>
</div>
</code>```

How can i use template from Category.vue in template attribute of Vue.component? Or Suggest me better approach.

答:
This link can be useful

```<code> Vue.component('my-component', {
   template: require('./Category.html')
 });
 new Vue({
     el: '#example'
 })
</code>```

Category.html.js

```<code>module.exports = `<div>Hello, {{ name }}!</div>`;
</code>```

Body:
I am beginner to vue js, not sure i am asking correct or not.

I want to make following type of structure for my Laravel 5.3 - Vue Js App.

my-vue.js

 Vue.component('my-component', {
        template: 'template from Catgory.Vue'
 })

 new Vue({
    el: '#example'
 })

Category.vue

<template>

        // some code goes here

</template>

index.blade.php

   <my-component></my-component>

How can i use template from Category.vue in template attribute of Vue.component? Or Suggest me better approach.

Body:
This link can be useful

 Vue.component('my-component', {
   template: require('./Category.html')
 });
 new Vue({
     el: '#example'
 })

Category.html.js

module.exports = `<div>Hello, {{ name }}!</div>`;


问:
MySQL Date comparison advice
I'm setting up a script to run daily and check for members who meet a certain age - automated emails can be set up in a CMS and assigned to be sent at any age, either in months or years. To handle this via PHP and MySQL, the number of months is passed as a parameter to a method, which I deal with as below. However, I'm not sure I'm going about this in the easiest way! Partly because of the formatting of the UK date format, I'm converting from string to datetime to unix timestamp to make the comparison.
Can anyone find a better way of going about this? Thanks</p>

```<code>        // If num of months provided is a year, make calculation based on exact year
        if ($age_in_months % 12 == 0)
        {
            // Using 365 days here (60 * 60 * 24 * 365 = 3153600)
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 31536000) = ' . $age_in_months;
        }
        else
        {
            // Using 30 days as avg month length (60 * 60 * 24 = 86400) - convert months to days
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 86400) = ' . $age_in_months * 30;
        }
</code>```

答:
change that column to type date or datetime

don't use UK date format, use ISO-8601 format

and index on that column

Title: MySQL Date comparison advice

Body:
I'm setting up a script to run daily and check for members who meet a certain age - automated emails can be set up in a CMS and assigned to be sent at any age, either in months or years. To handle this via PHP and MySQL, the number of months is passed as a parameter to a method, which I deal with as below. However, I'm not sure I'm going about this in the easiest way! Partly because of the formatting of the UK date format, I'm converting from string to datetime to unix timestamp to make the comparison.
Can anyone find a better way of going about this? Thanks

        // If num of months provided is a year, make calculation based on exact year
        if ($age_in_months % 12 == 0)
        {
            // Using 365 days here (60 * 60 * 24 * 365 = 3153600)
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 31536000) = ' . $age_in_months;
        }
        else
        {
            // Using 30 days as avg month length (60 * 60 * 24 = 86400) - convert months to days
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 86400) = ' . $age_in_months * 30;
        }


问:
Elasticsearch skips @-symbol
I have a custom analyzer with provided char filter:

```<code>"char_filter": {
     "hash_repl": {
         "pattern": "(^[^\\#@].+)",
         "type": "pattern_replace",
         "preserve_original": "false",
         "replacement": "$1 #$1 @$1"
      }
  }
</code>```

When I'm sending POST request for testing analyzer, I'm waiting for behaviour like:

```<code>a => a #a @a
#a => #a
@a => @a
</code>```

The problem is that elastic doesn't render "@" symbol in responses and usually I get

```<code>a => a #a a
#a => #a
@a => a
</code>```

答:
Well, solution was easy. My custom analyzer also contains several char filters and token filters. The problem was solved by adding custom mappings:</p>

```<code>"char_filter": {
    "custom": {
        "type": "mapping",
        "mappings": [
            "#=>|#"
        ]
      }
},
"filter": {
    "custom": {
        "type": "word_delimiter",
        "type_table": [
            "# => ALPHA",
            "@ => ALPHA"
         ],
         "split_on_numerics": "false"
     }
}
</code>```

Title: Elasticsearch skips @-symbol

Body:
I have a custom analyzer with provided char filter:

"char_filter": {
     "hash_repl": {
         "pattern": "(^[^\\#@].+)",
         "type": "pattern_replace",
         "preserve_original": "false",
         "replacement": "$1 #$1 @$1"
      }
  }

When I'm sending POST request for testing analyzer, I'm waiting for behaviour like:

a => a #a @a
#a => #a
@a => @a

The problem is that elastic doesn't render "@" symbol in responses and usually I get

a => a #a a
#a => #a
@a => a

Body:
Well, solution was easy. My custom analyzer also contains several char filters and token filters. The problem was solved by adding custom mappings:

"char_filter": {
    "custom": {
        "type": "mapping",
        "mappings": [
            "#=>|#"
        ]
      }
},
"filter": {
    "custom": {
        "type": "word_delimiter",
        "type_table": [
            "# => ALPHA",
            "@ => ALPHA"
         ],
         "split_on_numerics": "false"
     }
}


问:
Backstack android wear not working
I am trying to create an android wear app that only has one activity with one fragment inside of it. I want to be able to switch the fragments out based on button clicks or other user actions.

I can replace fragments just fine; however, when I swipe from left side of the screen to the right side of the screen. The app closes. I expected this swipe to act like a back button and not exit the app.

Main activity

```<code>import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import  android.support.v4.app.FragmentTransaction;
import android.support.wearable.view.WatchViewStub;

public class MainActivity extends FragmentActivity implements FragmentChangeListener {

    int  fragmentContainerId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        final WatchViewStub stub = (WatchViewStub)findViewById(R.id.watch_view_stub);

        // instialize the fragment to the loading page
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub watchViewStub) {
                fragmentContainerId =  R.id.fragmentContainer;

                if (watchViewStub.findViewById(R.id.fragmentContainer) != null) {

                    Fragment1 fragment1= new Fragment1 ();

                    // In case this activity was started with special instructions from an Intent,
                    // pass the Intent's extras to the fragment as arguments
                    fragment1.setArguments(getIntent().getExtras());

                    // Add the fragment to the 'fragment_container'
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.add(R.id.fragmentContainer, fragment1).addToBackStack(null);
                    fragmentTransaction.commit();
                }
            }
        });
    }

    @Override
    public void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentContainer, fragment, fragment.toString()).addToBackStack(null);
        System.out.println("Entry count in backstack is: " + fragmentManager.getBackStackEntryCount());
        fragmentTransaction.commit();
    }
}
</code>```

Fragment 1

```<code>import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Fragment1 extends Fragment {

    public Fragment1() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment1,
                container, false);

        Button button1= (Button)view.findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Fragment2 fragment2= new Fragment2 ();
                FragmentChangeListener fc=(FragmentChangeListener)getActivity();
                fc.replaceFragment(fragment2);
            }
        });
        return view;
    }
}
</code>```

Fragment 2

```<code>import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment2 extends Fragment {

    public Fragment2() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =inflater.inflate(R.layout.fragment2, container, false);

        return v;
    }

}
</code>```

FragmentChangeListner

```<code>import android.support.v4.app.Fragment;

public interface FragmentChangeListener
{
    public void replaceFragment(Fragment fragment);
}
</code>```

When I navigate from Fragment1 to Fragment2 via the button click. How can I navigate back to Fragment1 without exiting the app?

答:
One solution would be to wrap your second layout inside a

android.support.wearable.view.SwipeDismissFrameLayout

Then you can capture the dismiss gesture and inside the parent activity call getFragmentManager().popBackStack();

you can set listener on the SwipeDismissFrameLayout like so:
swipeFrame.setDismissEnabled(true);
 swipeFrame.setOnDismissedListener(new SwipeDismissLayout.OnDismissedListener() {
            @Override
            public void onDismissed(SwipeDismissLayout swipeDismissLayout) {
               getActivity().getFragmentManager().popBackStack();
            }
        });

Title: Backstack android wear not working

Body:
I am trying to create an android wear app that only has one activity with one fragment inside of it. I want to be able to switch the fragments out based on button clicks or other user actions.

I can replace fragments just fine; however, when I swipe from left side of the screen to the right side of the screen. The app closes. I expected this swipe to act like a back button and not exit the app.

Main activity

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import  android.support.v4.app.FragmentTransaction;
import android.support.wearable.view.WatchViewStub;

public class MainActivity extends FragmentActivity implements FragmentChangeListener {

    int  fragmentContainerId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        final WatchViewStub stub = (WatchViewStub)findViewById(R.id.watch_view_stub);

        // instialize the fragment to the loading page
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub watchViewStub) {
                fragmentContainerId =  R.id.fragmentContainer;

                if (watchViewStub.findViewById(R.id.fragmentContainer) != null) {

                    Fragment1 fragment1= new Fragment1 ();

                    // In case this activity was started with special instructions from an Intent,
                    // pass the Intent's extras to the fragment as arguments
                    fragment1.setArguments(getIntent().getExtras());

                    // Add the fragment to the 'fragment_container'
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.add(R.id.fragmentContainer, fragment1).addToBackStack(null);
                    fragmentTransaction.commit();
                }
            }
        });
    }

    @Override
    public void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentContainer, fragment, fragment.toString()).addToBackStack(null);
        System.out.println("Entry count in backstack is: " + fragmentManager.getBackStackEntryCount());
        fragmentTransaction.commit();
    }
}

Fragment 1

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Fragment1 extends Fragment {

    public Fragment1() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment1,
                container, false);

        Button button1= (Button)view.findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Fragment2 fragment2= new Fragment2 ();
                FragmentChangeListener fc=(FragmentChangeListener)getActivity();
                fc.replaceFragment(fragment2);
            }
        });
        return view;
    }
}

Fragment 2

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment2 extends Fragment {

    public Fragment2() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =inflater.inflate(R.layout.fragment2, container, false);

        return v;
    }

}

FragmentChangeListner

import android.support.v4.app.Fragment;

public interface FragmentChangeListener
{
    public void replaceFragment(Fragment fragment);
}

When I navigate from Fragment1 to Fragment2 via the button click. How can I navigate back to Fragment1 without exiting the app?


问:
Resolve git merge conflict by renaming one of the files
I'm using Flyway to keep track of database changes, and git for version control.

Flyway depends on migration scripts, which are named with increasing numbers for each migration.

Now I have the following situation: two features were developed on two separate branches (let's call them A and B), both requiring database changes. Both developers created a migration script for the database for their branch. As they branched off master at around the same time, they both assigned the same filename to the migration script: V42__migration.sql.

Now branch A was merged into master. When merging branch B, I got into a merge conflict because of the V42__migration.sql file. The correct solution to solve this conflict would be to rename the migration script of the branch B to V43__migration.sql. However, at time of merging git tries to merge both files in to one, where I actually need both of them untouched, but one renamed.

What's the best way to solve this kind of merge conflicts with git?

答:
If you don't rely on splited commits on the unmerged branch, squash all commits on the brach to one single commit.
You have to force the push to your branch git push -f (the old commits are overwritten and replaced by your new one).

Rename the file in the unmerged branch and ammend git commit --ammend your changes. Ammending also needs a forced push .

This may be more tricky if you didn't squash the commits.


问:
Golang -- where should resources be kept
For quite some time, I have been wondering where to save resources for my go package and I just cannot find a correct answer.

Right now, resources are kept into

main/module1/resources

main/module2/resources

When I just use go run *.go from main, it works fine. When I run tests, however, the resources cannot be found because Go changes the current working directory to the corresponding module. One workaround is to just os.Chdir('..') but doing that for every test seems kind of annoying. Furthermore, sometimes the resources are loaded as the package initializes. That means there is a global map with all templates (and their corresponding names):

```<code>package module2

var myTemplates = map[string]template { "index": loadTemplateFromFile() }
</code>```

I know you should not be using globals in go because of concurrency but this variable is safe for concurrent reads (and it is only written to during startup). So I put the templates into a global var so that they can be loaded on startup and some errors are caught during startup and the template are already in memory.

This means that I cannot change the working directory in time because the problem will already panic'd with an error telling me the file could not be found (this is the exact behavior I want).

Later, I discovered a method runtime.Caller to get the path from where the go files were compiled (if available):

```<code>base := "."
if _, filename, _, ok := runtime.Caller(0); ok {
    base = path.Join(path.Dir(filename), "..")
}
file := path.Join(base, "module1", "resources", ...)
</code>```

Now, all tests work just fine and go run *.go also finds the correct resources. This method becomes an issue as soon as I start deploying my package. Because runtime.Caller uses the path which was used during compilation, I have to have the resources in the excact same location where I complied them. This means when I build the binary in /home/matt3o12/go/src/domain.tld/matt3o12/mypackage, I have to have all resource folders at the exact same path on the server.

I also tried to use os.Executable but this is pretty pointless because it just points to some temporary path with the compiled executable inside (and no resources). Unless I compile a test package and run it manually but this is very work intense.

I am also not looking to store the resources inside the binary (having a folder structure of the project resources is just fine).

I do have some ideas to solve this problem but I don't think any of them are optional:

Use a flag to point to the resource folder. This would work but using that for every test I run would be pretty annoying (because now everytime I use go test ./... or go run *.go, I have to worry about the proper resource path).

Use "magic" to figure out if tests are run and change the path accordingling. I would hate to use that because I would have to place those checks all over my code and I hate to have many "edge/special" cases.

This is not a duplicate of:

Where should resources be kept in golang

https://github.com/golang/go/issues/3035

Golang serve static files from memory

https://www.reddit.com/r/golang/comments/66uewv/golang_compile_static_files_in_app/

答: There is no "should". You can put them wherever you see fit. You can embed them if you want. The easiest is probably to make the path to your resources configurable with some sane default (like defaulting to "." or runtime.Caller(0).

Body:
For quite some time, I have been wondering where to save resources for my go package and I just cannot find a correct answer.

Right now, resources are kept into

main/module1/resources

main/module2/resources

When I just use go run *.go from main, it works fine. When I run tests, however, the resources cannot be found because Go changes the current working directory to the corresponding module. One workaround is to just os.Chdir('..') but doing that for every test seems kind of annoying. Furthermore, sometimes the resources are loaded as the package initializes. That means there is a global map with all templates (and their corresponding names):

package module2

var myTemplates = map[string]template { "index": loadTemplateFromFile() }

I know you should not be using globals in go because of concurrency but this variable is safe for concurrent reads (and it is only written to during startup). So I put the templates into a global var so that they can be loaded on startup and some errors are caught during startup and the template are already in memory.

This means that I cannot change the working directory in time because the problem will already panic'd with an error telling me the file could not be found (this is the exact behavior I want).

Later, I discovered a method runtime.Caller to get the path from where the go files were compiled (if available):

base := "."
if _, filename, _, ok := runtime.Caller(0); ok {
    base = path.Join(path.Dir(filename), "..")
}
file := path.Join(base, "module1", "resources", ...)

Now, all tests work just fine and go run *.go also finds the correct resources. This method becomes an issue as soon as I start deploying my package. Because runtime.Caller uses the path which was used during compilation, I have to have the resources in the excact same location where I complied them. This means when I build the binary in /home/matt3o12/go/src/domain.tld/matt3o12/mypackage, I have to have all resource folders at the exact same path on the server.

I also tried to use os.Executable but this is pretty pointless because it just points to some temporary path with the compiled executable inside (and no resources). Unless I compile a test package and run it manually but this is very work intense.

I am also not looking to store the resources inside the binary (having a folder structure of the project resources is just fine).

I do have some ideas to solve this problem but I don't think any of them are optional:

Use a flag to point to the resource folder. This would work but using that for every test I run would be pretty annoying (because now everytime I use go test ./... or go run *.go, I have to worry about the proper resource path).

Use "magic" to figure out if tests are run and change the path accordingling. I would hate to use that because I would have to place those checks all over my code and I hate to have many "edge/special" cases.

This is not a duplicate of:

Where should resources be kept in golang

https://github.com/golang/go/issues/3035

Golang serve static files from memory

https://www.reddit.com/r/golang/comments/66uewv/golang_compile_static_files_in_app/


问:
Joomla front-end login leads to 404 error
I recently updated my website from Joomla 3.6.2 to 3.7.2.
Everything is OK except the front-end logging, which now leads to 404.

Diagnosis

One can still create a new user from here, but not logging.

When a logging attempt is made, the url changes to /index.php but I get a 404 error page.

If I try to directly access /index.php (ie. without logging), I get the correct main page.
Hence I would be tempted to say htaccess is not faulty here.

The /administrator logging page works perfectly.

Therefore, I suspect the problem is in the front-end logging module.

Any ideas ?

答:
I found that disabling the "Encrypt login form" option has it working again.

HTTPS being disabled on this site, I guess it's logical.


问:
Programmatically extract data from an Excel spreadsheet
Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV?  Specifically, this one:

http://www.econ.yale.edu/~shiller/data/ie_data.xls

And specifically the third sheet of that spreadsheet (the first two being charts).

Body:
With pyexcel library, you can do this:

>>> import pyexcel as p
>>> data_sheet=p.get_sheet(file_name='/Users/jaska/Downloads/ie_data.xls', sheet_name='Data')
>>> data_sheet.top_left()
pyexcel sheet:
+---------------------------------------------------------------------------------------------------------+---+---+---+------------+---+---+---+---+---+------------+---+---+---+---+---+---+
|                                                                                |   |   |   |            |   |   |   |   |   |            |   |   |   |   |   |   |
+---------------------------------------------------------------------------------------------------------+---+---+---+------------+---+---+---+---+---+------------+---+---+---+---+---+---+
| Stock Market Data Used in "Irrational Exuberance" Princeton University Press, 2000, 2005, 2015, updated |   |   |   |            |   |   |   |   |   | Cyclically |   |   |   |   |   |   |
+---------------------------------------------------------------------------------------------------------+---+---+---+------------+---+---+---+---+---+------------+---+---+---+---+---+---+
| Robert J. Shiller                                                                                |   |   |   |            |   |   |   |   |   | Adjusted   |   |   |   |   |   |   |
+---------------------------------------------------------------------------------------------------------+---+---+---+------------+---+---+---+---+---+------------+---+---+---+---+---+---+
|                                                                                |   |   |   |            |   |   |   |   |   | Price      |   |   |   |   |   |   |
+---------------------------------------------------------------------------------------------------------+---+---+---+------------+---+---+---+---+---+------------+---+---+---+---+---+---+
|                                                                                |   |   |   |   Consumer |   |   |   |   |   | Earnings   |   |   |   |   |   |   |
+---------------------------------------------------------------------------------------------------------+---+---+---+------------+---+---+---+---+---+------------+---+---+---+---+---+---+
>>> data_sheet.save_as('ie_data.csv')

And for it to work, you need to install:

$ pip install pyexcel
$ pip install pyexcel-xls

What's more, you can install pyexcel-cli in addition and get your csv data in one command line:

$ pyexcel transcode --sheet-name 'Data' /your/home/Downloads/ie_data.xls ie_data.csv


问:
returns the exact returned value if wget fails
I'd love to return the exact value if wget command fails in efficient way without changing it.

Can exit #? output the returned value from wget?

Ex.

```<code># If it succeeds, then wget returns zero instead of non zero
## 0    No problems occurred.
## 1    Generic error code.
## 2    Parse error—for instance, when parsing command-line options, the ‘.wgetrc’ or ‘.netrc’...
## 3    File I/O error.
## 4    Network failure.
## 5    SSL verification failure.
## 6    Username/password authentication failure.
## 7    Protocol errors.
## 8    Server issued an error response.
wget https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png -o test.img
if [ $? -ne 0 ]
then
    # exit 16 # failed ends1 <== This doesn't tell anything
    exit #?
fi
</code>```

答:
```<code>wget https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png -o test.img
# grab wget's exit code
exit_code=$?
# if exit code is not 0 (failed), then return it
test $exit_code -eq 0 || exit $exit_code
</code>```

Body:
I'd love to return the exact value if wget command fails in efficient way without changing it.

Can exit #? output the returned value from wget?

Ex.

# If it succeeds, then wget returns zero instead of non zero
## 0    No problems occurred.
## 1    Generic error code.
## 2    Parse error—for instance, when parsing command-line options, the ‘.wgetrc’ or ‘.netrc’...
## 3    File I/O error.
## 4    Network failure.
## 5    SSL verification failure.
## 6    Username/password authentication failure.
## 7    Protocol errors.
## 8    Server issued an error response.
wget https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png -o test.img
if [ $? -ne 0 ]
then
    # exit 16 # failed ends1 <== This doesn't tell anything
    exit #?
fi


问:
Best data structure for 1)Inserting an element 2)Finding minimum element 3)Deleting minimum element
Best data structure for
1)Inserting an element
2)Finding minimum element
3)Deleting minimum element

Options:

a)Array
b)Stack
c)Queue
d)Linked list
e)Heap.

Explain why

答: A min heap has O(log n) for delete min and insert, and O(1) for find min.</p>


问:
profiling a method of a class in Python using cProfile?
I'd like to profile a method of a function in Python, using cProfile. I tried the following:

```<code>import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")
</code>```

But it does not work. How can I call a self.method with "run"?

答:
I wouldn't recommend profiling a single routine, because that implies knowing in advance there's a problem there.

A fundamental aspect of performance problems is they're sneaky.
They're not where you think they are, because if they were you would have solved them already.

It's better to run the whole program with a realistic workload and let the profiling technique tell you where the problems are.

Here's an example where profiling finds the problem, and it is not where expected.

Body:
I'd like to profile a method of a function in Python, using cProfile. I tried the following:

import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")

But it does not work. How can I call a self.method with "run"?


问:
Angular 4 Back and Next buttons
I'm learning right now Angular 4 because I have to build a project with it. In one task I have to implement a Back and Next buttons functionality.

These buttons are only on 4 pages(step1 to step4), pages that are in the sidebar.
I get to step one from a search result. The result from searches is step1 page. So after I search a companies, I select the one that I want and click next. The back, next buttons are in the bottom of each these 4 steps pages.  So I click next each step until step 4 or I can go back, with back button.
On the sidebar, each step when is active has a diff color.

Each step page is a individual component. Sidebar, where I have the links for these steps, is another component. The buttons is another component, included in the bottom of each 4 steps page.

Because I'm new to angular 4, my question is how to do this flow: click next from step 1 to step 4(or back) and the sidebar component to be informed too about this change.

Because of the security, believe I can't put any code. I sign too many papers in this direction. Please I need some ideas, if someone can give me a hand.

答: Your project looks like a step wizard component, so maybe you can take a look to this project : https://github.com/maiyaporn/angular2-wizard

Title: Angular 4 Back and Next buttons


问:
UWP: Add styling to specific words in textblock
I have a couple of strings in a resource file, which all needs to be translated. These strings will be concatenated into one sentence and displayed inside a TextBlock in my app and I would like to make some of the strings bold inside the TextBlock.
E.g.

```<code>string a = "This {0} a {1} string.";
string b = "is";
string c = "formatted";
string output = string.Format(a, b, c);
</code>```

And I would like the output to be: This is a formatted string.

Any hints and tips are welcome.

答:
Use <Run /> inside your TextBlock for additional styling on specific words.

```<code><TextBlock>
    This
    <Run FontWeight="Bold">is</Run>
    a
    <Run FontWeight="Bold">formatted</Run>
    string.
</TextBlock>
</code>```

Update

Here's a simple example to give you an idea. I have created a UserControl called TextControl where the XAML contains only this -

```<code><TextBlock x:Name="MyTextBlock" />
</code>```

In its code-behind, I have defined three dependency properties. One is to take the full resource string, the other two are for passing in {0} and {1}. The idea is to split the full string by space, then replace {x} with the input properties and also make them bold.

```<code>public string ResourceString
{
    get => (string)GetValue(ResourceStringProperty);
    set => SetValue(ResourceStringProperty, value);
}
public static readonly DependencyProperty ResourceStringProperty = DependencyProperty.Register(
    "ResourceString", typeof(string), typeof(TextControl), new PropertyMetadata(default(string), (s, e) =>
    {
        var self = (TextControl)s;
        var full = e.NewValue.ToString();

        foreach (var seg in full.Split(' '))
        {
            var run = new Run();

            if (seg.Contains("{0}"))
            {
                run.Text = self.Input0;
                run.FontWeight = FontWeights.Bold;
            }
            else if (seg.Contains("{1}"))
            {
                run.Text = self.Input1;
                run.FontWeight = FontWeights.Bold;
            }
            else
            {
                run.Text = seg;
            }

            run.Text += " ";

            self.MyTextBlock.Inlines.Add(run);
        }
    }));

public string Input0
{
    get => (string)GetValue(Input0Property);
    set => SetValue(Input0Property, value);
}
public static readonly DependencyProperty Input0Property = DependencyProperty.Register(
    "Input0", typeof(string), typeof(TextControl), new PropertyMetadata(default(string)));

public string Input1
{
    get => (string)GetValue(Input1Property);
    set => SetValue(Input1Property, value);
}
public static readonly DependencyProperty Input1Property = DependencyProperty.Register(
    "Input1", typeof(string), typeof(TextControl), new PropertyMetadata(default(string)));
</code>```

Then you can just use it like this -

```<code><local:TextControl Input0="is" Input1="formatted" ResourceString="This {0} indeed a {1} string." />
</code>```

And you get -

Body:
I have a couple of strings in a resource file, which all needs to be translated. These strings will be concatenated into one sentence and displayed inside a TextBlock in my app and I would like to make some of the strings bold inside the TextBlock.
E.g.

string a = "This {0} a {1} string.";
string b = "is";
string c = "formatted";
string output = string.Format(a, b, c);

And I would like the output to be: This is a formatted string.

Any hints and tips are welcome.

Body:
Use <Run /> inside your TextBlock for additional styling on specific words.

<TextBlock>
    This
    <Run FontWeight="Bold">is</Run>
    a
    <Run FontWeight="Bold">formatted</Run>
    string.
</TextBlock>

Update

Here's a simple example to give you an idea. I have created a UserControl called TextControl where the XAML contains only this -

<TextBlock x:Name="MyTextBlock" />

In its code-behind, I have defined three dependency properties. One is to take the full resource string, the other two are for passing in {0} and {1}. The idea is to split the full string by space, then replace {x} with the input properties and also make them bold.

public string ResourceString
{
    get => (string)GetValue(ResourceStringProperty);
    set => SetValue(ResourceStringProperty, value);
}
public static readonly DependencyProperty ResourceStringProperty = DependencyProperty.Register(
    "ResourceString", typeof(string), typeof(TextControl), new PropertyMetadata(default(string), (s, e) =>
    {
        var self = (TextControl)s;
        var full = e.NewValue.ToString();

        foreach (var seg in full.Split(' '))
        {
            var run = new Run();

            if (seg.Contains("{0}"))
            {
                run.Text = self.Input0;
                run.FontWeight = FontWeights.Bold;
            }
            else if (seg.Contains("{1}"))
            {
                run.Text = self.Input1;
                run.FontWeight = FontWeights.Bold;
            }
            else
            {
                run.Text = seg;
            }

            run.Text += " ";

            self.MyTextBlock.Inlines.Add(run);
        }
    }));

public string Input0
{
    get => (string)GetValue(Input0Property);
    set => SetValue(Input0Property, value);
}
public static readonly DependencyProperty Input0Property = DependencyProperty.Register(
    "Input0", typeof(string), typeof(TextControl), new PropertyMetadata(default(string)));

public string Input1
{
    get => (string)GetValue(Input1Property);
    set => SetValue(Input1Property, value);
}
public static readonly DependencyProperty Input1Property = DependencyProperty.Register(
    "Input1", typeof(string), typeof(TextControl), new PropertyMetadata(default(string)));

Then you can just use it like this -

<local:TextControl Input0="is" Input1="formatted" ResourceString="This {0} indeed a {1} string." />

And you get -


问:
How to make query string readable in Python?
How to make this string readable in Python 2.7?

%D0%9A%D0%BE%D0%BD%D1%86%D0%B5%D0%BF%D1%86%D0%B8%D1%8F_%D0%A4%D0%B5%D0%B4%D0%B5%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B9_%D1%86%D0%B5%D0%BB%D0%B5%D0%B2%D0%BE%D0%B9_%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D1%8B_%D1%80%D0%B0%D0%B7%D0%B2%D0%B8%D1%82%D0%B8%D1%8F_%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_%D0%BD%D0%B0_2016-2020_%D0%B3%D0%B3

This string contains Cyrillic symbol and it's a part of a URL (a query string parameter).

答:
use urllib.unquote from the standard library.

urllib.unquote(string)¶

Replace %xx escapes by their single-character equivalent.

Example: unquote('/%7Econnolly/') yields '/~connolly/'.


问:
cant change data-percent mark (%) size of jquery progress bar cercle
I'm working on a project that calls for a circular progress bar. i want to change  data-percent (%) mark size , im try to using % tag, but not working , how can i change it? im use this tutorial Jquery Progress bar

(function($) {
  $.fn.loading = function() {
    var DEFAULTS = {
      backgroundColor: '#b3cef6',
      progressColor: '#4b86db',
      percent: 75,
      duration: 2000
    };

    $(this).each(function() {
      var $target = $(this);

      var opts = {
        backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
        progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
        percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
        duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
      };
      // console.log(opts);

      $target.append('

' + opts.percent + '%
');

      $target.find('.background').css('background-color', opts.backgroundColor);
      $target.find('.left').css('background-color', opts.backgroundColor);
      $target.find('.rotate').css('background-color', opts.progressColor);
      $target.find('.right').css('background-color', opts.progressColor);

      var $rotate = $target.find('.rotate');
      setTimeout(function() {
        $rotate.css({
          'transition': 'transform ' + opts.duration + 'ms linear',
          'transform': 'rotate(' + opts.percent * 3.6 + 'deg)'
        });
      }, 1);

      if (opts.percent > 50) {
        var animationRight = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-end';
        var animationLeft = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-start';
        $target.find('.right').css({
          animation: animationRight,
          opacity: 1
        });
        $target.find('.left').css({
          animation: animationLeft,
          opacity: 0
        });
      }
    });
  }
})(jQuery);

 $(".progress-bar").loading()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.progress-bar {
  display: block;
  margin: 0 auto;
  text-align: center;
  height: 0px;
  width: 200px;
  font-size: 12px;
  font-family: sans-serif;
  line-height: 20px;
  color: #fff;
  margin-top: 55px;
  background-color: white;
}

.progress-bar div {
  position: absolute;
  height: 200px;
  width: 200px;
  border-radius: 50%;
  text-align: center;
  margin-top: -52px;
  margin-left: -27px;
}

.progress-bar data-percen {
  font-size: 8px;
}

.progress-bar div span {
  position: absolute;
  font-family: sans-serif;
  font-size: 60px;
  line-height: 175px;
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 183px;
  width: 185px;
  left: 8.5px;
  top: 8.5px;
  text-align: center;
  border-radius: 50%;
  background-color: #f9f7f7;
  color: black;
}

.progress-bar .background {
  background-color: #b3cef6;
}

.progress-bar .rotate {
  clip: rect(0 100px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 100px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 100px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}

@keyframes toggle {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}</code>```

```

答:
The span is positionned absolute and is the element making the center of the circle.

To have a second span for the percent sign,

like this: ' + opts.percent + '% is not a bad idea...

But you have to play with the CSS a little.

In the below snippet, notice that I changed .progress-bar div span by removing two lines defining the font-size and the background-color.

Those must now be applyed to the right span.

So I made two new CSS rules: .progress-bar div span:nth-of-type(1) and .progress-bar div span:nth-of-type(2).

The second one id the CSS for you percentage sign.

(function($) {
  $.fn.loading = function() {
    var DEFAULTS = {
      backgroundColor: '#b3cef6',
      progressColor: '#4b86db',
      percent: 75,
      duration: 2000
    };

    $(this).each(function() {
      var $target = $(this);

      var opts = {
        backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
        progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
        percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
        duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
      };
      // console.log(opts);

      $target.append('

' + opts.percent + '%
');

      $target.find('.background').css('background-color', opts.backgroundColor);
      $target.find('.left').css('background-color', opts.backgroundColor);
      $target.find('.rotate').css('background-color', opts.progressColor);
      $target.find('.right').css('background-color', opts.progressColor);

      var $rotate = $target.find('.rotate');
      setTimeout(function() {
        $rotate.css({
          'transition': 'transform ' + opts.duration + 'ms linear',
          'transform': 'rotate(' + opts.percent * 3.6 + 'deg)'
        });
      }, 1);

      if (opts.percent > 50) {
        var animationRight = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-end';
        var animationLeft = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-start';
        $target.find('.right').css({
          animation: animationRight,
          opacity: 1
        });
        $target.find('.left').css({
          animation: animationLeft,
          opacity: 0
        });
      }
    });
  }
})(jQuery);

$(".progress-bar").loading()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.progress-bar {
  display: block;
  margin: 0 auto;
  text-align: center;
  height: 0px;
  width: 200px;
  font-size: 12px;
  font-family: sans-serif;
  line-height: 20px;
  color: #fff;
  margin-top: 55px;
  background-color: white;
}

.progress-bar div {
  position: absolute;
  height: 200px;
  width: 200px;
  border-radius: 50%;
  text-align: center;
  margin-top: -52px;
  margin-left: -27px;
}

.progress-bar data-percen {
  font-size: 8px;
}

.progress-bar div span {
  position: absolute;
  font-family: sans-serif;
  /*font-size: 60px;*/
  line-height: 175px;
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 183px;
  width: 185px;
  left: 8.5px;
  top: 8.5px;
  text-align: center;
  border-radius: 50%;
  /*background-color: #f9f7f7;*/
  color: black;
}

.progress-bar div span:nth-of-type(1) {
  font-size: 60px;
  background-color: #f9f7f7;
}
.progress-bar div span:nth-of-type(2) {
  font-size: 12px;
  text-align:right;
  padding-right:4em;
}

.progress-bar .background {
  background-color: #b3cef6;
}

.progress-bar .rotate {
  clip: rect(0 100px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 100px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 100px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}

@keyframes toggle {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}</code>```

```

Body:
I'm working on a project that calls for a circular progress bar. i want to change  data-percent (%) mark size , im try to using % tag, but not working , how can i change it? im use this tutorial Jquery Progress bar

(function($) {
  $.fn.loading = function() {
    var DEFAULTS = {
      backgroundColor: '#b3cef6',
      progressColor: '#4b86db',
      percent: 75,
      duration: 2000
    };

    $(this).each(function() {
      var $target = $(this);

      var opts = {
        backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
        progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
        percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
        duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
      };
      // console.log(opts);

      $target.append('

' + opts.percent + '%
');

      $target.find('.background').css('background-color', opts.backgroundColor);
      $target.find('.left').css('background-color', opts.backgroundColor);
      $target.find('.rotate').css('background-color', opts.progressColor);
      $target.find('.right').css('background-color', opts.progressColor);

      var $rotate = $target.find('.rotate');
      setTimeout(function() {
        $rotate.css({
          'transition': 'transform ' + opts.duration + 'ms linear',
          'transform': 'rotate(' + opts.percent * 3.6 + 'deg)'
        });
      }, 1);

      if (opts.percent > 50) {
        var animationRight = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-end';
        var animationLeft = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-start';
        $target.find('.right').css({
          animation: animationRight,
          opacity: 1
        });
        $target.find('.left').css({
          animation: animationLeft,
          opacity: 0
        });
      }
    });
  }
})(jQuery);

 $(".progress-bar").loading()

.progress-bar {
  display: block;
  margin: 0 auto;
  text-align: center;
  height: 0px;
  width: 200px;
  font-size: 12px;
  font-family: sans-serif;
  line-height: 20px;
  color: #fff;
  margin-top: 55px;
  background-color: white;
}

.progress-bar div {
  position: absolute;
  height: 200px;
  width: 200px;
  border-radius: 50%;
  text-align: center;
  margin-top: -52px;
  margin-left: -27px;
}

.progress-bar data-percen {
  font-size: 8px;
}

.progress-bar div span {
  position: absolute;
  font-family: sans-serif;
  font-size: 60px;
  line-height: 175px;
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 183px;
  width: 185px;
  left: 8.5px;
  top: 8.5px;
  text-align: center;
  border-radius: 50%;
  background-color: #f9f7f7;
  color: black;
}

.progress-bar .background {
  background-color: #b3cef6;
}

.progress-bar .rotate {
  clip: rect(0 100px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 100px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 100px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}

@keyframes toggle {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

Body:
The span is positionned absolute and is the element making the center of the circle.

To have a second span for the percent sign,

like this: <span>' + opts.percent + '</span><span>%</span> is not a bad idea...

But you have to play with the CSS a little.

In the below snippet, notice that I changed .progress-bar div span by removing two lines defining the font-size and the background-color.

Those must now be applyed to the right span.

So I made two new CSS rules: .progress-bar div span:nth-of-type(1) and .progress-bar div span:nth-of-type(2).

The second one id the CSS for you percentage sign.

(function($) {
  $.fn.loading = function() {
    var DEFAULTS = {
      backgroundColor: '#b3cef6',
      progressColor: '#4b86db',
      percent: 75,
      duration: 2000
    };

    $(this).each(function() {
      var $target = $(this);

      var opts = {
        backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
        progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
        percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
        duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
      };
      // console.log(opts);

      $target.append('<div class="background"></div><div class="rotate"></div><div class="left"></div><div class="right"></div><div class=""><span>' + opts.percent + '</span><span>%</span></div>');

      $target.find('.background').css('background-color', opts.backgroundColor);
      $target.find('.left').css('background-color', opts.backgroundColor);
      $target.find('.rotate').css('background-color', opts.progressColor);
      $target.find('.right').css('background-color', opts.progressColor);

      var $rotate = $target.find('.rotate');
      setTimeout(function() {
        $rotate.css({
          'transition': 'transform ' + opts.duration + 'ms linear',
          'transform': 'rotate(' + opts.percent * 3.6 + 'deg)'
        });
      }, 1);

      if (opts.percent > 50) {
        var animationRight = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-end';
        var animationLeft = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-start';
        $target.find('.right').css({
          animation: animationRight,
          opacity: 1
        });
        $target.find('.left').css({
          animation: animationLeft,
          opacity: 0
        });
      }
    });
  }
})(jQuery);

$(".progress-bar").loading()

.progress-bar {
  display: block;
  margin: 0 auto;
  text-align: center;
  height: 0px;
  width: 200px;
  font-size: 12px;
  font-family: sans-serif;
  line-height: 20px;
  color: #fff;
  margin-top: 55px;
  background-color: white;
}

.progress-bar div {
  position: absolute;
  height: 200px;
  width: 200px;
  border-radius: 50%;
  text-align: center;
  margin-top: -52px;
  margin-left: -27px;
}

.progress-bar data-percen {
  font-size: 8px;
}

.progress-bar div span {
  position: absolute;
  font-family: sans-serif;
  /*font-size: 60px;*/
  line-height: 175px;
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 183px;
  width: 185px;
  left: 8.5px;
  top: 8.5px;
  text-align: center;
  border-radius: 50%;
  /*background-color: #f9f7f7;*/
  color: black;
}

.progress-bar div span:nth-of-type(1) {
  font-size: 60px;
  background-color: #f9f7f7;
}
.progress-bar div span:nth-of-type(2) {
  font-size: 12px;
  text-align:right;
  padding-right:4em;
}

.progress-bar .background {
  background-color: #b3cef6;
}

.progress-bar .rotate {
  clip: rect(0 100px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 100px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 100px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}

@keyframes toggle {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress-bar" data-percent="48" data-duration="1000" data-color="#6a6f77,#5fb756">

</div>


问:
How to change column model of my TableModel dynamically
I have a simple Java Desktop application that show a JTable with a custom TableModel.

In base of a boolean variables, I want to show a Table with different column.
But I'm not able to do this.

```<code>This is my code:

static String[] ColName = { "Cod.Articolo","Nome Articolo","Cod.Barre", "Qtà.iniziale","Scontrini(-)","Bolla(-)","Fattura(-)","DDT(-)","NC(+)","Carico(+)"};
static String[] ColNameNero = { "Cod.Articolo","Nome Articolo","Cod.Barre", "Qtà.iniziale","Scontrini(-)","Scontrini Nero(-)","Bolla(-)","Fattura(-)","DDT(-)","NC(+)","Carico(+)"};

public void creaTabellaMerci(boolean isNero){
    try{
        if(isNero)
            tableMovimentiMagazzinoMerci = new MyTableModelMovimentiMagazzinoMerci(ColNameNero,isNero);
        else
            tableMovimentiMagazzinoMerci = new MyTableModelMovimentiMagazzinoMerci(ColName,isNero);

        tableMovimentiMerci = new DefaultTableCustom(tableMovimentiMagazzinoMerci);
        sorter = new TableRowSorter<MyTableModelMovimentiMagazzinoMerci>(tableMovimentiMagazzinoMerci);
        tableMovimentiMerci.setRowSorter(sorter);
        jScrollPaneAmministrazione = new javax.swing.JScrollPane();
        jScrollPaneAmministrazione.setViewportView(tableMovimentiMerci);
        jScrollPaneAmministrazione.setPreferredSize(dTabella2);
        jScrollPaneAmministrazione.getViewport().add(tableMovimentiMerci);
        tableMovimentiMagazzinoMerci.fireTableDataChanged();
        tableMovimentiMerci.repaint();
    }catch(Exception e){
        log.logStackTrace(e);
    }
}
</code>```

Now at first time, I call the method with variables isNero = true. At the second time, I call the same method with variables isNero = false but the columns not changes.

How can I fix it ?

答:
```<code>jScrollPaneAmministrazione = new javax.swing.JScrollPane();
</code>```

You create a new JScrollPane, but you never add the scroll pane to the frame. Changing the value of the reference variable does NOT add the component to the frame.

Don't create a new JTable or JScrollPane!

Instead you can just update the TableModel of the table that is currently display on the frame:

```<code>//tableMovimentiMerci = new DefaultTableCustom(tableMovimentiMagazzinoMerci);
tableMovimentiMerci.setModel( tableMovementiMagazzinoMerci );
sorter = new TableRowSorter<MyTableModelMovimentiMagazzinoMerci>(tableMovimentiMagazzinoMerci);
tableMovimentiMerci.setRowSorter(sorter);
//jScrollPaneAmministrazione = new javax.swing.JScrollPane();
//jScrollPaneAmministrazione.setViewportView(tableMovimentiMerci);
//jScrollPaneAmministrazione.setPreferredSize(dTabella2);
//jScrollPaneAmministrazione.getViewport().add(tableMovimentiMerci);
//tableMovimentiMagazzinoMerci.fireTableDataChanged();
//tableMovimentiMerci.repaint();
</code>```

Body:
I have a simple Java Desktop application that show a JTable with a custom TableModel.

In base of a boolean variables, I want to show a Table with different column.
But I'm not able to do this.

This is my code:

static String[] ColName = { "Cod.Articolo","Nome Articolo","Cod.Barre", "Qtà.iniziale","Scontrini(-)","Bolla(-)","Fattura(-)","DDT(-)","NC(+)","Carico(+)"};
static String[] ColNameNero = { "Cod.Articolo","Nome Articolo","Cod.Barre", "Qtà.iniziale","Scontrini(-)","Scontrini Nero(-)","Bolla(-)","Fattura(-)","DDT(-)","NC(+)","Carico(+)"};

public void creaTabellaMerci(boolean isNero){
    try{
        if(isNero)
            tableMovimentiMagazzinoMerci = new MyTableModelMovimentiMagazzinoMerci(ColNameNero,isNero);
        else
            tableMovimentiMagazzinoMerci = new MyTableModelMovimentiMagazzinoMerci(ColName,isNero);

        tableMovimentiMerci = new DefaultTableCustom(tableMovimentiMagazzinoMerci);
        sorter = new TableRowSorter<MyTableModelMovimentiMagazzinoMerci>(tableMovimentiMagazzinoMerci);
        tableMovimentiMerci.setRowSorter(sorter);
        jScrollPaneAmministrazione = new javax.swing.JScrollPane();
        jScrollPaneAmministrazione.setViewportView(tableMovimentiMerci);
        jScrollPaneAmministrazione.setPreferredSize(dTabella2);
        jScrollPaneAmministrazione.getViewport().add(tableMovimentiMerci);
        tableMovimentiMagazzinoMerci.fireTableDataChanged();
        tableMovimentiMerci.repaint();
    }catch(Exception e){
        log.logStackTrace(e);
    }
}

Now at first time, I call the method with variables isNero = true. At the second time, I call the same method with variables isNero = false but the columns not changes.

How can I fix it ?

Body:
jScrollPaneAmministrazione = new javax.swing.JScrollPane();

You create a new JScrollPane, but you never add the scroll pane to the frame. Changing the value of the reference variable does NOT add the component to the frame.

Don't create a new JTable or JScrollPane!

Instead you can just update the TableModel of the table that is currently display on the frame:

//tableMovimentiMerci = new DefaultTableCustom(tableMovimentiMagazzinoMerci);
tableMovimentiMerci.setModel( tableMovementiMagazzinoMerci );
sorter = new TableRowSorter<MyTableModelMovimentiMagazzinoMerci>(tableMovimentiMagazzinoMerci);
tableMovimentiMerci.setRowSorter(sorter);
//jScrollPaneAmministrazione = new javax.swing.JScrollPane();
//jScrollPaneAmministrazione.setViewportView(tableMovimentiMerci);
//jScrollPaneAmministrazione.setPreferredSize(dTabella2);
//jScrollPaneAmministrazione.getViewport().add(tableMovimentiMerci);
//tableMovimentiMagazzinoMerci.fireTableDataChanged();
//tableMovimentiMerci.repaint();


问:
Can I stop the mouse from interacting with the intelliJ IDEA switcher?
I often switch between editors in intellJ with Ctrl-Tab and at the same time I accidentally move the mouse (which is sometimes over the switcher), which means I end up choosing a random editor rather than the one I wanted.

Is there any way I can prevent the switcher from reacting to mouse input?

答:
What OS and IDEA version do you use? I've tested with IDEA 10 on Windows and mouse events do not affect the Ctrl+Tab window at all.

If it still happens for you in the latest IDEA version, please file a bug with the steps to reproduce at: http://youtrack.jetbrains.net/issues/IDEA.

It's a known bug in IDEA versions before IDEA 10.


问:
If ... else switch ... statement
Following code compiles on my gcc 5.4.0, doesn't generate any warnings and works fine:

```<code>if (a == 0) {
    puts("0");
} else switch (a) {
    case 1: puts("1"); break;
    case 2: puts("2"); break;
    default: puts("default"); break;
}
</code>```

Is if ... else switch ... correct statement?

答:
There's nothing wrong with your code. The grammar for if ... else is as follows:

attr(optional) if ( condition ) statement-true else statement-false

switch is a statement, so it is allowed to go after else.

Note that else if is not a special construct either, it's just an if statement after an else.

Title: If ... else switch ... statement

Body:
Following code compiles on my gcc 5.4.0, doesn't generate any warnings and works fine:

if (a == 0) {
    puts("0");
} else switch (a) {
    case 1: puts("1"); break;
    case 2: puts("2"); break;
    default: puts("default"); break;
}

Is if ... else switch ... correct statement?


问:
Cannot include project artifact: com.test.mmm.jar:1.0; it doesn't have an associated file or directory
I'm pretty lost with maven and I can't seem to find a solution for my problem. When I try to generate the jar file with all the dependencies of my project to execute it on another computer I find this warning when I execute sudo mvn clean compile assembly:single:

```<code>[WARNING] Cannot include project artifact: com.test:mmm:jar:1.0; it doesn't have an associated file or directory.
</code>```

Also, when I try to execute the .jar with java -jar target/test.jar this error appears:

```<code>Error: Unable to access jarfile target/test.jar
</code>```

here's my pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>mmm</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>mmm</name>
<url>http://maven.apache.org</url>
<properties>
    <nd4j.backend>nd4j-cuda-8.0-platform</nd4j.backend>
</properties>

<dependencies>
    <dependency>
        <groupId>org.jblas</groupId>
        <artifactId>jblas</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.nd4j</groupId>
        <artifactId>nd4j-native-platform</artifactId>
        <version>0.8.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.deeplearning4j</groupId>
        <artifactId>deeplearning4j-core</artifactId>
        <version>0.8.0</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.test.mmm.Main</mainClass>
                    </manifest>
                </archive>
                <finalName>test</finalName>
                <descriptorRefs>jar-with-dependencies</descriptorRefs>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

The main class is located in src/
I've tried many solutions from stack overflow but had no success, can someone help me?

Thank you!

答:
Use mvn package first to build your module classes then assembly:single.

mvn package assembly:single

Body:
I'm pretty lost with maven and I can't seem to find a solution for my problem. When I try to generate the jar file with all the dependencies of my project to execute it on another computer I find this warning when I execute sudo mvn clean compile assembly:single:

[WARNING] Cannot include project artifact: com.test:mmm:jar:1.0; it doesn't have an associated file or directory.

Also, when I try to execute the .jar with java -jar target/test.jar this error appears:

Error: Unable to access jarfile target/test.jar

here's my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>mmm</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>mmm</name>
<url>http://maven.apache.org</url>
<properties>
    <nd4j.backend>nd4j-cuda-8.0-platform</nd4j.backend>
</properties>

<dependencies>
    <dependency>
        <groupId>org.jblas</groupId>
        <artifactId>jblas</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.nd4j</groupId>
        <artifactId>nd4j-native-platform</artifactId>
        <version>0.8.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.deeplearning4j</groupId>
        <artifactId>deeplearning4j-core</artifactId>
        <version>0.8.0</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.test.mmm.Main</mainClass>
                    </manifest>
                </archive>
                <finalName>test</finalName>
                <descriptorRefs>jar-with-dependencies</descriptorRefs>
            </configuration>
        </plugin>
    </plugins>
</build>

The main class is located in src/
I've tried many solutions from stack overflow but had no success, can someone help me?

Thank you!