问:
.LIC / Licence (AjaxUploader.lic) not copy after publish / build
I recently checked that the ajaxuploader license file is not copied to the IIS publishing folder, I tried with the options in the file property of:
Build Action = None / Content
Copy to Output Directory = Copy Always

However for .lic files this seems to be ignored

I've also tried to copy through the Build Events in .WEB properties using Xcopy commands, but I could not solve the problem.

Any suggestion?

答:
I was able to figure out the problem ...

Let's go there to solve the problem add these lines in webConfig:

```<code><remove extension=".lic"/>
<add extension=".lic" type="System.Web.Compilation.ForceCopyBuildProvider"/>
</code>```

They should be in the following structure:

```<code><Configuration>
   <System.web>
      <Compilation>
         <BuildProviders>
           <Remove extension=".lic"/>
           <Add extension=".lic"
               Type="System.Web.Compilation.ForceCopyBuildProvider"/>
         </BuildProviders>
      </Compilation>
   </system.web>
</Configuration>
</code>```

By analyzing the publish output I found that the ajaxuploader.lic file can not be interpreted by "aspnet_compiler.exe", it does not understand the .lic and ends up ignoring it, if you try to change the extension .lic to nothing or to .exe , .txt the file will rise, knowing that I analyzed that in the publication when it executes aspnet_compiler.exe doing the trasnferencia:

Of the folder: obj \ Development \ AspnetCompileMerge \ Source
To folder: obj \ Development \ AspnetCompileMerge \ TempBuildDir

In the Source folder the .lic file already exists in the TempBuildDir folder it disappears, the problem itself is that when executing the command aspnet_compiler.exe with source -> target (TempBuildDir) the .lic file is not copied, so the keys are placed in the Webconfig specifically serves to remove the .lic extension before aspnet_compiler.exe is run and then adds the .lic to the file.

Hugs

Body:
I was able to figure out the problem ...

Let's go there to solve the problem add these lines in webConfig:

<remove extension=".lic"/>
<add extension=".lic" type="System.Web.Compilation.ForceCopyBuildProvider"/>

They should be in the following structure:

<Configuration>
   <System.web>
      <Compilation>
         <BuildProviders>
           <Remove extension=".lic"/>
           <Add extension=".lic"
               Type="System.Web.Compilation.ForceCopyBuildProvider"/>
         </BuildProviders>
      </Compilation>
   </system.web>
</Configuration>

By analyzing the publish output I found that the ajaxuploader.lic file can not be interpreted by "aspnet_compiler.exe", it does not understand the .lic and ends up ignoring it, if you try to change the extension .lic to nothing or to .exe , .txt the file will rise, knowing that I analyzed that in the publication when it executes aspnet_compiler.exe doing the trasnferencia:

Of the folder: obj \ Development \ AspnetCompileMerge \ Source
To folder: obj \ Development \ AspnetCompileMerge \ TempBuildDir

In the Source folder the .lic file already exists in the TempBuildDir folder it disappears, the problem itself is that when executing the command aspnet_compiler.exe with source -> target (TempBuildDir) the .lic file is not copied, so the keys are placed in the Webconfig specifically serves to remove the .lic extension before aspnet_compiler.exe is run and then adds the .lic to the file.

Hugs


来源: stackexchange

问:
Right-click context menu for Java JTree?
I'm trying to implement pop-up menus in Java JTree. I've sub-classed DefaultTreeCellRenderer (to change node appearance) and DefaultTreeCellEditor (to create Components to attach event listeners to, since apparently the Components that DefaultTreeCellRenderer.getTreeCellRendererComponent() returns can't do it?). I don't really want to "edit" the nodes, just be able to pop-up a menu when a node gets right-clicked, but this is the only way I can think of doing it right now...

Below is the code that I have so far-- I'm just trying to figure out how to capture MouseEvents. It sort of works, but badly. What's a better way to accomplish what I'm trying to do here?

```<code>private class My_TreeCellRenderer extends DefaultTreeCellRenderer {
    My_TreeCellRenderer() {
        super ();
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

        // set label text and tool tips
        setText(((My_Object)value).getTreeLabel());
        setToolTipText(((My_Object)value).getTreeToolTip());

        return this;
    }
}

private class My_TreeCellEditor extends DefaultTreeCellEditor {
    private MouseAdapter ma;

    My_TreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
        super (tree, renderer);
        ma = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    System.out.println("My Popup");
                }
            }
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    System.out.println("My Popup");
                }
            }
        };
    }

    public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) {
        String src_filename = null;

        // return non-editing component
        Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, true);

        // add mouse listener if it's not listening already
        MouseListener mouseListeners[] = c.getMouseListeners();
        int i;
        for (i=0; i < mouseListeners.length && mouseListeners[i] != ma; i++);
        if (i >= mouseListeners.length)
            c.addMouseListener(ma);

        return c;
    }

    protected boolean canEditImmediately(EventObject event) {
        if (event instanceof MouseEvent && ((MouseEvent)event).getClickCount() == 1)
            return true;
        else
            return false;
    }
}
</code>```

答:
Call addRightClickListener() to add the right-click context menu listener to your JTree. Both overrides are for proper cross-platform functionality (Windows and Linux differ here).

```<code>private void addRightClickListener()
{
    MouseListener mouseListener = new MouseAdapter()
    {
        @Override
        public void mousePressed(MouseEvent mouseEvent)
        {
            handleContextMenu(mouseEvent);
        }

        @Override
        public void mouseReleased(MouseEvent mouseEvent)
        {
            handleContextMenu(mouseEvent);
        }
    };

    tree.addMouseListener(mouseListener);
}

private void handleContextMenu(MouseEvent mouseEvent)
{
    if (mouseEvent.isPopupTrigger())
    {
        MyContextMenu contextMenu = new MyContextMenu();

        contextMenu.show(mouseEvent.getComponent(),
                mouseEvent.getX(),
                mouseEvent.getY());
    }
}
</code>```

OwnerDisplayName: arcanex

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to implement pop-up menus in Java JTree. I've sub-classed DefaultTreeCellRenderer (to change node appearance) and DefaultTreeCellEditor (to create Components to attach event listeners to, since apparently the Components that DefaultTreeCellRenderer.getTreeCellRendererComponent() returns can't do it?). I don't really want to "edit" the nodes, just be able to pop-up a menu when a node gets right-clicked, but this is the only way I can think of doing it right now...

Below is the code that I have so far-- I'm just trying to figure out how to capture MouseEvents. It sort of works, but badly. What's a better way to accomplish what I'm trying to do here?

private class My_TreeCellRenderer extends DefaultTreeCellRenderer {
    My_TreeCellRenderer() {
        super ();
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

        // set label text and tool tips
        setText(((My_Object)value).getTreeLabel());
        setToolTipText(((My_Object)value).getTreeToolTip());

        return this;
    }
}

private class My_TreeCellEditor extends DefaultTreeCellEditor {
    private MouseAdapter ma;

    My_TreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
        super (tree, renderer);
        ma = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    System.out.println("My Popup");
                }
            }
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    System.out.println("My Popup");
                }
            }
        };
    }

    public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) {
        String src_filename = null;

        // return non-editing component
        Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, true);

        // add mouse listener if it's not listening already
        MouseListener mouseListeners[] = c.getMouseListeners();
        int i;
        for (i=0; i < mouseListeners.length && mouseListeners[i] != ma; i++);
        if (i >= mouseListeners.length)
            c.addMouseListener(ma);

        return c;
    }

    protected boolean canEditImmediately(EventObject event) {
        if (event instanceof MouseEvent && ((MouseEvent)event).getClickCount() == 1)
            return true;
        else
            return false;
    }
}

Body:
Call addRightClickListener() to add the right-click context menu listener to your JTree. Both overrides are for proper cross-platform functionality (Windows and Linux differ here).

private void addRightClickListener()
{
    MouseListener mouseListener = new MouseAdapter()
    {
        @Override
        public void mousePressed(MouseEvent mouseEvent)
        {
            handleContextMenu(mouseEvent);
        }

        @Override
        public void mouseReleased(MouseEvent mouseEvent)
        {
            handleContextMenu(mouseEvent);
        }
    };

    tree.addMouseListener(mouseListener);
}

private void handleContextMenu(MouseEvent mouseEvent)
{
    if (mouseEvent.isPopupTrigger())
    {
        MyContextMenu contextMenu = new MyContextMenu();

        contextMenu.show(mouseEvent.getComponent(),
                mouseEvent.getX(),
                mouseEvent.getY());
    }
}

ContentLicense: CC BY-SA 3.0


问:
Change select columns from character to integers
I have a dataframe as such:

```<code>sample = data.frame(
  beer_brewerId = c("8481", "8481", "8481"),
  rev_app = c("4/5","1/5", "2/5"),
  beer_name = c("John Harvards Simcoe IPA", "John Harvards Simcoe IPA", "John Harvards American Brown Ale"),
  review_taste =c("6/10", "7/10", "6/10"), stringsAsFactors = FALSE
)
str(sample)
</code>```

I would like to convert only columns 2 and 4 from a character vector into an integer for analysis purposes. Normally, this would not be so difficult if all of the character columns I have I want to convert to  numeric with the following code, but this does not work as I want to keep column 3 as a chr type:

```<code>sample %>%
  select(2,4) %>%
  mutate_if(is.character, as.numeric)
</code>```

You can easily accomplish this with base r as:

```<code>#base approach
cols <- c("2","4")
data[cols] <- lapply(data[cols], as.numeric)
</code>```

Is there an easy way to do this using dplyr, and even within a pipe sequence? If you were to select only certain columns using select(), it would not allow you to save the results back into the dataframe

Something like this would work, but as my dataset has 15+ columns, this seems like its very cumbersome code:

```<code>cleandf <- sample %>%
#Use transform or mutate to convert each column manually
transform(rev_app = as.integer(rev_app)) %>%
transform(review_taste = as.integer(review_taste))
</code>```

Is mutate_at, or mutate_each meant to perform this task? Any help would be appreciated. Thanks.

```<code>#Maybe something like this:
cols <- c("2","4")
data %>%
  mutate_each(is.character[cols], as.numeric)
</code>```

答:
You can achieve this with the mutate_at function.

```<code>sample = data.frame(beer_brewerId = c("8481", "8481", "8481"),
     rev_app = c("4/5","1/5", "2/5"),
     beer_name = c("John Harvards Simcoe IPA", "John Harvards Simcoe IPA", "John Harvards American Brown Ale"),
     review_taste =c("6/10", "7/10", "6/10"), stringsAsFactors = FALSE)

# get rid of "/"
clean <- function(foo) {
         sapply(foo, function(x) eval(parse(text = x)))
         }
# you can replace c(2,4) by whatever columns you need
clean_sample <- sample %>%
                mutate_at(c(2,4), clean)
</code>```

Columns 2 and 4 are now numeric.

Body:
I have a dataframe as such:

sample = data.frame(
  beer_brewerId = c("8481", "8481", "8481"),
  rev_app = c("4/5","1/5", "2/5"),
  beer_name = c("John Harvards Simcoe IPA", "John Harvards Simcoe IPA", "John Harvards American Brown Ale"),
  review_taste =c("6/10", "7/10", "6/10"), stringsAsFactors = FALSE
)
str(sample)

I would like to convert only columns 2 and 4 from a character vector into an integer for analysis purposes. Normally, this would not be so difficult if all of the character columns I have I want to convert to  numeric with the following code, but this does not work as I want to keep column 3 as a chr type:

sample %>%
  select(2,4) %>%
  mutate_if(is.character, as.numeric)

You can easily accomplish this with base r as:

#base approach
cols <- c("2","4")
data[cols] <- lapply(data[cols], as.numeric)

Is there an easy way to do this using dplyr, and even within a pipe sequence? If you were to select only certain columns using select(), it would not allow you to save the results back into the dataframe

Something like this would work, but as my dataset has 15+ columns, this seems like its very cumbersome code:

cleandf <- sample %>%
#Use transform or mutate to convert each column manually
transform(rev_app = as.integer(rev_app)) %>%
transform(review_taste = as.integer(review_taste))

Is mutate_at, or mutate_each meant to perform this task? Any help would be appreciated. Thanks.

#Maybe something like this:
cols <- c("2","4")
data %>%
  mutate_each(is.character[cols], as.numeric)

Body:
You can achieve this with the mutate_at function.

sample = data.frame(beer_brewerId = c("8481", "8481", "8481"),
     rev_app = c("4/5","1/5", "2/5"),
     beer_name = c("John Harvards Simcoe IPA", "John Harvards Simcoe IPA", "John Harvards American Brown Ale"),
     review_taste =c("6/10", "7/10", "6/10"), stringsAsFactors = FALSE)

# get rid of "/"
clean <- function(foo) {
         sapply(foo, function(x) eval(parse(text = x)))
         }
# you can replace c(2,4) by whatever columns you need
clean_sample <- sample %>%
                mutate_at(c(2,4), clean)

Columns 2 and 4 are now numeric.


问:
Git: Manually merge changes in an undetected rename
This question uses Git 2.7.0.windows.1, so some of the git commands might be outdated.

If my git merge command doesn't detect a renamed file, how can I tell git to manually merge the changes in two files that are supposed to be a single file, without starting the merge over and using a lower rename threshold?

Reproduction Steps:

```<code>git init
echo "//Hello world!" > hw.h
git add . && git commit -m "Initial commit"
git checkout -b someBranch
mv hw.h hw.hpp
echo "//Foobar" > hw.hpp
git add . && git commit -m "Change hw to HPP & change content"
git checkout master
echo "//Boofar" > hw.h
git add . && git commit -m "Change content of hw"
git merge -X rename-threshold=100% someBranch
</code>```

You will get merge conflicts, but no conflicted chunks. That is, the only conflict/error you should get is:

```<code>CONFLICT (modify/delete): hw.h deleted in branchB and modified in HEAD. Version HEAD of hw.h left in tree.
Automatic merge failed; fix conflicts and then commit the result.
</code>```

And git status --porcelain will show:

```<code>UD hw.h
A  hw.hpp
</code>```

Normally, when merging, it's ideal to set the threshold for detecting renames low enough that renames are detected. Some people recommend 5%, for example. In my case, I'm doing a massive merge (>1000 files and about 9m LOC), and I had to raise the rename threshold high enough to avoid any "false positives"; literally one percent lower and I got a huge swath of falsely-detected renames (I know, duplicated code sucks). At the value I wound up using, I get only a small handful of missed renames, which seems like a better option.

TL;DR lowering the rename threshold is not an option for me; how can I, without starting the merge over, tell git to consider hw.h and hw.hpp to be a single file (with conflicts), rather than two files as shown above?

答:
The tools for this are a bit klunky, but they are there.

You need to be sure that the merge itself stops before committing.  In your case this happens automatically.  For trickier merges, where Git thinks it's doing it correctly but is not, you would add --no-commit, but this then affects the next few steps.  We'll ignore that problem for now.

Next, you need to get all three versions of the file in question.  Since Git stopped with a conflict, we're in good shape: the three versions are all accessible through the index.  Remember that the three versions we care about are merge base, --ours, and --theirs.

If Git had detected the rename correctly, all three versions would be in the index under a single name.  Since it did not, they are not: we need two names.  (With the "Git thinks it did the merge correctly" case, the merge base version of the file is not in the index at all, and we have to retrieve it some other way.)  The two names in your case here are hw.h and hw.hpp, so now we do this:

```<code>$ git show :1:hw.h > hw.h.base    # extract base version
$ git show :2:hw.h > hw.h         # extract ours
$ mv hw.hpp hw.h.theirs           # move theirs into place
</code>```

(The renaming is not strictly necessary, it's just to help keep it all straight and nicely illustrated.)

Now we want to merge the one file with git merge-file:

```<code>$ git merge-file hw.h hw.h.base hw.h.theirs
</code>```

This uses your configured merge.conflictStyle so that what's in the merged file looks just as you would expect, except that the labels on the conflicted lines are a bit different.  I have diff3 set, so I get:

```<code>$ cat hw.h
<<<<<<< hw.h
//Boofar
||||||| hw.h.base
//Hello world!
=======
//Foobar
>>>>>>> hw.h.theirs
</code>```

You can now resolve this as usual, rm the extra .base and .theirs files, git add the final result, git rm --cached hw.hpp, and git commit.  (It's up to you when to git rm --cached hw.hpp: it's safe to do this at any point in time before the commit, but once done you can no longer get "theirs" from the index; see below.)

Note that the "ours" and "theirs" versions are also available through git show HEAD:path and git show MERGE_HEAD:path.  To get at the base version without the index, we would have to run git merge-base HEAD MERGE_HEAD to find its hash ID (and then assume there's a single merge base as well1), and git show <hash>:path.  This is what we must do if Git thinks it has done the merge correctly.

Note also that if you really want to—I imagine this would only be true if you wanted to use some other tool(s) you have, that require it—you can use git update-index to shuffle the entries around in the index, moving hw.hpp into slot-3 of hw.h so that it does show up as "theirs", and shows up that way in git status.  For this particular example:

```<code> $ printf '100644 bbda177a6ecfe285153467ff8fd332de5ecfb2f8 3\thw.h' |
     git update-index --index-info
</code>```

The hash here came from git ls-files --stage and is the hash for hw.hpp.  (You need a second step to remove the hw.hpp index entry.)

1Use git merge-base --all to find all merge bases.  If there is more than one, you can either pick one arbitrarily (this is what -s resolve does), or try to merge all the merge bases into a virtual merge base.  To merge two merge bases, you find their own merge base, and merge two bases as if they are branch tips, using that merge base.  Recurse and iterate as needed—this is what Git does with the default -s recursive strategy—until you have a single merge base version of the file.

Body:
This question uses Git 2.7.0.windows.1, so some of the git commands might be outdated.

If my git merge command doesn't detect a renamed file, how can I tell git to manually merge the changes in two files that are supposed to be a single file, without starting the merge over and using a lower rename threshold?

Reproduction Steps:

git init
echo "//Hello world!" > hw.h
git add . && git commit -m "Initial commit"
git checkout -b someBranch
mv hw.h hw.hpp
echo "//Foobar" > hw.hpp
git add . && git commit -m "Change hw to HPP & change content"
git checkout master
echo "//Boofar" > hw.h
git add . && git commit -m "Change content of hw"
git merge -X rename-threshold=100% someBranch

You will get merge conflicts, but no conflicted chunks. That is, the only conflict/error you should get is:

CONFLICT (modify/delete): hw.h deleted in branchB and modified in HEAD. Version HEAD of hw.h left in tree.
Automatic merge failed; fix conflicts and then commit the result.

And git status --porcelain will show:

UD hw.h
A  hw.hpp

Normally, when merging, it's ideal to set the threshold for detecting renames low enough that renames are detected. Some people recommend 5%, for example. In my case, I'm doing a massive merge (>1000 files and about 9m LOC), and I had to raise the rename threshold high enough to avoid any "false positives"; literally one percent lower and I got a huge swath of falsely-detected renames (I know, duplicated code sucks). At the value I wound up using, I get only a small handful of missed renames, which seems like a better option.

TL;DR lowering the rename threshold is not an option for me; how can I, without starting the merge over, tell git to consider hw.h and hw.hpp to be a single file (with conflicts), rather than two files as shown above?

Body:
The tools for this are a bit klunky, but they are there.

You need to be sure that the merge itself stops before committing.  In your case this happens automatically.  For trickier merges, where Git thinks it's doing it correctly but is not, you would add --no-commit, but this then affects the next few steps.  We'll ignore that problem for now.

Next, you need to get all three versions of the file in question.  Since Git stopped with a conflict, we're in good shape: the three versions are all accessible through the index.  Remember that the three versions we care about are merge base, --ours, and --theirs.

If Git had detected the rename correctly, all three versions would be in the index under a single name.  Since it did not, they are not: we need two names.  (With the "Git thinks it did the merge correctly" case, the merge base version of the file is not in the index at all, and we have to retrieve it some other way.)  The two names in your case here are hw.h and hw.hpp, so now we do this:

$ git show :1:hw.h > hw.h.base    # extract base version
$ git show :2:hw.h > hw.h         # extract ours
$ mv hw.hpp hw.h.theirs           # move theirs into place

(The renaming is not strictly necessary, it's just to help keep it all straight and nicely illustrated.)

Now we want to merge the one file with git merge-file:

$ git merge-file hw.h hw.h.base hw.h.theirs

This uses your configured merge.conflictStyle so that what's in the merged file looks just as you would expect, except that the labels on the conflicted lines are a bit different.  I have diff3 set, so I get:

$ cat hw.h
<<<<<<< hw.h
//Boofar
||||||| hw.h.base
//Hello world!
=======
//Foobar
>>>>>>> hw.h.theirs

You can now resolve this as usual, rm the extra .base and .theirs files, git add the final result, git rm --cached hw.hpp, and git commit.  (It's up to you when to git rm --cached hw.hpp: it's safe to do this at any point in time before the commit, but once done you can no longer get "theirs" from the index; see below.)

Note that the "ours" and "theirs" versions are also available through git show HEAD:path and git show MERGE_HEAD:path.  To get at the base version without the index, we would have to run git merge-base HEAD MERGE_HEAD to find its hash ID (and then assume there's a single merge base as well1), and git show <hash>:path.  This is what we must do if Git thinks it has done the merge correctly.

Note also that if you really want to—I imagine this would only be true if you wanted to use some other tool(s) you have, that require it—you can use git update-index to shuffle the entries around in the index, moving hw.hpp into slot-3 of hw.h so that it does show up as "theirs", and shows up that way in git status.  For this particular example:

 $ printf '100644 bbda177a6ecfe285153467ff8fd332de5ecfb2f8 3\thw.h' |
     git update-index --index-info

The hash here came from git ls-files --stage and is the hash for hw.hpp.  (You need a second step to remove the hw.hpp index entry.)

1Use git merge-base --all to find all merge bases.  If there is more than one, you can either pick one arbitrarily (this is what -s resolve does), or try to merge all the merge bases into a virtual merge base.  To merge two merge bases, you find their own merge base, and merge two bases as if they are branch tips, using that merge base.  Recurse and iterate as needed—this is what Git does with the default -s recursive strategy—until you have a single merge base version of the file.


问:
How can identify strong reference cycles in Swift?
Is there a tool or method to locate strong references cycles in my SWIFT code?

A strong reference cycle is when two instances of classes reference each other without the proper safeties (weak/unowned) hence preventing the garbage collector from disposing of them once all the variables I created stopped referencing those objects.

答:
You can add deinit functions to your classes that will get called when your objects are deallocated.

If deinit isn't getting called, while your app is running, you can press the Debug Memory Graph button (circled below) and inspect what has a reference to what.

Use the dropdown menus at the top of the middle pane to toggle between classes and instances of classes.

If something is getting allocated over and over again without getting released you should see multiple instances, and you should be able to see via the directional graph if one of its children is holding a strong reference to its parent.


问:
Any success stories for JSF, GWT, Wicket or Tapestry on the web?
I am searching for framework references. In other words I am looking for companies, which have successfully implemented a framework solution in java web application environment (success stories). Frameworks I am interested in are JSF, GWT, Wicket and Tapestry. I wasn't able to google any results, nor to find any references at the official sites. At the end I am a bit confused if there are any. Can someone help me out?</p>

答:
Some more webresearches resulted in nice findings:

Wicket: http://web.me.com/jonathan.locke/JonathanLocke/Wicket.html

Tapestry: http://wiki.apache.org/tapestry/PoweredByTapestry and http://wiki.apache.org/tapestry/SuccessStories

JSF: http://wiki.java.net/bin/view/Projects/RealWorldJSFLinks

If you can find anymore, plz let me know :)


问:
Generating new columns as a full-combination of other columns
Could not find similar cases here.
Suppose, i have a DataFrame

```<code>df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})
</code>```

So it is:

```<code>    A   B   C   I   II
0   2   2   3   1   0
1   2   2   3   0   1
2   1   3   3   0   0
3   2   3   4   1   1
</code>```

I want to make a full pairwise combination between {A,B,C} and {I,II}, so i get {I-A,I-B,I-C,II-A,II-B,II-C}:

Each of a new column is just an elementwise multiplication of corresponding base columns

```<code>    I-A I-B I-C II-A  II-B  II-C
 0   2   2   3    0    0      0
 1   0   0   0    2    2      3
 2   0   0   0    0    0      0
 3   2   3   4    2    3      4
</code>```

ATM i dont have any working solution. I'am trying to use loops(not succeding in this), but i hope there's more sufficient way.

答:
It's pretty simple, really. You have two sets of columns that you want to combine pairwise. I won't even bother with permutation tools:

```<code>>>> new_df = pd.DataFrame()
>>>
>>> for i in ["I", "II"]:
        for a in ["A", "B", "C"]:
            new_df[i+"-"+a] = df[i] * df[a]
>>> new_df
   I-A  I-B  I-C  II-A  II-B  II-C
0    2    2    3     0     0     0
1    0    0    0     2     2     3
2    0    0    0     0     0     0
3    2    3    4     2     3     4
</code>```

Of course you could obtain the lists of column names as slices off df.columns, or in whatever other way is convenient. E.g. for your example dataframe you could write

```<code>>>> for i in df.columns[3:]:
        for a in df.columns[:3]:
            new_df[i+"-"+a] = df[i] * df[a]
</code>```

Body:
Could not find similar cases here.
Suppose, i have a DataFrame

df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})

So it is:

    A   B   C   I   II
0   2   2   3   1   0
1   2   2   3   0   1
2   1   3   3   0   0
3   2   3   4   1   1

I want to make a full pairwise combination between {A,B,C} and {I,II}, so i get {I-A,I-B,I-C,II-A,II-B,II-C}:

Each of a new column is just an elementwise multiplication of corresponding base columns

    I-A I-B I-C II-A  II-B  II-C
 0   2   2   3    0    0      0
 1   0   0   0    2    2      3
 2   0   0   0    0    0      0
 3   2   3   4    2    3      4

ATM i dont have any working solution. I'am trying to use loops(not succeding in this), but i hope there's more sufficient way.

Body:
It's pretty simple, really. You have two sets of columns that you want to combine pairwise. I won't even bother with permutation tools:

>>> new_df = pd.DataFrame()
>>>
>>> for i in ["I", "II"]:
        for a in ["A", "B", "C"]:
            new_df[i+"-"+a] = df[i] * df[a]
>>> new_df
   I-A  I-B  I-C  II-A  II-B  II-C
0    2    2    3     0     0     0
1    0    0    0     2     2     3
2    0    0    0     0     0     0
3    2    3    4     2     3     4

Of course you could obtain the lists of column names as slices off df.columns, or in whatever other way is convenient. E.g. for your example dataframe you could write

>>> for i in df.columns[3:]:
        for a in df.columns[:3]:
            new_df[i+"-"+a] = df[i] * df[a]


问:
Is it possible to scrape mails within hotmail using Python?
Can this actually be done? Like checking if my browser is logged in and if so, scraw some of my emails? Or does hotmail prevent you from scraping your mails?</p>

答:
Yes actually very easily.
All you have to do is connect to a POP or IMAP(gmail,hotmail) and then manipulate data however you want.import smtplib
Here's a link documentation  --- Stackoverflow question
 --- POP -email ---  Gmail
You can use regular expressions if you want to find something specific
Python RE-Regular Expressions

I don't know how would you check if you're already logged in, there isn't an obvious way to tell.
Of course it could be done but in some weird manner.


问:
TypeError: unsupported operand type(s) for +=: 'method' and 'int' (Python)
I am making a small game in the console that takes place over several days. The game starts by initializing the miners ore and money amounts as 0. When he mines, my function chooses a random integer between 20 and 71 that will then award him that amount in 'ore'. I am trying to assign the ore that has been mined to my player's ore amount. I am having a reoccurring error that states that += is an unsupported operand for method and int. Full code and trace is below.

Code

```<code>import pyautogui as pag
import time
import sys
import random

class Miner:
    def __init__(self, oreDeposit, moneyDeposit):
        self.oreAmount = oreDeposit
        self.moneyAmount = moneyDeposit

    def oreDeposit(self, oreAmount):
        self.oreDeposit += oreAmount

    def oreWithdraw(self, oreAmount):
        self.oreWithdraw -= oreAmount
# -------------end of ore

    def moneyDeposit(self, moneyAmount):
        self.moneyDeposit += moneyAmount

    def moneyWithdraw(self, moneyAmount):
        self.moneyWithdraw -= moneyAmount
# -------------end of money

    def oreBalance(self):
        return self.oreAmount

    def moneyBalance(self):
        return self.moneyAmount
# -------------end of balances

def miningAction():
    x = random.randint(20, 71)
    for i in range(x):
        time.sleep(0.1)
        print(i)
        oreRecovered = i
        player.oreDeposit(oreRecovered)

player = Miner(0, 0)
miningAction()
print (player.oreAmount)
</code>```

Full traceback

```<code>0
Traceback (most recent call last):
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 41, in <module>
    miningAction()
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 38, in miningAction
    player.oreDeposit(oreRecovered)
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 12, in oreDeposit
    self.oreDeposit += oreAmount
TypeError: unsupported operand type(s) for +=: 'method' and 'int'

Process finished with exit code 1
</code>```

答:
self.moneyDeposit is a reference to the moneyDeposit method and it cannot be incremented by a number (and even if it could, it wouldn't do what you want it to do).

You should change

```<code>def moneyDeposit(self, moneyAmount):
    self.moneyDeposit += moneyAmount

def moneyWithdraw(self, moneyAmount):
    self.moneyWithdraw -= moneyAmount
</code>```

into

```<code>def moneyDeposit(self, moneyAmount):
    self.moneyAmount += moneyAmount

def moneyWithdraw(self, moneyAmount):
    self.moneyAmount -= moneyAmount
</code>```

and similarly for the other methods.

ContentLicense: CC BY-SA 4.0

Body:
I am making a small game in the console that takes place over several days. The game starts by initializing the miners ore and money amounts as 0. When he mines, my function chooses a random integer between 20 and 71 that will then award him that amount in 'ore'. I am trying to assign the ore that has been mined to my player's ore amount. I am having a reoccurring error that states that += is an unsupported operand for method and int. Full code and trace is below.

Code

import pyautogui as pag
import time
import sys
import random

class Miner:
    def __init__(self, oreDeposit, moneyDeposit):
        self.oreAmount = oreDeposit
        self.moneyAmount = moneyDeposit

    def oreDeposit(self, oreAmount):
        self.oreDeposit += oreAmount

    def oreWithdraw(self, oreAmount):
        self.oreWithdraw -= oreAmount
# -------------end of ore

    def moneyDeposit(self, moneyAmount):
        self.moneyDeposit += moneyAmount

    def moneyWithdraw(self, moneyAmount):
        self.moneyWithdraw -= moneyAmount
# -------------end of money

    def oreBalance(self):
        return self.oreAmount

    def moneyBalance(self):
        return self.moneyAmount
# -------------end of balances

def miningAction():
    x = random.randint(20, 71)
    for i in range(x):
        time.sleep(0.1)
        print(i)
        oreRecovered = i
        player.oreDeposit(oreRecovered)

player = Miner(0, 0)
miningAction()
print (player.oreAmount)

Full traceback

0
Traceback (most recent call last):
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 41, in <module>
    miningAction()
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 38, in miningAction
    player.oreDeposit(oreRecovered)
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 12, in oreDeposit
    self.oreDeposit += oreAmount
TypeError: unsupported operand type(s) for +=: 'method' and 'int'

Process finished with exit code 1

Body:
self.moneyDeposit is a reference to the moneyDeposit method and it cannot be incremented by a number (and even if it could, it wouldn't do what you want it to do).

You should change

def moneyDeposit(self, moneyAmount):
    self.moneyDeposit += moneyAmount

def moneyWithdraw(self, moneyAmount):
    self.moneyWithdraw -= moneyAmount

into

def moneyDeposit(self, moneyAmount):
    self.moneyAmount += moneyAmount

def moneyWithdraw(self, moneyAmount):
    self.moneyAmount -= moneyAmount

and similarly for the other methods.


问:
Adding a parameter when naming a variable
I would like to create a dictionary for each Identification number.

The argument passed in could be e.g. {Id, Key, Value}

I want to create a new dictionary by appending the Id to a prefix e.g. Dict

Then I want to write the Key to the dict using dict:store(Key, [Value], oldDict)

The Value at this point is a queue, so I will first read the queue and add to it then write back to the dictionary.

My question is how does the Id get appended to the prefix?

答:
The dict structure in Erlang doesn't allow you to give it a name. And it's probably pointless to have a name in a dict. A dict is a mere key/value dictionary, whose representation is not defined.

If you have multiple dictionaries that you want to refer to, it's probably a good idea to store them in a record or in a tuple, to "name" them. You shouldn't create variable names out of function parameters.

```<code>{my_dict, Dict}

#state{
  my_dict = Dict
}
</code>```

Supposing you need to have the dictionary names as d_mycustomname, you could write something like:

```<code>atomize(Name) ->
  list_to_atom("d_" ++ Name).
</code>```

As the other respondents, I'm not sure this is exactly what you've asked for. Please re-formulate your question to get better answers. My answer at this point is just guess-work driven by alcohol.

AFTER YOUR UPDATE:

Regarding the way you add values to the dictionary, what you want is probably an update and not a store operation.

```<code>enqueue(D, {_Id, Key, Value}) ->
    Update = fun (Old) -> Old ++ [Value] end,
    dict:update(Key, Update, [Value], D).
</code>```

That will append your value to the "queue". If not present yet, it will create one.

Regarding the prefixed names, you may store your dictionaries in a proplist:

```<code>enqueue(ListOfDicts, {Id, Key, Value}) ->
    Name = "dict_" ++ Id,
    case proplists:get_value(Name, ListOfDicts) of
      undefined -> % No such a dict yet
        [{Name, dict:new()}|ListOfDicts];
      D ->
        Update = fun (Old) -> Old ++ [Value] end,
        NewD = dict:update(Key, Update, [Value], D),
        lists:keyreplace(Name, 1, ListOfDicts, {Name, NewD})
    end.
</code>```

I didn't test the code, this is just t give you an idea about what I'm suggesting.

Body:
The dict structure in Erlang doesn't allow you to give it a name. And it's probably pointless to have a name in a dict. A dict is a mere key/value dictionary, whose representation is not defined.

If you have multiple dictionaries that you want to refer to, it's probably a good idea to store them in a record or in a tuple, to "name" them. You shouldn't create variable names out of function parameters.

{my_dict, Dict}

#state{
  my_dict = Dict
}

Supposing you need to have the dictionary names as d_mycustomname, you could write something like:

atomize(Name) ->
  list_to_atom("d_" ++ Name).

As the other respondents, I'm not sure this is exactly what you've asked for. Please re-formulate your question to get better answers. My answer at this point is just guess-work driven by alcohol.

AFTER YOUR UPDATE:

Regarding the way you add values to the dictionary, what you want is probably an update and not a store operation.

enqueue(D, {_Id, Key, Value}) ->
    Update = fun (Old) -> Old ++ [Value] end,
    dict:update(Key, Update, [Value], D).

That will append your value to the "queue". If not present yet, it will create one.

Regarding the prefixed names, you may store your dictionaries in a proplist:

enqueue(ListOfDicts, {Id, Key, Value}) ->
    Name = "dict_" ++ Id,
    case proplists:get_value(Name, ListOfDicts) of
      undefined -> % No such a dict yet
        [{Name, dict:new()}|ListOfDicts];
      D ->
        Update = fun (Old) -> Old ++ [Value] end,
        NewD = dict:update(Key, Update, [Value], D),
        lists:keyreplace(Name, 1, ListOfDicts, {Name, NewD})
    end.

I didn't test the code, this is just t give you an idea about what I'm suggesting.


问:
Finding the max value in an array, however being less than the first number in the array
I need to find out how to find the max value in an array, being less than the first index of the array. So far, I have only found out how to find the maximum value in my array (shown below), but I need help only returning the max value less than the first number in my array from my method.

```<code>public static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {

if (endIndex == startIndex) {

    return numbers[endIndex];

}

else {

    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);   //Calling method using recursion.

    if (max < numbers[endIndex]) {

        return numbers[endIndex];

    }

    else {

        return max;

    }

}
</code>```

}

答: You need two variables, one to store the first index so will have something to compare with and the other to store any value that is less than the first index while you loop through your array. And you keep replacing the second value to any number that is lower than what it currently holds.</p>

Body:
I need to find out how to find the max value in an array, being less than the first index of the array. So far, I have only found out how to find the maximum value in my array (shown below), but I need help only returning the max value less than the first number in my array from my method.

public static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {

if (endIndex == startIndex) {

    return numbers[endIndex];

}

else {

    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);   //Calling method using recursion.

    if (max < numbers[endIndex]) {

        return numbers[endIndex];

    }

    else {

        return max;

    }

}

}


问:
Referencing PowerPoint Object in Excel VBA
Long story short - I am trying to pass a string to PowerPoint from PowerShell to update a textbox on a master slide. I can do this from within PowerPoint vba, but it is completely static. As soon as I try to pass data through PowerShell to PowerPoint, I get an error that I have been unable to solve. (see here)

So instead I am attempting to do it through an Excel proxy! I already use Excel VBA to update content on PowerPoint slides, so thought this would be suitable. I currently have shapes set up in Excel, data is updated, and then this is pasted in to a PowerPoint deck, saved and closed.

I need to now extend this Excel macro with functionality that updates the textbox on the master slide. I need to translate "PowerPoint VBA" to "Excel VBA for PowerPoint", what a horrible sentence... I digress:

PowerPoint VBA

```<code>Function UpdateMasterF(message As Variant)
    Dim sourceLabel As Shape
    Dim curSLD As Long
    curSLD = ActiveWindow.View.Slide.SlideIndex

    'switch to SlideMaster
    Application.Windows(1).ViewType = ppViewSlideMaster

    Set sourceLabel = ActivePresentation.SlideMaster.CustomLayouts(1).Shapes("sourcelabel")
    sourceLabel.TextFrame.TextRange.Text = message

    'return to default
    Application.Windows(1).ViewType = ppViewNormal

    'set slide
    ActiveWindow.Presentation.Slides(curSLD).Select
</code>```

Excel VBA

```<code>Function TestPowerPoint(message As Variant, presPath As Variant)
    Dim oPPTApp As Object
    Dim oPPTFile As Object

    Set oPPTApp = CreateObject("PowerPoint.Application")
    oPPTApp.Visible = msoTrue
    Set oPPTFile = oPPTApp.Presentations.Open(presPath)

    ' translate e.g. ApplicationWindow, ActivePresentation etc

    oPPTFile.Save
    oPPTFile.Close
    Set oPPTFile = Nothing
    oPPTApp.Quit
    Set oPPTApp = Nothing
</code>```

I need to be able to complete the same steps as in the PowerPoint VBA but in the Excel macro. I'm having issues finding the right names for it though. So where it says

```<code>Application.Windows(1).ViewType = ppViewSlideMaster
</code>```

Can this be replaced with oPPTApp or oPPTFile? I've read through MSDN Docs and it seems to match but doesn't work.

Hopefully that's conveyed my ask! I expect most people to read and shudder at such a situation...

答:
The hierarchy's like this:

To access a presentation open in PPT, you'd use e.g.

```<code>Set oPPTPres = oPPTApp.Presentations(1) or
Set oPPTPres = oPPTApp.ActivePresentation
</code>```

Each presentation object has a Designs collection representing the different masters in the presentation, so to access SlideMaster of the first design,

```<code>With oPPTPres.Designs(1).SlideMaster
   ' for example:
   With .Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 500, 50)
      .TextFrame.TextRange.Text = "Well, look at that, will ya!"
   End With

End with
</code>```

Each Design has a collection of custom layouts (the thumbnails you see indented beneath the main master when in Slide Master view).  They can be similarly accessed.

Body:
Long story short - I am trying to pass a string to PowerPoint from PowerShell to update a textbox on a master slide. I can do this from within PowerPoint vba, but it is completely static. As soon as I try to pass data through PowerShell to PowerPoint, I get an error that I have been unable to solve. (see here)

So instead I am attempting to do it through an Excel proxy! I already use Excel VBA to update content on PowerPoint slides, so thought this would be suitable. I currently have shapes set up in Excel, data is updated, and then this is pasted in to a PowerPoint deck, saved and closed.

I need to now extend this Excel macro with functionality that updates the textbox on the master slide. I need to translate "PowerPoint VBA" to "Excel VBA for PowerPoint", what a horrible sentence... I digress:

PowerPoint VBA

Function UpdateMasterF(message As Variant)
    Dim sourceLabel As Shape
    Dim curSLD As Long
    curSLD = ActiveWindow.View.Slide.SlideIndex

    'switch to SlideMaster
    Application.Windows(1).ViewType = ppViewSlideMaster

    Set sourceLabel = ActivePresentation.SlideMaster.CustomLayouts(1).Shapes("sourcelabel")
    sourceLabel.TextFrame.TextRange.Text = message

    'return to default
    Application.Windows(1).ViewType = ppViewNormal

    'set slide
    ActiveWindow.Presentation.Slides(curSLD).Select

Excel VBA

Function TestPowerPoint(message As Variant, presPath As Variant)
    Dim oPPTApp As Object
    Dim oPPTFile As Object

    Set oPPTApp = CreateObject("PowerPoint.Application")
    oPPTApp.Visible = msoTrue
    Set oPPTFile = oPPTApp.Presentations.Open(presPath)

    ' translate e.g. ApplicationWindow, ActivePresentation etc

    oPPTFile.Save
    oPPTFile.Close
    Set oPPTFile = Nothing
    oPPTApp.Quit
    Set oPPTApp = Nothing

I need to be able to complete the same steps as in the PowerPoint VBA but in the Excel macro. I'm having issues finding the right names for it though. So where it says

Application.Windows(1).ViewType = ppViewSlideMaster

Can this be replaced with oPPTApp or oPPTFile? I've read through MSDN Docs and it seems to match but doesn't work.

Hopefully that's conveyed my ask! I expect most people to read and shudder at such a situation...

Body:
The hierarchy's like this:

To access a presentation open in PPT, you'd use e.g.

Set oPPTPres = oPPTApp.Presentations(1) or
Set oPPTPres = oPPTApp.ActivePresentation

Each presentation object has a Designs collection representing the different masters in the presentation, so to access SlideMaster of the first design,

With oPPTPres.Designs(1).SlideMaster
   ' for example:
   With .Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 500, 50)
      .TextFrame.TextRange.Text = "Well, look at that, will ya!"
   End With

End with

Each Design has a collection of custom layouts (the thumbnails you see indented beneath the main master when in Slide Master view).  They can be similarly accessed.


问:
Copy/move semantics documentation of &T/&mut T types itself
I'm looking for the document about copy/move semantics of reference and mutable reference types.

The following code snippet shows immutable references (& T) implement the Copy trait and mutable references (&mut T) do not.

```<code>struct T;
fn copyable<U>(_: U) where U: Copy {}

fn main() {
    let a = &T;
    copyable(a);  // OK

    let b = &mut T;
    copyable(b);
    // error: the trait `core::marker::Copy` is not implemented for the type `&mut T`
}
</code>```

But I can't find the description of this behavior. Someone know some (un)official documents? (or am I wrong?)

答:
As an addition to your code, you can always ask the compiler to tell you if a type can be copied, even without being able to construct that type:

```<code>fn is_this_type_copy<T: Copy>() {}

fn main() {
    is_this_type_copy::<&u8>();
}
</code>```

If a type does not implement Copy, the compiler will produce an error.

You can extend this to ask the question for every reference to a type. Your existing code only shows that an immutable reference to a specific type implements Copy:

```<code>fn is_every_reference_copy<T>() {
    is_this_copy::<&T>()
}
</code>```

Doing the same thing for &mut T:

```<code>fn is_every_mut_reference_copy<T>() {
    is_this_copy::<&mut T>()
}
</code>```

Produces the same error you saw:

error[E0277]: the trait bound `&mut T: std::marker::Copy` is not satisfied
 --> src/main.rs:8:5
  |
8 |     is_this_copy::<&mut T>()
  |     ^^^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `&mut T`
  |
  = note: required by `is_this_copy`
```

We've already seen why &mut T cannot be copied, but why can &T be copied? In a way, that's kind of the entire point of a reference. A reference is a way of cheaply sharing data. Instead of needing to clone (potentially expensively) something to give to multiple things, we can simply give each thing a lightweight reference to the original thing. If references couldn't be copied, they wouldn't have nearly the same amount of value.

Body:
I'm looking for the document about copy/move semantics of reference and mutable reference types.

The following code snippet shows immutable references (& T) implement the Copy trait and mutable references (&mut T) do not.

struct T;
fn copyable(_: U) where U: Copy {}

fn main() {
    let a = &T;
    copyable(a);  // OK

    let b = &mut T;
    copyable(b);
    // error: the trait `core::marker::Copy` is not implemented for the type `&mut T`
}

But I can't find the description of this behavior. Someone know some (un)official documents? (or am I wrong?)

Body:
As an addition to your code, you can always ask the compiler to tell you if a type can be copied, even without being able to construct that type:

fn is_this_type_copy<T: Copy>() {}

fn main() {
    is_this_type_copy::<&u8>();
}

If a type does not implement Copy, the compiler will produce an error.

You can extend this to ask the question for every reference to a type. Your existing code only shows that an immutable reference to a specific type implements Copy:

fn is_every_reference_copy<T>() {
    is_this_copy::<&T>()
}

Doing the same thing for &mut T:

fn is_every_mut_reference_copy<T>() {
    is_this_copy::<&mut T>()
}

Produces the same error you saw:

error[E0277]: the trait bound `&mut T: std::marker::Copy` is not satisfied
 --> src/main.rs:8:5
  |
8 |     is_this_copy::<&mut T>()
  |     ^^^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `&mut T`
  |
  = note: required by `is_this_copy`

We've already seen why &mut T cannot be copied, but why can &T be copied? In a way, that's kind of the entire point of a reference. A reference is a way of cheaply sharing data. Instead of needing to clone (potentially expensively) something to give to multiple things, we can simply give each thing a lightweight reference to the original thing. If references couldn't be copied, they wouldn't have nearly the same amount of value.


问:
how to get the content from external url when that page is fully loaded?
```<code>$data = array();

$html = file_get_html('www.example.com');

foreach($html->find(".bidsTable tr") as $tr){
    $row = array();
    foreach($tr->find("td") as $td){
        /* enter code here */
       $row[] = $td->plaintext;
    }
    $data[] = $row;
}
</code>```

I am using this code to get the content from external url but I do not get the full html code is there any way to get the content when that page is fully loaded.
any help will be appreciated.

答:
You can use cURL to get HTML content,

try like this, It will certainly wait until content is loaded.

```<code>$ch = curl_init("http://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$html = curl_exec($ch);
curl_close($ch);

foreach($html->find(".bidsTable tr") as $tr){
$row = array();
foreach($tr->find("td") as $td){
  /* enter code here */
  $row[] = $td->plaintext;
}
$data[] = $row;
}
</code>```

Body:
$data = array();

$html = file_get_html('www.example.com');

foreach($html->find(".bidsTable tr") as $tr){
    $row = array();
    foreach($tr->find("td") as $td){
        /* enter code here */
       $row[] = $td->plaintext;
    }
    $data[] = $row;
}

I am using this code to get the content from external url but I do not get the full html code is there any way to get the content when that page is fully loaded.
any help will be appreciated.

Body:
You can use cURL to get HTML content,

try like this, It will certainly wait until content is loaded.

$ch = curl_init("http://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$html = curl_exec($ch);
curl_close($ch);

foreach($html->find(".bidsTable tr") as $tr){
$row = array();
foreach($tr->find("td") as $td){
  /* enter code here */
  $row[] = $td->plaintext;
}
$data[] = $row;
}


问:
d3.js animation of a dougnut pie chart
I am working on an application that will be a hybrid pie chart and bubble chart -

here is a working animation for a simple doughnut pie chart.

http://jsfiddle.net/Qh9X5/8817/

```<code>var svg = d3.select("body")
    .append("svg")
    .append("g")

svg.append("g")
    .attr("class", "slices");
svg.append("g")
    .attr("class", "labels");
svg.append("g")
    .attr("class", "lines");

var width = 560,
    height = 450,
    radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) {
        return d.value;
    });

var arc = d3.svg.arc()
    .outerRadius(radius * 0.85)
    .innerRadius(radius * 0.83);

var outerArc = d3.svg.arc()
    .innerRadius(radius * 0.9)
    .outerRadius(radius * 0.9);

svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var key = function(d){ return d.data.label; };

var color = d3.scale.ordinal()
    .domain(["Lorem ipsum", "dolor sit", "amet", "consectetur", "adipisicing"])
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]);

function randomData (){
    var labels = color.domain();
    return labels.map(function(label){
        return { label: label, value: Math.random() }
    });
}

console.log("randomData()", randomData());
change(randomData());

d3.select(".randomize")
    .on("click", function(){
        change(randomData());
    });

function change(data) {

    /* ------- PIE SLICES -------*/
    var slice = svg.select(".slices").selectAll("path.slice")
        .data(pie(data), key);

    slice.enter()
        .insert("path")
        .style("fill", function(d) { return color(d.data.label); })
        .attr("class", "slice");

    slice
        .transition().duration(1000)
        .attrTween("d", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                return arc(interpolate(t));
            };
        })

    slice.exit()
        .remove();

};
</code>```

http://jsfiddle.net/NYEaX/1487/
This is a static doughnut chart -- where I have calculated the mid-arcs -- but have lost the animation. So with the above sample of code -- where is it possible to obtain the arc.centroid(d)?

```<code>var width = 960,
    height = 500,
    radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var arc = d3.svg.arc()
    .outerRadius(radius - 60)
    .innerRadius(radius - 70);

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.value; });

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

  var data = [
    {
      "group": "<5",
      "value": 1000,
      "children": [
        {
          "group": "<5",
          "label": "Mel",
          "value": 1000,
          "totalGroupValue": 1000
        }
      ]
    },
    {
      "group": "5-13",
      "value": 1000,
      "children": [
        {
          "group": "5-13",
          "label": "Erica",
          "value": 1000,
          "totalGroupValue": 1000
        }
      ]
    },
    {
      "group": "14-17",
      "value": 2000,
      "children": [
        {
          "group": "14-17",
          "label": "Jessica",
          "value": 1500,
          "totalGroupValue": 2000
        },
        {
          "group": "14-17",
          "label": "Jill",
          "value": 500,
          "totalGroupValue": 2000
        }
      ]
    },
    {
      "group": "18-24",
      "value": 1300,
      "children": [
        {
          "group": "18-24",
          "label": "Jerry",
          "value": 500,
          "totalGroupValue": 1300
        },
        {
          "group": "18-24",
          "label": "Ben",
          "value": 500,
          "totalGroupValue": 1300
        },
        {
          "group": "18-24",
          "label": "Billy",
          "value": 300,
          "totalGroupValue": 1300
        }
      ]
    },
    {
      "group": "25-44",
      "value": 1000,
      "children": [
        {
          "group": "25-44",
          "label": "Kelly",
          "value": 1000,
          "totalGroupValue": 1000
        }
      ]
    }
  ];

  var g = svg.selectAll(".arc")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arc");

  g.append("path")
      .attr("d", arc)
      .style("fill", function(d) {
        return color(d.data.group);
      });

  arc
    .outerRadius(radius - 10)
    .innerRadius(0);

//create zone regions

var zones = [];
g.append("circle")
  .attr("transform", function(d) {
        zones[d.data.group] = arc.centroid(d);
    return "translate(" + arc.centroid(d) + ")";
  })
  .attr("r", "1px")
  .style("fill", function(d) {
    return "black"//color(d.data.group);
  });

 g.append("g")
    .attr("class", function(d,i) {
    console.log("d", d)
    return "bubble"+i;//color(d.data.group);
  })
  .attr("transform", function(d) {
        zones[d.data.group] = arc.centroid(d);
    return "translate(" + arc.centroid(d) + ")";
  })
  .attr("r", "1px")
  .style("fill", function(d) {
    return "black"//color(d.data.group);
  });

//create zone regions

//custom bubble chart
function makeBubbles(transform, group, radius){
    g.append("circle")
    .attr("transform", function(d) {
      return "translate("+transform+")";
    })
    .attr("r", radius)
    .style("stroke", function(d) {
      return "black";//color(group);
    })
    .style("fill", function(d) {
      return color(group);
    });
}

            function bubbledata(data){
      console.log("data", data)
                //loop through data -- and MERGE children
                var childs = [];
                $.each(data, function( index, value ) {
                    childs.push(value.children);
                });
                var merged = data;//[].concat.apply([], childs);//flatterns multidimensional array

                return $.extend(true, {}, {"children": merged});// return deep clone
            }

function setBubbleChart(width, index, data){

                  //_create bubble
                    var diameter = width/2;//take half/width

                    var bubs = svg.select(".bubble"+index).append("g")
                            .attr("class", "bubs");

                    bubs.attr("transform", "translate("+-diameter/2+","+-diameter/2+")");

                    var bubble = d3.layout.pack()
                      .size([diameter, diameter])
                      .value(function(d) {
                        return d.value;
                      })
                      .padding(3);

                  //_create bubble
          var data = bubbledata(data);

                        var nodes = bubble.nodes(data)
                          .filter(function(d) {
                             return !d.children;
                          }); // filter out the outer bubble

                        var bubbles = bubs.selectAll('circle')
                          .data(nodes);

                bubbles.enter()
                    .insert("circle")
                    .attr('transform', function (d) {
                        return 'translate(' + d.x + ',' + d.y + ')';
                    })
                    .attr('r', function (d) {
                        return d.r;
                    })
                    .style("fill", function (d) {
return color(d.group);
                    });

                bubbles = bubbles.transition()
                    .transition()
                    .duration(250)
                    .attr('transform', function(d) {
                        return 'translate(' + d.x + ',' + d.y + ')';
                    })
                    .attr('r', function (d) {
                        return d.r;
                    })
                    .ease('sine');

}

//loop through data and for EACH children array paint dots.
$.each(data, function( index, value ) {
setBubbleChart(100, index, value.children);

});
//custom bubble chart

function type(d) {
  d.value = +d.value;
  return d;
}
</code>```

答:
I've plotted the mid-arcs - but they are not being updated on a change of data?

http://jsfiddle.net/Qh9X5/10066/

```<code>function change(data) {

  var slice = svg.select(".slices").selectAll("path.slice")
    .data(pie(data), key);

  slice.enter()
    .insert("path")
    .style("fill", function(d) {
      return color(d.data.label);
    })
    .attr("class", "slice");

  slice
    .transition().duration(1000)
    .attrTween("d", function(d) {
      this._current = this._current || d;
      var interpolate = d3.interpolate(this._current, d);
      this._current = interpolate(0);
      return function(t) {
        return arc(interpolate(t));
      };
    })

  slice.exit()
    .remove();

  var placeholders = svg.select(".placeholders").selectAll("circle.placeholder")
    .data(pie(data), key);

  placeholders.enter()
    .insert("circle")
    .style("fill", function(d) {
      return "white";
      //return color(d.data.label);
    })
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("r", "5")
    .attr("class", "placeholder");

  placeholders
    .transition().duration(1000)

  placeholders.exit()
    .remove();

};
</code>```

I've managed to create an arc2 -- and animate the placeholders.

http://jsfiddle.net/Qh9X5/10068/

```<code>var svg = d3.select("#pies")
  .append("svg")
  .append("g")

svg.append("g")
  .attr("class", "slices");
svg.append("g")
  .attr("class", "placeholders");
svg.append("g")
  .attr("class", "labels");
svg.append("g")
  .attr("class", "lines");

var width = 560,
  height = 450,
  radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
  .sort(null)
  .value(function(d) {
    return d.value;
  });

var arc = d3.svg.arc()
  .outerRadius(radius * 0.85)
  .innerRadius(radius * 0.83);

var arc2 = d3.svg.arc()
    .outerRadius(radius - 10)
    .innerRadius(0);

var outerArc = d3.svg.arc()
  .innerRadius(radius * 0.9)
  .outerRadius(radius * 0.9);

svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var key = function(d) {
  return d.data.label;
};

var color = d3.scale.ordinal()
  .domain(["Lorem ipsum", "dolor sit", "amet", "consectetur", "adipisicing"])
  .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]);

function randomData() {
  var labels = color.domain();
  return labels.map(function(label) {
    return {
      label: label,
      value: Math.random()
    }
  });
}

console.log("randomData()", randomData());
change(randomData());

d3.select(".randomize")
  .on("click", function() {
    change(randomData());
  });

function change(data) {

  var slice = svg.select(".slices").selectAll("path.slice")
    .data(pie(data), key);

  slice.enter()
    .insert("path")
    .style("fill", function(d) {
      return color(d.data.label);
    })
    .attr("class", "slice");

  slice
    .transition().duration(1000)
    .attrTween("d", function(d) {
      this._current = this._current || d;
      var interpolate = d3.interpolate(this._current, d);
      this._current = interpolate(0);
      return function(t) {
        return arc(interpolate(t));
      };
    })

  slice.exit()
    .remove();

  var placeholders = svg.select(".placeholders").selectAll("circle.placeholder")
    .data(pie(data), key);

  placeholders.enter()
    .insert("circle")
    .style("fill", function(d) {
      return "white";
    })
    .attr("r", "5")
    .attr("class", "placeholder");

  placeholders
    .transition().duration(1000)
    .attr("transform", function(d) {
        console.log("arc.centroid(d)", arc2.centroid(d))
      return "translate(" + arc2.centroid(d) + ")";
    })

  placeholders.exit()
    .remove();

};
</code>```

http://jsfiddle.net/Qh9X5/10075/

I have managed to merge the pie chart with the bubble chart -- if the data sets change - the animations should be stable.

```<code>var svg = d3.select("#pies")
  .append("svg")
  .append("g")

svg.append("g")
  .attr("class", "slices");
svg.append("g")
  .attr("class", "placeholders");

var width = 560,
  height = 450,
  radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
  .sort(null)
  .value(function(d) {
    return d.value;
  });

var arc = d3.svg.arc()
  .outerRadius(radius * 0.85)
  .innerRadius(radius * 0.83);

var arc2 = d3.svg.arc()
  .outerRadius(radius - 10)
  .innerRadius(0);

var outerArc = d3.svg.arc()
  .innerRadius(radius * 0.9)
  .outerRadius(radius * 0.9);

svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

function colores_google(n) {
  var colores_g = ["#f7b363", "#448875", "#c12f39", "#2b2d39", "#f8dd2f"];
  return colores_g[n % colores_g.length];
}

var data = [{
  "group": "<5",
  "value": 1000,
  "children": [{
    "group": "<5",
    "label": "Mel",
    "value": 1000,
    "totalGroupValue": 1000
  }]
}, {
  "group": "5-13",
  "value": 1000,
  "children": [{
    "group": "5-13",
    "label": "Erica",
    "value": 1000,
    "totalGroupValue": 1000
  }]
}, {
  "group": "14-17",
  "value": 2000,
  "children": [{
    "group": "14-17",
    "label": "Jessica",
    "value": 1500,
    "totalGroupValue": 2000
  }, {
    "group": "14-17",
    "label": "Jill",
    "value": 500,
    "totalGroupValue": 2000
  }]
}, {
  "group": "18-24",
  "value": 1300,
  "children": [{
    "group": "18-24",
    "label": "Jerry",
    "value": 500,
    "totalGroupValue": 1300
  }, {
    "group": "18-24",
    "label": "Ben",
    "value": 500,
    "totalGroupValue": 1300
  }, {
    "group": "18-24",
    "label": "Billy",
    "value": 300,
    "totalGroupValue": 1300
  }]
}, {
  "group": "25-44",
  "value": 1000,
  "children": [{
    "group": "25-44",
    "label": "Kelly",
    "value": 1000,
    "totalGroupValue": 1000
  }]
}];

$.each(data, function(index, value) {
  value["groupid"] = index;
  $.each(value.children, function(i, v) {
    v["groupid"] = index;
  });
});

//slices
var slice = svg.select(".slices").selectAll("path.slice")
  .data(pie(data));

slice.enter()
  .insert("path")
  .style("fill", function(d) {
    return colores_google(d.data.groupid);
  })
  .attr("class", "slice");

slice
  .transition().duration(1000)
  .attrTween("d", function(d) {
    this._current = this._current || d;
    var interpolate = d3.interpolate(this._current, d);
    this._current = interpolate(0);
    return function(t) {
      return arc(interpolate(t));
    };
  })

slice.exit()
  .remove();
//slices

//placeholder bubbles
var placeholders = svg.select(".placeholders").selectAll("g.placeholder")
  .data(pie(data));

placeholders.enter()
  .insert("g")
  .attr("class", function(d, i) {
    return "placeholder place" + i;
  });

placeholders
  .transition().duration(1000)
  .attr("transform", function(d) {
    return "translate(" + arc2.centroid(d) + ")";
  })

placeholders.exit()
  .remove();
//placeholder bubbles

//bubbles
function bubbledata(data) {
  //loop through data -- and MERGE children
  var childs = [];
  $.each(data, function(index, value) {
    childs.push(value.children);
  });

  return $.extend(true, {}, {
    "children": data
  }); // return deep clone
}

function setBubbleChart(width, index, data) {

  //_create bubble
  var diameter = width / 2; //take half/width

  var bubs = svg.select(".place" + index).append("g")
    .attr("class", "bubs");

  bubs.attr("transform", "translate(" + -diameter / 2 + "," + -diameter / 2 + ")");

  var bubble = d3.layout.pack()
    .size([diameter, diameter])
    .value(function(d) {
      return d.value;
    })
    .padding(3);

  //_create bubble
  var data = bubbledata(data);

  var nodes = bubble.nodes(data)
    .filter(function(d) {
      return !d.children;
    }); // filter out the outer bubble

  var bubbles = bubs.selectAll('circle')
    .data(nodes);

  bubbles.enter()
    .insert("circle")
    .attr('transform', function(d) {
      return 'translate(' + d.x + ',' + d.y + ')';
    })
    .attr('r', function(d) {
      return d.r;
    })
    .style("fill", function(d) {
      return colores_google(d.groupid);
    });

  bubbles = bubbles.transition()
    .transition()
    .duration(250)
    .attr('transform', function(d) {
      return 'translate(' + d.x + ',' + d.y + ')';
    })
    .attr('r', function(d) {
      return d.r;
    })
    .ease('sine');

}

//loop through data and for EACH children array paint dots.
$.each(data, function(index, value) {
  setBubbleChart(100, index, value.children);
});
//custom bubble chart
</code>```

Title: d3.js animation of a dougnut pie chart

Body:
I am working on an application that will be a hybrid pie chart and bubble chart -

here is a working animation for a simple doughnut pie chart.

http://jsfiddle.net/Qh9X5/8817/

var svg = d3.select("body")
    .append("svg")
    .append("g")

svg.append("g")
    .attr("class", "slices");
svg.append("g")
    .attr("class", "labels");
svg.append("g")
    .attr("class", "lines");

var width = 560,
    height = 450,
    radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) {
        return d.value;
    });

var arc = d3.svg.arc()
    .outerRadius(radius * 0.85)
    .innerRadius(radius * 0.83);

var outerArc = d3.svg.arc()
    .innerRadius(radius * 0.9)
    .outerRadius(radius * 0.9);

svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var key = function(d){ return d.data.label; };

var color = d3.scale.ordinal()
    .domain(["Lorem ipsum", "dolor sit", "amet", "consectetur", "adipisicing"])
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]);

function randomData (){
    var labels = color.domain();
    return labels.map(function(label){
        return { label: label, value: Math.random() }
    });
}

console.log("randomData()", randomData());
change(randomData());

d3.select(".randomize")
    .on("click", function(){
        change(randomData());
    });

function change(data) {

    /* ------- PIE SLICES -------*/
    var slice = svg.select(".slices").selectAll("path.slice")
        .data(pie(data), key);

    slice.enter()
        .insert("path")
        .style("fill", function(d) { return color(d.data.label); })
        .attr("class", "slice");

    slice
        .transition().duration(1000)
        .attrTween("d", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                return arc(interpolate(t));
            };
        })

    slice.exit()
        .remove();

};

http://jsfiddle.net/NYEaX/1487/
This is a static doughnut chart -- where I have calculated the mid-arcs -- but have lost the animation. So with the above sample of code -- where is it possible to obtain the arc.centroid(d)?

var width = 960,
    height = 500,
    radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var arc = d3.svg.arc()
    .outerRadius(radius - 60)
    .innerRadius(radius - 70);

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.value; });

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

  var data = [
    {
      "group": "<5",
      "value": 1000,
      "children": [
        {
          "group": "<5",
          "label": "Mel",
          "value": 1000,
          "totalGroupValue": 1000
        }
      ]
    },
    {
      "group": "5-13",
      "value": 1000,
      "children": [
        {
          "group": "5-13",
          "label": "Erica",
          "value": 1000,
          "totalGroupValue": 1000
        }
      ]
    },
    {
      "group": "14-17",
      "value": 2000,
      "children": [
        {
          "group": "14-17",
          "label": "Jessica",
          "value": 1500,
          "totalGroupValue": 2000
        },
        {
          "group": "14-17",
          "label": "Jill",
          "value": 500,
          "totalGroupValue": 2000
        }
      ]
    },
    {
      "group": "18-24",
      "value": 1300,
      "children": [
        {
          "group": "18-24",
          "label": "Jerry",
          "value": 500,
          "totalGroupValue": 1300
        },
        {
          "group": "18-24",
          "label": "Ben",
          "value": 500,
          "totalGroupValue": 1300
        },
        {
          "group": "18-24",
          "label": "Billy",
          "value": 300,
          "totalGroupValue": 1300
        }
      ]
    },
    {
      "group": "25-44",
      "value": 1000,
      "children": [
        {
          "group": "25-44",
          "label": "Kelly",
          "value": 1000,
          "totalGroupValue": 1000
        }
      ]
    }
  ];

  var g = svg.selectAll(".arc")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arc");

  g.append("path")
      .attr("d", arc)
      .style("fill", function(d) {
        return color(d.data.group);
      });

  arc
    .outerRadius(radius - 10)
    .innerRadius(0);

//create zone regions

var zones = [];
g.append("circle")
  .attr("transform", function(d) {
        zones[d.data.group] = arc.centroid(d);
    return "translate(" + arc.centroid(d) + ")";
  })
  .attr("r", "1px")
  .style("fill", function(d) {
    return "black"//color(d.data.group);
  });

 g.append("g")
    .attr("class", function(d,i) {
    console.log("d", d)
    return "bubble"+i;//color(d.data.group);
  })
  .attr("transform", function(d) {
        zones[d.data.group] = arc.centroid(d);
    return "translate(" + arc.centroid(d) + ")";
  })
  .attr("r", "1px")
  .style("fill", function(d) {
    return "black"//color(d.data.group);
  });

//create zone regions

//custom bubble chart
function makeBubbles(transform, group, radius){
    g.append("circle")
    .attr("transform", function(d) {
      return "translate("+transform+")";
    })
    .attr("r", radius)
    .style("stroke", function(d) {
      return "black";//color(group);
    })
    .style("fill", function(d) {
      return color(group);
    });
}

            function bubbledata(data){
      console.log("data", data)
                //loop through data -- and MERGE children
                var childs = [];
                $.each(data, function( index, value ) {
                    childs.push(value.children);
                });
                var merged = data;//[].concat.apply([], childs);//flatterns multidimensional array

                return $.extend(true, {}, {"children": merged});// return deep clone
            }

function setBubbleChart(width, index, data){

                  //_create bubble
                    var diameter = width/2;//take half/width

                    var bubs = svg.select(".bubble"+index).append("g")
                            .attr("class", "bubs");

                    bubs.attr("transform", "translate("+-diameter/2+","+-diameter/2+")");

                    var bubble = d3.layout.pack()
                      .size([diameter, diameter])
                      .value(function(d) {
                        return d.value;
                      })
                      .padding(3);

                  //_create bubble
          var data = bubbledata(data);

                        var nodes = bubble.nodes(data)
                          .filter(function(d) {
                             return !d.children;
                          }); // filter out the outer bubble

                        var bubbles = bubs.selectAll('circle')
                          .data(nodes);

                bubbles.enter()
                    .insert("circle")
                    .attr('transform', function (d) {
                        return 'translate(' + d.x + ',' + d.y + ')';
                    })
                    .attr('r', function (d) {
                        return d.r;
                    })
                    .style("fill", function (d) {
return color(d.group);
                    });

                bubbles = bubbles.transition()
                    .transition()
                    .duration(250)
                    .attr('transform', function(d) {
                        return 'translate(' + d.x + ',' + d.y + ')';
                    })
                    .attr('r', function (d) {
                        return d.r;
                    })
                    .ease('sine');

}

//loop through data and for EACH children array paint dots.
$.each(data, function( index, value ) {
setBubbleChart(100, index, value.children);

});
//custom bubble chart

function type(d) {
  d.value = +d.value;
  return d;
}

Body:
I've plotted the mid-arcs - but they are not being updated on a change of data?

http://jsfiddle.net/Qh9X5/10066/

function change(data) {

  var slice = svg.select(".slices").selectAll("path.slice")
    .data(pie(data), key);

  slice.enter()
    .insert("path")
    .style("fill", function(d) {
      return color(d.data.label);
    })
    .attr("class", "slice");

  slice
    .transition().duration(1000)
    .attrTween("d", function(d) {
      this._current = this._current || d;
      var interpolate = d3.interpolate(this._current, d);
      this._current = interpolate(0);
      return function(t) {
        return arc(interpolate(t));
      };
    })

  slice.exit()
    .remove();

  var placeholders = svg.select(".placeholders").selectAll("circle.placeholder")
    .data(pie(data), key);

  placeholders.enter()
    .insert("circle")
    .style("fill", function(d) {
      return "white";
      //return color(d.data.label);
    })
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("r", "5")
    .attr("class", "placeholder");

  placeholders
    .transition().duration(1000)

  placeholders.exit()
    .remove();

};

I've managed to create an arc2 -- and animate the placeholders.

http://jsfiddle.net/Qh9X5/10068/

var svg = d3.select("#pies")
  .append("svg")
  .append("g")

svg.append("g")
  .attr("class", "slices");
svg.append("g")
  .attr("class", "placeholders");
svg.append("g")
  .attr("class", "labels");
svg.append("g")
  .attr("class", "lines");

var width = 560,
  height = 450,
  radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
  .sort(null)
  .value(function(d) {
    return d.value;
  });

var arc = d3.svg.arc()
  .outerRadius(radius * 0.85)
  .innerRadius(radius * 0.83);

var arc2 = d3.svg.arc()
    .outerRadius(radius - 10)
    .innerRadius(0);

var outerArc = d3.svg.arc()
  .innerRadius(radius * 0.9)
  .outerRadius(radius * 0.9);

svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var key = function(d) {
  return d.data.label;
};

var color = d3.scale.ordinal()
  .domain(["Lorem ipsum", "dolor sit", "amet", "consectetur", "adipisicing"])
  .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]);

function randomData() {
  var labels = color.domain();
  return labels.map(function(label) {
    return {
      label: label,
      value: Math.random()
    }
  });
}

console.log("randomData()", randomData());
change(randomData());

d3.select(".randomize")
  .on("click", function() {
    change(randomData());
  });

function change(data) {

  var slice = svg.select(".slices").selectAll("path.slice")
    .data(pie(data), key);

  slice.enter()
    .insert("path")
    .style("fill", function(d) {
      return color(d.data.label);
    })
    .attr("class", "slice");

  slice
    .transition().duration(1000)
    .attrTween("d", function(d) {
      this._current = this._current || d;
      var interpolate = d3.interpolate(this._current, d);
      this._current = interpolate(0);
      return function(t) {
        return arc(interpolate(t));
      };
    })

  slice.exit()
    .remove();

  var placeholders = svg.select(".placeholders").selectAll("circle.placeholder")
    .data(pie(data), key);

  placeholders.enter()
    .insert("circle")
    .style("fill", function(d) {
      return "white";
    })
    .attr("r", "5")
    .attr("class", "placeholder");

  placeholders
    .transition().duration(1000)
    .attr("transform", function(d) {
        console.log("arc.centroid(d)", arc2.centroid(d))
      return "translate(" + arc2.centroid(d) + ")";
    })

  placeholders.exit()
    .remove();

};

http://jsfiddle.net/Qh9X5/10075/

I have managed to merge the pie chart with the bubble chart -- if the data sets change - the animations should be stable.

var svg = d3.select("#pies")
  .append("svg")
  .append("g")

svg.append("g")
  .attr("class", "slices");
svg.append("g")
  .attr("class", "placeholders");

var width = 560,
  height = 450,
  radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
  .sort(null)
  .value(function(d) {
    return d.value;
  });

var arc = d3.svg.arc()
  .outerRadius(radius * 0.85)
  .innerRadius(radius * 0.83);

var arc2 = d3.svg.arc()
  .outerRadius(radius - 10)
  .innerRadius(0);

var outerArc = d3.svg.arc()
  .innerRadius(radius * 0.9)
  .outerRadius(radius * 0.9);

svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

function colores_google(n) {
  var colores_g = ["#f7b363", "#448875", "#c12f39", "#2b2d39", "#f8dd2f"];
  return colores_g[n % colores_g.length];
}

var data = [{
  "group": "<5",
  "value": 1000,
  "children": [{
    "group": "<5",
    "label": "Mel",
    "value": 1000,
    "totalGroupValue": 1000
  }]
}, {
  "group": "5-13",
  "value": 1000,
  "children": [{
    "group": "5-13",
    "label": "Erica",
    "value": 1000,
    "totalGroupValue": 1000
  }]
}, {
  "group": "14-17",
  "value": 2000,
  "children": [{
    "group": "14-17",
    "label": "Jessica",
    "value": 1500,
    "totalGroupValue": 2000
  }, {
    "group": "14-17",
    "label": "Jill",
    "value": 500,
    "totalGroupValue": 2000
  }]
}, {
  "group": "18-24",
  "value": 1300,
  "children": [{
    "group": "18-24",
    "label": "Jerry",
    "value": 500,
    "totalGroupValue": 1300
  }, {
    "group": "18-24",
    "label": "Ben",
    "value": 500,
    "totalGroupValue": 1300
  }, {
    "group": "18-24",
    "label": "Billy",
    "value": 300,
    "totalGroupValue": 1300
  }]
}, {
  "group": "25-44",
  "value": 1000,
  "children": [{
    "group": "25-44",
    "label": "Kelly",
    "value": 1000,
    "totalGroupValue": 1000
  }]
}];

$.each(data, function(index, value) {
  value["groupid"] = index;
  $.each(value.children, function(i, v) {
    v["groupid"] = index;
  });
});

//slices
var slice = svg.select(".slices").selectAll("path.slice")
  .data(pie(data));

slice.enter()
  .insert("path")
  .style("fill", function(d) {
    return colores_google(d.data.groupid);
  })
  .attr("class", "slice");

slice
  .transition().duration(1000)
  .attrTween("d", function(d) {
    this._current = this._current || d;
    var interpolate = d3.interpolate(this._current, d);
    this._current = interpolate(0);
    return function(t) {
      return arc(interpolate(t));
    };
  })

slice.exit()
  .remove();
//slices

//placeholder bubbles
var placeholders = svg.select(".placeholders").selectAll("g.placeholder")
  .data(pie(data));

placeholders.enter()
  .insert("g")
  .attr("class", function(d, i) {
    return "placeholder place" + i;
  });

placeholders
  .transition().duration(1000)
  .attr("transform", function(d) {
    return "translate(" + arc2.centroid(d) + ")";
  })

placeholders.exit()
  .remove();
//placeholder bubbles

//bubbles
function bubbledata(data) {
  //loop through data -- and MERGE children
  var childs = [];
  $.each(data, function(index, value) {
    childs.push(value.children);
  });

  return $.extend(true, {}, {
    "children": data
  }); // return deep clone
}

function setBubbleChart(width, index, data) {

  //_create bubble
  var diameter = width / 2; //take half/width

  var bubs = svg.select(".place" + index).append("g")
    .attr("class", "bubs");

  bubs.attr("transform", "translate(" + -diameter / 2 + "," + -diameter / 2 + ")");

  var bubble = d3.layout.pack()
    .size([diameter, diameter])
    .value(function(d) {
      return d.value;
    })
    .padding(3);

  //_create bubble
  var data = bubbledata(data);

  var nodes = bubble.nodes(data)
    .filter(function(d) {
      return !d.children;
    }); // filter out the outer bubble

  var bubbles = bubs.selectAll('circle')
    .data(nodes);

  bubbles.enter()
    .insert("circle")
    .attr('transform', function(d) {
      return 'translate(' + d.x + ',' + d.y + ')';
    })
    .attr('r', function(d) {
      return d.r;
    })
    .style("fill", function(d) {
      return colores_google(d.groupid);
    });

  bubbles = bubbles.transition()
    .transition()
    .duration(250)
    .attr('transform', function(d) {
      return 'translate(' + d.x + ',' + d.y + ')';
    })
    .attr('r', function(d) {
      return d.r;
    })
    .ease('sine');

}

//loop through data and for EACH children array paint dots.
$.each(data, function(index, value) {
  setBubbleChart(100, index, value.children);
});
//custom bubble chart


问:
Outlook 2016 VML width issue
This is first question so please be gentle :-)

I am in charge of creating surveys which is sent as an email invite to users.  Recently I created a 10 point scale for users on an email where they click on a number of their choice and it takes them to the survey.

Problem:
The VML i have placed for outlooks is causing issues. Below is the screenshot of how it looks. The scale starts at 0 and is supposed to end at 10 but Outlook 2016 is showing only 1 rather than 10.

What i have tried:

I tested this email through Litmus and it showed everything properly

I tried to increase the width of the table in VML to see if it fixes it but it didn't work.

I have outlook 2016 (Office 365) and i don't see this issue.

Code snippet for the whole table:

0

1

2

3

4

5

6

7

8

9

10

```

Has anyone encountered this issue and have found a fix?

Looking forward to your replies/comments.

Cheers

答:
First of all the screenshot provided doesn't correspond to the code snippet you have provided. Some styles from your "grey" table are overwrites the styles of the elements of the table, snippet of which you have provided. This is exactly why you cannot find your mistake ... you are looking at the part of the whole picture and surprise yourself why it works in Litmus (I even don't know what is this) and doesn't under Outlook. But, let's get to the point of the question.

Has anyone encountered this issue and have found a fix?

I inserted your code from snippet into the HTML body of my test message and it was looking fine as you mention it. All numbers were displayed properly (on the white background through as you provided just the part of HTML).

Next I set for one of the cell the number with more digits (4 digits "1056") than you expect (you are expecting a maximum of 2 digits). The code (part of it) I have inserted this time was ...

```<code><td width="9%" align="center" valign="top" class="selectors">
<!-- answer for Q10 -->
<!--[if mso]>
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="10" style="height:40px;v-text-anchor:middle;width:45px; text-align:center;" arcsize="10%" strokecolor="#ec00Bc"  fillcolor="#ec00Bc" onmouseover='this.fillcolor="#0088cc"'>
<w:anchorlock/>
<center style="color:#ffffff;font-family:sans-serif;font-size:16px;font-weight:bold;">
1056
</center>
</v:roundrect>
<![endif]-->

<!--[if !mso]><!-->
<a href="10" target="_blank" class="button_link" style="width:90%;padding:8px 0px;display: inline-block;text-decoration: none;border:0;text-align: center;font-weight: bold;font-size: 15px;font-family: sans-serif;color: #ffffff;background: #ec00Bc;border: 1px solid #ec00Bc;-moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;line-height:17px;">
10
</a>
<!--><![endif]-->

</td>
</code>```

The result as I expected looks like ...

You already noticed the digits don't fit the width of the cell and wrap underneath. This is exactly what's happening with your "10" becoming "1": the digit "0" doesn't fit into the cell of the screenshot provided and wraps under. You don't see it because of some style from the parent table you didn't provide code for.

And finally how to fix it ... As long as I increase width of the cell (to 90px in my case):

```<code><v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word' href='10' style='height:40px;v-text-anchor:middle;width:90px; text-align:center;' arcsize='10%' strokecolor='#ec00Bc'  fillcolor='#ec00Bc'>
</code>```

I able to see entire number in one line again ...

You need to make sure the width of each cell has enough width to fit 2 digits and not overridden by the styles from parent elements.

Title: Outlook 2016 VML width issue

Body:
This is first question so please be gentle :-)

I am in charge of creating surveys which is sent as an email invite to users.  Recently I created a 10 point scale for users on an email where they click on a number of their choice and it takes them to the survey.

Problem:
The VML i have placed for outlooks is causing issues. Below is the screenshot of how it looks. The scale starts at 0 and is supposed to end at 10 but Outlook 2016 is showing only 1 rather than 10.

What i have tried:

I tested this email through Litmus and it showed everything properly

I tried to increase the width of the table in VML to see if it fixes it but it didn't work.

I have outlook 2016 (Office 365) and i don't see this issue.

Code snippet for the whole table:

0

1

2

3

4

5

6

7

8

9

10

Has anyone encountered this issue and have found a fix?

Looking forward to your replies/comments.

Cheers

Body:
First of all the screenshot provided doesn't correspond to the code snippet you have provided. Some styles from your "grey" table are overwrites the styles of the elements of the table, snippet of which you have provided. This is exactly why you cannot find your mistake ... you are looking at the part of the whole picture and surprise yourself why it works in Litmus (I even don't know what is this) and doesn't under Outlook. But, let's get to the point of the question.

Has anyone encountered this issue and have found a fix?

I inserted your code from snippet into the HTML body of my test message and it was looking fine as you mention it. All numbers were displayed properly (on the white background through as you provided just the part of HTML).

Next I set for one of the cell the number with more digits (4 digits "1056") than you expect (you are expecting a maximum of 2 digits). The code (part of it) I have inserted this time was ...

<td width="9%" align="center" valign="top" class="selectors">
<!-- answer for Q10 -->
<!--[if mso]>
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="10" style="height:40px;v-text-anchor:middle;width:45px; text-align:center;" arcsize="10%" strokecolor="#ec00Bc"  fillcolor="#ec00Bc" onmouseover='this.fillcolor="#0088cc"'>
<w:anchorlock/>
<center style="color:#ffffff;font-family:sans-serif;font-size:16px;font-weight:bold;">
1056
</center>
</v:roundrect>
<![endif]-->

<!--[if !mso]><!-->
<a href="10" target="_blank" class="button_link" style="width:90%;padding:8px 0px;display: inline-block;text-decoration: none;border:0;text-align: center;font-weight: bold;font-size: 15px;font-family: sans-serif;color: #ffffff;background: #ec00Bc;border: 1px solid #ec00Bc;-moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;line-height:17px;">
10
</a>
<!--><![endif]-->

</td>

The result as I expected looks like ...

You already noticed the digits don't fit the width of the cell and wrap underneath. This is exactly what's happening with your "10" becoming "1": the digit "0" doesn't fit into the cell of the screenshot provided and wraps under. You don't see it because of some style from the parent table you didn't provide code for.

And finally how to fix it ... As long as I increase width of the cell (to 90px in my case):

<v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word' href='10' style='height:40px;v-text-anchor:middle;width:90px; text-align:center;' arcsize='10%' strokecolor='#ec00Bc'  fillcolor='#ec00Bc'>

I able to see entire number in one line again ...

You need to make sure the width of each cell has enough width to fit 2 digits and not overridden by the styles from parent elements.