问:
Is there a maven repository to quickstart Java 11 app
There is a quickstart maven archetype for Java 7, as I can see here:
https://maven.apache.org/archetypes/maven-archetype-quickstart/
The problem with this is when I fire this command:

```<code>mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart
</code>```

Enter project directory and fire this command:

```<code>mvn package
</code>```

I get this error:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.20.1:test (default-test) on project gfg-stuff: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.20.1:test failed. NullPointerException
</code>```

Please note that there is some problem with my JDK install, as update-alternatives tells me that I am running JDK 11:

```<code>$ sudo update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                         Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java   1101      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java   1101      manual mode
  2            /usr/lib/jvm/java-8-oracle/jre/bin/java       1081      manual mode
</code>```

But, when I run java -version, it gives me this:

```<code>$ java -version
openjdk version "10.0.2" 2018-07-17
OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.3)
OpenJDK 64-Bit Server VM (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.3, mixed mode)
</code>```

I am not sure why I am not getting OpenJDK 11, despite the fact that I installed JDK 11 only in the first place. Maybe will start a different thread on that.

答:
tl;dr

The quickstart archetype, sadly, is often out-of-date.

Update your maven-surefire-plugin element of your POM to the latest version such as 3.0.0-M7.

Update your dependencies to current version

Oddly, the maven-archetype-quickstart artifact is never kept up-to-date. It lists dependencies with old versions that may not work well with the latest versions of Java, your IDE, or other libraries.

This is quite frustrating, as you would think the artifact would be kept up-to-date via some automated scripting. After all, the entire point of Maven is to make this kind of configuration chore easy and automated!

Fortunately, you can easily update the version numbers yourself.

How do you know what is the latest version number to enter for each dependency?

You can look up manually the latest version number using the web site of a Maven repository. Copy-paste the version number to your POM.

You can let your IDE (IntelliJ, NetBeans, etc.) suggest the latest number as you edit the version number XML element value. You may or may not to type some “help-me” keystroke depending on how your IDE works. Before doing this, be sure to update your IDE’s cache of Maven repository data so it knows the current latest version numbers. For example, in IntelliJ go to preferences, and in the search field for settings, type repo, and in the list of known repositories click each Update button.

Steps

First, if using your IDE to work with Maven, be sure to update its cache of Maven repository data so you are getting the latest quickstart artifact. For example, in IntelliJ, Preferences > Build, Execution, Deployment > Build tools > Maven > Repositories > Update button.

The initial POM should expand into a bigger one. You may need a Maven clean and install.

After first use, go through your POM.

<?xml version="1.0" encoding="UTF-8"?>

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

  <groupId>work.basil.work.example</groupId>
  <artifactId>quickstart</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>quickstart</name>

  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>

        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>

        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>

        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
```
<p>On each element in the POM, change the version number to the latest.</p>
<p>Your IDE may assist by showing you a list of version numbers it knows of.</p>
<p><img src="https://i.stack.imgur.com/r9Wyb.png" alt="enter image description here" /></p>
<p>Or use a Maven repository web site to verify the latest version number. Like this:</p>
<p><img src="https://i.stack.imgur.com/UoO02.png" alt="enter image description here" /></p>
<p>You may find most of the items are out-of-date. In particular, regarding the surefire problem described in the Question, change the surefire element to v3.</p>
<pre class="lang-xml prettyprint-override"><code>    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>3.0.0-M3</version>
    </plugin>
</code>```

This will fix your surefire specifically, in my experience. Some problems were recently fixed in later versions. I don’t recall the nature of the problems, perhaps related to the Java Platform Module System.

My version of the POM after updating to the latest as of 2019-05-29.

<?xml version="1.0" encoding="UTF-8"?>

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

  <groupId>work.basil.work.example</groupId>
  <artifactId>quickstart</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>quickstart</name>

  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.5.0-M1</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement>
      <plugins>

        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>

        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>3.0.0-M3</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>3.0.0-M1</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>3.0.0-M1</version>
        </plugin>

        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
```
<h1>JUnit</h1>
<p>Notice I also updated JUnit from v4 to the vastly improved v5 "Jupiter". If you do this, you will also need to update the <code>AppTest.java</code> file to simply change the <code>import</code> lines.</p>
<p>Old:</p>
<pre class="lang-java prettyprint-override"><code>package work.basil.work.example;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class AppTest
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        assertTrue( true );
    }
}
</code>```

New:

package work.basil.work.example;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Unit test for simple App.
 */
public class AppTest
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        assertTrue( true );
    }
}
```

Lastly, do a Maven clean and install to get those latest versions of your dependencies actually installed inside your app.

By the way, for more about JUnit Jupiter, and how to run old JUnit 3 & 4 testes, see my Answer to another Question.

Body:
There is a quickstart maven archetype for Java 7, as I can see here:
https://maven.apache.org/archetypes/maven-archetype-quickstart/
The problem with this is when I fire this command:

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart

Enter project directory and fire this command:

mvn package

I get this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.20.1:test (default-test) on project gfg-stuff: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.20.1:test failed. NullPointerException

Please note that there is some problem with my JDK install, as update-alternatives tells me that I am running JDK 11:

$ sudo update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                         Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java   1101      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java   1101      manual mode
  2            /usr/lib/jvm/java-8-oracle/jre/bin/java       1081      manual mode

But, when I run java -version, it gives me this:

$ java -version
openjdk version "10.0.2" 2018-07-17
OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.3)
OpenJDK 64-Bit Server VM (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.3, mixed mode)

I am not sure why I am not getting OpenJDK 11, despite the fact that I installed JDK 11 only in the first place. Maybe will start a different thread on that.

Body:
tl;dr

The quickstart archetype, sadly, is often out-of-date.

Update your maven-surefire-plugin element of your POM to the latest version such as 3.0.0-M7.

Update your dependencies to current version

Oddly, the maven-archetype-quickstart artifact is never kept up-to-date. It lists dependencies with old versions that may not work well with the latest versions of Java, your IDE, or other libraries.

This is quite frustrating, as you would think the artifact would be kept up-to-date via some automated scripting. After all, the entire point of Maven is to make this kind of configuration chore easy and automated!

Fortunately, you can easily update the version numbers yourself.

How do you know what is the latest version number to enter for each dependency?

You can look up manually the latest version number using the web site of a Maven repository. Copy-paste the version number to your POM.

You can let your IDE (IntelliJ, NetBeans, etc.) suggest the latest number as you edit the version number XML element value. You may or may not to type some “help-me” keystroke depending on how your IDE works. Before doing this, be sure to update your IDE’s cache of Maven repository data so it knows the current latest version numbers. For example, in IntelliJ go to preferences, and in the search field for settings, type repo, and in the list of known repositories click each Update button.

Steps

First, if using your IDE to work with Maven, be sure to update its cache of Maven repository data so you are getting the latest quickstart artifact. For example, in IntelliJ, Preferences > Build, Execution, Deployment > Build tools > Maven > Repositories > Update button.

The initial POM should expand into a bigger one. You may need a Maven clean and install.

After first use, go through your POM.

<?xml version="1.0" encoding="UTF-8"?>

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

  <groupId>work.basil.work.example</groupId>
  <artifactId>quickstart</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>quickstart</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

On each element in the POM, change the version number to the latest.

Your IDE may assist by showing you a list of version numbers it knows of.

Or use a Maven repository web site to verify the latest version number. Like this:

You may find most of the items are out-of-date. In particular, regarding the surefire problem described in the Question, change the surefire element to v3.

    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>3.0.0-M3</version>
    </plugin>

This will fix your surefire specifically, in my experience. Some problems were recently fixed in later versions. I don’t recall the nature of the problems, perhaps related to the Java Platform Module System.

My version of the POM after updating to the latest as of 2019-05-29.

<?xml version="1.0" encoding="UTF-8"?>

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

  <groupId>work.basil.work.example</groupId>
  <artifactId>quickstart</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>quickstart</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.5.0-M1</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>3.0.0-M3</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>3.0.0-M1</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>3.0.0-M1</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

JUnit

Notice I also updated JUnit from v4 to the vastly improved v5 "Jupiter". If you do this, you will also need to update the AppTest.java file to simply change the import lines.

Old:

package work.basil.work.example;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class AppTest
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        assertTrue( true );
    }
}

New:

package work.basil.work.example;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Unit test for simple App.
 */
public class AppTest
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        assertTrue( true );
    }
}

Lastly, do a Maven clean and install to get those latest versions of your dependencies actually installed inside your app.

By the way, for more about JUnit Jupiter, and how to run old JUnit 3 & 4 testes, see my Answer to another Question.


来源: stackexchange

问:
Code linting for Objective C
Are there any code linting tools for ObjectiveC? </p>

答:
Have a look at the LLVM/Clang Static Analyzer

The LLVM/Clang static analyzer is a standalone tool that find bugs in C and Objective-C programs and it is very early in development.

A static analyzer based on clang. The goal of the Clang project is to create a new C, C++, Objective C and Objective C++ front-end for the LLVM compiler.

Edit

Clang has now been integrated into Xcode and can easily be run as a menu option "Build & Analyse"

OwnerDisplayName: DasBoot

ContentLicense: CC BY-SA 2.5

Title: Code linting for Objective C

LastEditorDisplayName: epatel

OwnerDisplayName: epatel

ContentLicense: CC BY-SA 4.0


问:
dependency inversion in top class (main)
i want to create an app in which i have these two classes, MainApp and Model (in reality more, but this is the base and the core of the problem). MainApp is also the starting class. I want to apply dependency inversion so mainApp doesn't have to be rebuild each time Model changes (Well, mainly because its good practice). I can't do this:

```<code>MainApp - - - > IModel
                  ^
                  |
                  |
                Model
</code>```

because i'd have to create Model in MainApp anyway because it's the start of my app, it would be redundant.

I was thinking about shifting the contents of MainApp to another class and use MainApp just as factory for MainAppContents and Model, like this:

```<code>MainApp -------------> Model
   |                     |
   |                     |
   v                     v
MainAppContents - - - > IModel
</code>```

Is this the correct approach and does this mean that any start of a well designed app is a factory?

答:
I'm not quite sure what the problem is, but if MainApp needs to create instances of Model, then you should use an abstract factory pattern, for example an IModelFactory which has a method that returns a new IModel.

If you're going to use an IoC container, then you'll want IModel to be resolved via the container.  Rather than have your IModelFactory take a dependency on your container, you can use features of your IoC container to create your concrete implementation of IModelFactory for you and implicitly use the container to resolve IModel.

Edit

I would also say, get Mark's book!  It's great!

ContentLicense: CC BY-SA 3.0

Body:
i want to create an app in which i have these two classes, MainApp and Model (in reality more, but this is the base and the core of the problem). MainApp is also the starting class. I want to apply dependency inversion so mainApp doesn't have to be rebuild each time Model changes (Well, mainly because its good practice). I can't do this:

MainApp - - - > IModel
                  ^
                  |
                  |
                Model

because i'd have to create Model in MainApp anyway because it's the start of my app, it would be redundant.

I was thinking about shifting the contents of MainApp to another class and use MainApp just as factory for MainAppContents and Model, like this:

MainApp -------------> Model
   |                     |
   |                     |
   v                     v
MainAppContents - - - > IModel

Is this the correct approach and does this mean that any start of a well designed app is a factory?


问:
general error handling message for different projects template
I have the following class which writes new line to a text file.

```<code>using System;
using System.Text;
using System.IO;

namespace TextStreamer
{
    class TextWriter
    {
        private string _FilePath;
        private string _TextToAdd;

        // Constructor will assign file Path variable and check if file is valid
        public TextWriter(string filePath)
        {
            this._FilePath = filePath;
            ValidateFile();
        }

        // Validate if the text file exist
        private void ValidateFile()
        {
            // If file does not exist show error message
            // and create new text file
            if(!File.Exists(_FilePath))
            {
                Console.WriteLine("File not found");
                File.Create(_FilePath);
                Console.WriteLine("Created new file {0}", _FilePath);
            }
        }

        // Write new line to the text file
        public void WriteNewLine(string text)
        {
            this._TextToAdd = text + Environment.NewLine;
            File.AppendAllText(_FilePath, _TextToAdd);
        }
    }
}
</code>```

Right now if the file does not exist it will write a message to the console and then it will create the text file, but what if i used say WPF application, in this case i prefer showing a message box with the same message, how can i achieve that.

I tried throwing exception FileNotFoundException but that just crashes the program and exit.

答:
A simple way to achieve this is by using a public variable to change the option to console log or show message.

Add the namespace for the generic message box:

```<code>using System.Windows;
</code>```

And add a public variable in your class that will let you programmatically change the logging method, such as:

```<code>public bool UseMsgBox = false;
</code>```

You could improve this by using things like using an int or enum to have more logging methods, though a bool is fine for only 2 options.

Add a logging method such as:

```<code>private void LogMsg(string msg)
{
    if(UseNsgBox) MessageBox.Show(msg);
    else Console.WriteLine(msg);
}
</code>```

And replace your Console.WriteLine's with LogMsg instead.

Make sure to change the option when you create your class:

```<code>TextWriter textWriter = new TextWriter("SomeFile.txt");
textWriter.UseMsgBox = true; // or false
</code>```

Actually, this might not work as you instantly call the LogMsg when your class is created, so perhaps add it as an initialization parameter as well:

```<code> public TextWriter(string filePath, bool useMsgBox = false)
 {
     UseMsgBox = useMsgBox;
     // ...
 }
</code>```

Body:
I have the following class which writes new line to a text file.

using System;
using System.Text;
using System.IO;

namespace TextStreamer
{
    class TextWriter
    {
        private string _FilePath;
        private string _TextToAdd;

        // Constructor will assign file Path variable and check if file is valid
        public TextWriter(string filePath)
        {
            this._FilePath = filePath;
            ValidateFile();
        }

        // Validate if the text file exist
        private void ValidateFile()
        {
            // If file does not exist show error message
            // and create new text file
            if(!File.Exists(_FilePath))
            {
                Console.WriteLine("File not found");
                File.Create(_FilePath);
                Console.WriteLine("Created new file {0}", _FilePath);
            }
        }

        // Write new line to the text file
        public void WriteNewLine(string text)
        {
            this._TextToAdd = text + Environment.NewLine;
            File.AppendAllText(_FilePath, _TextToAdd);
        }
    }
}

Right now if the file does not exist it will write a message to the console and then it will create the text file, but what if i used say WPF application, in this case i prefer showing a message box with the same message, how can i achieve that.

I tried throwing exception FileNotFoundException but that just crashes the program and exit.

Body:
A simple way to achieve this is by using a public variable to change the option to console log or show message.

Add the namespace for the generic message box:

using System.Windows;

And add a public variable in your class that will let you programmatically change the logging method, such as:

public bool UseMsgBox = false;

You could improve this by using things like using an int or enum to have more logging methods, though a bool is fine for only 2 options.

Add a logging method such as:

private void LogMsg(string msg)
{
    if(UseNsgBox) MessageBox.Show(msg);
    else Console.WriteLine(msg);
}

And replace your Console.WriteLine's with LogMsg instead.

Make sure to change the option when you create your class:

TextWriter textWriter = new TextWriter("SomeFile.txt");
textWriter.UseMsgBox = true; // or false

Actually, this might not work as you instantly call the LogMsg when your class is created, so perhaps add it as an initialization parameter as well:

 public TextWriter(string filePath, bool useMsgBox = false)
 {
     UseMsgBox = useMsgBox;
     // ...
 }


问:
Why don't onclick events work on touchscreen but do on desktop?
I checked many posts, but looks all different and none of solutions work for me, the following is an extreme simple example, img1_click works in the newest Chrome with mouse click on desktop, but on touchscreen the img1_clickis never called, and I could see:

uncaught referenceerror img1_click is not defined

I found this post which suggests:

```<code>document.getElementById ('img1').addEventListener ("click", img1_click, false);
</code>```

However, it is still not working!

I define function img1_click in a JavaScript file and it is loaded in this .html file:

```<code> <table >

 <td width="280">
 ...
 </td>
 <td width="280">
 <p id="img1"
 style="width:280px;height:157px;
 background:url(images/1.bmp);background-size: 280px 157px;"onclick="img1_click()">
  </p>
  </td>`
</code>```

There is a link to https://tommcfarlin.com/javascript-reference-error-is-not-defined/ to discuss this, it means sometimes HTML could not recognize or define the function, which is in JavaScript.

答:
It seems to me that the problem can be due to the function being in another file, had the similar problem sometimes. The thing is, while that javascript file is still loading, the browser reaches the part of the code where you try to assign that function to an onclick event. Try wrapping it inside window.onload function for the code to wait until all resources finish loading. </p>

```<code>window.onload = function() {
     document.getElementById ('img1').addEventListener ("click", img1_click, false);
}
</code>```

Body:
I checked many posts, but looks all different and none of solutions work for me, the following is an extreme simple example, img1_click works in the newest Chrome with mouse click on desktop, but on touchscreen the img1_clickis never called, and I could see:

uncaught referenceerror img1_click is not defined

I found this post which suggests:

document.getElementById ('img1').addEventListener ("click", img1_click, false);

However, it is still not working!

I define function img1_click in a JavaScript file and it is loaded in this .html file:

 ...

  	`

There is a link to https://tommcfarlin.com/javascript-reference-error-is-not-defined/ to discuss this, it means sometimes HTML could not recognize or define the function, which is in JavaScript.

Body:
It seems to me that the problem can be due to the function being in another file, had the similar problem sometimes. The thing is, while that javascript file is still loading, the browser reaches the part of the code where you try to assign that function to an onclick event. Try wrapping it inside window.onload function for the code to wait until all resources finish loading.

window.onload = function() {
     document.getElementById ('img1').addEventListener ("click", img1_click, false);
}


问:
In vue, how do I check if any parent component has subscribed for an event which child is emitting?
I have a component which is sometimes being used as a child of a parent and sometimes it does not have any parent.

This component emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this component itself.

So at run time, How do I programmatically check

```<code>if (someone is listening to the event){
    let them catch and handle it
}else {
    let's handle it by our own
}
</code>```

答:
This allows you to check listeners passed to a component:

```<code>this.$listeners;
</code>```

It returns the parent scope event listeners. See the doc here.

In particular for your use-case:

```<code>// To check whether the "myEvent" event is listened to
if (this.$listeners.myEvent){
  // let them catch and handle it
} else {
  // let's handle it by our own
}
</code>```

Body:
I have a component which is sometimes being used as a child of a parent and sometimes it does not have any parent.

This component emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this component itself.

So at run time, How do I programmatically check

if (someone is listening to the event){
    let them catch and handle it
}else {
    let's handle it by our own
}

Body:
This allows you to check listeners passed to a component:

this.$listeners;

It returns the parent scope event listeners. See the doc here.

In particular for your use-case:

// To check whether the "myEvent" event is listened to
if (this.$listeners.myEvent){
  // let them catch and handle it
} else {
  // let's handle it by our own
}


问:
list search in C#
I have a list in my C# web-application. this list is fill with keywords fetch from database.
Now i want to search in the list , as i have mulitliple keyword search.

if a person type in blue so all the record matching blue are fetched into the list. now when he type in 2nd keyword suppose yellow so the list should be filtered and it must contain only those records which having blue and yellow and same is for 3rd and fourth key word.

here is the code now what i have to do next ?

```<code>public override List<ThumbNail> GetSearchResults(string search1, string path)
        {
  List<ThumbNail> mylist = new List<ThumbNail>();
       if (search1.Length - 1 == search1.LastIndexOf(","))
       search1 = search.Remove(search1.Length - 1);
  List<string> search = new List<string>(search1.Split(','));
    for(int i=0; i <search1.Count;i++)

{
      OleDbCommand sqlcmdCommand1 =
      new OleDbCommand("select Name,File,keyword from table1 where keyword like @searchone", mycon);

 sqlcmdCommand1.Parameters.AddWithValue("searchone", search[i]);
 sqlcmdCommand1.CommandType = CommandType.Text;
 OleDbDataReader sdaResult = sqlcmdCommand1.ExecuteReader();
 while (sdaResult.Read())
 {
  mytable thmb = new Thumbl();
  thmb.Name = sdaResult.GetString(0);
  thmbN.File = sdaResult.GetString(1);
  thmb.keyword = sdaResult.IsDBNull(3) ? "" : sdaResult.GetString(6);
  mylist.Add(thmb);
 }
</code>```

}
     sdaResult.Close();

```<code>return mylist;
}

public class Thumbnail
{

        public int Id { get; set; }
        public string Name { get; set; }
        public string File { get; set; }
        public string keyword { get; set; }
        public string path { get; set; }
   }
</code>```

this action is performed when user type in first keyword. and all the records matching first keyword are now in mylist, now when user type in second keyword so a search must be performed on list which match the first and 2nd keyword and the result is returned.

```<code>The DB table look like this:

id   name   keyword  File  Fkey
1     a      yellow  c:/   20
2     a      blue    c:/   20
3     a      Pinky   c:/   20
4     b      orange  c:/   21
5     b      Redish  c:/   21
</code>```

答:
EDIT: After you updated your question, my answer no longer applies, since your table structure is different than what I expected. My answer would work if your table looked like this:

```<code>id   name   keywords            File
1     a     yellow blue pinky   c:/
2     b     orange reddish      c:/
</code>```

OLD ANSWER: First, you need to select the keywords as well, so that you can do further filtering.

```<code>thmb.Keywords = sdaResult.GetString(someIndex);
</code>```

Then, you can use LINQ to create a filtered version of your list...

```<code>var filtered = mylist.Where(thmb => thmb.Keywords.Contains(search2));
</code>```

...which you can filter further, as soon as new search keywords are entered.

```<code>var filtered = filtered.Where(thmb => thmb.Keywords.Contains(search3));
</code>```

filtered is an IEnumerable. If you need a list, apply .ToList() to it.

NEW ANSWER: Basically, what you need to do with your table structure is to:

Make a second fetch from the database, making a list of names that contain the second keyword and

remove all list entries of your first list that are not contained in the second list. For example, if your list of names containing the second keyword is a List<string> called narrowingSearch, then you could do

```<code>var filteredList = mylist.Where(thmb => narrowingSearch.Contains(thmb.Name));
</code>```

EDIT: Now that you have a common FK, you should be able to do this by using a more advanced SQL, something along the lines of:

```<code>SELECT name, file
  FROM table1
 WHERE keyword like @search0
   AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search1)
   AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search2)
   ...
</code>```

You can construct this SQL in a loop like this:

```<code>string[] search = search1.Split(',');

OleDbCommand cmd = new OleDbCommand("SELECT name, file FROM table1 WHERE keyword LIKE @search0", mycon);
cmd.Parameters.AddWithValue("@search0", search[0]);

for (int i = 1; i < search.Length; i++) {
    cmd.CommandText += " AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search" + i.ToString() + ")";
    cmd.Parameters.AddWithValue("@search" + i.ToString(), search[i]);
}
</code>```

Title: list search in C#

Body:
I have a list in my C# web-application. this list is fill with keywords fetch from database.
Now i want to search in the list , as i have mulitliple keyword search.

if a person type in blue so all the record matching blue are fetched into the list. now when he type in 2nd keyword suppose yellow so the list should be filtered and it must contain only those records which having blue and yellow and same is for 3rd and fourth key word.

here is the code now what i have to do next ?

public override List<ThumbNail> GetSearchResults(string search1, string path)
        {
  List<ThumbNail> mylist = new List<ThumbNail>();
       if (search1.Length - 1 == search1.LastIndexOf(","))
       search1 = search.Remove(search1.Length - 1);
  List<string> search = new List<string>(search1.Split(','));
    for(int i=0; i <search1.Count;i++)

{
      OleDbCommand sqlcmdCommand1 =
      new OleDbCommand("select Name,File,keyword from table1 where keyword like @searchone", mycon);

 sqlcmdCommand1.Parameters.AddWithValue("searchone", search[i]);
 sqlcmdCommand1.CommandType = CommandType.Text;
 OleDbDataReader sdaResult = sqlcmdCommand1.ExecuteReader();
 while (sdaResult.Read())
 {
  mytable thmb = new Thumbl();
  thmb.Name = sdaResult.GetString(0);
  thmbN.File = sdaResult.GetString(1);
  thmb.keyword = sdaResult.IsDBNull(3) ? "" : sdaResult.GetString(6);
  mylist.Add(thmb);
 }

}
     sdaResult.Close();

return mylist;
}

public class Thumbnail
{

        public int Id { get; set; }
        public string Name { get; set; }
        public string File { get; set; }
        public string keyword { get; set; }
        public string path { get; set; }
   }

this action is performed when user type in first keyword. and all the records matching first keyword are now in mylist, now when user type in second keyword so a search must be performed on list which match the first and 2nd keyword and the result is returned.

The DB table look like this:

id   name   keyword  File  Fkey
1     a      yellow  c:/   20
2     a      blue    c:/   20
3     a      Pinky   c:/   20
4     b      orange  c:/   21
5     b      Redish  c:/   21

Body:
EDIT: After you updated your question, my answer no longer applies, since your table structure is different than what I expected. My answer would work if your table looked like this:

id   name   keywords            File
1     a     yellow blue pinky   c:/
2     b     orange reddish      c:/

OLD ANSWER: First, you need to select the keywords as well, so that you can do further filtering.

thmb.Keywords = sdaResult.GetString(someIndex);

Then, you can use LINQ to create a filtered version of your list...

var filtered = mylist.Where(thmb => thmb.Keywords.Contains(search2));

...which you can filter further, as soon as new search keywords are entered.

var filtered = filtered.Where(thmb => thmb.Keywords.Contains(search3));

filtered is an IEnumerable. If you need a list, apply .ToList() to it.

NEW ANSWER: Basically, what you need to do with your table structure is to:

Make a second fetch from the database, making a list of names that contain the second keyword and

remove all list entries of your first list that are not contained in the second list. For example, if your list of names containing the second keyword is a List<string> called narrowingSearch, then you could do

var filteredList = mylist.Where(thmb => narrowingSearch.Contains(thmb.Name));

EDIT: Now that you have a common FK, you should be able to do this by using a more advanced SQL, something along the lines of:

SELECT name, file
  FROM table1
 WHERE keyword like @search0
   AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search1)
   AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search2)
   ...

You can construct this SQL in a loop like this:

string[] search = search1.Split(',');

OleDbCommand cmd = new OleDbCommand("SELECT name, file FROM table1 WHERE keyword LIKE @search0", mycon);
cmd.Parameters.AddWithValue("@search0", search[0]);

for (int i = 1; i < search.Length; i++) {
    cmd.CommandText += " AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search" + i.ToString() + ")";
    cmd.Parameters.AddWithValue("@search" + i.ToString(), search[i]);
}


问:
Deploy chef in Container/Kubernetes/Docker
How do i install chef/Ansible as a container on kubernetes/docker.
I have checked docker hub registry for chef image.
I have pulled chef/chef and chef/chefdk but none of them is working for me.
I have run the command:
docker run -d -p 443:443 chef/chef</p>

答: The chef/chef docker container exists mostly for the kitchen-dokken driver, not really independent use. If you want to make a containerized chef solo thingy, Chef Software has some Habitat examples you can follow, or at least they used to.</p>


问:
How do i find out the Structure of a Java Object?
I am working with the HttpExchange class, and want to use the getAttribute function to get the POST parameters. If i just call the function and print the results it works. But there has to be some better way to access the returned object and get the contained data.

The Manual is here: http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#getAttribute%28java.lang.String%29

How can i access the Object? Which methods does it have?

答:
Use Java Reflection. Using reflection you could do something like this</p>

```<code> Class c = Class.forName("YourClassName");
   Method m[] = c.getDeclaredMethods();
   for (int i = 0; i < m.length; i++)
   System.out.println(m[i].toString()); //iterate through these methods to find out data
</code>```

Body:
Use Java Reflection. Using reflection you could do something like this

 Class c = Class.forName("YourClassName");
   Method m[] = c.getDeclaredMethods();
   for (int i = 0; i < m.length; i++)
   System.out.println(m[i].toString()); //iterate through these methods to find out data


问:
Show Non matching values query of two columns
Tried this Query:

```<code>
    SELECT     Movements.[date of movement],
               Movements.[Date of value],
               Movements.Description
    FROM       Movements
    INNER JOIN Documents
    on         Movements.Description<> '%' + Documents.Costumer+ '%'
    AND        Documents.[Value with IVA] <> Movements.Value
    Group by   Movements.[date of Movement],
               Movements.[Date of value],
               Movements.Description,
               Documents.Costumer,
               Documents.[Value with IVA]

</code>```

The problem is that He shows me all Costumers that doesnt match with the the description... And what I want is the descriptions that do not match one single time....
 I want to me to show me like:

```<code>Date of movement    Date of Value    Description
12-12-2011           1-12-2011       123123
12-12-2011           12-12-2011      121121
13-12-2011           13-12-2011      121121
</code>```

What it shows me is this

```<code>Date of movement    Date of Value    Description
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
</code>```

答:
I think you mean to use the LIKE operator instead of <>:

```<code>on Movements.Description not like '%' + Documents.Costumer + '%'
</code>```

or is it the other way:

```<code>on Documents.Costumer not like '%' + Movements.Description + '%'
</code>```

Body:
Tried this Query:

    SELECT     Movements.[date of movement],
               Movements.[Date of value],
               Movements.Description
    FROM       Movements
    INNER JOIN Documents
    on         Movements.Description<> '%' + Documents.Costumer+ '%'
    AND        Documents.[Value with IVA] <> Movements.Value
    Group by   Movements.[date of Movement],
               Movements.[Date of value],
               Movements.Description,
               Documents.Costumer,
               Documents.[Value with IVA]

The problem is that He shows me all Costumers that doesnt match with the the description... And what I want is the descriptions that do not match one single time....
 I want to me to show me like:

Date of movement    Date of Value    Description
12-12-2011           1-12-2011       123123
12-12-2011           12-12-2011      121121
13-12-2011           13-12-2011      121121

What it shows me is this

Date of movement    Date of Value    Description
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121

Body:
I think you mean to use the LIKE operator instead of <>:

on Movements.Description not like '%' + Documents.Costumer + '%'

or is it the other way:

on Documents.Costumer not like '%' + Movements.Description + '%'


问:
Adding +1 to multiple values in one cell via excel formula
I got an excel file with a data source sheet. To be able to parse the data at the next step I need to add 1 to every value and get it into a new sheet. The thing is, that there are multiple values per cell, each separated by comma, and this number is not static. Adding the +1 at a later point is sadly not an option so I need to do this in excel.</p>

```<code>  Source sheet              Prepared data sheet

| MyValues   |             | MyValues + 1 |
|------------|             |--------------|
| 0,1,2,3    |             |  1,2,3,4     |
| 3          |   ----->    |  4           |
| 2,4,6      |             |  3,5,7       |
| 1          |             |  2           |
</code>```

答:
Here's helper column based solution. I have assumed data starts from cell A2 and concatenation formula in cell B2. I have considered case of 15 maximum values.

In cell C2, following formula shall be put:

=IFERROR((TRIM(MID(SUBSTITUTE(","&$A2,",",REPT(" ",99)),COLUMNS($A$1:A1)*99,99))/1)+1,"")

This shall be copied across (till column Q) and down (till last row of your data).

Then apply concatenation formula as below in cell B2:

=SUBSTITUTE(TRIM(CONCATENATE(C2," ",D2," ",E2," ",F2," ",G2," ",H2," ",I2," ",J2," ",K2," ",L2," ",M2," ",N2," ",O2," ",P2," ",Q2))," ",",")

shall work for Excel Version 2007 or higher.

Body:
I got an excel file with a data source sheet. To be able to parse the data at the next step I need to add 1 to every value and get it into a new sheet. The thing is, that there are multiple values per cell, each separated by comma, and this number is not static. Adding the +1 at a later point is sadly not an option so I need to do this in excel.

  Source sheet              Prepared data sheet

| MyValues   |             | MyValues + 1 |
|------------|             |--------------|
| 0,1,2,3    |             |  1,2,3,4     |
| 3          |   ----->    |  4           |
| 2,4,6      |             |  3,5,7       |
| 1          |             |  2           |


问:
Docker: How to fix "Job for docker.service failed because the control process exited with error code"
I'm trying to use docker in Manjaro (my kernel version is 4.19) and it is not working.

After running sudo pamac install docker I run sudo systemctl start docker.service and receive this message:

```<code>Job for docker.service failed because the control process exited with error code.
See "systemctl status docker.service" and "journalctl -xe" for details.

</code>```

So sudo systemctl status docker.service returns:

```<code>● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2019-04-29 12:28:44 -03; 39s ago
     Docs: https://docs.docker.com
  Process: 17769 ExecStart=/usr/bin/dockerd -H fd:// (code=exited, status=1/FAILURE)
 Main PID: 17769 (code=exited, status=1/FAILURE)

abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Service RestartSec=100ms expired, scheduling restart.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Scheduled restart job, restart counter is at 3.
abr 29 12:28:44 tamer-pc systemd[1]: Stopped Docker Application Container Engine.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Start request repeated too quickly.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Failed with result 'exit-code'.
abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine.

</code>```

and journalctl -xe returns:

```<code>-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The unit docker.service has entered the 'failed' state with result 'exit-code'.
abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: A unidade docker.service falhou
-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- A unidade docker.service falhou.
--
-- O resultado é failed.
abr 29 12:28:44 tamer-pc systemd[1]: docker.socket: Failed with result 'service-start-limit-hit'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The unit docker.socket has entered the 'failed' state with result 'service-start-limit-hit'.
abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activating via systemd: service name='org.freedesktop.resolve1' unit='>
abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activation via systemd failed for unit 'dbus-org.freedesktop.resolve1.>
abr 29 12:29:24 tamer-pc sudo[17879]:    tamer : TTY=pts/0 ; PWD=/etc/docker ; USER=root ; COMMAND=/usr/bin/systemctl stat>
abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session opened for user root by (uid=0)
abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session closed for user root
lines 1703-1725/1725 (END)

</code>```

I'm looking for resolution for two days but whatever I read seems not to be exactly the same as my problem.

答:
I had the same problem, but I folow the advise of @Zeitounator, and I run this command sudo dockerd --debug to see the problem. It display this message :

Your Linux kernel version 2.6.32-042stab138.1 is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.

I've update my kernel and it works perfectly. I hope that help you !

Body:
I'm trying to use docker in Manjaro (my kernel version is 4.19) and it is not working.

After running sudo pamac install docker I run sudo systemctl start docker.service and receive this message:

Job for docker.service failed because the control process exited with error code.
See "systemctl status docker.service" and "journalctl -xe" for details.

So sudo systemctl status docker.service returns:

● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2019-04-29 12:28:44 -03; 39s ago
     Docs: https://docs.docker.com
  Process: 17769 ExecStart=/usr/bin/dockerd -H fd:// (code=exited, status=1/FAILURE)
 Main PID: 17769 (code=exited, status=1/FAILURE)

abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Service RestartSec=100ms expired, scheduling restart.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Scheduled restart job, restart counter is at 3.
abr 29 12:28:44 tamer-pc systemd[1]: Stopped Docker Application Container Engine.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Start request repeated too quickly.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Failed with result 'exit-code'.
abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine.

and journalctl -xe returns:

-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The unit docker.service has entered the 'failed' state with result 'exit-code'.
abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: A unidade docker.service falhou
-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- A unidade docker.service falhou.
--
-- O resultado é failed.
abr 29 12:28:44 tamer-pc systemd[1]: docker.socket: Failed with result 'service-start-limit-hit'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The unit docker.socket has entered the 'failed' state with result 'service-start-limit-hit'.
abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activating via systemd: service name='org.freedesktop.resolve1' unit='>
abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activation via systemd failed for unit 'dbus-org.freedesktop.resolve1.>
abr 29 12:29:24 tamer-pc sudo[17879]:    tamer : TTY=pts/0 ; PWD=/etc/docker ; USER=root ; COMMAND=/usr/bin/systemctl stat>
abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session opened for user root by (uid=0)
abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session closed for user root
lines 1703-1725/1725 (END)

I'm looking for resolution for two days but whatever I read seems not to be exactly the same as my problem.


问:
Count the total (N) of duplicates in a column
I'm attempting to count the total number of duplicates in a column (not the individual duplicates).

```<code>from outputs
GROUP BY journal_id
HAVING ( COUNT(doi) > 1 )
WHERE journal_id = 1
</code>```

SQL TABLE

```<code>doi   journal_id
123       1
123       2
123       1
124       1

</code>```

The expected answer is 2

答:
Just sum up the count of the individual duplicates by journal id.</p>

```<code>SELECT
  SUM(COUNT(doi)) AS total_duplicates
from
  outputs
WHERE
  journal_id = 1
GROUP BY
  journal_id
HAVING
  (COUNT(doi) > 1)
</code>```

Body:
I'm attempting to count the total number of duplicates in a column (not the individual duplicates).

from outputs
GROUP BY journal_id
HAVING ( COUNT(doi) > 1 )
WHERE journal_id = 1

SQL TABLE

doi   journal_id
123       1
123       2
123       1
124       1

The expected answer is 2

Body:
Just sum up the count of the individual duplicates by journal id.

SELECT
  SUM(COUNT(doi)) AS total_duplicates
from
  outputs
WHERE
  journal_id = 1
GROUP BY
  journal_id
HAVING
  (COUNT(doi) > 1)


问:
Python JSON encoder to support datetime?
is there any elegant way to make Python JSON encoder support datetime? some 3rd party module or easy hack?

I am using tornado's database wrapper to fetch some rows from db to generate a json. The query result includes a regular MySQL timestamp column.

It's quite annoying that Python's default json encoder doesn't support its own datetime type, which is so common in all kinds of database queries.

I don't want to modify Python's own json encoder. any good practice? Thanks a lot!

ps: I found a dirty hack by modifying the Python JSON encoder default method:

Change:

```<code>def default(self, o):
    raise TypeError(repr(o) + " is not JSON serializable")
</code>```

To:

```<code>def default(self, o):
    from datetime import date
    from datetime import datetime
    if isinstance(o, datetime):
        return o.isoformat()
    elif isinstance(o, date):
        return o.isoformat()
    else:
        raise TypeError(repr(o) + " is not JSON serializable")
</code>```

well, it will be a temporary solution just for dev environment.

But for long term solution or production environment, this is quite ugly, and I have to do the modification every time I deploy to a new server.

Is there a better way? I do not want to modify Python code itself, neither Tornado source code. Is there something I can do with my own project code to make this happen? preferably in one pace.

Thanks a lot!

答:
Create a custom decoder/encoder:</p>

```<code>class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return http_date(obj)
        if isinstance(obj, uuid.UUID):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

class CustomJSONDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, source):
        for k, v in source.items():
            if isinstance(v, str):
                try:
                    source[k] = datetime.datetime.strptime(str(v), '%a, %d %b %Y %H:%M:%S %Z')
                except:
                    pass
        return source
</code>```

Body:
is there any elegant way to make Python JSON encoder support datetime? some 3rd party module or easy hack?

I am using tornado's database wrapper to fetch some rows from db to generate a json. The query result includes a regular MySQL timestamp column.

It's quite annoying that Python's default json encoder doesn't support its own datetime type, which is so common in all kinds of database queries.

I don't want to modify Python's own json encoder. any good practice? Thanks a lot!

ps: I found a dirty hack by modifying the Python JSON encoder default method:

Change:

def default(self, o):
    raise TypeError(repr(o) + " is not JSON serializable")

To:

def default(self, o):
    from datetime import date
    from datetime import datetime
    if isinstance(o, datetime):
        return o.isoformat()
    elif isinstance(o, date):
        return o.isoformat()
    else:
        raise TypeError(repr(o) + " is not JSON serializable")

well, it will be a temporary solution just for dev environment.

But for long term solution or production environment, this is quite ugly, and I have to do the modification every time I deploy to a new server.

Is there a better way? I do not want to modify Python code itself, neither Tornado source code. Is there something I can do with my own project code to make this happen? preferably in one pace.

Thanks a lot!

Body:
Create a custom decoder/encoder:

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return http_date(obj)
        if isinstance(obj, uuid.UUID):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

class CustomJSONDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, source):
        for k, v in source.items():
            if isinstance(v, str):
                try:
                    source[k] = datetime.datetime.strptime(str(v), '%a, %d %b %Y %H:%M:%S %Z')
                except:
                    pass
        return source


问:
'sqlite3.IntegrityError: UNIQUE constraint failed: student3--".ID.I am trying to create a table student3 and insert values of ID and name
I am writing a code for a program that connects to Database file12.sqllite3 and creates table 'student3' to store ID as primary key and Name. Also, I want that if the file is not created, then it should be created.
But my code shows error-->

sqlite3.IntegrityError: UNIQUE constraint failed: student3.ID

What is wrong?

Why is this error coming? Where has the UNIQUE constraint failed?

Here is my code :

```<code>       --- import sqlite3;

        conn=sqlite3.connect('file12.sqlite3');
        c=conn.cursor();``

        c.execute("CREATE TABLE IF NOT EXISTS student3(ID integer
                   PRIMARY KEY, NAME text)");
        c.execute("INSERT INTO student3 VALUES(11,'Tendo Sinha')");
        c.execute("INSERT INTO student3 VALUES(12,'Harsh Gupta')");
        c.execute("INSERT INTO student3 VALUES(13,'Vishwas Kumar')");
        c.execute("INSERT INTO student3 VALUES(14,'Goel')");
        c.execute("INSERT INTO student3 VALUES(15,'Alok')");

        conn.commit();

        c.execute("SELECT * from student3");
        print(c.fetchall());
        c.execute("SELECT ID from student3")
        print(c.fetchmany(4));

        c.execute("UPDATE student3 SET Name='Bhanu' where ID=14");
        print(c.fetchall());
</code>```

How to rectify the error -->

sqlite3.IntegrityError: UNIQUE constraint failed: student3.ID

答:
Your code fails if you run it twice : the first time it will run just fine as you are inserting with available ID values but as soon as you run it again, you try to insert on ID values that already exist, that is what causes the exception.

The primary key values are meant to be unique, there cannot be any duplicates

I would recommend inserting this way : c.execute("INSERT INTO student3 VALUES(NULL,'Alok')"); with a NULL instead of a given value for the ID. This allows SQLite to insert a value on an available value. You can therefor insert as many students as you wish with same or different names without getting the exception.

However, beware of your c.execute("UPDATE student3 SET Name='Bhanu' where ID=14"); if you use the NULL insert method as you will not know the ID's in advance, you may need to search on the name itself rather than the ID or get the ID as you insert and store it as a variable for later use

Note : Since SQLite3 already does the creation of the file if it doesn't exist, you do not need to do anything there

Body:
I am writing a code for a program that connects to Database file12.sqllite3 and creates table 'student3' to store ID as primary key and Name. Also, I want that if the file is not created, then it should be created.
But my code shows error-->

sqlite3.IntegrityError: UNIQUE constraint failed: student3.ID

What is wrong?

Why is this error coming? Where has the UNIQUE constraint failed?

Here is my code :

       --- import sqlite3;

        conn=sqlite3.connect('file12.sqlite3');
        c=conn.cursor();``

        c.execute("CREATE TABLE IF NOT EXISTS student3(ID integer
                   PRIMARY KEY, NAME text)");
        c.execute("INSERT INTO student3 VALUES(11,'Tendo Sinha')");
        c.execute("INSERT INTO student3 VALUES(12,'Harsh Gupta')");
        c.execute("INSERT INTO student3 VALUES(13,'Vishwas Kumar')");
        c.execute("INSERT INTO student3 VALUES(14,'Goel')");
        c.execute("INSERT INTO student3 VALUES(15,'Alok')");

        conn.commit();

        c.execute("SELECT * from student3");
        print(c.fetchall());
        c.execute("SELECT ID from student3")
        print(c.fetchmany(4));

        c.execute("UPDATE student3 SET Name='Bhanu' where ID=14");
        print(c.fetchall());

How to rectify the error -->

sqlite3.IntegrityError: UNIQUE constraint failed: student3.ID


问:
Up and down arrow inserting unwanted character in tkinter.Entry widget
The following code produces an app with a single Entry widget. When run on MacOS using Python 3.7.3 from Homebrew, pressing the up or down arrow while inside the entry box causes a character 0xF701 to be inserted:

```<code>import tkinter as tk

root = tk.Tk()
app = tk.Frame(master=root)
app.pack()

entry = tk.Entry(app)
entry.pack()

app.mainloop()
</code>```

This doesn't happen with Anaconda Python and I haven't been able to find anyone else having this issue.

By binding print to the up and down events I've been able to see that the character associated with these events is indeed 0xF700 and 0xF701.

```<code>entry.bind('<Down>', print)
entry.bind('<Up>', print)
</code>```

Output after pressing up and down:

```<code><KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' delta=8320768 x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' delta=8255233 x=-5 y=-50>
</code>```

With the Anaconda Python version the output is slightly different:

```<code><KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' x=-5 y=-50>
</code>```

Does anyone know of a simple solution to this problem?

答:
Can validating the Entry help?  The code below validates that the resulting string in Entry only contains characters in valid_chars.  A more complex validation rule could be written if required.

```<code>import tkinter as tk
import re

valid_chars = re.compile(r'^[0-9A-Za-z ]*$') # Accept Alphanumeric and Space

class ValidateEntry(tk.Entry):
    def __init__(self, parent, regex):
        self.valid = regex
        validate_cmd = (parent.register(self.validate),'%P') # %P pass the new string to validate
        super().__init__( parent, validate = 'key', validatecommand = validate_cmd)
        #  validate = 'key' runs the validation at each keystroke.

    def validate(self, new_str):
        if self.valid.match(new_str): return True
        return False

def do_key(ev):
    print(ev.widget, ev, entry.get())

root= tk.Tk()
root.title("Validation")
fram = tk.Frame(root)
fram.grid()

entry = ValidateEntry(fram, valid_chars)
entry.grid()
entry.bind('<Down>', do_key)
entry.bind('<Up>', do_key)

root.mainloop()
</code>```

This may be overkill but should work across all the platforms.

Body:
The following code produces an app with a single Entry widget. When run on MacOS using Python 3.7.3 from Homebrew, pressing the up or down arrow while inside the entry box causes a character 0xF701 to be inserted:

import tkinter as tk

root = tk.Tk()
app = tk.Frame(master=root)
app.pack()

entry = tk.Entry(app)
entry.pack()

app.mainloop()

This doesn't happen with Anaconda Python and I haven't been able to find anyone else having this issue.

By binding print to the up and down events I've been able to see that the character associated with these events is indeed 0xF700 and 0xF701.

entry.bind('<Down>', print)
entry.bind('<Up>', print)

Output after pressing up and down:

<KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' delta=8320768 x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' delta=8255233 x=-5 y=-50>

With the Anaconda Python version the output is slightly different:

<KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' x=-5 y=-50>

Does anyone know of a simple solution to this problem?

Body:
Can validating the Entry help?  The code below validates that the resulting string in Entry only contains characters in valid_chars.  A more complex validation rule could be written if required.

import tkinter as tk
import re

valid_chars = re.compile(r'^[0-9A-Za-z ]*$') # Accept Alphanumeric and Space

class ValidateEntry(tk.Entry):
    def __init__(self, parent, regex):
        self.valid = regex
        validate_cmd = (parent.register(self.validate),'%P') # %P pass the new string to validate
        super().__init__( parent, validate = 'key', validatecommand = validate_cmd)
        #  validate = 'key' runs the validation at each keystroke.

    def validate(self, new_str):
        if self.valid.match(new_str): return True
        return False

def do_key(ev):
    print(ev.widget, ev, entry.get())

root= tk.Tk()
root.title("Validation")
fram = tk.Frame(root)
fram.grid()

entry = ValidateEntry(fram, valid_chars)
entry.grid()
entry.bind('<Down>', do_key)
entry.bind('<Up>', do_key)

root.mainloop()

This may be overkill but should work across all the platforms.


问:
Get the total number of group names where there are multiple group names in a single cell surrounded by random text
This is regarding an export of a list from a Sharepoint site where I do not have access to exporting feature, but I can refresh the information in order to gather new information when is added on the Sharepoint site.
The excel list has several columns, out of which one of them is containing names of groups that were created.

There are several thousands of rows, with cells where each cell might contain this kind of data.
I want to be able to only count the number of groups in my excel sheet.

I was initially thinking to find a way to export somehow the data as text and to then try to remove any parts in the string BEFORE the rows (again, all these rows are in the same cell) in order to make the data uniform and to have only the name of the groups and then to try count in a different column the number of items in each cell and to have a sum.

```<code>"Please delete following CORP group:

PRD.12.SYOS.EXOA.XW12LAPP0171.TWSUSERS
PRD.12.SYOS.XW12LAPP0171.Administrators
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSAGENT
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSUSERS
PRD.12.SYOS.VM4P.XW12LAPP0063.ADMINISTRATORS
PRD.12.SYOS.VM4P.XW12LAPP0063.RDP
PRD.12.SYOS.XW12LAPP0063.Administrators"
</code>```

I am a beginner in excel and in coding. I tried using functions in excel like RIGHT, LEFT, MID, LEN but I am still unable to produce anything close to what I need.

I need the total number of the groups in the sheet.

答:
When your list doesn't have doublures you could use a rather simple formula like:

```<code>=LEN(A1)-LEN(SUBSTITUTE(A1,CHR(10),""))-1
</code>```

It would also be a nice issue to use REGEX on, like so for example:

```<code>Function CountGroup(RNG As Range) As Double

Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
    .Pattern = "(?=.*\d)[^\n " & Chr(34) & "]+"
    .Global = True
End With
Set Matches = regex.Execute(RNG.Value)
CountGroup = Matches.Count

End Function
</code>```

Or when your list can contain doublures:

```<code>Function CountGroup(RNG As Range) As Double

Dim regex As Object, ARR1() As String, X As Long, ARR2() As String
Set regex = CreateObject("VBScript.RegExp")
With regex
    .Pattern = "(?=.*\d)[^\n " & Chr(34) & "]+"
    .Global = True
End With
Set matches = regex.Execute(RNG.Value)
ReDim ARR1(X)
For Each HIT In matches
    ARR2 = Filter(SourceArray:=ARR1, Match:=HIT.Value, Include:=True, Compare:=vbTextCompare)
    If UBound(ARR2) = -1 Then
        ReDim Preserve ARR1(X)
        ARR1(X) = HIT.Value
        X = X + 1
    End If
Next HIT

If IsEmpty(ARR1) Then
    CountGroup = 0
Else
    CountGroup = UBound(ARR1) - LBound(ARR1)
End If

End Function
</code>```

Call in sheet through =CountGroup(A1)

Body:
This is regarding an export of a list from a Sharepoint site where I do not have access to exporting feature, but I can refresh the information in order to gather new information when is added on the Sharepoint site.
The excel list has several columns, out of which one of them is containing names of groups that were created.

There are several thousands of rows, with cells where each cell might contain this kind of data.
I want to be able to only count the number of groups in my excel sheet.

I was initially thinking to find a way to export somehow the data as text and to then try to remove any parts in the string BEFORE the rows (again, all these rows are in the same cell) in order to make the data uniform and to have only the name of the groups and then to try count in a different column the number of items in each cell and to have a sum.

"Please delete following CORP group:

PRD.12.SYOS.EXOA.XW12LAPP0171.TWSUSERS
PRD.12.SYOS.XW12LAPP0171.Administrators
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSAGENT
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSUSERS
PRD.12.SYOS.VM4P.XW12LAPP0063.ADMINISTRATORS
PRD.12.SYOS.VM4P.XW12LAPP0063.RDP
PRD.12.SYOS.XW12LAPP0063.Administrators"

I am a beginner in excel and in coding. I tried using functions in excel like RIGHT, LEFT, MID, LEN but I am still unable to produce anything close to what I need.

I need the total number of the groups in the sheet.

Body:
When your list doesn't have doublures you could use a rather simple formula like:

=LEN(A1)-LEN(SUBSTITUTE(A1,CHR(10),""))-1

It would also be a nice issue to use REGEX on, like so for example:

Function CountGroup(RNG As Range) As Double

Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
    .Pattern = "(?=.*\d)[^\n " & Chr(34) & "]+"
    .Global = True
End With
Set Matches = regex.Execute(RNG.Value)
CountGroup = Matches.Count

End Function

Or when your list can contain doublures:

Function CountGroup(RNG As Range) As Double

Dim regex As Object, ARR1() As String, X As Long, ARR2() As String
Set regex = CreateObject("VBScript.RegExp")
With regex
    .Pattern = "(?=.*\d)[^\n " & Chr(34) & "]+"
    .Global = True
End With
Set matches = regex.Execute(RNG.Value)
ReDim ARR1(X)
For Each HIT In matches
    ARR2 = Filter(SourceArray:=ARR1, Match:=HIT.Value, Include:=True, Compare:=vbTextCompare)
    If UBound(ARR2) = -1 Then
        ReDim Preserve ARR1(X)
        ARR1(X) = HIT.Value
        X = X + 1
    End If
Next HIT

If IsEmpty(ARR1) Then
    CountGroup = 0
Else
    CountGroup = UBound(ARR1) - LBound(ARR1)
End If

End Function

Call in sheet through =CountGroup(A1)


问:
How can i get locale info in Unity C#?
I am developing a project with Unity 2019.2b, it is expected to work at all platforms (android, ios, windows, macos) , i am trying to get device locale info(e.g. en-us, en-au, en-bz) but all i can find is Application.systemLanguage definition. Even i decide to use this information i will still need region info. Are there any sample or way to get locale info in Unity or to get device region info? (If the solution for only region info; I dont want to use device location or dont want to use user ip address, i want to get it from settings)

I tried to get locale or at least device region info with RegionInfo,CultureInfo,System.Threading.Thread.CurrentThread.CurrentUICulture and System.Threading.Thread.CurrentThread.CurrentCulture definitions, but it didn't work.

```<code>string regionName = System.Globalization.RegionInfo.CurrentRegion.Name;
string cultureName = System.Globalization.CultureInfo.CurrentCulture.Name;
string cname = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
string uiname = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
</code>```

Depending on the platform (ios, android, windows,macos) sometimes the result comes as InvariantCulture, sometimes always en-US even device locale is not en-US.

答:
The issue is coming from Mono, used by Unity.

I found a few solutions in this forum thread.

If you are working with Windows a workaround might be using PInvoke:

```<code> [System.Runtime.InteropServices.DllImport("KERNEL32.DLL")]
 private static extern int GetSystemDefaultLCID();
</code>```

And then check the global culture like so:

```<code>var currentCulture = new CultureInfo(GetSystemDefaultLCID());
</code>```

This might be used to set the culture:

```<code> Thread.CurrentThread.CurrentCulture = new CultureInfo(GetSystemDefaultLCID());
 Thread.CurrentThread.CurrentUICulture = new CultureInfo(GetSystemDefaultLCID());
</code>```

Title: How can i get locale info in Unity C#?

Body:
I am developing a project with Unity 2019.2b, it is expected to work at all platforms (android, ios, windows, macos) , i am trying to get device locale info(e.g. en-us, en-au, en-bz) but all i can find is Application.systemLanguage definition. Even i decide to use this information i will still need region info. Are there any sample or way to get locale info in Unity or to get device region info? (If the solution for only region info; I dont want to use device location or dont want to use user ip address, i want to get it from settings)

I tried to get locale or at least device region info with RegionInfo,CultureInfo,System.Threading.Thread.CurrentThread.CurrentUICulture and System.Threading.Thread.CurrentThread.CurrentCulture definitions, but it didn't work.

string regionName = System.Globalization.RegionInfo.CurrentRegion.Name;
string cultureName = System.Globalization.CultureInfo.CurrentCulture.Name;
string cname = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
string uiname = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;

Depending on the platform (ios, android, windows,macos) sometimes the result comes as InvariantCulture, sometimes always en-US even device locale is not en-US.

Body:
The issue is coming from Mono, used by Unity.

I found a few solutions in this forum thread.

If you are working with Windows a workaround might be using PInvoke:

 [System.Runtime.InteropServices.DllImport("KERNEL32.DLL")]
 private static extern int GetSystemDefaultLCID();

And then check the global culture like so:

var currentCulture = new CultureInfo(GetSystemDefaultLCID());

This might be used to set the culture:

 Thread.CurrentThread.CurrentCulture = new CultureInfo(GetSystemDefaultLCID());
 Thread.CurrentThread.CurrentUICulture = new CultureInfo(GetSystemDefaultLCID());


问:
WPF ProgressBar doesn't update?
I am trying to update my progressbar by using data bindings. The XAML file contains the progressbar:

```<code><ProgressBar Height="23" Name="progressBar" VerticalAlignment="Bottom" Margin="207,444,0,0" Minimum="0" Maximum="{Binding ProgressBarMax}" Value="{Binding ProgressBarValue}" />
</code>```

My relevant C# class contains the getter & setter:

```<code>    private int progressBarMax;
    public int ProgressBarMax
    {
        get
        {
            if (this.progressBarMax == 0)
                this.progressBarMax = 1;
            return this.progressBarMax;
        }
        set
        {
            this.progressBarMax = value;
        }
    }

    private int progressBarValue;
    public int ProgressBarValue
    {
        get
        {
            return progressBarValue;
        }
        set
        {
            progressBarValue = value;
        }
    }
</code>```

In my "update" method the maximum is being set. For example like this.progressBarMax = 100;. In a loop the progressbar value is getting the value += 1. To see the updates I used Application.DoEvents(), later I will implement threads. The data binding has to be correct, because I have other components that work fine.

So why doesn't my progressbar update?

Thank you for your help.

答: You need to implement a way to let your ProgressBar be notified whenever ProgressBarValue changes. Have a look at the INotifyPropertyChanged interface.</p>

Title: WPF ProgressBar doesn't update?

Body:
I am trying to update my progressbar by using data bindings. The XAML file contains the progressbar:

<ProgressBar Height="23" Name="progressBar" VerticalAlignment="Bottom" Margin="207,444,0,0" Minimum="0" Maximum="{Binding ProgressBarMax}" Value="{Binding ProgressBarValue}" />

My relevant C# class contains the getter & setter:

    private int progressBarMax;
    public int ProgressBarMax
    {
        get
        {
            if (this.progressBarMax == 0)
                this.progressBarMax = 1;
            return this.progressBarMax;
        }
        set
        {
            this.progressBarMax = value;
        }
    }

    private int progressBarValue;
    public int ProgressBarValue
    {
        get
        {
            return progressBarValue;
        }
        set
        {
            progressBarValue = value;
        }
    }

In my "update" method the maximum is being set. For example like this.progressBarMax = 100;. In a loop the progressbar value is getting the value += 1. To see the updates I used Application.DoEvents(), later I will implement threads. The data binding has to be correct, because I have other components that work fine.

So why doesn't my progressbar update?

Thank you for your help.


问:
React mui button input file not opening local machin file directory
I am trying to implement a button as an input field of file type, I have tried to wrap the input field with the button, and hide it. But, this is not working since nothing happens when I click on the button. I don't get the dialog to choose the files from the local machine. This is my component:

```<code>class MediaPlaceholder extends Component {
  constructor(props){
    super(props)
    this.state = {
      file: null
    }
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event) {
    this.setState({
      file: URL.createObjectURL(event.target.files[0])
    })
  }
  render() {
    const {classes} = this.props;
    return (
      <Paper className={classes.media}>
        <div>
          <label htmlFor="upload-file">
            <Button  onClick={event => this.handleChange(event)}>
              Add media...
              <input
                accept="image/*"
                className={classes.input}
                id="upload-file"
                type="file"
              />
            </Button>
          </label>
        </div>
      </Paper>
    );
  }
}
</code>```

I saw in few places that this is the suggested solution, so I am wondering why is it not working?

答:
From the Material-UI docs/example https://material-ui.com/components/buttons/#contained-buttons :

```<code><input
    accept="image/*"
    className={classes.input}
    id="contained-button-file"
    multiple
    type="file"
  />
  <label htmlFor="contained-button-file">
    <Button variant="contained" component="span" className={classes.button}>
      Upload
    </Button>
  </label>
</code>```

So you could try :

```<code>class MediaPlaceholder extends Component {
  constructor(props){
    super(props)
    this.state = {
      file: null
    }
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event) {
    this.setState({
      file: URL.createObjectURL(event.target.files[0])
    })
  }
  render() {
    const {classes} = this.props;
    return (
      <Paper className={classes.media}>
        <div>
          <input
              accept="image/*"
              className={classes.input}
              id="upload-file"
              type="file"
            />
          <label htmlFor="upload-file">
            <Button  onClick={this.handleChange.bind(this)}>
              Add media...
            </Button>
          </label>
        </div>
      </Paper>
    );
  }
}
</code>```

Body:
I am trying to implement a button as an input field of file type, I have tried to wrap the input field with the button, and hide it. But, this is not working since nothing happens when I click on the button. I don't get the dialog to choose the files from the local machine. This is my component:

class MediaPlaceholder extends Component {
  constructor(props){
    super(props)
    this.state = {
      file: null
    }
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event) {
    this.setState({
      file: URL.createObjectURL(event.target.files[0])
    })
  }
  render() {
    const {classes} = this.props;
    return (
      <Paper className={classes.media}>

            <Button  onClick={event => this.handleChange(event)}>
              Add media...
              <input
                accept="image/*"
                className={classes.input}
                id="upload-file"
                type="file"
              />
            </Button>

      </Paper>
    );
  }
}

I saw in few places that this is the suggested solution, so I am wondering why is it not working?

Body:
From the Material-UI docs/example https://material-ui.com/components/buttons/#contained-buttons :

<input
    accept="image/*"
    className={classes.input}
    id="contained-button-file"
    multiple
    type="file"
  />
  <label htmlFor="contained-button-file">
    <Button variant="contained" component="span" className={classes.button}>
      Upload
    </Button>
  </label>

So you could try :

class MediaPlaceholder extends Component {
  constructor(props){
    super(props)
    this.state = {
      file: null
    }
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event) {
    this.setState({
      file: URL.createObjectURL(event.target.files[0])
    })
  }
  render() {
    const {classes} = this.props;
    return (
      <Paper className={classes.media}>
        <div>
          <input
              accept="image/*"
              className={classes.input}
              id="upload-file"
              type="file"
            />
          <label htmlFor="upload-file">
            <Button  onClick={this.handleChange.bind(this)}>
              Add media...
            </Button>
          </label>
        </div>
      </Paper>
    );
  }
}


问:
How to authenticate https client certificates using Dancer/Starman or Mojolicious/Daemon?
I am trying to perform Authentication using HTTPS client certificates using perl Dancer framework.
I would like to accept requests sent with/without certificate and do validation on the certificate CN to proceed with the valid response
(https://medium.com/@sevcsik/authentication-using-https-client-certificates-3c9d270e8326, the link shows how to do it in node.js, need something very similar for perl Dancer/Starman/Plackup)

I have setup ssl using Dancer/Plackup, but have not found a way to get details about the peer certificate to perform validation in Dancer framework

I would like to achieve the following:

If the request is sent

without certificate => 401

with certificate but client has self-signed (CN doesn't match with server cert CN) => 401

with certificate but client cert has been signed using server cert (CN matches server cert CN) => 200

答:
To anyone who is facing the issue, I solved it by the following steps:
(To create client and server certificates, I followed https://medium.com/@sevcsik/authentication-using-https-client-certificates-3c9d270e8326)

1) Use nginx (Setup guide:https://gist.github.com/netpoetica/5879685)

2) Create the nginx config

```<code>server {
    listen 443 ssl;
    server_name localhost;
    ssl_certificate /to/path/server_cert.pem;  # server certificate
    ssl_certificate_key /to/path/server_key.pem; # server key

    ssl_client_certificate /to/path/server_cert.pem; # client CA => server certificate for self signed
    ssl_verify_client on;

    location / {
        proxy_pass http://localhost:5000;
        proxy_set_header SSL_CLIENT_CERT $ssl_client_cert; #ENTIRE CLIENT CERTIFICATE
        proxy_set_header SSL_CLIENT_S_DN $ssl_client_s_dn; #SUBJECT DN
        proxy_set_header SSL_CLIENT_I_DN $ssl_client_i_dn; #ISSUER DN
    }
}
</code>```

More details regarding ssl can be shared using the attributes mentioned on http://nginx.org/en/docs/http/ngx_http_ssl_module.html#variables

3) Dancer application

```<code>get '/' => sub {
    info to_dumper(request->headers);
    content_type 'text/xml';
    return "OK";
};
</code>```

4) Start the dancer application using plackup (or starman/your preferred choice)

```<code>carton exec plackup -R /bin,/lib bin/app.psgi
</code>```

5) Send the request to the server

```<code>curl -v https://localhost/ --key client_key.pem --cert client_cert.pem --cacert server_cert.pem
</code>```

6) You should observe client certificate details in the plackup logs

Body:
To anyone who is facing the issue, I solved it by the following steps:
(To create client and server certificates, I followed https://medium.com/@sevcsik/authentication-using-https-client-certificates-3c9d270e8326)

1) Use nginx (Setup guide:https://gist.github.com/netpoetica/5879685)

2) Create the nginx config

server {
    listen 443 ssl;
    server_name localhost;
    ssl_certificate /to/path/server_cert.pem;  # server certificate
    ssl_certificate_key /to/path/server_key.pem; # server key

    ssl_client_certificate /to/path/server_cert.pem; # client CA => server certificate for self signed
    ssl_verify_client on;

    location / {
        proxy_pass http://localhost:5000;
        proxy_set_header SSL_CLIENT_CERT $ssl_client_cert; #ENTIRE CLIENT CERTIFICATE
        proxy_set_header SSL_CLIENT_S_DN $ssl_client_s_dn; #SUBJECT DN
        proxy_set_header SSL_CLIENT_I_DN $ssl_client_i_dn; #ISSUER DN
    }
}

More details regarding ssl can be shared using the attributes mentioned on http://nginx.org/en/docs/http/ngx_http_ssl_module.html#variables

3) Dancer application

get '/' => sub {
    info to_dumper(request->headers);
    content_type 'text/xml';
    return "OK";
};

4) Start the dancer application using plackup (or starman/your preferred choice)

carton exec plackup -R /bin,/lib bin/app.psgi

5) Send the request to the server

curl -v https://localhost/ --key client_key.pem --cert client_cert.pem --cacert server_cert.pem

6) You should observe client certificate details in the plackup logs


问:
Equivalent of Rails "Raise" in Django
I am new to Django but I have experience in Rails.

In Rails, if you want to check what one of your action/function is doing, you can use the raise parameter.
The execution of the action will stop, and in http://locahost:3000 you can see the output of that function.

Example:

def answer:
    @banana = 2 + 2
    raise
end
```

If I reload localhost, a console opens and if I write @banana I get the result 4.

Is there something similar in Django?

答:
There's pdb. You can check more here. On your code, you can do something like this:

def answer():
    banana = 2 + 2
    import pdb; pdb.set_trace()
    return banana
```

Then on your terminal if you do banana you'll see the result of the sum.

Title: Equivalent of Rails "Raise" in Django

Body:
I am new to Django but I have experience in Rails.

In Rails, if you want to check what one of your action/function is doing, you can use the raise parameter.
The execution of the action will stop, and in http://locahost:3000 you can see the output of that function.

Example:

def answer:
    @banana = 2 + 2
    raise
end

If I reload localhost, a console opens and if I write @banana I get the result 4.

Is there something similar in Django?

Body:
There's pdb. You can check more here. On your code, you can do something like this:

def answer():
    banana = 2 + 2
    import pdb; pdb.set_trace()
    return banana

Then on your terminal if you do banana you'll see the result of the sum.


问:
Codename one set remove Accordion border
I am working on a codename one application. I need to remove the border for Accordion component. (or) Is there anyway to change the Accordion's border color..
Can someone guide me...

The black border shown in the image

答:
To remove(hide) the border of an accordion from the code you can define it's border colour to be the same as the background colour and to be as narrow as possible.</p>

```<code>    Border border = Border.createCompoundBorder(Border.createLineBorder(1, 0xffffff), Border.createLineBorder(1, 0xffffff), Border.createLineBorder(1, 0xffffff), Border.createLineBorder(1, 0xffffff));

    my_accordion = new Accordion(ifont_keyboard_right, ifont_keyboard_down);
    my_accordion.getAllStyles().setBgColor(0xffffff);
    my_accordion.getAllStyles().setBgTransparency(255);
    my_accordion.getAllStyles().setPadding(0, 0, 0, 0);
    my_accordion.getAllStyles().setMargin(0, 0, 0, 0);
    my_accordion.getAllStyles().setBorder(border);
</code>```

Body:
To remove(hide) the border of an accordion from the code you can define it's border colour to be the same as the background colour and to be as narrow as possible.

    Border border = Border.createCompoundBorder(Border.createLineBorder(1, 0xffffff), Border.createLineBorder(1, 0xffffff), Border.createLineBorder(1, 0xffffff), Border.createLineBorder(1, 0xffffff));

    my_accordion = new Accordion(ifont_keyboard_right, ifont_keyboard_down);
    my_accordion.getAllStyles().setBgColor(0xffffff);
    my_accordion.getAllStyles().setBgTransparency(255);
    my_accordion.getAllStyles().setPadding(0, 0, 0, 0);
    my_accordion.getAllStyles().setMargin(0, 0, 0, 0);
    my_accordion.getAllStyles().setBorder(border);


问:
$this->load->model() not working in CodeIgniter
I'm using CodeIgniter 2.1.2 and here's my situation right now. I have a model named math.php in C:\wamp\www\cr8v\application\models. I am trying to load this in my controller from C:\wamp\www\cr8v\application\controllers\site.php yet I am getting this error:

Unable to locate the model you have specified: math_model

Here's the content of math.php:

```<code> <?php
    class Math_model extends CI_Model(){
        public function add(){
            return 1+1;
        }
    }
 ?>
</code>```

And here's the content of my site.php:

```<code><?php
    class Site extends CI_Controller{
        public function index(){
            $this->addstuff();
        }

        public function addstuff(){
            $this->load->model("math_model");
            echo $this->math->add();
        }
    }
?>
</code>```

I followed this in a tutorial in YouTube. Yet, it doesn't give me my desired output. I've tried Googling about it and read other related questions with this, however those information are not enough.

I have read this just a while ago.

Now I have the following error:

```<code>( ! ) Parse error: syntax error, unexpected '(', expecting '{' in C:\wamp\www\cr8v\application\models\math_model.php on line 2
Call Stack
#   Time    Memory  Function    Location
1   0.0036  148768  {main}( )   ..\index.php:0
2   0.0062  185072  require_once( 'C:\wamp\www\cr8v\system\core\CodeIgniter.php' )  ..\index.php:202
3   0.0561  784312  call_user_func_array ( )    ..\CodeIgniter.php:359
4   0.0561  784360  Site->index( )  ..\CodeIgniter.php:359
5   0.0561  784376  Site->addstuff( )   ..\site.php:4
6   0.0561  784504  CI_Loader->model( ) ..\site.php:8
</code>```

答:
File name and model name should be same
try this instead

```<code>class Math_model extends CI_Model {
   // your code
}
</code>```

and the file name
should be Math_model.php

Body:
I'm using CodeIgniter 2.1.2 and here's my situation right now. I have a model named math.php in C:\wamp\www\cr8v\application\models. I am trying to load this in my controller from C:\wamp\www\cr8v\application\controllers\site.php yet I am getting this error:

Unable to locate the model you have specified: math_model

Here's the content of math.php:

 <?php
    class Math_model extends CI_Model(){
        public function add(){
            return 1+1;
        }
    }
 ?>

And here's the content of my site.php:

<?php
    class Site extends CI_Controller{
        public function index(){
            $this->addstuff();
        }

        public function addstuff(){
            $this->load->model("math_model");
            echo $this->math->add();
        }
    }
?>

I followed this in a tutorial in YouTube. Yet, it doesn't give me my desired output. I've tried Googling about it and read other related questions with this, however those information are not enough.

I have read this just a while ago.

Now I have the following error:

( ! ) Parse error: syntax error, unexpected '(', expecting '{' in C:\wamp\www\cr8v\application\models\math_model.php on line 2
Call Stack
#   Time    Memory  Function    Location
1   0.0036  148768  {main}( )   ..\index.php:0
2   0.0062  185072  require_once( 'C:\wamp\www\cr8v\system\core\CodeIgniter.php' )  ..\index.php:202
3   0.0561  784312  call_user_func_array ( )    ..\CodeIgniter.php:359
4   0.0561  784360  Site->index( )  ..\CodeIgniter.php:359
5   0.0561  784376  Site->addstuff( )   ..\site.php:4
6   0.0561  784504  CI_Loader->model( ) ..\site.php:8

Body:
File name and model name should be same
try this instead

class Math_model extends CI_Model {
   // your code
}

and the file name
should be Math_model.php


问:
How do I get the user claims after I have logged in with IdentityServer 4?
I have used this sample to setup IdentityServer4 with angular and WebApi (ASP.NET Core): https://github.com/damienbod/AspNet5IdentityServerAngularImplicitFlow

Everything is working, I can login and use the API and everything, but the problem is that I dont get the user information back after login. I need the subjectId so I can get the specific user. I thought it would be returned with claims or something, but the only thing I see in the cookies is the token.

答:
It's in the this.user object

```<code>private manager = new UserManager(getClientSettings());
  private user: User | null;

  constructor(private http: HttpClient, private configService: ConfigService) {
    super();

    this.manager.getUser().then(user => {
      this.user = user;
      this._authNavStatusSource.next(this.isAuthenticated());
    });
  }
</code>```

The above is from the authentication serivce in angular

Body:
It's in the this.user object

private manager = new UserManager(getClientSettings());
  private user: User | null;

  constructor(private http: HttpClient, private configService: ConfigService) {
    super();

    this.manager.getUser().then(user => {
      this.user = user;
      this._authNavStatusSource.next(this.isAuthenticated());
    });
  }

The above is from the authentication serivce in angular