问:
How does the imports field in R package description behave (with example)
I am struggling to get my R package to install dependencies in the way I would expect. When my package is installed, I would like it to install the version of the magrittr dependency specified in the DESCRIPTION file however it is not working. see minimal example below:</p>

```<code>remove.packages("magrittr")
install.packages("devtools")
library(devtools)
devtools::install_github('maxwell8888/descriptiontest', dependencies = TRUE, force = TRUE)

packageVersion("magrittr") # returns '1.0.0'

# install package with Imports: magrittr (>= 1.5) in the DESCRIPTION
devtools::install_github('maxwell8888/descriptiontest')

packageVersion("magrittr") # still returns '1.0.0'

# confirm that 1.5 is availble
install.packages("magrittr")
packageVersion("magrittr") # now returns '1.5'

devtools::session_info()
Session info -------------------------------------------------------------------------
setting  value
 version  R version 3.4.1 (2017-06-30)
 system   i386, mingw32
 ui       RStudio (1.0.153)
 language (EN)
 collate  English_United Kingdom.1252
 tz       Europe/London
 date     2017-11-14

Packages -----------------------------------------------------------------------------
 package   * version date       source
 base      * 3.4.1   2017-06-30 local
 compiler    3.4.1   2017-06-30 local
 curl        2.8.1   2017-07-21 CRAN (R 3.4.1)
 datasets  * 3.4.1   2017-06-30 local
 devtools  * 1.13.4  2017-11-09 CRAN (R 3.4.2)
 digest      0.6.12  2017-01-27 CRAN (R 3.4.1)
 git2r       0.19.0  2017-07-19 CRAN (R 3.4.1)
 graphics  * 3.4.1   2017-06-30 local
 grDevices * 3.4.1   2017-06-30 local
 httr        1.2.1   2016-07-03 CRAN (R 3.4.1)
 knitr       1.17    2017-08-10 CRAN (R 3.4.2)
 memoise     1.1.0   2017-04-21 CRAN (R 3.4.1)
 methods   * 3.4.1   2017-06-30 local
 R6          2.2.2   2017-06-17 CRAN (R 3.4.1)
 stats     * 3.4.1   2017-06-30 local
 tools       3.4.1   2017-06-30 local
 utils     * 3.4.1   2017-06-30 local
 withr       2.0.0   2017-07-28 CRAN (R 3.4.1)
</code>```

答:
You can try this for the version you are looking for</p>

```<code>packageurl <-
"https://cran.r-project.org/src/contrib/Archive/magrittr/magrittr_1.0.0.tar.gz"

install.packages(packageurl, repos=NULL, type="source")
</code>```

Body:
I am struggling to get my R package to install dependencies in the way I would expect. When my package is installed, I would like it to install the version of the magrittr dependency specified in the DESCRIPTION file however it is not working. see minimal example below:

remove.packages("magrittr")
install.packages("devtools")
library(devtools)
devtools::install_github('maxwell8888/descriptiontest', dependencies = TRUE, force = TRUE)

packageVersion("magrittr") # returns '1.0.0'

# install package with Imports: magrittr (>= 1.5) in the DESCRIPTION
devtools::install_github('maxwell8888/descriptiontest')

packageVersion("magrittr") # still returns '1.0.0'

# confirm that 1.5 is availble
install.packages("magrittr")
packageVersion("magrittr") # now returns '1.5'

devtools::session_info()
Session info -------------------------------------------------------------------------
setting  value
 version  R version 3.4.1 (2017-06-30)
 system   i386, mingw32
 ui       RStudio (1.0.153)
 language (EN)
 collate  English_United Kingdom.1252
 tz       Europe/London
 date     2017-11-14

Packages -----------------------------------------------------------------------------
 package   * version date       source
 base      * 3.4.1   2017-06-30 local
 compiler    3.4.1   2017-06-30 local
 curl        2.8.1   2017-07-21 CRAN (R 3.4.1)
 datasets  * 3.4.1   2017-06-30 local
 devtools  * 1.13.4  2017-11-09 CRAN (R 3.4.2)
 digest      0.6.12  2017-01-27 CRAN (R 3.4.1)
 git2r       0.19.0  2017-07-19 CRAN (R 3.4.1)
 graphics  * 3.4.1   2017-06-30 local
 grDevices * 3.4.1   2017-06-30 local
 httr        1.2.1   2016-07-03 CRAN (R 3.4.1)
 knitr       1.17    2017-08-10 CRAN (R 3.4.2)
 memoise     1.1.0   2017-04-21 CRAN (R 3.4.1)
 methods   * 3.4.1   2017-06-30 local
 R6          2.2.2   2017-06-17 CRAN (R 3.4.1)
 stats     * 3.4.1   2017-06-30 local
 tools       3.4.1   2017-06-30 local
 utils     * 3.4.1   2017-06-30 local
 withr       2.0.0   2017-07-28 CRAN (R 3.4.1)

Body:
You can try this for the version you are looking for

packageurl <-
"https://cran.r-project.org/src/contrib/Archive/magrittr/magrittr_1.0.0.tar.gz"

install.packages(packageurl, repos=NULL, type="source")


来源: stackexchange

问:
How do I find out the name of a variable in python 2.7.9?
I often need to print variables for debugging purposes, and I found out that it helps a lot to also know what those variables are. So I would like to have a function that does sort of the following:

```<code>from __future__ import print_function

def get_variable_name(my_variable):
  ... ?

def print_with_variable_name(my_variable):
  print (get_variable_name(my_variable), ': ', my_variable)

a = 30
print_with_variable_name(a);
</code>```

Expected output:

```<code>a: 30
</code>```

I found some partial solutions to the problem where I could do that only in the function where the function was defined by the name a, otherwise it would print:

```<code>my_variable: 30
</code>```

Is there any elegant solution to the problem where I can just write a module with this new print function and import it wherever I like?

答:
Try with dictionary:
dict((name,eval(name)) for name in ['list', 'of', 'vars'])

ContentLicense: CC BY-SA 3.0

Body:
I often need to print variables for debugging purposes, and I found out that it helps a lot to also know what those variables are. So I would like to have a function that does sort of the following:

from __future__ import print_function

def get_variable_name(my_variable):
  ... ?

def print_with_variable_name(my_variable):
  print (get_variable_name(my_variable), ': ', my_variable)

a = 30
print_with_variable_name(a);

Expected output:

a: 30

I found some partial solutions to the problem where I could do that only in the function where the function was defined by the name a, otherwise it would print:

my_variable: 30

Is there any elegant solution to the problem where I can just write a module with this new print function and import it wherever I like?


问:
How does Maven come to know which is a test class and which is not

I have worked with junits but never gave a thought on how maven comes to know that the class defined src/test/java is a test class and not a normal class.

One possibility is it may scan for @Test in the class. Is this how it is achived? If not how?.

What exactly are Runners and what is their role.
Can I have test cases without Runners?

答:
There are multiple factors and parameters Maven will use to decide which classes are Test classes. In fact it is not Maven in itself that does it, but one or more plugins.

Most of the time you will use the Surefire Plugin which binds by default to the test phase (you can also use the Failsafe Plugin which behave quite similarly but is aimed for IT tests)

The Surefire Plugin configuration will define which classes are your test classes:

testSourceDirectory : folder containing test classes, src/test/java by default

includes : defines name patterns of classes to include, there are multiple default patterns such as **/*Test.java

... And others such as includesFile, test, see the doc for details

All these classes will be used for your tests.

The Runner is basically the class that will run your tests. From the JUnit docs:

A Runner runs tests and notifies a RunNotifier of significant events
  as it does so. You will need to subclass Runner when using RunWith to
  invoke a custom runner. When creating a custom runner, in addition to
  implementing the abstract methods here you must also provide a
  constructor that takes as an argument the Class containing the tests.

A similar behavior is observed with TestNG. Basically a Runner will manage how your test classes are instanciated and executed. The behavior highly depends on implementation, I recommend reading source codes for said Runners and JUnit / TestNN docs about them to learn more.


问:
Slider not moving automatically
I am developing a single page website but my slider is not automatically moving even after i am adding the script. I want my slider to move automatically. Please find the following HTML code below:

```<code>       <div id="slider" class="sl-slider-wrapper">

            <div class="sl-slider">

                <div class="sl-slide" data-orientation="horizontal" data-slice1-rotation="-25" data-slice2-rotation="-25" data-slice1-scale="2" data-slice2-scale="2">

                    <div class="bg-img bg-img-1"></div>

                    <div class="slide-caption">
                        <div class="caption-content">
                            <h2 class="animated fadeInDown">Lorem ipsum</h2>
                            <span class="animated fadeInDown">Lorem ipsum</span>
                            <a href="#" class="btn btn-blue btn-effect">Join US</a>
                        </div>
                    </div>

                </div>

                <div class="sl-slide" data-orientation="vertical" data-slice1-rotation="10" data-slice2-rotation="-15" data-slice1-scale="1.5" data-slice2-scale="1.5">

                    <div class="bg-img bg-img-2"></div>
                    <div class="slide-caption">
                        <div class="caption-content">
                            <h2>Lorem ipsum</h2>
                            <span>Lorem ipsum</span>
                            <a href="#" class="btn btn-blue btn-effect">Join US</a>
                        </div>
                    </div>

                </div>

                <div class="sl-slide" data-orientation="horizontal" data-slice1-rotation="3" data-slice2-rotation="3" data-slice1-scale="2" data-slice2-scale="1">

                    <div class="bg-img bg-img-3"></div>
                    <div class="slide-caption">
                        <div class="caption-content">
                            <h2>Lorem ipsum</h2>
                            <span>Lorem ipsum</span>
                            <a href="#" class="btn btn-blue btn-effect">Join US</a>
                        </div>
                    </div>

                </div>

            </div><!-- /sl-slider -->

            <!--
            <nav id="nav-arrows" class="nav-arrows">
                <span class="nav-arrow-prev">Previous</span>
                <span class="nav-arrow-next">Next</span>
            </nav>
            -->

            <nav id="nav-arrows" class="nav-arrows hidden-xs hidden-sm visible-md visible-lg">
                <a href="javascript:;" class="sl-prev">
                    <i class="fa fa-angle-left fa-3x"></i>
                </a>
                <a href="javascript:;" class="sl-next">
                    <i class="fa fa-angle-right fa-3x"></i>
                </a>
            </nav>

            <nav id="nav-dots" class="nav-dots visible-xs visible-sm hidden-md hidden-lg">
                <span class="nav-dot-current"></span>
                <span></span>
                <span></span>
            </nav>

        </div><!-- /slider-wrapper -->
</code>```

I am also adding my script code which i tried to add. How can I find the appropriate script file so that my slider starts moving automatically after some interval?

Here is my script:

```<code>// Carousel Auto-Cycle
          $(document).ready(function() {
            $('.sl-slider-wrapper').sl-slider-wrapper({
              interval: 1000
            })
          });
</code>```

答:
Have you looked at the devtools of your page while it's running? i'm sure it's throwing an error - the javascript inside the document ready function should read:

```<code>...
$('.sl-slider-wrapper').slitslider({
...
</code>```

I think it's a copy/paste error in your javascript.

ContentLicense: CC BY-SA 4.0

Title: Slider not moving automatically

Body:
I am developing a single page website but my slider is not automatically moving even after i am adding the script. I want my slider to move automatically. Please find the following HTML code below:

Lorem ipsum

                            Lorem ipsum
                            Join US

Lorem ipsum

                            Lorem ipsum
                            Join US

Lorem ipsum

                            Lorem ipsum
                            Join US

I am also adding my script code which i tried to add. How can I find the appropriate script file so that my slider starts moving automatically after some interval?

Here is my script:

// Carousel Auto-Cycle
          $(document).ready(function() {
            $('.sl-slider-wrapper').sl-slider-wrapper({
              interval: 1000
            })
          });

Body:
Have you looked at the devtools of your page while it's running? i'm sure it's throwing an error - the javascript inside the document ready function should read:

...
$('.sl-slider-wrapper').slitslider({
...

I think it's a copy/paste error in your javascript.


问:
Testing AngularJS with Protractor- test fails because element is not clickable despite waiting for elementToBeClickable...?
I have encountered a strange problem while writing up one of the tests in a test suite I am developing for an AngularJS application using Protractor.

While initially developing the tests, I was using a call to browser.pause() to ensure that I manually had to tell the tests to execute each line while running through the test scripts. I am now happy that the tests that I have written so far are executing correctly & all pass/ fail correctly depending on their criteria.

I now want to remove the call to browser.pause() so that the script can run through each of the tests automatically, without the need for any user interaction. However, because the application is Angular, doing this has caused some issues with timing/ waiting for elements to load before the test steps that reference them are executed- so I am currently going through each of the tests, and trying to ensure that they are allowing the required times for elements to load/ waiting for an element before interacting with it, etc.

When I run my test script at the moment, it is failing on the second test (navigate to the Export page), which I have written as follows:

```<code>it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000).then(
        browser.actions().mouseMove(exportMenuBtn).perform().then(
            exportMenuBtn.click().then(
                function() {
                    console.log("Export page test completed ");
                    expect(browser.getCurrentUrl()).toBe(VM + '/#/export');
                }
            )
        )
    );
});
</code>```

The error message I get in the command line where I'm running my script says:

Failed: unknown error: Element ... is not clickable at point (40, 301). Other element would receive the click:

```<code><div tabindex="-1" role="dialog" class="modal fade ng-isolate-scope ult-loading modal-message ng-animate in-remove in-remove-active" ng-class="{in: animate}" ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)" modal-window="" window-class="ult-loading modal-message" size="sm" index="0" animate="animate" style="z-index: 1050; display: block;; transition-property: opacity;transition-duration: 0.15s;">...</div>
</code>```

(Session info: chrome=62.0.3202.89)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)

which indicates to me that the exportMenuBtn element is not 'clickable' at the point at which my test script is trying to call .click() on it. But this doesn't make sense, since I have used the line browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000) to wait for the exportMenuBtn element to be clickable before I try to click it...

I have tried increasing the time that I wait for the element to be clickable, but this doesn't seem to have made a difference...

Can anyone explain why this test is failing? How can I ensure that the test waits for the exportMenuBtn element to be clickable before it tries to click it?

Edit

So I tried doing what @Ernst Zwingli suggested in their answer- added a function to close the dialog to my spec.js file with:

```<code>var pageLoaded = function() {
    var blockingElement = $('div[window-class="ult-loading modal-message"');
    return EC.invisibilityOf(blockingElement);
}
module.exports = new pageLoaded();
</code>```

and then updated the test script to:

```<code>it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(pageLoaded, 5000);
    exportMenuBtn.click();
    browser.wait(pageLoaded, 5000);
    browser.wait(EC.urlIs(VM + '/#/export'), 5000);
});
</code>```

But my test script still fails, giving the same error message:

Failed: unknown error: Element

```<code><a href="#/export" target="_self">...</a>
</code>```

is not clickable at point (40, 301).

Other element would receive the click:

```<code><div tabindex="-1" role="dialog" class="modal fade ng-isolate-scope ult-loading modal-message ng-animate in-remove in-remove-active" ng-class="{in: animate}" ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)" modal-window="" window-class="ult-loading modal-message" size="sm" index="0" animate="animate" style="z-index: 1050; display: block;; transition-property: opacity;transition-duration: 0.15s;">...</div>
</code>```

```<code> (Session info: chrome=62.0.3202.89)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)
</code>```

The dialog that seems to be causing the issue is defined in Dialog/service.js with:

```<code>function wait(msg, progress, title) {
    // Create a wait dialog
    var dlg = dialogs.wait(
        title,
        msg,
        progress,
        {
            // Disable keyboard ESC to close dialogue instances
            keyboard: false,

            // lock the background window
            backdrop: "static",
            size: "sm",
            windowClass: "ult-loading modal-message",
            animation: false
        }
    );

    // Push the dialog into the pool
    dlgs.push(dlg);

    // Return the created dialog
    return dlg;
}
</code>```

This dialog is never actually visible when running the test/ browsing to the page manually, so it seems to be some sort of 'background task' that is run while browsing to/ loading a new page. I should also note that this dialog is defined within a factory:

```<code>.factory('DialogMgr', function($rootScope, $document, dialogs) {
    ...
    function wait(...) {
        ...
    }
});
</code>```

I'm wondering if this possibly has anything to do with the 'fade' animation that is set on the dialog? How would I resolve this?

答:
Although I know it's not considered 'best practice', the only way I was actually able to resolve this was to insert a browser.sleep() line just before the call to browser.click():

```<code>it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(pageLoaded, 5000);
    browser.sleep(500);
    exportMenuBtn.click();
    browser.wait(EC.urlIs(site + '/#/export'), 5000);
});
</code>```

using the pageLoaded() function that Ernst Zwingli provided in their answer:

```<code>var pageLoaded = function() {
    var blockingElement = $('div[window-class="ult-loading modal-message"');
    //console.log("blockingElement: ", blockingElement);
    return EC.invisibilityOf(blockingElement);
}
module.exports = new pageLoaded();
</code>```

Without the call to browser.sleep(500);, the page did not have time for animation to complete on a dialog that was opened & closed in the background while the page was loading- meaning that the dialog received the click, rather than the menu button I had intended.

Body:
I have encountered a strange problem while writing up one of the tests in a test suite I am developing for an AngularJS application using Protractor.

While initially developing the tests, I was using a call to browser.pause() to ensure that I manually had to tell the tests to execute each line while running through the test scripts. I am now happy that the tests that I have written so far are executing correctly & all pass/ fail correctly depending on their criteria.

I now want to remove the call to browser.pause() so that the script can run through each of the tests automatically, without the need for any user interaction. However, because the application is Angular, doing this has caused some issues with timing/ waiting for elements to load before the test steps that reference them are executed- so I am currently going through each of the tests, and trying to ensure that they are allowing the required times for elements to load/ waiting for an element before interacting with it, etc.

When I run my test script at the moment, it is failing on the second test (navigate to the Export page), which I have written as follows:

it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000).then(
        browser.actions().mouseMove(exportMenuBtn).perform().then(
            exportMenuBtn.click().then(
                function() {
                    console.log("Export page test completed ");
                    expect(browser.getCurrentUrl()).toBe(VM + '/#/export');
                }
            )
        )
    );
});

The error message I get in the command line where I'm running my script says:

Failed: unknown error: Element ... is not clickable at point (40, 301). Other element would receive the click:

...

(Session info: chrome=62.0.3202.89)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)

which indicates to me that the exportMenuBtn element is not 'clickable' at the point at which my test script is trying to call .click() on it. But this doesn't make sense, since I have used the line browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000) to wait for the exportMenuBtn element to be clickable before I try to click it...

I have tried increasing the time that I wait for the element to be clickable, but this doesn't seem to have made a difference...

Can anyone explain why this test is failing? How can I ensure that the test waits for the exportMenuBtn element to be clickable before it tries to click it?

Edit

So I tried doing what @Ernst Zwingli suggested in their answer- added a function to close the dialog to my spec.js file with:

var pageLoaded = function() {
    var blockingElement = $('div[window-class="ult-loading modal-message"');
    return EC.invisibilityOf(blockingElement);
}
module.exports = new pageLoaded();

and then updated the test script to:

it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(pageLoaded, 5000);
    exportMenuBtn.click();
    browser.wait(pageLoaded, 5000);
    browser.wait(EC.urlIs(VM + '/#/export'), 5000);
});

But my test script still fails, giving the same error message:

Failed: unknown error: Element

...

is not clickable at point (40, 301).

Other element would receive the click:

...

 (Session info: chrome=62.0.3202.89)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)

The dialog that seems to be causing the issue is defined in Dialog/service.js with:

function wait(msg, progress, title) {
    // Create a wait dialog
    var dlg = dialogs.wait(
        title,
        msg,
        progress,
        {
            // Disable keyboard ESC to close dialogue instances
            keyboard: false,

            // lock the background window
            backdrop: "static",
            size: "sm",
            windowClass: "ult-loading modal-message",
            animation: false
        }
    );

    // Push the dialog into the pool
    dlgs.push(dlg);

    // Return the created dialog
    return dlg;
}

This dialog is never actually visible when running the test/ browsing to the page manually, so it seems to be some sort of 'background task' that is run while browsing to/ loading a new page. I should also note that this dialog is defined within a factory:

.factory('DialogMgr', function($rootScope, $document, dialogs) {
    ...
    function wait(...) {
        ...
    }
});

I'm wondering if this possibly has anything to do with the 'fade' animation that is set on the dialog? How would I resolve this?

Body:
Although I know it's not considered 'best practice', the only way I was actually able to resolve this was to insert a browser.sleep() line just before the call to browser.click():

it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(pageLoaded, 5000);
    browser.sleep(500);
    exportMenuBtn.click();
    browser.wait(EC.urlIs(site + '/#/export'), 5000);
});

using the pageLoaded() function that Ernst Zwingli provided in their answer:

var pageLoaded = function() {
    var blockingElement = $('div[window-class="ult-loading modal-message"');
    //console.log("blockingElement: ", blockingElement);
    return EC.invisibilityOf(blockingElement);
}
module.exports = new pageLoaded();

Without the call to browser.sleep(500);, the page did not have time for animation to complete on a dialog that was opened & closed in the background while the page was loading- meaning that the dialog received the click, rather than the menu button I had intended.


问:
tidytext -- how to do commonality and comparsion word clouds
Let me start with the following and fully working code from Introduction to tidytext @ CRAN

```<code>library(janeaustenr)
library(dplyr)
library(stringr)

original_books <- austen_books() %>%
  group_by(book) %>%
  mutate(linenumber = row_number(),
         chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
                                                 ignore_case = TRUE)))) %>%
  ungroup()

original_books

library(tidytext)
tidy_books <- original_books %>%
  unnest_tokens(word, text)

tidy_books

data("stop_words")
cleaned_books <- tidy_books %>%
  anti_join(stop_words)
</code>```

All good so far.  I have a tibble with six Jane Austen novels, with the standard junk words removed.

```<code>unique(cleaned_books$book)
</code>```

Which gets me: Sense & Sensibility, Pride & Prejudice,   Mansfield Park,      Emma, Northanger Abbey,   Persuasion.

So if I want to do a standard TF word cloud of all six, no problem.  Just like this (color added):

```<code>library(wordcloud)
library(RColorBrewer)
dark2 <- brewer.pal(8, "Dark2")

cleaned_books %>%
  count(word) %>%
  with(wordcloud(word, n, color = dark2, max.words = 100))
</code>```

Works beautifully.  But how do I then do a commonality.cloud() with all six novels, and a comparison.cloud() with the same?

All the data I need is in cleaned_books -- but I can't figure out how to reshape it.  Your help appreciated!

Got it.  Thanks.

Will leave up in case anyone else has a similar issue.

The above code &

```<code>set1 <- brewer.pal(8, "Set1") ## a second color just for other cloud type

library(reshape2)

# title size and scale optional, obviously
cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   comparison.cloud(color = dark2, title.size = 1,  scale = c(3,  0.3), random.order = FALSE, max.words = 100)

cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   commonality.cloud(color = set1, title.size = 1, scale = c(3,  0.3), random.order = FALSE,  max.words = 100)
</code>```

That worked out nicely.

答:
Got it.  Thanks.  Run the above code. Then

```<code>set1 <- brewer.pal(8, "Set1") ## a second color just for other cloud type
library(reshape2)
</code>```

Color is optional.  reshape2 essential.  Then just group by book, and go.

```<code>cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   comparison.cloud(color = dark2, title.size = 1, scale = c(3,  0.3), random.order = FALSE,  max.words = 100)

cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   commonality.cloud(color = set1, title.size = 1, scale = c(3,  0.3), random.order = FALSE,  max.words = 100)
</code>```

All good!

Body:
Let me start with the following and fully working code from Introduction to tidytext @ CRAN

library(janeaustenr)
library(dplyr)
library(stringr)

original_books <- austen_books() %>%
  group_by(book) %>%
  mutate(linenumber = row_number(),
         chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
                                                 ignore_case = TRUE)))) %>%
  ungroup()

original_books

library(tidytext)
tidy_books <- original_books %>%
  unnest_tokens(word, text)

tidy_books

data("stop_words")
cleaned_books <- tidy_books %>%
  anti_join(stop_words)

All good so far.  I have a tibble with six Jane Austen novels, with the standard junk words removed.

unique(cleaned_books$book)

Which gets me: Sense & Sensibility, Pride & Prejudice,   Mansfield Park,      Emma, Northanger Abbey,   Persuasion.

So if I want to do a standard TF word cloud of all six, no problem.  Just like this (color added):

library(wordcloud)
library(RColorBrewer)
dark2 <- brewer.pal(8, "Dark2")

cleaned_books %>%
  count(word) %>%
  with(wordcloud(word, n, color = dark2, max.words = 100))

Works beautifully.  But how do I then do a commonality.cloud() with all six novels, and a comparison.cloud() with the same?

All the data I need is in cleaned_books -- but I can't figure out how to reshape it.  Your help appreciated!

Got it.  Thanks.

Will leave up in case anyone else has a similar issue.

The above code &

set1 <- brewer.pal(8, "Set1") ## a second color just for other cloud type

library(reshape2)

# title size and scale optional, obviously
cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   comparison.cloud(color = dark2, title.size = 1,  scale = c(3,  0.3), random.order = FALSE, max.words = 100)

cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   commonality.cloud(color = set1, title.size = 1, scale = c(3,  0.3), random.order = FALSE,  max.words = 100)

That worked out nicely.

Body:
Got it.  Thanks.  Run the above code. Then

set1 <- brewer.pal(8, "Set1") ## a second color just for other cloud type
library(reshape2)

Color is optional.  reshape2 essential.  Then just group by book, and go.

cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   comparison.cloud(color = dark2, title.size = 1, scale = c(3,  0.3), random.order = FALSE,  max.words = 100)

cleaned_books %>%
   group_by(book) %>%
   count(word) %>%
   acast(word ~ book, value.var = "n", fill = 0) %>%
   commonality.cloud(color = set1, title.size = 1, scale = c(3,  0.3), random.order = FALSE,  max.words = 100)

All good!


问:
Java Spring Hibernate Saving Duplicate Values to MySQL table is throwing error
I am trying to save some values to a MYSQL database using CrudRepository but doesnt seem to work. I have tried the following guide https://spring.io/guides/gs/accessing-data-mysql/ and it works fine but when iam trying to follow the same principle for my program it doesnt seem to work for some reason.

Here is the class iam creating a database for, The table gets created properly:

```<code> @Entity
 public class MeasurementPoint {

 @Id

 @JsonProperty("f1")
 private double f1;

 @JsonProperty("precison")
 private double precison;

 @JsonProperty("recall")
 private double recall;

 private String date;

 public MeasurementPoint(double f1, double precison, double recall, String
 date)  {
     this.f1 = f1;
     this.precison = precison;
     this.recall = recall;
     this.date=date;
 }

 public double getF1() {
     return f1;
 }

 public double getPrecison() {
     return precison;
 }

 public String getDate() {
     return date;
 }
 public double getRecall() {
     return recall;
 }
}
</code>```

Here is the MSQL terminal outputting the columns for the entity created:

```<code>+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| f1       | double       | NO   | PRI | NULL    | auto_increment |
| date     | varchar(255) | YES  |     | NULL    |                |
| precison | double       | NO   |     | NULL    |                |
| recall   | double       | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
</code>```

Here is the class iam trying to add values to the database from:

```<code>@Controller
public class DataChart {

private static final Logger logger= LoggerFactory.getLogger(DataChart.class);

@Autowired
private static MeasurementRepository measurementRepository;

@GetMapping(value = "/statementchart")
@ResponseBody
public List<Measurement> scoreChartData() {

    List<MeasurementPoint> needDataPoints = new ArrayList<>();
    List<MeasurementPoint> backgroundDataPoints = new ArrayList<>();
    List<MeasurementPoint> goalDataPoints=new ArrayList<>();
    needDataPoints.add(new MeasurementPoint(0.3, 0.5, 0.2,  "2017-11-19"));
    needDataPoints.add(new MeasurementPoint(0.7, 0.4, 0.15, "2017-11-12"));
    needDataPoints.add(new MeasurementPoint(0.5, 0.3, 0.10, "2017-11-15"));
    needDataPoints.add(new MeasurementPoint(0.6, 0.2, 0.05, "2017-11-18"));
    measurementRepository.save(needDataPoints);

    backgroundDataPoints.add(new MeasurementPoint(0.2, 0.4, 0.2, "2017-11-19"));
    backgroundDataPoints.add(new MeasurementPoint(0.4, 0.3, 0.15, "2017-11-12"));
    measurementRepository.save(backgroundDataPoints);
   //backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
   //measurementRepository.save(backgroundDataPoints);
</code>```

Here is the output from saving these points:

```<code>+-----+------------+----------+--------+
| f1  | date       | precison | recall |
+-----+------------+----------+--------+
| 0.2 | 2017-11-19 |      0.4 |    0.2 |
| 0.3 | 2017-11-19 |      0.5 |    0.2 |
| 0.4 | 2017-11-12 |      0.3 |   0.15 |
| 0.5 | 2017-11-15 |      0.3 |    0.1 |
| 0.6 | 2017-11-18 |      0.2 |   0.05 |
| 0.7 | 2017-11-12 |      0.4 |   0.15 |
+-----+------------+----------+--------+
6 rows in set (0.00 sec)
</code>```

Here is my CrudRepository class:

```<code>public interface MeasurementRepository extends CrudRepository<MeasurementPoint,Long> {
}
</code>```

SOLVED

saving these points works fine but as soon i save that out-commented new MeasurementPoint

```<code>//backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
//measurementRepository.save(backgroundDataPoints);
</code>```

i get a error saying: I guess it has to do with duplicate values but how do i fix this?

```<code>javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session :
</code>```

I solved it by creating a field of type long called id with annotation @Id because apparently every object created should get a unique id, the error thrown is because objects had some id. @GeneratedValue makes sure that everytime a new object is created a unqiue Id is given to that object.

```<code>    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
</code>```

答:
Maybe you have this problem because you specified wrong ID type in you CrudRepository, your entity has ID of Double type but in repository is Long.

Edited:

Looks like save method of JpaRepository have some problems with double values, as I can see it always call persist method but it should call merge if Id is specified.

To solve this you can create your own Repository implementation where you will handle this.

Another solution is to change your Id type to Long if you have such possibility.

Body:
I am trying to save some values to a MYSQL database using CrudRepository but doesnt seem to work. I have tried the following guide https://spring.io/guides/gs/accessing-data-mysql/ and it works fine but when iam trying to follow the same principle for my program it doesnt seem to work for some reason.

Here is the class iam creating a database for, The table gets created properly:

 @Entity
 public class MeasurementPoint {

 @Id

 @JsonProperty("f1")
 private double f1;

 @JsonProperty("precison")
 private double precison;

 @JsonProperty("recall")
 private double recall;

 private String date;

 public MeasurementPoint(double f1, double precison, double recall, String
 date)  {
     this.f1 = f1;
     this.precison = precison;
     this.recall = recall;
     this.date=date;
 }

 public double getF1() {
     return f1;
 }

 public double getPrecison() {
     return precison;
 }

 public String getDate() {
     return date;
 }
 public double getRecall() {
     return recall;
 }
}

Here is the MSQL terminal outputting the columns for the entity created:

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| f1       | double       | NO   | PRI | NULL    | auto_increment |
| date     | varchar(255) | YES  |     | NULL    |                |
| precison | double       | NO   |     | NULL    |                |
| recall   | double       | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

Here is the class iam trying to add values to the database from:

@Controller
public class DataChart {

private static final Logger logger= LoggerFactory.getLogger(DataChart.class);

@Autowired
private static MeasurementRepository measurementRepository;

@GetMapping(value = "/statementchart")
@ResponseBody
public List<Measurement> scoreChartData() {

    List<MeasurementPoint> needDataPoints = new ArrayList<>();
    List<MeasurementPoint> backgroundDataPoints = new ArrayList<>();
    List<MeasurementPoint> goalDataPoints=new ArrayList<>();
    needDataPoints.add(new MeasurementPoint(0.3, 0.5, 0.2,  "2017-11-19"));
    needDataPoints.add(new MeasurementPoint(0.7, 0.4, 0.15, "2017-11-12"));
    needDataPoints.add(new MeasurementPoint(0.5, 0.3, 0.10, "2017-11-15"));
    needDataPoints.add(new MeasurementPoint(0.6, 0.2, 0.05, "2017-11-18"));
    measurementRepository.save(needDataPoints);

    backgroundDataPoints.add(new MeasurementPoint(0.2, 0.4, 0.2, "2017-11-19"));
    backgroundDataPoints.add(new MeasurementPoint(0.4, 0.3, 0.15, "2017-11-12"));
    measurementRepository.save(backgroundDataPoints);
   //backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
   //measurementRepository.save(backgroundDataPoints);

Here is the output from saving these points:

+-----+------------+----------+--------+
| f1  | date       | precison | recall |
+-----+------------+----------+--------+
| 0.2 | 2017-11-19 |      0.4 |    0.2 |
| 0.3 | 2017-11-19 |      0.5 |    0.2 |
| 0.4 | 2017-11-12 |      0.3 |   0.15 |
| 0.5 | 2017-11-15 |      0.3 |    0.1 |
| 0.6 | 2017-11-18 |      0.2 |   0.05 |
| 0.7 | 2017-11-12 |      0.4 |   0.15 |
+-----+------------+----------+--------+
6 rows in set (0.00 sec)

Here is my CrudRepository class:

public interface MeasurementRepository extends CrudRepository<MeasurementPoint,Long> {
}

SOLVED

saving these points works fine but as soon i save that out-commented new MeasurementPoint

//backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
//measurementRepository.save(backgroundDataPoints);

i get a error saying: I guess it has to do with duplicate values but how do i fix this?

javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session :

I solved it by creating a field of type long called id with annotation @Id because apparently every object created should get a unique id, the error thrown is because objects had some id. @GeneratedValue makes sure that everytime a new object is created a unqiue Id is given to that object.

    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;


问:
How to evaluate multiple expression in if--elif statement in python?
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

```<code>n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"
</code>```

答:
Try this</p>

```<code>n = 5

if n%2 != 0:
    print('weird')
elif n%2 == 0 and 2 <= n <= 5:
    print("Not Weird")
elif n%2 == 0 and 6 <= n <= 20:
    print("Weird")
elif n%2 == 0 and n > 20:
    print("Not Weird")
</code>```

Body:
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"

Body:
Try this

n = 5

if n%2 != 0:
    print('weird')
elif n%2 == 0 and 2 <= n <= 5:
    print("Not Weird")
elif n%2 == 0 and 6 <= n <= 20:
    print("Weird")
elif n%2 == 0 and n > 20:
    print("Not Weird")


问:
Menu in not showing up in Fragment
I make fragment and i want to show menu for click to post. but menu not show. i don't know problem at not show. now i wanna show menu for the next step program pls help me.

```<code>    public class FragmentViewPost extends Fragment {

    public static FragmentViewPost newInstance() {
        FragmentViewPost fragment = new FragmentViewPost();
        return fragment;
    }

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

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

    private RecyclerView mBlogList;
    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if(firebaseAuth.getCurrentUser() == null){

                    startActivity();

                }
            }
        };

        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
        mBlogList = (RecyclerView) view.findViewById(R.id.blog_list_fragment);
        mBlogList.setHasFixedSize(true);
        mBlogList.setLayoutManager(new LinearLayoutManager(getContext()));

    }

    private void startActivity() {

        Intent loginIntent = new Intent(getActivity(),PageLogin.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(loginIntent);

    }

    @Override
    public void onStart() {
        super.onStart();

        mAuth.addAuthStateListener(mAuthListener);

        FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(

                Blog.class, R.layout.blog_row, BlogViewHolder.class, mDatabase

        ) {
            @Override
            protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {

                viewHolder.setTitle(model.getTitle());
                viewHolder.setDesc(model.getDesc());
                viewHolder.setImage(getActivity(), model.getImage());
                viewHolder.setUsername(model.getUsername());

            }
        };

        mBlogList.setAdapter(firebaseRecyclerAdapter);
    }

    public static class BlogViewHolder extends RecyclerView.ViewHolder{

        View mView;

        public BlogViewHolder(View itemView) {
            super(itemView);

            mView = itemView;
        }

        public void setTitle(String title){

            TextView post_title = (TextView) mView.findViewById(R.id.post_title);
            post_title.setText(title);

        }

        public void setDesc(String desc){

            TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
            post_desc.setText(desc);

        }

        public void setImage(Context ctx, String image){

            ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
            Picasso.with(ctx).load(image).into(post_image);

        }

        public void setUsername(String username){

            TextView post_username = (TextView) mView.findViewById(R.id.post_username);
            post_username.setText(username);

        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        super.onCreateOptionsMenu(menu,inflater);
        inflater.inflate(R.menu.menu_post, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == R.id.action_add){

            goToAttract();

//        switch (item.getItemId()) {
//            case R.id.action_add:
//                // Not implemented here
//                Log.d("=============>>>","search1");
//                return false;
//            case R.id.action_adduser:
//                Log.d("=============>>>","scan1");
//                return true;
//            default:
//                break;

        }

        return super.onOptionsItemSelected(item);

//        return false;
    }

    private void goToAttract() {

        Intent intent = new Intent(getActivity(), Post.class);
        startActivity(intent);

    }
</code>```

and xml code :

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_add"
        android:icon="@mipmap/ic_add_white_24dp"
        android:title="Post"
        app:showAsAction="always"/>

</menu>
</code>```

Thank you for help me :)

答:
Don't place toolbar inside relativelayout.

Please place toolbar inside LinearLayout. It will solve the problem.

Title: Menu in not showing up in Fragment

Body:
I make fragment and i want to show menu for click to post. but menu not show. i don't know problem at not show. now i wanna show menu for the next step program pls help me.

    public class FragmentViewPost extends Fragment {

    public static FragmentViewPost newInstance() {
        FragmentViewPost fragment = new FragmentViewPost();
        return fragment;
    }

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

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

    private RecyclerView mBlogList;
    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if(firebaseAuth.getCurrentUser() == null){

                    startActivity();

                }
            }
        };

        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
        mBlogList = (RecyclerView) view.findViewById(R.id.blog_list_fragment);
        mBlogList.setHasFixedSize(true);
        mBlogList.setLayoutManager(new LinearLayoutManager(getContext()));

    }

    private void startActivity() {

        Intent loginIntent = new Intent(getActivity(),PageLogin.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(loginIntent);

    }

    @Override
    public void onStart() {
        super.onStart();

        mAuth.addAuthStateListener(mAuthListener);

        FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(

                Blog.class, R.layout.blog_row, BlogViewHolder.class, mDatabase

        ) {
            @Override
            protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {

                viewHolder.setTitle(model.getTitle());
                viewHolder.setDesc(model.getDesc());
                viewHolder.setImage(getActivity(), model.getImage());
                viewHolder.setUsername(model.getUsername());

            }
        };

        mBlogList.setAdapter(firebaseRecyclerAdapter);
    }

    public static class BlogViewHolder extends RecyclerView.ViewHolder{

        View mView;

        public BlogViewHolder(View itemView) {
            super(itemView);

            mView = itemView;
        }

        public void setTitle(String title){

            TextView post_title = (TextView) mView.findViewById(R.id.post_title);
            post_title.setText(title);

        }

        public void setDesc(String desc){

            TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
            post_desc.setText(desc);

        }

        public void setImage(Context ctx, String image){

            ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
            Picasso.with(ctx).load(image).into(post_image);

        }

        public void setUsername(String username){

            TextView post_username = (TextView) mView.findViewById(R.id.post_username);
            post_username.setText(username);

        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        super.onCreateOptionsMenu(menu,inflater);
        inflater.inflate(R.menu.menu_post, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == R.id.action_add){

            goToAttract();

//        switch (item.getItemId()) {
//            case R.id.action_add:
//                // Not implemented here
//                Log.d("=============>>>","search1");
//                return false;
//            case R.id.action_adduser:
//                Log.d("=============>>>","scan1");
//                return true;
//            default:
//                break;

        }

        return super.onOptionsItemSelected(item);

//        return false;
    }

    private void goToAttract() {

        Intent intent = new Intent(getActivity(), Post.class);
        startActivity(intent);

    }

and xml code :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_add"
        android:icon="@mipmap/ic_add_white_24dp"
        android:title="Post"
        app:showAsAction="always"/>

</menu>

Thank you for help me :)


问:
convert from Color to brush
How do I convert a Color to a Brush in C#?

答:
I had same issue before, here is my class which solved color conversions
Use it and enjoy :

Here U go, Use my Class to Multi Color Conversion

```<code>using System;
using System.Windows.Media;
using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;
using SWMBrush = System.Windows.Media.Brush;

//Developed by امین امیری دربان
namespace APREndUser.CodeAssist
{
    public static class ColorHelper
    {
        public static SWMColor ToSWMColor(SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SDColor ToSDColor(SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SWMBrush ToSWMBrush(SDColor color) => (SolidColorBrush)(new BrushConverter().ConvertFrom(ToHexColor(color)));
        public static string ToHexColor(SDColor c) => "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
        public static string ToRGBColor(SDColor c) => "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
        public static Tuple<SDColor, SDColor> GetColorFromRYGGradient(double percentage)
        {
            var red = (percentage > 50 ? 1 - 2 * (percentage - 50) / 100.0 : 1.0) * 255;
            var green = (percentage > 50 ? 1.0 : 2 * percentage / 100.0) * 255;
            var blue = 0.0;
            SDColor result1 = SDColor.FromArgb((int)red, (int)green, (int)blue);
            SDColor result2 = SDColor.FromArgb((int)green, (int)red, (int)blue);
            return new Tuple<SDColor, SDColor>(result1, result2);
        }
    }

}
</code>```

Title: convert from Color to brush

Body:
I had same issue before, here is my class which solved color conversions
Use it and enjoy :

Here U go, Use my Class to Multi Color Conversion

using System;
using System.Windows.Media;
using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;
using SWMBrush = System.Windows.Media.Brush;

//Developed by امین امیری دربان
namespace APREndUser.CodeAssist
{
    public static class ColorHelper
    {
        public static SWMColor ToSWMColor(SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SDColor ToSDColor(SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SWMBrush ToSWMBrush(SDColor color) => (SolidColorBrush)(new BrushConverter().ConvertFrom(ToHexColor(color)));
        public static string ToHexColor(SDColor c) => "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
        public static string ToRGBColor(SDColor c) => "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
        public static Tuple<SDColor, SDColor> GetColorFromRYGGradient(double percentage)
        {
            var red = (percentage > 50 ? 1 - 2 * (percentage - 50) / 100.0 : 1.0) * 255;
            var green = (percentage > 50 ? 1.0 : 2 * percentage / 100.0) * 255;
            var blue = 0.0;
            SDColor result1 = SDColor.FromArgb((int)red, (int)green, (int)blue);
            SDColor result2 = SDColor.FromArgb((int)green, (int)red, (int)blue);
            return new Tuple<SDColor, SDColor>(result1, result2);
        }
    }

}


问:
How to know data coming from JSON is a Float or an Integer in Swift 3?
I am getting data from Json and displaying it in table view how to check whether the number is float or double or integer in swift 3 if it is float how to get the no.of digits after decimal can anyone help me how to implement this in swift 3 ?</p>

```<code>                    if specialLoop.attributeCode == "special_price" {
                        let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "$ \((arr.price))")
                        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
                        let specialPrice = specialLoop.value.replacingOccurrences(of: ".0000", with: "0")
                        print(specialPrice)
                        cell.productPrice.text = "$ \(specialPrice)"
                        cell.specialPriceLabel.isHidden = false
                        cell.specialPriceLabel.attributedText = attributeString
                        break
                     }
                     else {
                        cell.specialPriceLabel.isHidden = true
                        let price = arr.price
                        print(price)
                        cell.productPrice.text = "$ \( (price))0"
                    }
</code>```

答:
You can use (if let) </p>

```<code>let data = [String: Any]()

if let value = data["key"] as? Int {

} else if let value = data["key"] as? Float {

} else if let value = data["key"] as? Double {

}
</code>```

Body:
I am getting data from Json and displaying it in table view how to check whether the number is float or double or integer in swift 3 if it is float how to get the no.of digits after decimal can anyone help me how to implement this in swift 3 ?

                    if specialLoop.attributeCode == "special_price" {
                        let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "$ \((arr.price))")
                        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
                        let specialPrice = specialLoop.value.replacingOccurrences(of: ".0000", with: "0")
                        print(specialPrice)
                        cell.productPrice.text = "$ \(specialPrice)"
                        cell.specialPriceLabel.isHidden = false
                        cell.specialPriceLabel.attributedText = attributeString
                        break
                     }
                     else {
                        cell.specialPriceLabel.isHidden = true
                        let price = arr.price
                        print(price)
                        cell.productPrice.text = "$ \( (price))0"
                    }

Body:
You can use (if let)

let data = [String: Any]()

if let value = data["key"] as? Int {

} else if let value = data["key"] as? Float {

} else if let value = data["key"] as? Double {

}


问:
Call a class method as soon as an object it extends is created
Assume we have the following class (simplified):

```<code>class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

```<code>class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}
</code>```

and I could access the properties in the child class like this:

```<code>class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}
</code>```

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

```<code>class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

答:
Well, in this particular case you just need:</p>

```<code>class SuperConfig {
    public $mainDir = "path/to/dir";
}
</code>```

Body:
Assume we have the following class (simplified):

class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}

and I could access the properties in the child class like this:

class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

Body:
Well, in this particular case you just need:

class SuperConfig {
    public $mainDir = "path/to/dir";
}


问:
DatabaseAccessor not connected in a high load scenario
I'm having an issue chasing down the culprit of a "EclipseLink-4005 (..) DatabaseAccessor not connected" error in our app. It's a standalone application (not a web-app) with multiple threads connecting to the same db (Oracle). We use EclipseLink 2.4.2 and its internal connection pool with default settings. Transactions are managed in the app and can be nested. The app works fine most of the time, but occasionally, under high load fails with the "EclipseLink-4005 (..) DatabaseAccessor not connected" error.

I was able to reproduce the error in our test environment but have trouble understanding under what conditions it might happen. Some transactions are long running. Is it possible that some of them time out, causing the respective session to log out and resulting in the error in another thread?

Below are sample stack traces:

```<code>Exception [EclipseLink-4005] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: DatabaseAccessor not connected.
    at org.eclipse.persistence.exceptions.DatabaseException.databaseAccessorNotConnected(DatabaseException.java:116)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.incrementCallCount(DatasourceAccessor.java:309)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.beginTransaction(DatasourceAccessor.java:238)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicBeginTransaction(AbstractSession.java:526)
    at org.eclipse.persistence.sessions.server.ClientSession.addWriteConnection(ClientSession.java:693)
    at org.eclipse.persistence.sessions.server.ServerSession.acquireClientConnection(ServerSession.java:246)
    at org.eclipse.persistence.sessions.server.ClientSession.getAccessor(ClientSession.java:333)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.getAccessor(UnitOfWorkImpl.java:1867)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.unwrap(EntityManagerImpl.java:2540)
    (..)
</code>```

and

```<code>Exception [EclipseLink-4005] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: DatabaseAccessor not connected.
    at org.eclipse.persistence.exceptions.DatabaseException.databaseAccessorNotConnected(DatabaseException.java:116)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.incrementCallCount(DatasourceAccessor.java:309)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.rollbackTransaction(DatasourceAccessor.java:671)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.rollbackTransaction(DatabaseAccessor.java:1576)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicRollbackTransaction(AbstractSession.java:629)
    at org.eclipse.persistence.sessions.server.ClientSession.basicRollbackTransaction(ClientSession.java:186)
    at org.eclipse.persistence.internal.sessions.AbstractSession.rollbackTransaction(AbstractSession.java:3561)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.rollbackTransaction(UnitOfWorkImpl.java:4641)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.rollbackTransaction(RepeatableWriteUnitOfWork.java:522)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.release(UnitOfWorkImpl.java:4448)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.rollback(EntityTransactionImpl.java:127)
    (..)
</code>```

Please let me know if you need any more info. I'm happy to share it, as I'm currently out of ideas.

More info after enabling EclipseLink logging.

In the log I found that a connection gets disconnected shortly before the error occurs (see below). My first thought was that it's because it was marked as invalid (with DatabaseAccessor.setIsValid) but the only issue that happened before the error was an OptimisticLockException thrown 30min earlier, and it was gracefully handled by the app. Moreover, the same connection is then happily used for the next half an hour, so I don't think it was marked as invalid.

```<code>TRACE  [2017-09-01 10:01:04.851/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.851--ClientSession(436256688)--Connection(148152749)--Thread(Thread[Worker-659,5,main])-- commit transaction
TRACE  [2017-09-01 10:01:04.914/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.914--ServerSession(441145695)--Connection(148152749)--Thread(Thread[Worker-659,5,main])-- Connection released to connection pool [default].
DEBUG  [2017-09-01 10:01:04.914/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.914--ServerSession(441145695)--Connection(148152749)--Thread(Thread[Worker-659,5,main])-- disconnect
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- end unit of work commit
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- resume unit of work
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- release unit of work
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.929--ClientSession(436256688)--Thread(Thread[Worker-659,5,main])-- client released
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.query] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- Execute query ReadAllQuery(...)
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.929--ServerSession(441145695)--Connection(985262420)--Thread(Thread[Worker-659,5,main])-- Connection acquired from connection pool [default].
TRACE  [2017-09-01 10:01:04.961/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.961--ServerSession(441145695)--Connection(985262420)--Thread(Thread[Worker-659,5,main])-- Connection released to connection pool [default].
WARN   [2017-09-01 10:01:04.961/-0700] [Worker-659:org.eclipse.persistence] [ ] 2017-09-01 10:01:04.961--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])--
Local Exception Stack:
Exception [EclipseLink-4005] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: DatabaseAccessor not connected.
    at org.eclipse.persistence.exceptions.DatabaseException.databaseAccessorNotConnected(DatabaseException.java:116)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.incrementCallCount(DatasourceAccessor.java:309)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:581)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:537)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1805)
    at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:566)
(..)
</code>```

Is there any other reason why it could get disconnected?

答:
Allow me to answer my own question, so others can benefit from my finding.

The issue turned out to be caused by a bug in Eclipse Link. See bug 432410, at the time of writing still open.

The solution in my particular case was to avoid unwraping Connection i.e. do not call EntityManager.unwrap(Connection.class)

Body:
I'm having an issue chasing down the culprit of a "EclipseLink-4005 (..) DatabaseAccessor not connected" error in our app. It's a standalone application (not a web-app) with multiple threads connecting to the same db (Oracle). We use EclipseLink 2.4.2 and its internal connection pool with default settings. Transactions are managed in the app and can be nested. The app works fine most of the time, but occasionally, under high load fails with the "EclipseLink-4005 (..) DatabaseAccessor not connected" error.

I was able to reproduce the error in our test environment but have trouble understanding under what conditions it might happen. Some transactions are long running. Is it possible that some of them time out, causing the respective session to log out and resulting in the error in another thread?

Below are sample stack traces:

Exception [EclipseLink-4005] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: DatabaseAccessor not connected.
    at org.eclipse.persistence.exceptions.DatabaseException.databaseAccessorNotConnected(DatabaseException.java:116)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.incrementCallCount(DatasourceAccessor.java:309)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.beginTransaction(DatasourceAccessor.java:238)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicBeginTransaction(AbstractSession.java:526)
    at org.eclipse.persistence.sessions.server.ClientSession.addWriteConnection(ClientSession.java:693)
    at org.eclipse.persistence.sessions.server.ServerSession.acquireClientConnection(ServerSession.java:246)
    at org.eclipse.persistence.sessions.server.ClientSession.getAccessor(ClientSession.java:333)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.getAccessor(UnitOfWorkImpl.java:1867)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.unwrap(EntityManagerImpl.java:2540)
    (..)

and

Exception [EclipseLink-4005] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: DatabaseAccessor not connected.
    at org.eclipse.persistence.exceptions.DatabaseException.databaseAccessorNotConnected(DatabaseException.java:116)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.incrementCallCount(DatasourceAccessor.java:309)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.rollbackTransaction(DatasourceAccessor.java:671)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.rollbackTransaction(DatabaseAccessor.java:1576)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicRollbackTransaction(AbstractSession.java:629)
    at org.eclipse.persistence.sessions.server.ClientSession.basicRollbackTransaction(ClientSession.java:186)
    at org.eclipse.persistence.internal.sessions.AbstractSession.rollbackTransaction(AbstractSession.java:3561)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.rollbackTransaction(UnitOfWorkImpl.java:4641)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.rollbackTransaction(RepeatableWriteUnitOfWork.java:522)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.release(UnitOfWorkImpl.java:4448)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.rollback(EntityTransactionImpl.java:127)
    (..)

Please let me know if you need any more info. I'm happy to share it, as I'm currently out of ideas.

More info after enabling EclipseLink logging.

In the log I found that a connection gets disconnected shortly before the error occurs (see below). My first thought was that it's because it was marked as invalid (with DatabaseAccessor.setIsValid) but the only issue that happened before the error was an OptimisticLockException thrown 30min earlier, and it was gracefully handled by the app. Moreover, the same connection is then happily used for the next half an hour, so I don't think it was marked as invalid.

TRACE  [2017-09-01 10:01:04.851/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.851--ClientSession(436256688)--Connection(148152749)--Thread(Thread[Worker-659,5,main])-- commit transaction
TRACE  [2017-09-01 10:01:04.914/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.914--ServerSession(441145695)--Connection(148152749)--Thread(Thread[Worker-659,5,main])-- Connection released to connection pool [default].
DEBUG  [2017-09-01 10:01:04.914/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.914--ServerSession(441145695)--Connection(148152749)--Thread(Thread[Worker-659,5,main])-- disconnect
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- end unit of work commit
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- resume unit of work
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.transaction] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- release unit of work
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.929--ClientSession(436256688)--Thread(Thread[Worker-659,5,main])-- client released
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.query] [ ] 2017-09-01 10:01:04.929--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])-- Execute query ReadAllQuery(...)
TRACE  [2017-09-01 10:01:04.929/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.929--ServerSession(441145695)--Connection(985262420)--Thread(Thread[Worker-659,5,main])-- Connection acquired from connection pool [default].
TRACE  [2017-09-01 10:01:04.961/-0700] [Worker-659:org.eclipse.persistence.connection] [ ] 2017-09-01 10:01:04.961--ServerSession(441145695)--Connection(985262420)--Thread(Thread[Worker-659,5,main])-- Connection released to connection pool [default].
WARN   [2017-09-01 10:01:04.961/-0700] [Worker-659:org.eclipse.persistence] [ ] 2017-09-01 10:01:04.961--UnitOfWork(122187888)--Thread(Thread[Worker-659,5,main])--
Local Exception Stack:
Exception [EclipseLink-4005] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: DatabaseAccessor not connected.
    at org.eclipse.persistence.exceptions.DatabaseException.databaseAccessorNotConnected(DatabaseException.java:116)
    at org.eclipse.persistence.internal.databaseaccess.DatasourceAccessor.incrementCallCount(DatasourceAccessor.java:309)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:581)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:537)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1805)
    at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:566)
(..)

Is there any other reason why it could get disconnected?


问:
pass image to other view controller in collection view didSelectItemAt
I want to implement a collection view for images in an array and when I will select the image in collection view cell it should take me to other view controller with an image view in it and should show the enlarged image of the selected on.

What should be the code written for this in did select Item so that the selected image will be displayed in the other view controller?

答:
After you have created a DetailViewController with an imageView (with the frame you prefer) and a variable called for example var selectedImage: String?, in your collectionView delegate function didSelectItemAt you have to instantiate your DetailViewController and before presenting it you can set its selected image var.

Example:

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let selectedImage: String = imagesArray[indexPath.row]

    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let detailVC = storyboard.instantiateViewController(withIdentifier: "Your identifier") as? DetailViewController
    detailVC?.selectedImage = selectedImage
    //present or push your detailViewController
}
</code>```

Then in your DetailViewController:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    if let image = selectedImage {
        myImageView.image = UIImage(named: image)
    }
}
</code>```

Body:
After you have created a DetailViewController with an imageView (with the frame you prefer) and a variable called for example var selectedImage: String?, in your collectionView delegate function didSelectItemAt you have to instantiate your DetailViewController and before presenting it you can set its selected image var.

Example:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let selectedImage: String = imagesArray[indexPath.row]

    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let detailVC = storyboard.instantiateViewController(withIdentifier: "Your identifier") as? DetailViewController
    detailVC?.selectedImage = selectedImage
    //present or push your detailViewController
}

Then in your DetailViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    if let image = selectedImage {
        myImageView.image = UIImage(named: image)
    }
}


问:
How to set default working directory in Emacs - troubleshooting
I know this has been posted many times, but the solutions are not working for me. I've tried the following solutions from this post (Changing the default folder in Emacs):

Solution 1: Add (cd "C:/Users/Name/Desktop") to the .emacs file

Solution 2: Add (setq default-directory "C:/Documents and Settings/USER NAME/Desktop/" ) to the .emacs file

Solution 3: Right click the emacs short cut, hit properties and change the start in field to the desired directory.

and only solution 3 is working. Unfortunately, I need to use either solution 1 or 2.

I believe that my .emacs file is correct, because my theme is being correctly loaded/unloaded when I add/remove (load-theme 'light-blue t) from the .emacs file.

Here is my MOST RECENT .emacs file:

(message "Default Dir: %S" default-directory)
(setq-default default-directory "C:/Users/Lucas/")
(message "Default Dir: %S" default-directory)
(setq-default indent-tabs-mode nil)
(add-hook 'ruby-mode-hook
      (lambda ()
        (define-key ruby-mode-map "\C-c#" 'comment-or-uncomment-region)
        )
 )
(defadvice comment-or-uncomment-region (before slick-comment activate compile)
  "When called interactively with no active region, comment a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
       (line-beginning-position 2)))))
(load-theme 'light-blue t)
;setq default-directory "~/")
(setq-default default-directory "C:/Users/Lucas/")

(defun xp-read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
(setq last-nonmenu-event nil)
  (funcall (or read-file-name-function #'read-file-name-default)
           prompt dir default-filename mustmatch initial predicate))

(defun xp-save-as (filename &optional confirm)
  (interactive
   (list (if buffer-file-name
       (xp-read-file-name "Write file: " nil nil nil nil)
     (xp-read-file-name "Write file: " "C:/Users/Lucas/"
         (expand-file-name
          (file-name-nondirectory (buffer-name))
          "C:/Users/Lucas/")
         nil nil))
   (not current-prefix-arg)))
  (or (null filename) (string-equal filename "")
      (progn
  (if (file-directory-p filename)
      (setq filename (concat (file-name-as-directory filename)
           (file-name-nondirectory
            (or buffer-file-name (buffer-name))))))
  (and confirm
       (file-exists-p filename)
       (not (and (eq (framep-on-display) 'ns)
           (listp last-nonmenu-event)
           use-dialog-box))
       (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
     (error "Canceled")))
  (set-visited-file-name filename (not confirm))))
  (set-buffer-modified-p t)
  (and buffer-file-name
       (file-writable-p buffer-file-name)
       (setq buffer-read-only nil))
  (save-buffer)
  (vc-find-file-hook))
(defun comment-or-uncomment-region-or-line ()
    "Comments or uncomments the region or the current line if there's no active region."
    (interactive)
    (let (beg end)
        (if (region-active-p)
            (setq beg (region-beginning) end (region-end))
            (setq beg (line-beginning-position) end (line-end-position)))
        (comment-or-uncomment-region beg end)
        (next-line)))
(global-set-key (kbd "C-x C-;") 'comment-region)
(setq lazy-highlight-cleanup nil)
(message "Default Dir: %S" default-directory)
```

<p>My <code>emacs.exe</code> is saved under <code>C:\emacs\emacs-24.3\bin</code> (which is also my default directory, but I want to change it to <code>C:/Users/Lucas/</code>), and my <code>.emacs</code> is under my home - <code>C:\Users\Lucas</code>. </p>

<p><strong>UPDATE</strong></p>

<p>I RECENTLY found out that my command <code>(setq-default default-directory "C:/Users/Lucas/")</code>, which should set my <code>default-directory</code>, is not performing. Immediately after startup, this is my <code>*Messages*</code> buffer:</p>

```Default Dir: "C:\\emacs\\emacs-24.3\\bin/" [3 times]
For information about GNU Emacs and the GNU system, type C-h C-a.
```

It behaves as if I am overriding the .emacs file. I double/triple checked, and I cannot find another .emacs in my path. Also, I am not running Emacs from a shortcut. Any suggestions would be appreciated. Thanks for all of the support.

答:
The problem for me was the Initial Start Up Screen of emacs.

It can be deactivated by:

```<code>;; no startup msg
(setq inhibit-startup-message t)
</code>```

It seems that the default welcome screen of emacs (with the tutorial links) forces you to start in your $HOME path.

After that you can either cd or setq default-directory like so:

```<code>(setq default-directory "~/")
</code>```

or

```<code>(cd "~/")
</code>```

Body:
I know this has been posted many times, but the solutions are not working for me. I've tried the following solutions from this post (Changing the default folder in Emacs):

Solution 1: Add (cd "C:/Users/Name/Desktop") to the .emacs file

Solution 2: Add (setq default-directory "C:/Documents and Settings/USER NAME/Desktop/" ) to the .emacs file

Solution 3: Right click the emacs short cut, hit properties and change the start in field to the desired directory.

and only solution 3 is working. Unfortunately, I need to use either solution 1 or 2.

I believe that my .emacs file is correct, because my theme is being correctly loaded/unloaded when I add/remove (load-theme 'light-blue t) from the .emacs file.

Here is my MOST RECENT .emacs file:

(message "Default Dir: %S" default-directory)
(setq-default default-directory "C:/Users/Lucas/")
(message "Default Dir: %S" default-directory)
(setq-default indent-tabs-mode nil)
(add-hook 'ruby-mode-hook
      (lambda ()
        (define-key ruby-mode-map "\C-c#" 'comment-or-uncomment-region)
        )
 )
(defadvice comment-or-uncomment-region (before slick-comment activate compile)
  "When called interactively with no active region, comment a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
       (line-beginning-position 2)))))
(load-theme 'light-blue t)
;setq default-directory "~/")
(setq-default default-directory "C:/Users/Lucas/")

(defun xp-read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
(setq last-nonmenu-event nil)
  (funcall (or read-file-name-function #'read-file-name-default)
           prompt dir default-filename mustmatch initial predicate))

(defun xp-save-as (filename &optional confirm)
  (interactive
   (list (if buffer-file-name
       (xp-read-file-name "Write file: " nil nil nil nil)
     (xp-read-file-name "Write file: " "C:/Users/Lucas/"
         (expand-file-name
          (file-name-nondirectory (buffer-name))
          "C:/Users/Lucas/")
         nil nil))
   (not current-prefix-arg)))
  (or (null filename) (string-equal filename "")
      (progn
  (if (file-directory-p filename)
      (setq filename (concat (file-name-as-directory filename)
           (file-name-nondirectory
            (or buffer-file-name (buffer-name))))))
  (and confirm
       (file-exists-p filename)
       (not (and (eq (framep-on-display) 'ns)
           (listp last-nonmenu-event)
           use-dialog-box))
       (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
     (error "Canceled")))
  (set-visited-file-name filename (not confirm))))
  (set-buffer-modified-p t)
  (and buffer-file-name
       (file-writable-p buffer-file-name)
       (setq buffer-read-only nil))
  (save-buffer)
  (vc-find-file-hook))
(defun comment-or-uncomment-region-or-line ()
    "Comments or uncomments the region or the current line if there's no active region."
    (interactive)
    (let (beg end)
        (if (region-active-p)
            (setq beg (region-beginning) end (region-end))
            (setq beg (line-beginning-position) end (line-end-position)))
        (comment-or-uncomment-region beg end)
        (next-line)))
(global-set-key (kbd "C-x C-;") 'comment-region)
(setq lazy-highlight-cleanup nil)
(message "Default Dir: %S" default-directory)

My emacs.exe is saved under C:\emacs\emacs-24.3\bin (which is also my default directory, but I want to change it to C:/Users/Lucas/), and my .emacs is under my home - C:\Users\Lucas.

UPDATE

I RECENTLY found out that my command (setq-default default-directory "C:/Users/Lucas/"), which should set my default-directory, is not performing. Immediately after startup, this is my *Messages* buffer:

Default Dir: "C:\\emacs\\emacs-24.3\\bin/" [3 times]
For information about GNU Emacs and the GNU system, type C-h C-a.

It behaves as if I am overriding the .emacs file. I double/triple checked, and I cannot find another .emacs in my path. Also, I am not running Emacs from a shortcut. Any suggestions would be appreciated. Thanks for all of the support.

Body:
The problem for me was the Initial Start Up Screen of emacs.

It can be deactivated by:

;; no startup msg
(setq inhibit-startup-message t)

It seems that the default welcome screen of emacs (with the tutorial links) forces you to start in your $HOME path.

After that you can either cd or setq default-directory like so:

(setq default-directory "~/")

or

(cd "~/")


问:
No provider for Http
I have issue with injecting HTTP into Angular 2 application. Few days ago it was working fine but now I have error:

ORIGINAL EXCEPTION: No provider for Http!

There is main.ts

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
import { LoginModule } from "./login/login.module";
import { Http } from "@angular/http";

platformBrowserDynamic().bootstrapModule(LoginModule);
</code>```

Login module.ts

```<code>@NgModule({
    imports: [BrowserModule, FormsModule], // external modules for all components
    declarations: [LoginComponent], // component which belong to this module
    bootstrap: [LoginComponent] // component on load
})
export class LoginModule {
}
</code>```

And finally LoginComponent in LoginModule

```<code>import { Component } from '@angular/core';
import { AccountService } from "../data/account.service";
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { LocalStorage } from '../storage/storage';

@Component({
    selector: 'tp-login',
    templateUrl: `app/login/login.html`,
    styleUrls: ['app/login/login.css'],
    providers: [AccountService, LocalStorage]

})
</code>```

There is exception in LoginComponent about no HttpProvider.
Somone know how to solve that issue ?

答:
Add HttpModule in your component/ service file :

```<code>import { Http , HttpModule} from '@angular/http';
</code>```

and then add it HttpModule in app.module.ts:

```<code>import { Http ,HttpModule} from '@angular/http';
</code>```

and in ngModules imports also

```<code>imports: [
    BrowserModule,
    HttpModule   ]
</code>```

Title: No provider for Http

Body:
I have issue with injecting HTTP into Angular 2 application. Few days ago it was working fine but now I have error:

ORIGINAL EXCEPTION: No provider for Http!

There is main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
import { LoginModule } from "./login/login.module";
import { Http } from "@angular/http";

platformBrowserDynamic().bootstrapModule(LoginModule);

Login module.ts

@NgModule({
    imports: [BrowserModule, FormsModule], // external modules for all components
    declarations: [LoginComponent], // component which belong to this module
    bootstrap: [LoginComponent] // component on load
})
export class LoginModule {
}

And finally LoginComponent in LoginModule

import { Component } from '@angular/core';
import { AccountService } from "../data/account.service";
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { LocalStorage } from '../storage/storage';

@Component({
    selector: 'tp-login',
    templateUrl: `app/login/login.html`,
    styleUrls: ['app/login/login.css'],
    providers: [AccountService, LocalStorage]

})

There is exception in LoginComponent about no HttpProvider.
Somone know how to solve that issue ?

Body:
Add HttpModule in your component/ service file :

import { Http , HttpModule} from '@angular/http';

and then add it HttpModule in app.module.ts:

import { Http ,HttpModule} from '@angular/http';

and in ngModules imports also

imports: [
    BrowserModule,
    HttpModule   ]


问:
CUPS with Zebra printer doesn't print
EDIT:

I have found that the EPL2 driver allows for a partial print and crashes the printer after. Still no useful printing though

--------------------------

I have a Zebra printer (LP2844) hooked up to an RPI, with Jessie installed. The printer used to work with the direct USB connection and the CUPS service.

I tried adding a second one, but couldn't get it to work. After a day of fiddling I wanted to revert to the first setup. But now, even with one printer I can not get it to print even a test page.

The state in CUPS goes from "Rendering page 1" to "Rendering complete" and the job then disappears. CUPS believes the job to be completed successfully and the error_log is not appended.

I have been trying to switch the drivers between the ZPL driver and a raw driver. Previous to the second printer, I used the raw driver.

Windows seems to be able to print pages on the Zebra via USB connection.

I am totally at a loss here. Any help or insight would be greatly appreciated

答:
Turns out the printer was broken for some reason after adding a second one. Had to "recalibrate" the autosense feature.

Followed: https://km.zebra.com/kb/index?page=content&id=SO8281

Auto Sense Procedure

Make sure you have configured your driver or application for the media type you are using. Gap/Web or Black Bar (Mark). Send a test
  print to the printer before proceding so it is properly configured.
  Note: You can only send data when the button is green so cycle power
  if the printer button is red. 2 Turn off printer and have media loaded

Hold feed button down, and turn printer back on

When the red light starts flashing, release the feed button.

Printer light will turn green and advance a few blanks.

After printer stops advancing and prints the internal information, press the feed button one time.

You will get another label with the "Out of Dump" message on it.

The printer should feed one label each time you press the Feed Button.
  If one label is issued each time you press the Feed Button the printer
  has been properly calibrated.

Skipping labels or printing across multiple labels

If the printer is properly calibrated but still issues multiple labels
  when printing then assure your label setup for printing is set to the
  correct label size. If it is longer than the calibrated length the
  printer will print additional labels attempting to print the complete
  image. Allow for a small dead band if this is occurring by shortening
  your driver/software label size.

Title: CUPS with Zebra printer doesn't print


答: I would suggest using a dictionary if that will suit how your program works (Lots of different variables). The dictionary will allow you to grab the value and the values name.</p>

Title: How do I find out the name of a variable in python 2.7.9?

Body:
I often need to print variables for debugging purposes, and I found out that it helps a lot to also know what those variables are. So I would like to have a function that does sort of the following:

from __future__ import print_function

def get_variable_name(my_variable):
  ... ?

def print_with_variable_name(my_variable):
  print (get_variable_name(my_variable), ': ', my_variable)

a = 30
print_with_variable_name(a);

Expected output:

a: 30

I found some partial solutions to the problem where I could do that only in the function where the function was defined by the name a, otherwise it would print:

my_variable: 30

Is there any elegant solution to the problem where I can just write a module with this new print function and import it wherever I like?