问:
Why can't Docker see the driver executable in my Selenium Project? It throws The driver executable does not exist
```<code>See the stackrace:

[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
...
... TestNG 6.14.3 by C?dric Beust (cedric@beust.com)
...

Local Operating System: LINUX
Local Architecture: amd64
Selected Browser: FIREFOX
Disable AI based Visual Testing: true
Headless Mode: true
Connecting to Selenium Grid: false

Local Operating System: LINUX
Local Architecture: amd64
Selected Browser: FIREFOX
Disable AI based Visual Testing: true
Headless Mode: true
Connecting to Selenium Grid: false

Unable to capture screenshot: null

Local Operating System: LINUX
Local Architecture: amd64
Selected Browser: FIREFOX
Disable AI based Visual Testing: true
Headless Mode: true
Connecting to Selenium Grid: false

Unable to clear cookies: null
Test Execution Time: 0 minutes, 0 seconds
java.lang.NullPointerException
    at com.netsol.configs.AutomationFactory.closeEyes(AutomationFactory.java:151)
    at com.netsol.base.SeleniumBase.closeAutomationObjects(SeleniumBase.java:101)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:425)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:283)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:120)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
[ERROR] Tests run: 2, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 0.615 s <<< FAILURE! - in TestSuite
[ERROR] searchSomethingInGoogle(com.package.tests.features.frontend.TEST_GoogleSearch)  Time elapsed: 0.108 s  <<< FAILURE!
java.lang.IllegalStateException: The driver executable does not exist: /home/automation/myproject
    at com.package.tests.features.frontend.TEST_GoogleSearch.searchSomethingInGoogle(TEST_GoogleSearch.java:25)

[ERROR] closeAutomationObjects(com.package.tests.features.frontend.TEST_Demo)  Time elapsed: 0.175 s  <<< FAILURE!
java.lang.NullPointerException

[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR]   TEST_Demo>SeleniumBase.closeAutomationObjects:101 ? NullPointer
[ERROR]   TEST_GoogleSearch.searchSomethingInGoogle:25->SeleniumBase.getDriver:62 ? IllegalState
[INFO]
[ERROR] Tests run: 2, Failures: 2, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  23.142 s
[INFO] Finished at: 2019-05-29T09:21:51Z
</code>```

I need to execute my Selenium tests in Docker containers. I know Selenium provides hub and nodes containers but I have to write my own Dockerfile that will build a container which will execute tests with no grid configuration. Basically, I cannot use grid for some reason. I have written a Dockerfile. It gets passed at build stage. However, when I run the container it does not instantiate browser and throws exception that java.lang.IllegalStateException: The driver executable does not exist: /home/automation/myproject

Also, please note that I need to execute my tests in headless mode so configuration for running browser in headless mode is already there in myproject.

I have tried giving +rwx permissions to where I am downloading and unzipping my files.

See my Dockerfile below:

```<code>FROM ubuntu:latest
LABEL name="myproject" \
                author="TAFSEER HAIDER" \
                version="1.0" \
                description="Execute backend and frontend tests using myproject in containers"

    # Install Essential Softwares
RUN apt-get update \
    && apt-get install -y software-properties-common \
    && apt-get -y install openjdk-8-jdk \
    && apt-get install -y maven \
    && apt-get install -y firefox \
    && apt-get install -y unzip \
    && apt-get install -y curl \
    && apt-get install -y xvfb \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

# Chrome browser to run the tests
ARG CHROME_VERSION=latest
RUN if [ ${CHROME_VERSION} = "latest" ]; then curl https://dl-ssl.google.com/linux/linux_signing_key.pub -o /tmp/google.pub && cat /tmp/google.pub | apt-key add -; rm /tmp/google.pub  && echo 'deb http://dl.google.com/linux/chrome/deb/ stable main' > /etc/apt/sources.list.d/google.list  && mkdir -p /usr/share/desktop-directories  && apt-get -y update && apt-get install -y google-chrome-stable; else curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add && wget https://www.slimjet.com/chrome/download-chrome.php?file=lnx%2Fchrome64_$CHROME_VERSION.deb && dpkg -i download-chrome*.deb || true && apt-get install -y -f && rm -rf /var/lib/apt/lists/*;fi

# Disable the SUID sandbox so that chrome can launch without being in a privileged container
RUN dpkg-divert --add --rename --divert /opt/google/chrome/google-chrome.real /opt/google/chrome/google-chrome \
        && echo "#!/bin/bash\nexec /opt/google/chrome/google-chrome.real --no-sandbox --disable-setuid-sandbox \"\$@\"" > /opt/google/chrome/google-chrome \
        && chmod 755 /opt/google/chrome/google-chrome

RUN if [ ${CHROME_DRIVER_VERSION} != "latest" ]; then mkdir -p /opt/selenium && curl http://chromedriver.storage.googleapis.com/$CHROME_DRIVER_VERSION/chromedriver_linux64.zip -o /opt/selenium/chromedriver_linux64.zip && cd /opt/selenium; unzip /opt/selenium/chromedriver_linux64.zip; rm -rf chromedriver_linux64.zip; ln -fs /opt/selenium/chromedriver /usr/local/bin/chromedriver;fi

#Firefox browser to run the tests
ARG FIREFOX_VERSION=latest
RUN FIREFOX_DOWNLOAD_URL=$(if [ $FIREFOX_VERSION = "latest" ]; then echo "https://download.mozilla.org/?product=firefox-$FIREFOX_VERSION-ssl&os=linux64&lang=en-US"; else echo "https://download-installer.cdn.mozilla.net/pub/firefox/releases/$FIREFOX_VERSION/linux-x86_64/en-US/firefox-$FIREFOX_VERSION.tar.bz2"; fi) \
  && apt-get update -qqy \
  && apt-get -qqy --no-install-recommends install firefox \
  && rm -rf /var/lib/apt/lists/* /var/cache/apt/* \
  && wget --no-verbose -O /tmp/firefox.tar.bz2 $FIREFOX_DOWNLOAD_URL \
  && apt-get -y purge firefox \
  && rm -rf /opt/firefox \
  && tar -C /opt -xjf /tmp/firefox.tar.bz2 \
  && rm /tmp/firefox.tar.bz2 \
  && mv /opt/firefox /opt/firefox-$FIREFOX_VERSION \
  && ln -fs /opt/firefox-$FIREFOX_VERSION/firefox /usr/bin/firefox

# Add a user for running applications.
RUN apt-get update && apt-get install sudo -y \
    && adduser --disabled-password --gecos '' automation \
    && adduser automation sudo \
    && echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

# Copy myprojectproject to the specified directory in containerized Ubuntu Linux
COPY --chown=automation . /home/automation/myproject/

# Set working directory
WORKDIR /home/automation/myproject/

RUN chown -R automation:automation /home/automation/myproject\
    && chmod -R 777 /home/automation/myproject\
    && chmod -R +rwx /home/automation/myproject

USER automation

# Clean & compile myproject
RUN mvn clean test-compile
</code>```

答:
Your code would appear to be expecting to find geckodriver and chromedriver at /home/automation/myproject

Looking at your Dockerfile you haven't installed CromeDriver anywhere and Geckodriver is in /home/automation/myproject/src/test/resources/webdrivers/selenium_standalone_binaries/linux/marionette/64bit

It would be useful if you printed out the value of the ENV variables:

webdriver.chrome.driver

webdriver.gecko.driver

We can then be 100% sure where you code is expecting to find the driver binaries and you can then check they actually exist there.

Body:
See the stackrace:

[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
...
... TestNG 6.14.3 by C?dric Beust (cedric@beust.com)
...

Local Operating System: LINUX
Local Architecture: amd64
Selected Browser: FIREFOX
Disable AI based Visual Testing: true
Headless Mode: true
Connecting to Selenium Grid: false

Local Operating System: LINUX
Local Architecture: amd64
Selected Browser: FIREFOX
Disable AI based Visual Testing: true
Headless Mode: true
Connecting to Selenium Grid: false

Unable to capture screenshot: null

Local Operating System: LINUX
Local Architecture: amd64
Selected Browser: FIREFOX
Disable AI based Visual Testing: true
Headless Mode: true
Connecting to Selenium Grid: false

Unable to clear cookies: null
Test Execution Time: 0 minutes, 0 seconds
java.lang.NullPointerException
    at com.netsol.configs.AutomationFactory.closeEyes(AutomationFactory.java:151)
    at com.netsol.base.SeleniumBase.closeAutomationObjects(SeleniumBase.java:101)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:425)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:283)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:120)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
[ERROR] Tests run: 2, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 0.615 s <<< FAILURE! - in TestSuite
[ERROR] searchSomethingInGoogle(com.package.tests.features.frontend.TEST_GoogleSearch)  Time elapsed: 0.108 s  <<< FAILURE!
java.lang.IllegalStateException: The driver executable does not exist: /home/automation/myproject
    at com.package.tests.features.frontend.TEST_GoogleSearch.searchSomethingInGoogle(TEST_GoogleSearch.java:25)

[ERROR] closeAutomationObjects(com.package.tests.features.frontend.TEST_Demo)  Time elapsed: 0.175 s  <<< FAILURE!
java.lang.NullPointerException

[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR]   TEST_Demo>SeleniumBase.closeAutomationObjects:101 ? NullPointer
[ERROR]   TEST_GoogleSearch.searchSomethingInGoogle:25->SeleniumBase.getDriver:62 ? IllegalState
[INFO]
[ERROR] Tests run: 2, Failures: 2, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  23.142 s
[INFO] Finished at: 2019-05-29T09:21:51Z

I need to execute my Selenium tests in Docker containers. I know Selenium provides hub and nodes containers but I have to write my own Dockerfile that will build a container which will execute tests with no grid configuration. Basically, I cannot use grid for some reason. I have written a Dockerfile. It gets passed at build stage. However, when I run the container it does not instantiate browser and throws exception that java.lang.IllegalStateException: The driver executable does not exist: /home/automation/myproject

Also, please note that I need to execute my tests in headless mode so configuration for running browser in headless mode is already there in myproject.

I have tried giving +rwx permissions to where I am downloading and unzipping my files.

See my Dockerfile below:

FROM ubuntu:latest
LABEL name="myproject" \
                author="TAFSEER HAIDER" \
                version="1.0" \
                description="Execute backend and frontend tests using myproject in containers"

    # Install Essential Softwares
RUN apt-get update \
    && apt-get install -y software-properties-common \
    && apt-get -y install openjdk-8-jdk \
    && apt-get install -y maven \
    && apt-get install -y firefox \
    && apt-get install -y unzip \
    && apt-get install -y curl \
    && apt-get install -y xvfb \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

# Chrome browser to run the tests
ARG CHROME_VERSION=latest
RUN if [ ${CHROME_VERSION} = "latest" ]; then curl https://dl-ssl.google.com/linux/linux_signing_key.pub -o /tmp/google.pub && cat /tmp/google.pub | apt-key add -; rm /tmp/google.pub  && echo 'deb http://dl.google.com/linux/chrome/deb/ stable main' > /etc/apt/sources.list.d/google.list  && mkdir -p /usr/share/desktop-directories  && apt-get -y update && apt-get install -y google-chrome-stable; else curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add && wget https://www.slimjet.com/chrome/download-chrome.php?file=lnx%2Fchrome64_$CHROME_VERSION.deb && dpkg -i download-chrome*.deb || true && apt-get install -y -f && rm -rf /var/lib/apt/lists/*;fi

# Disable the SUID sandbox so that chrome can launch without being in a privileged container
RUN dpkg-divert --add --rename --divert /opt/google/chrome/google-chrome.real /opt/google/chrome/google-chrome \
        && echo "#!/bin/bash\nexec /opt/google/chrome/google-chrome.real --no-sandbox --disable-setuid-sandbox \"\$@\"" > /opt/google/chrome/google-chrome \
        && chmod 755 /opt/google/chrome/google-chrome

RUN if [ ${CHROME_DRIVER_VERSION} != "latest" ]; then mkdir -p /opt/selenium && curl http://chromedriver.storage.googleapis.com/$CHROME_DRIVER_VERSION/chromedriver_linux64.zip -o /opt/selenium/chromedriver_linux64.zip && cd /opt/selenium; unzip /opt/selenium/chromedriver_linux64.zip; rm -rf chromedriver_linux64.zip; ln -fs /opt/selenium/chromedriver /usr/local/bin/chromedriver;fi

#Firefox browser to run the tests
ARG FIREFOX_VERSION=latest
RUN FIREFOX_DOWNLOAD_URL=$(if [ $FIREFOX_VERSION = "latest" ]; then echo "https://download.mozilla.org/?product=firefox-$FIREFOX_VERSION-ssl&os=linux64&lang=en-US"; else echo "https://download-installer.cdn.mozilla.net/pub/firefox/releases/$FIREFOX_VERSION/linux-x86_64/en-US/firefox-$FIREFOX_VERSION.tar.bz2"; fi) \
  && apt-get update -qqy \
  && apt-get -qqy --no-install-recommends install firefox \
  && rm -rf /var/lib/apt/lists/* /var/cache/apt/* \
  && wget --no-verbose -O /tmp/firefox.tar.bz2 $FIREFOX_DOWNLOAD_URL \
  && apt-get -y purge firefox \
  && rm -rf /opt/firefox \
  && tar -C /opt -xjf /tmp/firefox.tar.bz2 \
  && rm /tmp/firefox.tar.bz2 \
  && mv /opt/firefox /opt/firefox-$FIREFOX_VERSION \
  && ln -fs /opt/firefox-$FIREFOX_VERSION/firefox /usr/bin/firefox

# Add a user for running applications.
RUN apt-get update && apt-get install sudo -y \
    && adduser --disabled-password --gecos '' automation \
    && adduser automation sudo \
    && echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

# Copy myprojectproject to the specified directory in containerized Ubuntu Linux
COPY --chown=automation . /home/automation/myproject/

# Set working directory
WORKDIR /home/automation/myproject/

RUN chown -R automation:automation /home/automation/myproject\
    && chmod -R 777 /home/automation/myproject\
    && chmod -R +rwx /home/automation/myproject

USER automation

# Clean & compile myproject
RUN mvn clean test-compile


来源: stackexchange

问:
Compare a two column with the same table to remove duplicate
A sample table with two column and I need to compare the column 1 and column 2 to the same table records and need to remove the column 1 + column 2 = column 2+column 1.

I tried to do self join and case condition. But its not working

答:
You can use the except operator.

"EXCEPT returns distinct rows from the left input query that aren't output by the right input query."

```<code>SELECT C1, C2 FROM table
Except
SELECT C2, C1 FROM table
</code>```

Example with your given data set : dbfiddle

ContentLicense: CC BY-SA 4.0

Body:
You can use the except operator.

"EXCEPT returns distinct rows from the left input query that aren't output by the right input query."

SELECT C1, C2 FROM table
Except
SELECT C2, C1 FROM table

Example with your given data set : dbfiddle


问:
How to apply "to_f" to a column for all results in an active record query inside rails console
I have this query:
p = Payment.where(:client_id => 1)

Then only some fields, so I execute this:
p.select(:id, :created_at, :amount)

The issue is that every amount in the result comes as BigDecimal, and it's not readable. I need to apply to_f function inside rails console to have a readable set of results.

I tried map,like this:
p.map {|p| p.amount.to_f}
But it returns to me an array only with the amounts, and I need it to be along with the other attributes.

答:
if you always want float of amount you can set callback after_find

```<code>class Payment < ActiveRecord::Base
  after_find do |payment|
    self.amount = self.amount.to_f
  end
end
</code>```

it will always give you float value when you find object

It will not update value in your db.

Please Look on this Rails Callback

Body:
if you always want float of amount you can set callback after_find

class Payment < ActiveRecord::Base
  after_find do |payment|
    self.amount = self.amount.to_f
  end
end

it will always give you float value when you find object

It will not update value in your db.

Please Look on this Rails Callback


问:
MassAssignmentException in updateorcreate in laravel 5.4
I am newbie to laravel I am using updateorcreate for model. But this is showing error MassAssignmentException end_time In Model Tasktimelog I am using protected $guarded = array(); Here is what I am Doing.</p>

```<code>$endtask= Tasktimelog::updateOrCreate(
        [
            'task_id' => $taskid,
            'action_type'=>4,
            'user_id'=> auth()->id()
        ],
        [
          'end_time'             => $endtimeis,
          'total_time'           => request('totalseconds'),
          'remark'               => request('remark'),
          'actual_complete_time' => $diff,
          'project_id'           => $getprojectid->project_id
        ]);
</code>```

答:
Laravel doesn't let you to massive update fields of your database if you don't specificate it:

What you have to do is add the $fillable variable to your model with the fields that can be massively updated:

```<code>class Tasktimelog extends Model
{
    protected $fillable = ['task_id', 'action_type', 'user_id']; //and the rest of your fields
}
</code>```

Laravel Doc: While $fillable serves as a "white list" of attributes that should be mass assignable, you may also choose to use $guarded. The $guarded property should contain an array of attributes that you do not want to be mass assignable.

https://laravel.com/docs/5.5/eloquent#eloquent-model-conventions

ContentLicense: CC BY-SA 3.0

Body:
I am newbie to laravel I am using updateorcreate for model. But this is showing error MassAssignmentException end_time In Model Tasktimelog I am using protected $guarded = array(); Here is what I am Doing.

$endtask= Tasktimelog::updateOrCreate(
        [
            'task_id' => $taskid,
            'action_type'=>4,
            'user_id'=> auth()->id()
        ],
        [
          'end_time'             => $endtimeis,
          'total_time'           => request('totalseconds'),
          'remark'               => request('remark'),
          'actual_complete_time' => $diff,
          'project_id'           => $getprojectid->project_id
        ]);

Body:
Laravel doesn't let you to massive update fields of your database if you don't specificate it:

What you have to do is add the $fillable variable to your model with the fields that can be massively updated:

class Tasktimelog extends Model
{
    protected $fillable = ['task_id', 'action_type', 'user_id']; //and the rest of your fields
}

Laravel Doc: While $fillable serves as a "white list" of attributes that should be mass assignable, you may also choose to use $guarded. The $guarded property should contain an array of attributes that you do not want to be mass assignable.

https://laravel.com/docs/5.5/eloquent#eloquent-model-conventions


问:
Why are cookies set with `setcookie` starting with a dot?
Example:

```<code><?php
setcookie('test_cookie', '1', time()+3600, '/', $_SERVER['SERVER_NAME']);
echo $_SERVER['SERVER_NAME'];  // outputs: entwicklung.hausfux
</code>```

Afaik the dot is a wildcard selector.

This causes login problems if you are trying to login into subdomain websites.

答:
There are the two example for this.

```<code>n1.example.com and .n1.example.com
</code>```

n1.example.com using for domain and .n1.example.com for subdomain.
subdomain set dot value. it just use for subdomains as inherit cookies from their parent domain.

Body:
Example:

<?php
setcookie('test_cookie', '1', time()+3600, '/', $_SERVER['SERVER_NAME']);
echo $_SERVER['SERVER_NAME'];  // outputs: entwicklung.hausfux

Afaik the dot is a wildcard selector.

This causes login problems if you are trying to login into subdomain websites.

Body:
There are the two example for this.

n1.example.com and .n1.example.com

n1.example.com using for domain and .n1.example.com for subdomain.
subdomain set dot value. it just use for subdomains as inherit cookies from their parent domain.


问:
Drupal: Render a view from admin using frontend theme
Does anyone know a way to programmatically render a view from a module using the default theme after editing a node?

I'm basically trying to create a static html page of a view.

I have the following code in a custom module:

```<code>function MODULENAME_node_update($node) {
  unset($node->is_new);
  unset($node->original);
  entity_get_controller('node')->resetCache(array($node->nid));
  $view = views_get_view('references');
  $view->set_display('block');
  $output = $view->render();
  file_put_contents('references.html', $output);
}
</code>```

The code works but for obvious reasons it renders the view using the admin theme.

I have tried several things to no avail:

variable_set

```<code>function MODULENAME_node_update($node) {
  variable_set('admin_theme', 'DEFAULT THEME HERE');
  [...]
  variable_set('admin_theme', 'ADMIN THEME HERE');
}
</code>```

This hook is probably not the right place to switch themes as it is invoked too late for this.

global $custom_theme

```<code>function MODULENAME_node_update($node) {
  global $custom_theme;
  $custom_theme = 'DEFAULT THEME HERE';
  [...]
  $custom_theme = 'ADMIN THEME HERE';
}
</code>```

custom menu item

```<code>function MODULE_NAME_menu(){
  $items = array();

  $items['outputview'] = array(
    'title' => 'Test',
    'type' => MENU_CALLBACK,
    'page callback' => 'MODULE_NAME_output_view',
    'access callback' => TRUE,
    'theme callback' => 'DEFAULT THEME HERE'
  );

  return $items;
}

function MODULE_NAME_output_view() {
  $view = views_get_view('references');
  $view->set_display('block');
  $output = $view->render();
  file_put_contents('references.html', $output);
}

function MODULE_NAME_node_update($node) {
    unset($node->is_new);
    unset($node->original);
    entity_get_controller('node')->resetCache(array($node->nid));
    menu_execute_active_handler('outputview', FALSE); // or via curl
}
</code>```

This works as the view gets rendered correctly but still uses the admin theme.

hook_custom_theme

```<code>function MODULENAME_custom_theme(){
  return 'DEFAULT THEME HERE';
}
</code>```

答:
Here is some self-documenting code based on the answer by lmeurs:</p>

```<code>/**
 * Switch to or from an alternative theme in the middle of a request.
 *
 * This is useful if you need to render something (like a node) in a different
 * theme without changing the theme of the entire page. An example use case is
 * when you need to render something for a front end user from an admin page.
 *
 * Usage example:
 *     my_module_switch_theme('bartik');
 *     $node = node_load(1);
 *     $renderable = node_view($node);
 *     $rendered = render($renderable);
 *     my_module_switch_theme();
 *
 * @param string|null $to
 *   The name of the theme to switch to. If NULL, it switches back to the
 *   original theme.
 */
function my_module_switch_theme(string $to = NULL) {
  // Backup the original theme.
  static $original_theme;
  if (empty($original_theme)) {
    $original_theme = drupal_static('menu_get_custom_theme');
  }

  // Get a reference to the current theme value.
  $custom_theme = &drupal_static('menu_get_custom_theme');

  // Perform the switch.
  $custom_theme = $to ?? $original_theme;
  unset($GLOBALS['theme']);
  drupal_theme_initialize();
}
</code>```

Body:
Does anyone know a way to programmatically render a view from a module using the default theme after editing a node?

I'm basically trying to create a static html page of a view.

I have the following code in a custom module:

function MODULENAME_node_update($node) {
  unset($node->is_new);
  unset($node->original);
  entity_get_controller('node')->resetCache(array($node->nid));
  $view = views_get_view('references');
  $view->set_display('block');
  $output = $view->render();
  file_put_contents('references.html', $output);
}

The code works but for obvious reasons it renders the view using the admin theme.

I have tried several things to no avail:

variable_set

function MODULENAME_node_update($node) {
  variable_set('admin_theme', 'DEFAULT THEME HERE');
  [...]
  variable_set('admin_theme', 'ADMIN THEME HERE');
}

This hook is probably not the right place to switch themes as it is invoked too late for this.

global $custom_theme

function MODULENAME_node_update($node) {
  global $custom_theme;
  $custom_theme = 'DEFAULT THEME HERE';
  [...]
  $custom_theme = 'ADMIN THEME HERE';
}

custom menu item

function MODULE_NAME_menu(){
  $items = array();

  $items['outputview'] = array(
    'title' => 'Test',
    'type' => MENU_CALLBACK,
    'page callback' => 'MODULE_NAME_output_view',
    'access callback' => TRUE,
    'theme callback' => 'DEFAULT THEME HERE'
  );

  return $items;
}

function MODULE_NAME_output_view() {
  $view = views_get_view('references');
  $view->set_display('block');
  $output = $view->render();
  file_put_contents('references.html', $output);
}

function MODULE_NAME_node_update($node) {
    unset($node->is_new);
    unset($node->original);
    entity_get_controller('node')->resetCache(array($node->nid));
    menu_execute_active_handler('outputview', FALSE); // or via curl
}

This works as the view gets rendered correctly but still uses the admin theme.

hook_custom_theme

function MODULENAME_custom_theme(){
  return 'DEFAULT THEME HERE';
}

Body:
Here is some self-documenting code based on the answer by lmeurs:

/**
 * Switch to or from an alternative theme in the middle of a request.
 *
 * This is useful if you need to render something (like a node) in a different
 * theme without changing the theme of the entire page. An example use case is
 * when you need to render something for a front end user from an admin page.
 *
 * Usage example:
 *     my_module_switch_theme('bartik');
 *     $node = node_load(1);
 *     $renderable = node_view($node);
 *     $rendered = render($renderable);
 *     my_module_switch_theme();
 *
 * @param string|null $to
 *   The name of the theme to switch to. If NULL, it switches back to the
 *   original theme.
 */
function my_module_switch_theme(string $to = NULL) {
  // Backup the original theme.
  static $original_theme;
  if (empty($original_theme)) {
    $original_theme = drupal_static('menu_get_custom_theme');
  }

  // Get a reference to the current theme value.
  $custom_theme = &drupal_static('menu_get_custom_theme');

  // Perform the switch.
  $custom_theme = $to ?? $original_theme;
  unset($GLOBALS['theme']);
  drupal_theme_initialize();
}


问:
Unable to get proper GET response
I am trying to implement a GET and a POST method in spring-boot. While calling GET method not getting proper response.

My Controller class

```<code>@RestController
@RequestMapping("api/public")
public class PublicRestApiController {

@GetMapping("users")
public List<User> users(){
    return this.userRepository.findAll();
}

@PostMapping(path="/save")
@ResponseBody public User insertusers( @RequestBody UserRequest requestUser){
    User user = new User(requestUser.getUsername(),passwordEncoder.encode(requestUser.getPassword()),requestUser.getRoles(),requestUser.getPermissions());
    try {
        user = this.userRepository.save(user);
        return user;
    }
    catch(Error e) {
        return user;
    }
}

}
</code>```

UserRequest class

```<code>public class UserRequest {

public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public int getActive() {
    return active;
}
public void setActive(int active) {
    this.active = active;
}
public String getRoles() {
    return roles;
}
public void setRoles(String roles) {
    this.roles = roles;
}
public String getPermissions() {
    return permissions;
}
public void setPermissions(String permissions) {
    this.permissions = permissions;
}
private String username;
private String password;
private int active;
private String roles = "";
private String permissions = "";

}
</code>```

User Class

```<code>@Entity
@Table(name = "USER_DETAILS")
public class User {

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

@Column(nullable = false)
private String username;

@Column(nullable = false)
private String PASSWORD;

@Column
private int ACTIVE;

@Column
private String ROLES = "";

@Column
private String PERMISSIONS = "";

public User(String username, String password, String roles, String permissions){
    this.username = username;
    this.PASSWORD = password;
    this.ROLES = roles;
    this.PERMISSIONS = permissions;
    this.ACTIVE = 1;
}

public User(){}

public int getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return PASSWORD;
}

public int getActive() {
    return ACTIVE;
}

public String getRoles() {
    return ROLES;
}

public String getPermissions() {
    return PERMISSIONS;
}

public void setId(int id) {
    this.id = id;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.PASSWORD = password;
}

public void setActive(int active) {
    this.ACTIVE = active;
}

public void setRoles(String roles) {
    this.ROLES = roles;
}

public void setPermissions(String permissions) {
    this.PERMISSIONS = permissions;
}
}
</code>```

UserRepository class

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Long>{

}
</code>```

POST method is working fine, but while calling GET method, id field is coming default value 0.Not fetching proper ID values. And also while running server, if I call POST method, it is inserting data in database, but that newly inserted data is not getting fetched by GET method.Only those data are getting fetched, which I have already inserted in the database.

This is the data in database

This is the response which I am getting form GET method

答:
You are not returning reponse properly. Try this.</p>

```<code>    @GetMapping("users")
public ResponseEntity<List<Article>> users(){
        return new ResponseEntity<List<Article>>(this.userRepository.findAll(), HttpStatus.OK);
}
</code>```

Title: Unable to get proper GET response

Body:
I am trying to implement a GET and a POST method in spring-boot. While calling GET method not getting proper response.

My Controller class

@RestController
@RequestMapping("api/public")
public class PublicRestApiController {

@GetMapping("users")
public List<User> users(){
    return this.userRepository.findAll();
}

@PostMapping(path="/save")
@ResponseBody public User insertusers( @RequestBody UserRequest requestUser){
    User user = new User(requestUser.getUsername(),passwordEncoder.encode(requestUser.getPassword()),requestUser.getRoles(),requestUser.getPermissions());
    try {
        user = this.userRepository.save(user);
        return user;
    }
    catch(Error e) {
        return user;
    }
}

}

UserRequest class

public class UserRequest {

public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public int getActive() {
    return active;
}
public void setActive(int active) {
    this.active = active;
}
public String getRoles() {
    return roles;
}
public void setRoles(String roles) {
    this.roles = roles;
}
public String getPermissions() {
    return permissions;
}
public void setPermissions(String permissions) {
    this.permissions = permissions;
}
private String username;
private String password;
private int active;
private String roles = "";
private String permissions = "";

}

User Class

@Entity
@Table(name = "USER_DETAILS")
public class User {

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

@Column(nullable = false)
private String username;

@Column(nullable = false)
private String PASSWORD;

@Column
private int ACTIVE;

@Column
private String ROLES = "";

@Column
private String PERMISSIONS = "";

public User(String username, String password, String roles, String permissions){
    this.username = username;
    this.PASSWORD = password;
    this.ROLES = roles;
    this.PERMISSIONS = permissions;
    this.ACTIVE = 1;
}

public User(){}

public int getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return PASSWORD;
}

public int getActive() {
    return ACTIVE;
}

public String getRoles() {
    return ROLES;
}

public String getPermissions() {
    return PERMISSIONS;
}

public void setId(int id) {
    this.id = id;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.PASSWORD = password;
}

public void setActive(int active) {
    this.ACTIVE = active;
}

public void setRoles(String roles) {
    this.ROLES = roles;
}

public void setPermissions(String permissions) {
    this.PERMISSIONS = permissions;
}
}

UserRepository class

@Repository
public interface UserRepository extends JpaRepository<User, Long>{

}

POST method is working fine, but while calling GET method, id field is coming default value 0.Not fetching proper ID values. And also while running server, if I call POST method, it is inserting data in database, but that newly inserted data is not getting fetched by GET method.Only those data are getting fetched, which I have already inserted in the database.

This is the data in database

This is the response which I am getting form GET method

Body:
You are not returning reponse properly. Try this.

    @GetMapping("users")
public ResponseEntity<List<Article>> users(){
        return new ResponseEntity<List<Article>>(this.userRepository.findAll(), HttpStatus.OK);
}


问:
Convert from days to milliseconds
I want to create a function that will convert the days into milliseconds. The days format is stored as 0.2444, so how to convert this to milliseonds?</p>

答:
```<code>int day = 5;
long dayInMilliseconds = day * org.apache.commons.lang.time.DateUtils.MILLIS_PER_DAY
</code>```

Title: Convert from days to milliseconds


问:
What is the difference between "" and nothing
Hello I would like to know what is the difference between '' and nothing I mean for instance if I take this example :

```<code>"test":[""]
</code>```

and

```<code>"test":[""]
</code>```

答:
Though you have given identical examples, I think you tried to provide these two:

```<code>"test":[""]
</code>```

and this: "test":[]

For the first case, your test array length is 1. So, accessing test[0] will give you ""
But for the second case, its length is 0. So no element in the later but for the first one you have "".
That's it.

Body:
Hello I would like to know what is the difference between '' and nothing I mean for instance if I take this example :

"test":[""]

and

"test":[""]

Body:
Though you have given identical examples, I think you tried to provide these two:

"test":[""]

and this: "test":[]

For the first case, your test array length is 1. So, accessing test[0] will give you ""
But for the second case, its length is 0. So no element in the later but for the first one you have "".
That's it.


问:
How to sort (custom) strings from a list
I'm using a list structure that contains only strings. I have to sort them by length && alphabetically.

example input:

tea, tram, top, ter, troop, true

results in:

tea, ter, top, tram, true, troop

I can sort the strings on the number of characters, but I'm stuck on how to re-reorder alphabetically. The result string shows: tea,top,ter.. and they're not ordered alphabetically.
I'm using insertion sort and a auxiliary list.

```<code>List_pointer<string> odd1(odd);
auto p1 = odd1.next(odd1.begin());
auto p2 = p1;
if (!odd1.empty())
{
    while (!odd1.end(p1))
    {
        p2 = odd1.previous(p1);
    while (p1 != odd1.begin() && ((odd1.read(p2).size()) > (odd1.read(p1).size())))
    {
    {
        auto temp = odd1.read(p1);
        odd1.write(odd1.read(p2),p1);
        odd1.write(temp,p2);
    }
        p1 = odd1.previous(p1);
        p2 = odd1.previous(p1);
    }
    p1 = odd1.next(p1);
   }
}
cout << odd1 << endl;
</code>```

I know that the error is here: while (p1 != odd1.begin() && ((odd1.read(p2).size()) > (odd1.read(p1).size()))) but I'm stuck.

答:
The compare function to use is something like</p>

```<code>bool compare_size_then_alpha(const std::string& lhs, const std::string& rhs)
{
    if (lhs.size() != rhs.size()) {
        return lhs.size() < rhs.size();
    }
    return lhs < rhs; // lexical order
}
</code>```

Body:
I'm using a list structure that contains only strings. I have to sort them by length && alphabetically.

example input:

tea, tram, top, ter, troop, true

results in:

tea, ter, top, tram, true, troop

I can sort the strings on the number of characters, but I'm stuck on how to re-reorder alphabetically. The result string shows: tea,top,ter.. and they're not ordered alphabetically.
I'm using insertion sort and a auxiliary list.

List_pointer<string> odd1(odd);
auto p1 = odd1.next(odd1.begin());
auto p2 = p1;
if (!odd1.empty())
{
    while (!odd1.end(p1))
    {
        p2 = odd1.previous(p1);
    while (p1 != odd1.begin() && ((odd1.read(p2).size()) > (odd1.read(p1).size())))
    {
    {
        auto temp = odd1.read(p1);
        odd1.write(odd1.read(p2),p1);
        odd1.write(temp,p2);
    }
        p1 = odd1.previous(p1);
        p2 = odd1.previous(p1);
    }
    p1 = odd1.next(p1);
   }
}
cout << odd1 << endl;

I know that the error is here: while (p1 != odd1.begin() && ((odd1.read(p2).size()) > (odd1.read(p1).size()))) but I'm stuck.

Body:
The compare function to use is something like

bool compare_size_then_alpha(const std::string& lhs, const std::string& rhs)
{
    if (lhs.size() != rhs.size()) {
        return lhs.size() < rhs.size();
    }
    return lhs < rhs; // lexical order
}


问:
Coerce types in different namespaces with Identical layout in C#
I've started writing an interface for FedEx's webservice APIs.  They have 3 different APIs that I'm interested in; Rate, Ship, and Track.  I am generating the service proxies with SvcUtil.exe.

The different service endpoints are each specified by FedEx in their own WSDL files.  Each service endpoint has it's own xml namespace (e.g. http://fedex.com/ws/rate/v5 and http://fedex.com/ws/ship/v5)

The service endpoints do use quite a few identical types such as Address, Measurements, Weight, AuthenticationDetail, ClientDetail, etc...

And here is where the problem lies, I can provide all the WSDL files at the same time to SvcUtil.exe and normally it would coalesce any identical types into a single shared type, but since each of FedEx's services are in their own namespace, and they redeclare these types in each WSDL file under that namespace what I end up with instead is an Address, Address1, and Address2 one for each namespace.

To solve that issue, what I do now is to run each WSDL through svcutil separately and put them each in their own .NET namespace (e.g. FedEx.Rate, FedEx.Ship, FedEx.Track).  The problem with this is that now I have a distinct address type in each namespace (Fedex.Rate.Address, FedEx.Ship.Address).

This makes it difficult to generalize the code used between the services like a GetAuthenticationDetail() factory method so I don't have to repeat that code in every place I use the different services.

Is there any way in C# to Coerce FedEx.Rate.Address to FedEx.Ship.Address?

答:
So here is how I implemented the implicit conversion operators using reflection.  SvcUtil creates partial classes so I added an implicit conversion operator for each direction of the conversion so in the client code you can just type Type1 = Type2.

In this snippet WebAuthenticationCredentials is a property of WebAuthenticationDetails so while iterating the properties of the source object if the types arent the same (built-ins) it checks the name of the types (without the namespace) and recursively calls the copy function with those properties.

```<code>internal class ReflectionCopy
{
    public static ToType Copy<ToType>(object from) where ToType : new()
    {
        return (ToType)Copy(typeof(ToType), from);
    }

    public static object Copy(Type totype, object from)
    {
        object to = Activator.CreateInstance(totype);

        PropertyInfo[] tpis = totype.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo[] fpis = from.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        // Go through each property on the "to" object
        Array.ForEach(tpis, tpi =>
        {
            // Find a matching property by name on the "from" object
            PropertyInfo fpi = Array.Find(fpis, pi => pi.Name == tpi.Name);
            if (fpi != null)
            {
                // Do the source and destination have identical types (built-ins)?
                if (fpi.PropertyType == tpi.PropertyType)
                {
                    // Transfer the value
                    tpi.SetValue(to, fpi.GetValue(from, null), null);
                }
                else
                {
                    // If type names are the same (ignoring namespace) copy them recursively
                    if (fpi.PropertyType.Name == tpi.PropertyType.Name)
                        tpi.SetValue(to, Copy(fpi.PropertyType, tpi.GetValue(from, null)), null);
                }
            }
        });

        return to;
    }
}

namespace Rate
{
    partial class WebAuthenticationDetail
    {
        public static implicit operator Ship.WebAuthenticationDetail(WebAuthenticationDetail from)
        {
            return ReflectionCopy.Copy<Ship.WebAuthenticationDetail>(from);
        }
    }

    partial class WebAuthenticationCredential
    {
        public static implicit operator Ship.WebAuthenticationCredential(WebAuthenticationCredential from)
        {
            return ReflectionCopy.Copy<Ship.WebAuthenticationCredential>(from);
        }
    }
}

namespace Ship
{
    partial class WebAuthenticationDetail
    {
        public static implicit operator Rate.WebAuthenticationDetail(WebAuthenticationDetail from)
        {
            return ReflectionCopy.Copy<Rate.WebAuthenticationDetail>(from);
        }
    }

    partial class WebAuthenticationCredential
    {
        public static implicit operator Rate.WebAuthenticationCredential(WebAuthenticationCredential from)
        {
            return ReflectionCopy.Copy<Rate.WebAuthenticationCredential>(from);
        }
    }
}
</code>```

OwnerDisplayName: joshperry

ContentLicense: CC BY-SA 2.5

Body:
So here is how I implemented the implicit conversion operators using reflection.  SvcUtil creates partial classes so I added an implicit conversion operator for each direction of the conversion so in the client code you can just type Type1 = Type2.

In this snippet WebAuthenticationCredentials is a property of WebAuthenticationDetails so while iterating the properties of the source object if the types arent the same (built-ins) it checks the name of the types (without the namespace) and recursively calls the copy function with those properties.

internal class ReflectionCopy
{
    public static ToType Copy<ToType>(object from) where ToType : new()
    {
        return (ToType)Copy(typeof(ToType), from);
    }

    public static object Copy(Type totype, object from)
    {
        object to = Activator.CreateInstance(totype);

        PropertyInfo[] tpis = totype.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo[] fpis = from.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        // Go through each property on the "to" object
        Array.ForEach(tpis, tpi =>
        {
            // Find a matching property by name on the "from" object
            PropertyInfo fpi = Array.Find(fpis, pi => pi.Name == tpi.Name);
            if (fpi != null)
            {
                // Do the source and destination have identical types (built-ins)?
                if (fpi.PropertyType == tpi.PropertyType)
                {
                    // Transfer the value
                    tpi.SetValue(to, fpi.GetValue(from, null), null);
                }
                else
                {
                    // If type names are the same (ignoring namespace) copy them recursively
                    if (fpi.PropertyType.Name == tpi.PropertyType.Name)
                        tpi.SetValue(to, Copy(fpi.PropertyType, tpi.GetValue(from, null)), null);
                }
            }
        });

        return to;
    }
}

namespace Rate
{
    partial class WebAuthenticationDetail
    {
        public static implicit operator Ship.WebAuthenticationDetail(WebAuthenticationDetail from)
        {
            return ReflectionCopy.Copy<Ship.WebAuthenticationDetail>(from);
        }
    }

    partial class WebAuthenticationCredential
    {
        public static implicit operator Ship.WebAuthenticationCredential(WebAuthenticationCredential from)
        {
            return ReflectionCopy.Copy<Ship.WebAuthenticationCredential>(from);
        }
    }
}

namespace Ship
{
    partial class WebAuthenticationDetail
    {
        public static implicit operator Rate.WebAuthenticationDetail(WebAuthenticationDetail from)
        {
            return ReflectionCopy.Copy<Rate.WebAuthenticationDetail>(from);
        }
    }

    partial class WebAuthenticationCredential
    {
        public static implicit operator Rate.WebAuthenticationCredential(WebAuthenticationCredential from)
        {
            return ReflectionCopy.Copy<Rate.WebAuthenticationCredential>(from);
        }
    }
}

LastEditorDisplayName: joshperry


问:
How to set a timeout for a popup?
I created a popup that appears when I click a button, but to make it disappear I have to click again.
Is there a way to set a timer and make it disappear?

This is the code:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}</code>```

Click me to toggle the popup!
  A Simple Popup!

```

答:
I suggest you to read into the function setTimeout() on w3schools or mozilla dev, which are both two great sites for programming beginners.

Your problem could be solved like shown in the following snippet:

```<code>function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");

  if(popup.classList.contains("show")) // Check if the popup is shown
     setTimeout(() => popup.classList.remove("show"), 10000) // If yes hide it after 10000 milliseconds
}
</code>```

Title: How to set a timeout for a popup?

Body:
I created a popup that appears when I click a button, but to make it disappear I have to click again.
Is there a way to set a timer and make it disappear?

This is the code:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}

.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}

Click me to toggle the popup!
  A Simple Popup!

Body:
I suggest you to read into the function setTimeout() on w3schools or mozilla dev, which are both two great sites for programming beginners.

Your problem could be solved like shown in the following snippet:

function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");

  if(popup.classList.contains("show")) // Check if the popup is shown
     setTimeout(() => popup.classList.remove("show"), 10000) // If yes hide it after 10000 milliseconds
}


问:
How can i pass extra parameter when color changed?
I want to pass some addition parameter like this when the color changed?

I am using this angularjs color picker.

https://github.com/ruhley/angular-color-picker/

I want to use it like below

<color-picker ng-model="account_type.type_color" options="options" event-api="eventApi(extraParameter)">

<color-picker ng-model="account_type.type_color" options="options" event-api="eventApi">
```

Can you please help me to solve out this issue?

答:
You can add an attribute (Let's say id) to the component and read it in the onChange callback (using the api).

angular.module('app', ['color.picker']).
controller('ctrl', function($scope) {
  $scope.color = '#FF0000';
  $scope.eventApi = {
    onChange:  function(api, color, $event) {
      const id = api.getElement().attr('id');
      console.log(id, color);
    },
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/tinycolor/1.4.1/tinycolor.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-color-picker/3.4.8/angularjs-color-picker.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-color-picker/3.4.8/angularjs-color-picker.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <color-picker id="cp-1" ng-model="color" options="options" api="api" event-api="eventApi"></color-picker>
</div></code>```

https://stackblitz.com/edit/angularjs-bqe6ht?file=home%2Fhome.controller.js

Body:
I want to pass some addition parameter like this when the color changed?

I am using this angularjs color picker.

https://github.com/ruhley/angular-color-picker/

I want to use it like below

<color-picker ng-model="account_type.type_color" options="options" event-api="eventApi(extraParameter)">

<color-picker ng-model="account_type.type_color" options="options" event-api="eventApi">

Can you please help me to solve out this issue?

Body:
You can add an attribute (Let's say id) to the component and read it in the onChange callback (using the api).

angular.module('app', ['color.picker']).
controller('ctrl', function($scope) {
  $scope.color = '#FF0000';
  $scope.eventApi = {
    onChange:  function(api, color, $event) {
      const id = api.getElement().attr('id');
      console.log(id, color);
    },
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/tinycolor/1.4.1/tinycolor.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-color-picker/3.4.8/angularjs-color-picker.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-color-picker/3.4.8/angularjs-color-picker.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <color-picker id="cp-1" ng-model="color" options="options" api="api" event-api="eventApi"></color-picker>
</div>

https://stackblitz.com/edit/angularjs-bqe6ht?file=home%2Fhome.controller.js


问:
Unit testing void methods?
What is the best way to unit test a method that doesn't return anything? Specifically in c#.

What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.

答:
You can even try it this way:</p>

```<code>[TestMethod]
public void ReadFiles()
{
    try
    {
        Read();
        return; // indicates success
    }
    catch (Exception ex)
    {
        Assert.Fail(ex.Message);
    }
}
</code>```

OwnerDisplayName: jdiaz

Title: Unit testing void methods?

LastEditorDisplayName: jdiaz

Body:
You can even try it this way:

[TestMethod]
public void ReadFiles()
{
    try
    {
        Read();
        return; // indicates success
    }
    catch (Exception ex)
    {
        Assert.Fail(ex.Message);
    }
}


问:
Prevent NSIS "error opening file for writing"
On some computers the antivirus while the installation files are being copied blocks the file and the installer throws the error "Error opening file for writing filename.extension" is there any way to solve this? That before launching the exception to the user, try again? If the user clicks retry it works, but I want to avoid it to the user.

My Nsis code to include files.

```<code>File /r /x *.tlb "${MyPath}"
</code>```

答:
No, there no is way to work around this when using /r or wildcards with File.

In theory you could wrap single File commands in a macro that first calls FileOpen in a loop but there is no way to know how many retries you would need and if you need a Sleep etc.

Anti-Virus software is supposed to be transparent to normal applications. The best way to deal with this is to file a bug report with the vendor and to publicly name-and-shame them.

Body:
On some computers the antivirus while the installation files are being copied blocks the file and the installer throws the error "Error opening file for writing filename.extension" is there any way to solve this? That before launching the exception to the user, try again? If the user clicks retry it works, but I want to avoid it to the user.

My Nsis code to include files.

File /r /x *.tlb "${MyPath}"


问:
How to vary the thickness of doughnut chart, using ChartJs.?
How to vary the thickness of doughnut chart,  using ChartJs</p>

答:
If you are using chart.js for Angular via ng2-charts you would do something like this in your component.html file:

```<code>// component.html file

<canvas baseChart [options]='chartOptions'>
</canvas>

// Do note that other required directives are missing in this example, but that I chose to highlight the 'options' directive

</code>```

And do something like this in your component.ts file:

```<code>//component.ts file

chartOptions = {
  cutoutPercentage: 80
};

</code>```

A helpful source of information: available chart directives and config options for the [options] directive

Body:
If you are using chart.js for Angular via ng2-charts you would do something like this in your component.html file:

// component.html file

<canvas baseChart [options]='chartOptions'>
</canvas>

// Do note that other required directives are missing in this example, but that I chose to highlight the 'options' directive

And do something like this in your component.ts file:

//component.ts file

chartOptions = {
  cutoutPercentage: 80
};

A helpful source of information: available chart directives and config options for the [options] directive


问:
Is assigning two variables to items in the same list the best way to access and perform operations on those items?
Say I have a list

```<code>l = [1,2,3]
</code>```

and I want to sum each item in the list with every other item in the list. I could do this:

```<code>x = [(a, b) for a in l for b in l]
y = [(a + b) for a in l for b in l]

x = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
y = [2, 3, 4, 3, 4, 5, 4, 5, 6]
</code>```

Is assigning two variables (a and b) to items in the same list (l) the best way to access and perform operations on those items? Is there a better way to do this?

I've looked at list methods and functions, and couldn't find any.

UPDATE

Many people recommended the itertools product function so I thought I'd include timings before I mark as answered:

```<code>mysetup = """
from itertools import product
l = [10, 15, 3, 7]
k = 17
"""
mycode = """
[i for i in product(l, repeat=2)]
"""

t = timeit.timeit(setup=mysetup, stmt=mycode, number=100000)
# 0.1505305

mysetup2 = """
l = [10, 15, 3, 7]
k = 17
"""
mycode2 = """
[(a, b) for a in l for b in l]
"""

t1 = timeit.timeit(setup=mysetup2, stmt=mycode2, number=100000)
# 0.1432976
</code>```

答:
Try this, itertools.product</p>

```<code>>>> from itertools import product
>>> l = [1,2,3]
>>> [sum(combination) for combination in list(product(l, repeat = 2))]
[2, 3, 4, 3, 4, 5, 4, 5, 6]
</code>```

Body:
Say I have a list

l = [1,2,3]

and I want to sum each item in the list with every other item in the list. I could do this:

x = [(a, b) for a in l for b in l]
y = [(a + b) for a in l for b in l]

x = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
y = [2, 3, 4, 3, 4, 5, 4, 5, 6]

Is assigning two variables (a and b) to items in the same list (l) the best way to access and perform operations on those items? Is there a better way to do this?

I've looked at list methods and functions, and couldn't find any.

UPDATE

Many people recommended the itertools product function so I thought I'd include timings before I mark as answered:

mysetup = """
from itertools import product
l = [10, 15, 3, 7]
k = 17
"""
mycode = """
[i for i in product(l, repeat=2)]
"""

t = timeit.timeit(setup=mysetup, stmt=mycode, number=100000)
# 0.1505305

mysetup2 = """
l = [10, 15, 3, 7]
k = 17
"""
mycode2 = """
[(a, b) for a in l for b in l]
"""

t1 = timeit.timeit(setup=mysetup2, stmt=mycode2, number=100000)
# 0.1432976

Body:
Try this, itertools.product

>>> from itertools import product
>>> l = [1,2,3]
>>> [sum(combination) for combination in list(product(l, repeat = 2))]
[2, 3, 4, 3, 4, 5, 4, 5, 6]


问:
Best practice for keeping Helm chart in remote server for Jenkins deployment
Currently I am trying to deploy one sample micro service developed using Spring Boot using Jenkins and Kubernetes on my on premise server. For that I am already created my Kubernetes resource using Helm chart.

I tested the Helm chart deployment using login in remote machine and in my home directory I created. And using terminal command "helm install" I deployed into kubernetes cluster. And end point is successfully working.

My Confusion

Now only tested from terminal. Now I am trying to add the helm install command in my Jenkins pipeline job. So where I need to keep this helm chart? Need to copy to /var/lib/jenkins directory (Jenkins home directory) ? Or I only need to give the full path in command ?

What is the best practice for saving Helm chart for Jenkins deployment? I am confused about to follow standard way of implementation. I am new to this CI/CD pipeline.

答:
The Helm chart(s) should almost definitely be source controlled.

One reasonable approach is to keep a Helm chart in the same repository as your service.  Then when Jenkins builds your project, it will also have the chart available, and can directly run helm install.  (Possibly it can pass credentials it owns to helm install --set options to set values during deployment.)  This scales reasonably well, since it also means developers can make local changes to charts as part of their development work.

You can also set up a "repository" of charts.  In your Jenkins setup one path is just to keep a second source control repository with charts, and check that out during deployment.  Some tools like Artifactory also support keeping Helm charts that can be directly deployed without an additional checkout.  The corresponding downside here is that if something like a command line or environment variable changes, you need coordinated changes in two places to make it work.


问:
C# Lua Parser / Analyser
first things first;

I am writing a little LUA-Ide in C#. The code execution is done by an Assembly named LuaInterface. The code-editing is done by a Scintilla-Port & the RAD / UI Interface is via the extensible IDesignSurfaceExt Visual Studio (one way code generation). File handling is provided by a little sql-lite-db used as a project-package-file.

So all in all i've got everything i need together...

The only problem unsolved is the parser / lexer for lua. I do not want to load & execute the code! I just want to parse the String containing the Lua code and get some information about it like function and global vars. I really don't want to write the parser completly myself... (I hate regex - I get the wrong all the time ^^)

Anybody got a link to a .net lua parser lying around?

Just to clarify - I only want to analyse the code at this point - I dont wnat to run it!

Thanks in advance!

Corelgott

答:
Incomplete but:

http://luairony.codeplex.com/

Title: C# Lua Parser / Analyser


问:
Is there a way to specify which words in the training phrase are fulfilling slots in Dialogflow through java sdk
I would like to create an intent using the Dialogflow java-sdk. The problem is I am am able to create training phrases and slots but I am not able to alocate the specific word to the training phrase like we do in the dialogflow console.

I have checked and Dialogflow also does not do it by itself.
Below I have wrotten the code I am currently using and the functions I have used. This may not help but may help in providing info into the current method I am using .

Is there any function in the dialogflow java api that will help me to achive this.

```<code>public  OutputResponseDTO createIntent(CreateIntentInputDTO createIntentInputDTO)
{
    // Instantiates a client
    try (IntentsClient intentsClient = IntentsClient.create()) {

        // Set the project agent name using the projectID (my-project-id)
        ProjectAgentName parent = ProjectAgentName.of(createIntentInputDTO.getProjectId());

        //first check if intent already exists
        for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
            //logger.error(intent.getDisplayName()+"Inside delete!!!!!!"+createIntentInputDTO.getIntentName());
            if (intent.getDisplayName().equals(createIntentInputDTO.getDisplayName())) {
                logger.error("Inside delete!!!!!!");
                deleteIntent(createIntentInputDTO.getIntentName(),createIntentInputDTO.getProjectId());
            }
        }

        List<String> trainingPhrasesIP=new ArrayList<String>();
        for(int l=0;l<createIntentInputDTO.getTrainingPhrasesParts().size();l++)
        {
            trainingPhrasesIP.add(createIntentInputDTO.getTrainingPhrasesParts().get(l).getPhraseName());
        }
        // Build the trainingPhrases from the trainingPhrasesParts
        List<TrainingPhrase> trainingPhrases = new ArrayList<>();
        for (String trainingPhrase : trainingPhrasesIP) {
            trainingPhrases.add(
                    TrainingPhrase.newBuilder().addParts(
                            Part.newBuilder().setText(trainingPhrase).build())
                    .build());
        }

        // Build the message texts for the agent's response
        Message messages = Message.newBuilder()
                .setText(
                        Text.newBuilder()
                        .addAllText(createIntentInputDTO.getMessageTexts()).build()
                        ).build();

        List<Parameter> parameters=new ArrayList<Intent.Parameter>();

        for(int j=0;j<createIntentInputDTO.getSlotsInputDTOs().size();j++)
        {

            //String firstFourChars = createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName().substring(0, 5);
            //System.out.println(firstFourChars);

            String paraNameWithoutAtTwo;
            String paraNameWithoutAtOne;
            String paraNameWithoutAtAndWithDollar;
            String paraNameWithAt;

            try
            {
                paraNameWithoutAtOne=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName().replace("@sys.", "");
             paraNameWithoutAtTwo=paraNameWithoutAtOne.replace("@", "");
            }
            catch(Exception e)
            {
                paraNameWithoutAtTwo=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName();
                logger.info("Something happended when removing stuff");
            }

            paraNameWithoutAtAndWithDollar="$"+paraNameWithoutAtTwo;
            paraNameWithAt="@"+paraNameWithoutAtTwo;
            paraNameWithoutAt=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName();

            Parameter parameter=Parameter.newBuilder()
                .setValue(createIntentInputDTO.getSlotsInputDTOs().get(j).getValue())
                    .setDisplayName(paraNameWithoutAtTwo)
                    .setValue(paraNameWithoutAtAndWithDollar)

                    .setEntityTypeDisplayName(createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName())
                    .build();
            parameters.add(parameter);
        }

        // Build the intent
        Intent intent = Intent.newBuilder()
                .setDisplayName(createIntentInputDTO.getDisplayName())
                .addMessages(messages)
                //                  .addParameters(p)
                                    .addAllParameters(parameters)
                .addAllTrainingPhrases(trainingPhrases)
                .build();

        // Performs the create intent request
        Intent response = intentsClient.createIntent(parent, intent);

    //  System.out.format("Intent created: %s\n", response);

        try
        {
            IntentMasterCollection intentMasterCollection=new IntentMasterCollection();
            intentMasterCollection.setName(createIntentInputDTO.getDisplayName());
            intentActionMaster.save(intentMasterCollection);
        }
        catch(Exception e)
        {
            logger.error("Error adding in DB intent master");
        }

        try
        {
            //we gonna put the data again!(Training phrases only)
            String[] splitName = response.getName().split("/");
            //              intentIds.add(splitName[splitName.length - 1]);

            //finally setting all the values

            updateIntent(splitName[splitName.length - 1]);

        }
        catch(Exception e)
        {
            logger.error("Error in writing to intent");
        }
        return new OutputResponseDTO(true, message.getStatusCode("success.message.createIntent.id"),
                message.get("success.message.createIntent"), null,  null,requestBean.getTraceId());
    }
    catch(Exception e)
    {
        logger.error("Error Creating Intent:"+e.getMessage());
        return new OutputResponseDTO(false, message.getStatusCode("error.message.generalError.id"),
                message.get("error.message.generalError"), null,  e.getMessage(),requestBean.getTraceId());
    }
}
</code>```

答:
I think the problem you're having is related to Parts definition.
Every training phrase is split into parts, and for each part, you can define if it is just text or if it contains an entity:

```<code>        Part part1 = Part.newBuilder().setText("I want to cancel a card ended in  ").build();
        Part part2 = Part.newBuilder().setText("5123").setEntityType("@cardNumber").setAlias("cardNumber")
                .setUserDefined(true).build();
        List<Part> parts = new ArrayList<Part>();
        parts.add(part1);
        parts.add(part2);
</code>```

Then you build the training phrase:

```<code>    TrainingPhrase tp = TrainingPhrase.newBuilder().setType(Type.EXAMPLE).addAllParts(parts).build();
</code>```

Body:
I would like to create an intent using the Dialogflow java-sdk. The problem is I am am able to create training phrases and slots but I am not able to alocate the specific word to the training phrase like we do in the dialogflow console.

I have checked and Dialogflow also does not do it by itself.
Below I have wrotten the code I am currently using and the functions I have used. This may not help but may help in providing info into the current method I am using .

Is there any function in the dialogflow java api that will help me to achive this.

public  OutputResponseDTO createIntent(CreateIntentInputDTO createIntentInputDTO)
{
    // Instantiates a client
    try (IntentsClient intentsClient = IntentsClient.create()) {

        // Set the project agent name using the projectID (my-project-id)
        ProjectAgentName parent = ProjectAgentName.of(createIntentInputDTO.getProjectId());

        //first check if intent already exists
        for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
            //logger.error(intent.getDisplayName()+"Inside delete!!!!!!"+createIntentInputDTO.getIntentName());
            if (intent.getDisplayName().equals(createIntentInputDTO.getDisplayName())) {
                logger.error("Inside delete!!!!!!");
                deleteIntent(createIntentInputDTO.getIntentName(),createIntentInputDTO.getProjectId());
            }
        }

        List<String> trainingPhrasesIP=new ArrayList<String>();
        for(int l=0;l<createIntentInputDTO.getTrainingPhrasesParts().size();l++)
        {
            trainingPhrasesIP.add(createIntentInputDTO.getTrainingPhrasesParts().get(l).getPhraseName());
        }
        // Build the trainingPhrases from the trainingPhrasesParts
        List<TrainingPhrase> trainingPhrases = new ArrayList<>();
        for (String trainingPhrase : trainingPhrasesIP) {
            trainingPhrases.add(
                    TrainingPhrase.newBuilder().addParts(
                            Part.newBuilder().setText(trainingPhrase).build())
                    .build());
        }

        // Build the message texts for the agent's response
        Message messages = Message.newBuilder()
                .setText(
                        Text.newBuilder()
                        .addAllText(createIntentInputDTO.getMessageTexts()).build()
                        ).build();

        List<Parameter> parameters=new ArrayList<Intent.Parameter>();

        for(int j=0;j<createIntentInputDTO.getSlotsInputDTOs().size();j++)
        {

            //String firstFourChars = createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName().substring(0, 5);
            //System.out.println(firstFourChars);

            String paraNameWithoutAtTwo;
            String paraNameWithoutAtOne;
            String paraNameWithoutAtAndWithDollar;
            String paraNameWithAt;

            try
            {
                paraNameWithoutAtOne=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName().replace("@sys.", "");
             paraNameWithoutAtTwo=paraNameWithoutAtOne.replace("@", "");
            }
            catch(Exception e)
            {
                paraNameWithoutAtTwo=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName();
                logger.info("Something happended when removing stuff");
            }

            paraNameWithoutAtAndWithDollar="$"+paraNameWithoutAtTwo;
            paraNameWithAt="@"+paraNameWithoutAtTwo;
            paraNameWithoutAt=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName();

            Parameter parameter=Parameter.newBuilder()
                .setValue(createIntentInputDTO.getSlotsInputDTOs().get(j).getValue())
                    .setDisplayName(paraNameWithoutAtTwo)
                    .setValue(paraNameWithoutAtAndWithDollar)

                    .setEntityTypeDisplayName(createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName())
                    .build();
            parameters.add(parameter);
        }

        // Build the intent
        Intent intent = Intent.newBuilder()
                .setDisplayName(createIntentInputDTO.getDisplayName())
                .addMessages(messages)
                //                  .addParameters(p)
                                    .addAllParameters(parameters)
                .addAllTrainingPhrases(trainingPhrases)
                .build();

        // Performs the create intent request
        Intent response = intentsClient.createIntent(parent, intent);

    //  System.out.format("Intent created: %s\n", response);

        try
        {
            IntentMasterCollection intentMasterCollection=new IntentMasterCollection();
            intentMasterCollection.setName(createIntentInputDTO.getDisplayName());
            intentActionMaster.save(intentMasterCollection);
        }
        catch(Exception e)
        {
            logger.error("Error adding in DB intent master");
        }

        try
        {
            //we gonna put the data again!(Training phrases only)
            String[] splitName = response.getName().split("/");
            //              intentIds.add(splitName[splitName.length - 1]);

            //finally setting all the values

            updateIntent(splitName[splitName.length - 1]);

        }
        catch(Exception e)
        {
            logger.error("Error in writing to intent");
        }
        return new OutputResponseDTO(true, message.getStatusCode("success.message.createIntent.id"),
                message.get("success.message.createIntent"), null,  null,requestBean.getTraceId());
    }
    catch(Exception e)
    {
        logger.error("Error Creating Intent:"+e.getMessage());
        return new OutputResponseDTO(false, message.getStatusCode("error.message.generalError.id"),
                message.get("error.message.generalError"), null,  e.getMessage(),requestBean.getTraceId());
    }
}

Body:
I think the problem you're having is related to Parts definition.
Every training phrase is split into parts, and for each part, you can define if it is just text or if it contains an entity:

        Part part1 = Part.newBuilder().setText("I want to cancel a card ended in  ").build();
        Part part2 = Part.newBuilder().setText("5123").setEntityType("@cardNumber").setAlias("cardNumber")
                .setUserDefined(true).build();
        List<Part> parts = new ArrayList<Part>();
        parts.add(part1);
        parts.add(part2);

Then you build the training phrase:

    TrainingPhrase tp = TrainingPhrase.newBuilder().setType(Type.EXAMPLE).addAllParts(parts).build();


问:
BizTalk MAP project REBUILD takes very long time
My BizTalk Project Rebuild takes very very long time especially for MAP Projects, this is relatively very small schema and before it was taking very less time but suddenly the REBUILD time is up to 30-40 mins.

Please provide your expect comment on and if you known any cause for this.

Regards

答:
Used Rob Bowman's answer as principle, but I manage to just unload projects from solution from Solution Explorer directly (mark all projects, right click, and select Unload Project), and then run the

msbuild *.sln /t:Clean,Rebuild

from Visual Studio Command Prompt. When finished, just reload projects in Solution Explorer.

It saves me minutes (!) when I need to rebuild solution.


答:
Here's an itertools based approach:

```<code>from operator import add
from itertools import product, starmap
l = [1,2,3]

list(starmap(add, product(l, repeat=2)))
# [2, 3, 4, 3, 4, 5, 4, 5, 6]
</code>```

Let's check the timings:

```<code>l = list(range(1000))

%timeit list(map(sum, product(l, repeat=2)))
# 187 ms ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit [sum(combination) for combination in combinations_with_replacement(l, 2)]
# 123 ms ± 4.32 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

list(starmap(add, product(l, repeat=2)))
# 102 ms ± 4.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Title: Is assigning two variables to items in the same list the best way to access and perform operations on those items?

Body:
Here's an itertools based approach:

from operator import add
from itertools import product, starmap
l = [1,2,3]

list(starmap(add, product(l, repeat=2)))
# [2, 3, 4, 3, 4, 5, 4, 5, 6]

Let's check the timings:

l = list(range(1000))

%timeit list(map(sum, product(l, repeat=2)))
# 187 ms ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit [sum(combination) for combination in combinations_with_replacement(l, 2)]
# 123 ms ± 4.32 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

list(starmap(add, product(l, repeat=2)))
# 102 ms ± 4.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


问:
How to minimise time in converting numpy ndarray to list
I want to take pixel values of image as a list  of tuple so I converted it numpy array to list but it is taking to much time to convert

```<code>import time
t1=time.time()
import  cv2
import  numpy  as  np

img=cv2.imread("Desert.jpg")
array=np.array(img)
a=array.tolist()
t2=time.time()
print(t2-t1)
</code>```

答:
If your aim is to only to convert the 'img' matrix into a vector that needn't explicitly be a list then you can just convert the ndarray to a single line vector as:

```<code>img=cv2.imread("Desert.jpg")
array=np.array(img)
a = np.reshape(array,-1,1)
t2=time.time()
print(t2-t1)
</code>```

[out]

```<code>0.016440153121948242
</code>```

But if it is your intention to convert to a list then:

```<code>img=cv2.imread("Desert.jpg")
array=np.array(img)
a = list(array)
t2=time.time()
print(t2-t1)
</code>```

[out]

```<code>0.007548332214355469
</code>```

Body:
I want to take pixel values of image as a list  of tuple so I converted it numpy array to list but it is taking to much time to convert

import time
t1=time.time()
import  cv2
import  numpy  as  np

img=cv2.imread("Desert.jpg")
array=np.array(img)
a=array.tolist()
t2=time.time()
print(t2-t1)

Body:
If your aim is to only to convert the 'img' matrix into a vector that needn't explicitly be a list then you can just convert the ndarray to a single line vector as:

img=cv2.imread("Desert.jpg")
array=np.array(img)
a = np.reshape(array,-1,1)
t2=time.time()
print(t2-t1)

[out]

0.016440153121948242

But if it is your intention to convert to a list then:

img=cv2.imread("Desert.jpg")
array=np.array(img)
a = list(array)
t2=time.time()
print(t2-t1)

[out]

0.007548332214355469


问:
Why cant click on div tag?
Clicking on this div tag created a simple event to output a log window, but it doesn't work. How do I work?

$('#b').on('click', function() {
  console.log("click");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#b {
  width: 500px;
  height: 300px;
  border: 1px solid #444444;
}</code>```

Lorem Ipsum Dolor
asd

```

答:
```<code>$(document).ready(function(){
   $("#b").click(function(){
      console.log("clicked");
   });
});
</code>```

Title: Why cant click on div tag?

Body:
Clicking on this div tag created a simple event to output a log window, but it doesn't work. How do I work?

$('#b').on('click', function() {
  console.log("click");
});

#b {
  width: 500px;
  height: 300px;
  border: 1px solid #444444;
}

Lorem Ipsum Dolor
asd


问:
Why is "partial RVO" not performed?
Please take a look at this silly function, which should only illustrate the problem and a simplification of the real code:

```<code>struct A;

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}
</code>```

I understand, that because it is not clear which object will be returned during the compilation, we cannot expect return value optimization (RVO) to be always performed.

However, one maybe could expect RVO to be performed in 50% of the cases (assuming uniform distribution for true/false due to lack of further information): just decide for which case RVO (first==true or first==false) should be performed and apply it for this parameter-value, accepting that in the other case the copy constructor must be called.

Yet this "partial RVO" is not the case for all compilers I can get my hands on (see live with gcc, clang and MSVC) - in both cases (i.e. first==true or first==false) the copy-constructor is used and not omitted.

Is there something, that renders the "partial RVO" in the above case invalid or is this an unlikely case of missed optimization by all compilers?

Complete program:

```<code>#include <iostream>

struct A{
    int val;
    A(int val_):val(val_){}
    A(const A&o):val(o.val){
        std::cout<<"copying: "<<val<<"\n";
    }
};

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}

int main(){
    std::cout<<"With true: ";
    create(true);
    std::cout<<"With false: ";
    create(false);
}
</code>```

答:
Let's consider what happens if RVO is done for f, meaning it is constructed directly in the return value. If first==true and f gets returned, great, no copy is needed. But if first==false then s gets returned instead, so the program will copy construct s over the top of f before the destructor for f has run. Then after that, the destructor for f will run, and now the return value is an invalid object that has already been destroyed!

If RVO is done for s instead the same argument applies, except that now the problem happens when first==true.

Whichever one you choose, you avoid a copy in 50% of cases and get undefined behaviour in the other 50% of cases! That's not a desirable optimization!

In order to make this work the order of destruction of the local variables would have to be altered so that f is destroyed before copying s into that memory location (or vice versa), and that's a very risky thing to mess with. The order of destruction is a fundamental property of C++ that should not be fiddled with, or you'll break RAII and who knows how many other assumptions.

Title: Why is "partial RVO" not performed?

Body:
Please take a look at this silly function, which should only illustrate the problem and a simplification of the real code:

struct A;

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}

I understand, that because it is not clear which object will be returned during the compilation, we cannot expect return value optimization (RVO) to be always performed.

However, one maybe could expect RVO to be performed in 50% of the cases (assuming uniform distribution for true/false due to lack of further information): just decide for which case RVO (first==true or first==false) should be performed and apply it for this parameter-value, accepting that in the other case the copy constructor must be called.

Yet this "partial RVO" is not the case for all compilers I can get my hands on (see live with gcc, clang and MSVC) - in both cases (i.e. first==true or first==false) the copy-constructor is used and not omitted.

Is there something, that renders the "partial RVO" in the above case invalid or is this an unlikely case of missed optimization by all compilers?

Complete program:

#include <iostream>

struct A{
    int val;
    A(int val_):val(val_){}
    A(const A&o):val(o.val){
        std::cout<<"copying: "<<val<<"\n";
    }
};

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}

int main(){
    std::cout<<"With true: ";
    create(true);
    std::cout<<"With false: ";
    create(false);
}


问:
What is the use of overriding the finalize() method of Object class?
As far as I know , in java if we want to manually call the garbage collector we can do System.gc().

1.What are the operations that we do inside our overriden finalize() method?

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

答:
There is no guarantee that the finalizer will be called promptly so you should not do anything critical in your finalize method.

Release system resources (Such as IOStreams) as a safety net if they weren't already closed or released.

Release system resources iin native code that the GC doesn't know about.