问:
No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate
Repository class:

```<code> package ru.spb.repository.user;

@Repository
public class AnketUserRepository implements UserRepository {

     @Autowired
     private CrudUserRepository crudRepository;

 }
</code>```

Interface:

```<code>package ru.spb.repository;

public interface UserRepository {
}
</code>```

Service:

```<code>package ru.spb.service;

@Service
public class UserService {

   private final UserRepository repository;

   @Autowired
   public UserService (UserRepository repository){
       this.repository = repository;
   }
}
</code>```

Configs:
in spring-app.xml:

```<code> <context:component-scan base-package="ru.spb.service"/>
</code>```

in spring-db.xml:

```<code> <context:component-scan base-package="ru.spb.repository.user"/>
</code>```

But I catch the following exception:

```<code> NoSuchBeanDefinitionException: No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
</code>```

I tried to add @Repository on UserRepository-interface, but without success.

答:
I moved

```<code> <context:component-scan base-package="ru.spb.repository.user"/>
</code>```

from spring-db.xml  to  spring-app.xml.   And this problem is solved.
However I dont understand the reason of this problem.

Body:
Repository class:

 package ru.spb.repository.user;

@Repository
public class AnketUserRepository implements UserRepository {

     @Autowired
     private CrudUserRepository crudRepository;

 }

Interface:

package ru.spb.repository;

public interface UserRepository {
}

Service:

package ru.spb.service;

@Service
public class UserService {

   private final UserRepository repository;

   @Autowired
   public UserService (UserRepository repository){
       this.repository = repository;
   }
}

Configs:
in spring-app.xml:

 <context:component-scan base-package="ru.spb.service"/>

in spring-db.xml:

 <context:component-scan base-package="ru.spb.repository.user"/>

But I catch the following exception:

 NoSuchBeanDefinitionException: No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

I tried to add @Repository on UserRepository-interface, but without success.

Body:
I moved

 <context:component-scan base-package="ru.spb.repository.user"/>

from spring-db.xml  to  spring-app.xml.   And this problem is solved.
However I dont understand the reason of this problem.


来源: stackexchange

问:
How to properly use ControlFlowGraph from roslyn code analysis in C#
I cannot understand why I am getting an error (using VS2017) for the code in below related to not finding the class ControlFlowGraph which is supposed to be part of the package Microsoft.CodeAnalysis.FlowAnalysis:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FlowAnalysis;

namespace CodeAnalysisApp3
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Attempt to set the version of MSBuild.
            var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
            var instance = visualStudioInstances[0];

            Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");

            // NOTE: Be sure to register an instance with the MSBuildLocator
            //       before calling MSBuildWorkspace.Create()
            //       otherwise, MSBuildWorkspace won't MEF compose.
            MSBuildLocator.RegisterInstance(instance);

            using (var workspace = MSBuildWorkspace.Create())
            {
                // Print message for WorkspaceFailed event to help diagnosing project load failures.
                workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);

                var solutionPath = args[0];
                Console.WriteLine($"Loading solution '{solutionPath}'");

                // Attach progress reporter so we print projects as they are loaded.
                var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
                Console.WriteLine($"Finished loading solution '{solutionPath}'");

                // TODO: Do analysis on the projects in the loaded solution
                CSharpParseOptions options = CSharpParseOptions.Default
                .WithFeatures(new[] { new KeyValuePair<string, string>("flow-analysis", "") });

                var projIds = solution.ProjectIds;

                var project = solution.GetProject(projIds[0]);

                Compilation compilation = await project.GetCompilationAsync();

                if (compilation != null && !string.IsNullOrEmpty(compilation.AssemblyName))
                {
                    var mySyntaxTree = compilation.SyntaxTrees.First();

                    // get syntax nodes for methods
                    var methodNodes = from methodDeclaration in mySyntaxTree.GetRoot().DescendantNodes()
                               .Where(x => x is MethodDeclarationSyntax)
                                      select methodDeclaration;

                    foreach (MethodDeclarationSyntax node in methodNodes)
                    {
                        var model = compilation.GetSemanticModel(node.SyntaxTree);
                        node.Identifier.ToString();
                        if (node.SyntaxTree.Options.Features.Any())
                        {
                            var graph = ControlFlowGraph.Create(node, model); // CFG is here
                        }
                    }
                }
            }
        }

        private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
        {
            public void Report(ProjectLoadProgress loadProgress)
            {
                var projectDisplay = Path.GetFileName(loadProgress.FilePath);
                if (loadProgress.TargetFramework != null)
                {
                    projectDisplay += $" ({loadProgress.TargetFramework})";
                }

                Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
            }
        }
    }
}
</code>```

However, when I compile the above code I am getting the following error message with VS2017:

```<code>1>Program.cs(67,41,67,57): error CS0103: The name 'ControlFlowGraph' does not exist in the current context
1>Done building project "CodeAnalysisApp3.csproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
</code>```

Version used:

```<code>Microsoft (R) Visual C# Compiler version 4.8.3761.0
for C# 5
</code>```

答:
I was able to solve the problem when I used roslyn CodeAnalysis packages with the proper versions:

```<code>CodeAnalysis.CSharp.Workspaces (3.4.0)
CodeAnalysis.FlowAnalysis.Utilities (2.9.6)
CodeAnalysis.Workspaces.MSBuild (3.4.0)
</code>```

The target framework is .NETFramework 4.7.2

A link to a closed issue created for this question on roslyn Github repo is here

ContentLicense: CC BY-SA 4.0

Body:
I cannot understand why I am getting an error (using VS2017) for the code in below related to not finding the class ControlFlowGraph which is supposed to be part of the package Microsoft.CodeAnalysis.FlowAnalysis:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FlowAnalysis;

namespace CodeAnalysisApp3
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Attempt to set the version of MSBuild.
            var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
            var instance = visualStudioInstances[0];

            Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");

            // NOTE: Be sure to register an instance with the MSBuildLocator
            //       before calling MSBuildWorkspace.Create()
            //       otherwise, MSBuildWorkspace won't MEF compose.
            MSBuildLocator.RegisterInstance(instance);

            using (var workspace = MSBuildWorkspace.Create())
            {
                // Print message for WorkspaceFailed event to help diagnosing project load failures.
                workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);

                var solutionPath = args[0];
                Console.WriteLine($"Loading solution '{solutionPath}'");

                // Attach progress reporter so we print projects as they are loaded.
                var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
                Console.WriteLine($"Finished loading solution '{solutionPath}'");

                // TODO: Do analysis on the projects in the loaded solution
                CSharpParseOptions options = CSharpParseOptions.Default
                .WithFeatures(new[] { new KeyValuePair<string, string>("flow-analysis", "") });

                var projIds = solution.ProjectIds;

                var project = solution.GetProject(projIds[0]);

                Compilation compilation = await project.GetCompilationAsync();

                if (compilation != null && !string.IsNullOrEmpty(compilation.AssemblyName))
                {
                    var mySyntaxTree = compilation.SyntaxTrees.First();

                    // get syntax nodes for methods
                    var methodNodes = from methodDeclaration in mySyntaxTree.GetRoot().DescendantNodes()
                               .Where(x => x is MethodDeclarationSyntax)
                                      select methodDeclaration;

                    foreach (MethodDeclarationSyntax node in methodNodes)
                    {
                        var model = compilation.GetSemanticModel(node.SyntaxTree);
                        node.Identifier.ToString();
                        if (node.SyntaxTree.Options.Features.Any())
                        {
                            var graph = ControlFlowGraph.Create(node, model); // CFG is here
                        }
                    }
                }
            }
        }

        private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
        {
            public void Report(ProjectLoadProgress loadProgress)
            {
                var projectDisplay = Path.GetFileName(loadProgress.FilePath);
                if (loadProgress.TargetFramework != null)
                {
                    projectDisplay += $" ({loadProgress.TargetFramework})";
                }

                Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
            }
        }
    }
}

However, when I compile the above code I am getting the following error message with VS2017:

1>Program.cs(67,41,67,57): error CS0103: The name 'ControlFlowGraph' does not exist in the current context
1>Done building project "CodeAnalysisApp3.csproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Version used:

Microsoft (R) Visual C# Compiler version 4.8.3761.0
for C# 5

Body:
I was able to solve the problem when I used roslyn CodeAnalysis packages with the proper versions:

CodeAnalysis.CSharp.Workspaces (3.4.0)
CodeAnalysis.FlowAnalysis.Utilities (2.9.6)
CodeAnalysis.Workspaces.MSBuild (3.4.0)

The target framework is .NETFramework 4.7.2

A link to a closed issue created for this question on roslyn Github repo is here


问:
Convert Month Number to Month Name Function in SQL
I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.</p>

答:
Try this: SELECT MONTHNAME(concat('1970-',[Month int val],'-01'))

For example- SELECT MONTHNAME(concat('1970-',4,'-01'))

The answer is - April

OwnerDisplayName: Saif Khan

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Saif Khan


问:
is it possible to make equalizer android
Doing a little search i realized that to make an equalizer. I need to use C or C++ That would also mean that i have to use the NDK to integrate that with my Java code. The question is, how can i make the C and Java code interact with each other. I don't even know C but i really want that equalizer in my music player. Do you guys know of any good C book which is the best for beginners?

Thanks.

答: There should be no need to use the NDK. There already is an Equalizer-Class in Android, which is also used by the standard Android Music Player. Also, here is an answer on how to make the Sliders</p>


问:
Get smallest available key (>= 1) in a HashMap
I am using a Map in which I save all tracks that the user registers. Every new track should be assigned a new ID which starts at 1. However, if tracks 1, 2, 3, 4 exist and the user deletes track with ID 1 the next added track gets the smallest available ID >=1 which in this case would be 1.

How is it possible to do this efficiently? Or is there a better datatype available?

```<code>private Map<Integer, Track> tracks;

public Register() {
    this.trains = new HashMap<>();
}

public void addTrack(Track track) {
    int id = <get Smallest Value Available >= 1>;
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + id + " doesn't exist.");
    }
}
</code>```

答:
I would do it with a loop and see if the which value is not yet included in the map    </p>

```<code>public Integer getId(Map<Integer, Track> tracks) {
    // Set on max-value
    Integer id = Collections.max(tracks.keySet()) + 1;

    for (int i = 1; i <= tracks.keySet().size(); i++) {
        if (!tracks.keySet().contains(i)) {
            // lower value available
            id = i;
            break;
        }
    }

    return id;
}
</code>```

Body:
I am using a Map in which I save all tracks that the user registers. Every new track should be assigned a new ID which starts at 1. However, if tracks 1, 2, 3, 4 exist and the user deletes track with ID 1 the next added track gets the smallest available ID >=1 which in this case would be 1.

How is it possible to do this efficiently? Or is there a better datatype available?

private Map<Integer, Track> tracks;

public Register() {
    this.trains = new HashMap<>();
}

public void addTrack(Track track) {
    int id = <get Smallest Value Available >= 1>;
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + id + " doesn't exist.");
    }
}

Body:
I would do it with a loop and see if the which value is not yet included in the map

public Integer getId(Map<Integer, Track> tracks) {
    // Set on max-value
    Integer id = Collections.max(tracks.keySet()) + 1;

    for (int i = 1; i <= tracks.keySet().size(); i++) {
        if (!tracks.keySet().contains(i)) {
            // lower value available
            id = i;
            break;
        }
    }

    return id;
}


问:
Javascript changing function trouble
The code below is how it was originally

```<code>   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }
</code>```

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

```<code>function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`
</code>```

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???

答:
emailname is an array of string "testing testing2 testing3".

You don't need to again split.

Also, if you are using back-ticks (`) then you access variables/constant using ${variableName}, and NOT BY $(variableName)

function getRandomEmail() {
    var emailname = "testing testing2 testing3".split(" ");
    const randomElement = emailname[Math.floor(Math.random() * emailname.length)];
    return `User${randomElement}@example.com`;
}

console.log(getRandomEmail());```
</div>
</div>
</p>

<h1>UPDATE</h1>

<p><br></p>

<ol>
<li><p>First, generate a random index from the array.</p>

<p><code>const randomElementIndex = Math.floor(Math.random() * emailname.length);</code></p></li>
<li><p>Then find the element corresponds to that index.</p>

<p><code>const randomElement = emailname[randomElementIndex];</code>;</p></li>
<li><p>Now, you need to remove that element for the array.</p>

<p><code>emailname.splice(randomElementIndex , 1);</code>
// This will return you an array without the element you have used.</p></li>
</ol>

<p>So now your <code>getRandomEmail()</code> can be as follows.
<br><br></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getRandomEmail(emailName) {
        //Generating random element
        const randomElementIndex = Math.floor(Math.random() * emailName.length);

        // Getting random name based on random element.
        const randomElement = emailName[randomElementIndex];

        // Poping out that random element from an array
        emailName.splice(randomElementIndex , 1);
        return `User${randomElement}@example.com`;
    }

    var emailName = "testing testing2 testing3".split(" ");
    console.log(getRandomEmail(emailName));</code>```

Suppose you are having NO Database from you are getting this name strings.

In that case, you can save the string "testing testing2 testing3" in localStorage to store the string on the user's device and use it whenever you want to generate a new email.

So now the procedure will be

1) Save the string in the user's device.

  window.localStorage.setItem("names-list-string", "testing testing2 testing3");

2) Now fetch the string from localStorage and split in to array.

   var emailName = window.localStorage.getItem("names-list-string").split(" ");

3) Pass the emailName array to getRandomEmail()

   getRandomEmail(emailName);

4) We have to modify the getRandomEmail() a little.

   Now when we splice() and an array we convert back it to string and update the localStorage.

   emailName.splice(randomElementIndex , 1);

   let emailString = emailName.join(" ");

   window.localStorage.setItem("names-list-string", emailString);

Title: Javascript changing function trouble

Body:
The code below is how it was originally

   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???

Body:
emailname is an array of string "testing testing2 testing3".

You don't need to again split.

Also, if you are using back-ticks (`) then you access variables/constant using ${variableName}, and NOT BY $(variableName)

function getRandomEmail() {
    var emailname = "testing testing2 testing3".split(" ");
    const randomElement = emailname[Math.floor(Math.random() * emailname.length)];
    return `User${randomElement}@example.com`;
}

console.log(getRandomEmail());

UPDATE

First, generate a random index from the array.

const randomElementIndex = Math.floor(Math.random() * emailname.length);

Then find the element corresponds to that index.

const randomElement = emailname[randomElementIndex];;

Now, you need to remove that element for the array.

emailname.splice(randomElementIndex , 1);
// This will return you an array without the element you have used.

So now your getRandomEmail() can be as follows.

function getRandomEmail(emailName) {
        //Generating random element
        const randomElementIndex = Math.floor(Math.random() * emailName.length);

        // Getting random name based on random element.
        const randomElement = emailName[randomElementIndex];

        // Poping out that random element from an array
        emailName.splice(randomElementIndex , 1);
        return `User${randomElement}@example.com`;
    }

    var emailName = "testing testing2 testing3".split(" ");
    console.log(getRandomEmail(emailName));

Suppose you are having NO Database from you are getting this name strings.

In that case, you can save the string "testing testing2 testing3" in localStorage to store the string on the user's device and use it whenever you want to generate a new email.

So now the procedure will be

1) Save the string in the user's device.

  window.localStorage.setItem("names-list-string", "testing testing2 testing3");

2) Now fetch the string from localStorage and split in to array.

   var emailName = window.localStorage.getItem("names-list-string").split(" ");

3) Pass the emailName array to getRandomEmail()

   getRandomEmail(emailName);

4) We have to modify the getRandomEmail() a little.

   Now when we splice() and an array we convert back it to string and update the localStorage.

   emailName.splice(randomElementIndex , 1);

   let emailString = emailName.join(" ");

   window.localStorage.setItem("names-list-string", emailString);


问:
CSS counters doesn't work in subitems inside of div
I'm trying to use the CSS counter to create Chapter numbers.
As you can see in the example below, it's working properly if I deal with classes inside a container, but doesn't work when I try to use it in subitems inside div. Any idea how to correct this behavior ? (I need to use this kind of structure)

.itemsContainer {
  counter-reset: section;
}

.t1 {
  counter-reset: subsection;
}

.t1:before {
  counter-increment: section;
  content: counter(section) ". ";
}

.t2:before {
  counter-increment: subsection;
  content: counter(section) "."counter(subsection) " ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Direct access to class</h3>
<div class="itemsContainer">
  <p class="t1"></p>
  <p class="t2"></p>
  <p class="t2"></p>
</div>

<h3>Inside div</h3>
<div class="itemsContainer">
  <div class="item">
    <p class="t1"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
</div></code>```

答:
Error here come from the rule:

.itemsContainer {
  counter-reset: section;
}
```

<p>So each time that you have an <code>.itemsContainer</code> element the counter <code>section</code> is going to be reset.</p>

<p>To avoid this just say that only the <strong>first</strong> <code>.itemsContainer</code> element reset the counter:</p>

<pre class="lang-css prettyprint-override"><code>.itemsContainer:nth-of-type(1) {
  counter-reset: section;
}
</code>```

For the "Inside div" part you will need to increment the subsection using .item and not .item .t2. Don't forget that the first element don't have to increment the counter. In css you can use the :not() property for that:

.item:not(:first-child) {
  counter-increment: subsection;
}
```

<p>Please check the demo:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.itemsContainer:nth-of-type(1) {
  counter-reset: section;
}

.itemsContainer .t1 {
  counter-reset: subsection;
}

.t1::before {
  counter-increment: section;
  content: counter(section) ". ";
}

.item:not(:first-child) {
  counter-increment: subsection;
}

.itemsContainer>.t2::before {
  counter-increment: subsection;
  content: counter(section) "."counter(subsection) " ";
}

.itemsContainer>.item>.t2::before {
  content: counter(section) "."counter(subsection) " ";
}</code>```

Direct access to class

Inside div

```

For further details just check the W3C documentation: https://www.w3schools.com/CSS/css_counters.asp

Body:
I'm trying to use the CSS counter to create Chapter numbers.
As you can see in the example below, it's working properly if I deal with classes inside a container, but doesn't work when I try to use it in subitems inside div. Any idea how to correct this behavior ? (I need to use this kind of structure)

.itemsContainer {
  counter-reset: section;
}

.t1 {
  counter-reset: subsection;
}

.t1:before {
  counter-increment: section;
  content: counter(section) ". ";
}

.t2:before {
  counter-increment: subsection;
  content: counter(section) "."counter(subsection) " ";
}

Direct access to class

Inside div

Body:
Error here come from the rule:

.itemsContainer {
  counter-reset: section;
}

So each time that you have an .itemsContainer element the counter section is going to be reset.

To avoid this just say that only the first .itemsContainer element reset the counter:

.itemsContainer:nth-of-type(1) {
  counter-reset: section;
}

For the "Inside div" part you will need to increment the subsection using .item and not .item .t2. Don't forget that the first element don't have to increment the counter. In css you can use the :not() property for that:

.item:not(:first-child) {
  counter-increment: subsection;
}

Please check the demo:

.itemsContainer:nth-of-type(1) {
  counter-reset: section;
}

.itemsContainer .t1 {
  counter-reset: subsection;
}

.t1::before {
  counter-increment: section;
  content: counter(section) ". ";
}

.item:not(:first-child) {
  counter-increment: subsection;
}

.itemsContainer>.t2::before {
  counter-increment: subsection;
  content: counter(section) "."counter(subsection) " ";
}

.itemsContainer>.item>.t2::before {
  content: counter(section) "."counter(subsection) " ";
}

<h3>Direct access to class</h3>
<div class="itemsContainer">
  <p class="t1"></p>
  <p class="t2"></p>
  <p class="t2"></p>
</div>

<h3>Inside div</h3>
<div class="itemsContainer">
  <div class="item">
    <p class="t1"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
</div>

For further details just check the W3C documentation: https://www.w3schools.com/CSS/css_counters.asp


问:
Camunda : How to configure external Postgres database?
I use spring boot starter to run camunda. I can run with h2 database. But when i try to connect to postgres i havethe following error :

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
    at fr.casden.eficas.workflow.Application.main(Application.java:10)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1214)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1245)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1862)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1799)
    ... 16 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
    ... 33 common frames omitted
</code>```

Here are my pom.xml:

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

  <modelVersion>4.0.0</modelVersion>

  <properties>
    <java.version>8</java.version>
  </properties>

  <groupId>fr.my.work</groupId>
  <artifactId>my-workflow</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.camunda.bpm.springboot</groupId>
      <artifactId>camunda-bpm-spring-boot-starter-rest</artifactId>
      <version>3.4.1</version>
    </dependency>
    <!-- Driver JDBC Postgresql-->
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
        <version>42.2.10</version>
    </dependency>
    <dependency>
      <groupId>org.camunda.bpm.springboot</groupId>
      <artifactId>camunda-bpm-spring-boot-starter-webapp</artifactId>
      <version>3.4.1</version>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.4.200</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
      <version>2.2.1.RELEASE</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

application properties :

```<code>camunda.bpm.admin-user.id=demo
camunda.bpm.admin-user.password=demo
camunda.bpm.database.type=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/workflow
spring.datasource.username=user
spring.datasource.password=workflow
spring.datasource.driver-class-name=org.postgresql.Driver
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driverClassName=org.postgresql.Driver
</code>```

Spring Boot Application class

```<code>@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }

}
</code>```

What am i missing please ?

答:
Try to remove the version of postgres in your pom.xml and instead give <scope>runtime</scope>

Try to give this in application.yaml:

```<code>  # Database
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/postgres
    username: postgres
    password: postgres
  # JPA properties
  jpa:
    hibernate:
      ddl-auto: none
    show-sql: true
    database: postgresql
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    open-in-view: false
    generate-ddl: false
</code>```

Body:
I use spring boot starter to run camunda. I can run with h2 database. But when i try to connect to postgres i havethe following error :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
    at fr.casden.eficas.workflow.Application.main(Application.java:10)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1214)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1245)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1862)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1799)
    ... 16 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
    ... 33 common frames omitted

Here are my pom.xml:

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

  <modelVersion>4.0.0</modelVersion>

  <properties>
    <java.version>8</java.version>
  </properties>

  <groupId>fr.my.work</groupId>
  <artifactId>my-workflow</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.camunda.bpm.springboot</groupId>
      <artifactId>camunda-bpm-spring-boot-starter-rest</artifactId>
      <version>3.4.1</version>
    </dependency>

    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
        <version>42.2.10</version>
    </dependency>
    <dependency>
      <groupId>org.camunda.bpm.springboot</groupId>
      <artifactId>camunda-bpm-spring-boot-starter-webapp</artifactId>
      <version>3.4.1</version>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.4.200</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
      <version>2.2.1.RELEASE</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

application properties :

camunda.bpm.admin-user.id=demo
camunda.bpm.admin-user.password=demo
camunda.bpm.database.type=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/workflow
spring.datasource.username=user
spring.datasource.password=workflow
spring.datasource.driver-class-name=org.postgresql.Driver
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driverClassName=org.postgresql.Driver

Spring Boot Application class

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }

}

What am i missing please ?

Body:
Try to remove the version of postgres in your pom.xml and instead give <scope>runtime</scope>

Try to give this in application.yaml:

  # Database
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/postgres
    username: postgres
    password: postgres
  # JPA properties
  jpa:
    hibernate:
      ddl-auto: none
    show-sql: true
    database: postgresql
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    open-in-view: false
    generate-ddl: false


问:
Make local requirements.txt file available to microk8s stable/airflow
According to the stable/airflow docs you can:

mount a file to /requirements.txt to get additional Python modules for your DAGs to be installed on container start. Use the extraConfigMapMounts configuration option for this.

But the README is a bit thin on documentation for this option:

```<code>| airflow.extraConfigmapMounts  | Additional configMap volume mounts on the airflow pods. | [] |
</code>```

Can anyone give an example of how I can link a requirements.txt file stored locally to my (local) kubernetes cluster?

答:
The values.yaml file in the root of the stable/airflow repo has an example of how to do this:

```<code>airflow:
  extraConfigmapMounts: []
  # - name: extra-metadata
  #   mountPath: /opt/metadata
  #   configMap: airflow-metadata
  #   readOnly: true
  #
  # Example of configmap mount with subPath
  # - name: extra-metadata
  #   mountPath: /opt/metadata/file.yaml
  #   configMap: airflow-metadata
  #   readOnly: true
  #   subPath: file.yaml
</code>```

Body:
According to the stable/airflow docs you can:

mount a file to /requirements.txt to get additional Python modules for your DAGs to be installed on container start. Use the extraConfigMapMounts configuration option for this.

But the README is a bit thin on documentation for this option:

| airflow.extraConfigmapMounts  | Additional configMap volume mounts on the airflow pods. | [] |

Can anyone give an example of how I can link a requirements.txt file stored locally to my (local) kubernetes cluster?

Body:
The values.yaml file in the root of the stable/airflow repo has an example of how to do this:

airflow:
  extraConfigmapMounts: []
  # - name: extra-metadata
  #   mountPath: /opt/metadata
  #   configMap: airflow-metadata
  #   readOnly: true
  #
  # Example of configmap mount with subPath
  # - name: extra-metadata
  #   mountPath: /opt/metadata/file.yaml
  #   configMap: airflow-metadata
  #   readOnly: true
  #   subPath: file.yaml


问:
require is not defined? Node.js
Just started working with Node.js. In my app/js file, I am doing something like this:

app.js

```<code>var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');

console.log('running server!');
</code>```

When I'm in my terminal and run node app.js, the console spits out 'running server!', but in my browser I get, Uncaught ReferenceError: require is not defined.

Can someone explain to me why in the terminal, it works correctly but in the browser, it doesn't?

I am using the node's http-server to serve my page.

答:
This can now also happen in Node.js as of version 14.

It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.

To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.

Title: require is not defined? Node.js

Body:
Just started working with Node.js. In my app/js file, I am doing something like this:

app.js

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');

console.log('running server!');

When I'm in my terminal and run node app.js, the console spits out 'running server!', but in my browser I get, Uncaught ReferenceError: require is not defined.

Can someone explain to me why in the terminal, it works correctly but in the browser, it doesn't?

I am using the node's http-server to serve my page.


问:
Regular Expression for Code
I am having a hard time finding a regular expression that can match these Strings:

```<code>@OSMHO:6:75
@4F0SO:5:56
@40KIR:5:15
@VDXBC:4:13
@WYRRA:6:59
@A4AUN:1118:803
</code>```

As you guys can see these strings start with an '@' followed by 5 alphanumeric characters, then a ':', then a number, then another ':', then another number.
Thanks so much for your help.

答:
To match a @ at the beginning of a pattern, use ^ (beginning of line) followed by @. So, your pattern begins with^@.

Alphanumeric means any letter from a-z, A-Z and 0-9. When you want to represent "one of the following characters" in a regular expression the syntax is to enclose the set of characters in []. In this case it would look like [a-zA-Z0-9]. To say you want five of them you can use {5} after the set of characters. Your expression now looks like ^@[a-zA-Z0-9]{5}

A colon is just a colon :. A multi-digit number means you want one or more digits. A digit is represented as [0-9] (ie: one of the numbers between 0 and 9). "one or more" is represented by +. So, to add a colon, one-or-more digits, a colon and one-or-more digits you would add :[0-9]+:[0-9]+. Your pattern now looks like this: ^@[a-zA-Z0-9]{5}:[0-9]+:[0-9]+.

You can also use the shorthand \d to mean "a digit", so you could also write^@[a-zA-Z0-9]{5}:\d+:\d+, though that can be tricky because you might need extra backslashes depending on what sort of quotes you use to define that expression. Sometimes it's easiest to avoid shortcuts that use backslashes to make the pattern easier to understand, especially when you are first learning how to use regular expressions.

If you want to capture each part of that match in a group, you can use parenthesis. For example, you could do ^@([a-zA-Z0-9]{5}):([0-9]+):([0-9]+) which will put the value between the @ and first : in one group, the value between the two colons in a second group, and the value after the last colon in a third group. If you only care whether you have a match or not rather than wanting each individual piece of the match  you can leave the parenthesis off.

If you build up a pattern in the way I just did -- tackling one piece at a time -- regular expressions can be very easy.

Title: Regular Expression for Code

Body:
I am having a hard time finding a regular expression that can match these Strings:

@OSMHO:6:75
@4F0SO:5:56
@40KIR:5:15
@VDXBC:4:13
@WYRRA:6:59
@A4AUN:1118:803

As you guys can see these strings start with an '@' followed by 5 alphanumeric characters, then a ':', then a number, then another ':', then another number.
Thanks so much for your help.


问:
Replace value across multiple lines in bash
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

```<code>    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

```<code>pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt
</code>```

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

```<code>./run.sh r.start 0x284569
</code>```

should be

```<code>    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

Here's my best shot for the second part

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

答:
This might work for you (GNU sed):

```<code>sed -E '/^    \/start r\.start /{:a;N;/^    \/end$/M!ba;s/^(      GAIN |        CODE "r\.start" )0x\S+/\10x284569/Mg}' file
</code>```

Gather up lines between /start and /end and using pattern matching replace the desired values.

The solution may be placed in a function:

```<code>f () { sed -E '/^    \/start '"$1"' /{:a;N;/^    \/end$/M!ba;s/^(      GAIN |        CODE "'"$1"'" )0x\S+/\1'"$2"'/Mg}' "$3"; }
</code>```

And called:

```<code>f r\\.start 0x284569 file
</code>```

Body:
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

./run.sh r.start 0x284569

should be

    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

Here's my best shot for the second part

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

Body:
This might work for you (GNU sed):

sed -E '/^    \/start r\.start /{:a;N;/^    \/end$/M!ba;s/^(      GAIN |        CODE "r\.start" )0x\S+/\10x284569/Mg}' file

Gather up lines between /start and /end and using pattern matching replace the desired values.

The solution may be placed in a function:

f () { sed -E '/^    \/start '"$1"' /{:a;N;/^    \/end$/M!ba;s/^(      GAIN |        CODE "'"$1"'" )0x\S+/\1'"$2"'/Mg}' "$3"; }

And called:

f r\\.start 0x284569 file


问:
Sharing unpublished Gmail add-on with other people
guys!

I developed a gmail add-on and I am still testing it. The plan is to publish the add-on later.
What is the best way to share this add-on with my beta-testers?

Thank you!

答:
Share your script with your beta-testers and tell them to:

Install the unpublished Add-On

Here's how fast it is:

In the pop up, they should create a new deployment and finally they should install the add-on:


问:
Save ID in variable and add style to it
I want to highlight randomly a word which is inside a
 tag with the id=JShighlight. It should blink one time and then another randomly chosen word should blink.** I can't add the css style needed to the ID.

The words are nested in a span with an unique id like id="one" oder id="two".
Like:

```<code><p id="JShighlight"> <span id="one">Lorem </span><span id="two">Ipsum </span><span id="three">Dolores</span></p>
</code>```

To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray

```<code>let childNodeArray = document.getElementById('JShighlight').children;
</code>```

Then I randomly chose an index:

```<code>  let i = Math.floor(Math.random() * childNodeArray.length);
</code>```

The variable name saves the randomly chosen ID.

```<code>let name = childNodeArray[i].id;
</code>```

To this randomly chosen word /Id I want to add a certain style so that this word blinks one time.
I tried:

```<code>name.classList.add("blinking");
</code>```

(.blinking is the css-class:

```<code>.blinking {
    animation: blinkingText 0.6s 1;
    /* animation-iteration-count: 1; */
}
</code>```

)

But it does not work.
What "works" is:

```<code>document.getElementById(name).style.color = "red";
</code>```

Why can I pass a variable as an argument in the latter case and not in the former case?
How can I append a css class to an variable ID?

答:
Instead of

let name = childNodeArray[i].id;

try

let name = childNodeArray[i];

Hope your issue will be resolved;

Title: Save ID in variable and add style to it

Body:
I want to highlight randomly a word which is inside a
 tag with the id=JShighlight. It should blink one time and then another randomly chosen word should blink.** I can't add the css style needed to the ID.

The words are nested in a span with an unique id like id="one" oder id="two".
Like:

 Lorem Ipsum Dolores

To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray

let childNodeArray = document.getElementById('JShighlight').children;

Then I randomly chose an index:

  let i = Math.floor(Math.random() * childNodeArray.length);

The variable name saves the randomly chosen ID.

let name = childNodeArray[i].id;

To this randomly chosen word /Id I want to add a certain style so that this word blinks one time.
I tried:

name.classList.add("blinking");

(.blinking is the css-class:

.blinking {
    animation: blinkingText 0.6s 1;
    /* animation-iteration-count: 1; */
}

)

But it does not work.
What "works" is:

document.getElementById(name).style.color = "red";

Why can I pass a variable as an argument in the latter case and not in the former case?
How can I append a css class to an variable ID?


问:
Where does 'Hello world' come from?
'hello, world' is usually the first example for any programming language. I've always wondered where this sentence came from and where was it first used.

I've once been told that it was the first sentence ever to be displayed on a computer screen, but I've not been able to find any reference to this.

So my question is:

Where does the practice to use 'hello, world' as the first example for computer languages originate from?

Where was it first used?

Update

Although the answers are quite interesting, I should have noted that I had read the Wikipedia article. It does answer the question about the first use in literature, but does not answer when 'hello world' was first used.

So I think that it is safe to conclude that it was not the first sentence ever to be displayed on a computer screen and that there is no record about when it was first used?

答:
From http://en.wikipedia.org/wiki/Hello_world_program:

The first known instance of the usage
  of the words "hello" and "world"
  together in computer literature
  occurred earlier, in Kernighan's 1972
  Tutorial Introduction to the Language
  B[1], with the following code:

```<code>main( ) {
  extrn a, b, c;
  putchar(a); putchar(b); putchar(c); putchar('!*n');
}
a 'hell';
b 'o, w';
c 'orld';
</code>```

OwnerDisplayName: Jacco

Title: Where does 'Hello world' come from?

LastEditorDisplayName: Jacco

Body:
From http://en.wikipedia.org/wiki/Hello_world_program:

The first known instance of the usage
  of the words "hello" and "world"
  together in computer literature
  occurred earlier, in Kernighan's 1972
  Tutorial Introduction to the Language
  B[1], with the following code:

main( ) {
  extrn a, b, c;
  putchar(a); putchar(b); putchar(c); putchar('!*n');
}
a 'hell';
b 'o, w';
c 'orld';

OwnerDisplayName: tehvan

ContentLicense: CC BY-SA 2.5


问:
How do I test that Asp.Net MVC Views are rendered without exceptions?
I have come up with a small issue in my application.

I changed the namespace of my main application to be from MyApp.Models to MyApp.ViewModels so that the namespaces were less confusing overall (since that namespace only has view models and no business models).  I changed all the references I could find, including in my views, and I re-ran all my unit tests and went through the application, and all seemed fine.

A few days later I got a report that the registration page had an error when it was brought up.  After looking it turns out I forgot to fix the namespace on the registration page, and thus it was failing to compile the view.

This worries me.  The whole point of unit testing, and one of the biggest lures of Asp.Net MVC, is to be able to have confidence in your application by having everything tested individually automatically so that you know immediately when your modification breaks parts of the system.  Views right now seem like a major hole in this.

To be clear, I am aware you are able to turn on pre-compiling a views.  However, I do not like this option as it's not a good idea to have this on all the time (as it makes compiling a new build very, very slow), and having a separate configuration scheme for this means it's up to the user to remember to attempt to compile with that configuration scheme to check for view compile errors.

This also completely bypasses checking for runtime errors that may occur.  For example, lets say you change the viewmodel that a strongly-typed view is expecting.  You would then update the unit test to make sure that the Controller.Action() is returning a view result with the correct view model type, but that does nothing to make sure that the actual view was updated correctly for the new view, and yet this scenario will cause a run-time exception.  This is an easy scenario to occur, especially since if the differences in the two view models are only seen in partials used within the view.

Other examples of code that can cause runtime exceptions in views are incorrect loops (possibly caused by changes in a view model), code that checks a user's role (so buttons are only shown for users with credentials), incorrect casts (e.g. for converting a collection into a select list), incorrect code to sort a collection (how a collection is sorted in the display can construed as a view concern, not a controller or view model concern), if strings used for locations of files don't work correctly (T4MVC doesn't integrate well with some things, such as Telerik's script registration system) etc...

The way I see it, there are many things that can cause an exception to occur in the process of rendering a view, and I can't seem to find any way to create unit or integration tests to determine when these occur.  I would feel more comfortable if I did not have to check every page to make sure I missed a compile time or runtime error for something that a standard unit test should be able to catch.

What options do I have to do this?

I would prefer to stay away from WaTiN and other GUI testing tools, as for this I am not interested in the actual display of the page, I only want to know if the view renders or if an exception occurs and do not need the overhead of Watin running an IE instance for each test (I also think this will cause issues if I go with continuous integration at a later point).

答:
If you don't want to use WaTIN and IE, how about firing up your web site in IIS Express, and then using HttpWebRequest over each of your Views' urls to check the result is 200 OK. This is a complete integration test.

Otherwise, you have to get the ViewResult from your controller, and call the ExecuteResult method passing in a ControllerContext containing a stubbed HttpContextBase. This gives more of a true unit test, and would be faster, but you've got a lot of mocking and stubbing to do before it will work.


问:
How to pass data with history hook to react functional components
I am trying to implement a redirection after a fetch query is executed.
I want to be able to pass data to the next component (page) with React History.

It would go like this:

```<code> const history = useHistory({});
 /* ... */
 history.push({
       pathname: '/page',
       state: { data: data }
 })
</code>```

And then to retrieve the state in the receiver, assuming receiver is a class based component:

```<code>this.state.data
</code>```

Is it even possible to achieve something like this with functional components? What is the cleanest solution to this problem?

Thank you for your help

答:
you can not pass directly state with history but you can easily pass the values which you want to pass with the history like...

this.props.history.push('export', { value: data.dealer_userid, label: data.user_displayname, nicename: data.user_nicename, invid: data.dealer_invid, date: date });

Body:
I am trying to implement a redirection after a fetch query is executed.
I want to be able to pass data to the next component (page) with React History.

It would go like this:

 const history = useHistory({});
 /* ... */
 history.push({
       pathname: '/page',
       state: { data: data }
 })

And then to retrieve the state in the receiver, assuming receiver is a class based component:

this.state.data

Is it even possible to achieve something like this with functional components? What is the cleanest solution to this problem?

Thank you for your help


问:
MySQL: get total number of employees in each department
I am new to MySQL and Have following question.

Let's say I have two following tables

Departments

```<code>DepartmentId    Name
</code>```

Employees

```<code>ID    DepartmentId   Name
</code>```

I have written following query which is returning half of my expected result

```<code>select
  d.name as departmentName,
  count(*) as totalEmployees

from
  employees e

join department d
on d.departmentId = e.departmentId

group by
  d.departmentId,
  d.name
</code>```

which returns the result with number of employees in each department. but I want to have following two cases in my query.

```<code>1. Some departments don't have employees
2. Some departments have the same name
</code>```

I have tried my query with NOT EXISTS and NOT IN but could not get expected result. Could anyone please help me here to cover above two cases in MySQL query.

答:
I think you just need left join:

```<code>select d.departmentId, d.name as departmentName,
       count(e.departmentid) as totalEmployees
from department d left join
     employees e
     on d.departmentId = e.departmentId
group by d.departmentId, d.name;
</code>```

Including the department id distinguishes among departments with the same name.

If you want all departments with the same name to be combined, then remove departmentid from the select and group by:

```<code>select d.name as departmentName,
       count(e.departmentid) as totalEmployees
from department d left join
     employees e
     on d.departmentId = e.departmentId
group by d.name;
</code>```

Body:
I am new to MySQL and Have following question.

Let's say I have two following tables

Departments

DepartmentId    Name

Employees

ID    DepartmentId   Name

I have written following query which is returning half of my expected result

select
  d.name as departmentName,
  count(*) as totalEmployees

from
  employees e

join department d
on d.departmentId = e.departmentId

group by
  d.departmentId,
  d.name

which returns the result with number of employees in each department. but I want to have following two cases in my query.

1. Some departments don't have employees
2. Some departments have the same name

I have tried my query with NOT EXISTS and NOT IN but could not get expected result. Could anyone please help me here to cover above two cases in MySQL query.

Body:
I think you just need left join:

select d.departmentId, d.name as departmentName,
       count(e.departmentid) as totalEmployees
from department d left join
     employees e
     on d.departmentId = e.departmentId
group by d.departmentId, d.name;

Including the department id distinguishes among departments with the same name.

If you want all departments with the same name to be combined, then remove departmentid from the select and group by:

select d.name as departmentName,
       count(e.departmentid) as totalEmployees
from department d left join
     employees e
     on d.departmentId = e.departmentId
group by d.name;


问:
Count characters of dynamically created textareas with different id and name attr
I am having two textareas one under another

```<code><div class="form-group">
<span id="textarea_feedback1"></span>
<span> Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
<hr>
<span id="textarea_feedback2"></span>
<span> Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>
</code>```

Both textareas are created dynamically and they have different id and name attr. At some point, they might be 2, 3, 4... and so on.
What I am trying to do is to create a char counter for each textarea that also applies dynamically.

It would have had been easy if the number of the textareas was fixed (i.e, always 2).

But I am having trouble finding a way to apply one and the same JQuery script to textareas with a different name and id attribute.

I was thinking about adding a unique attribute like areaid="" to each textarea, so I can somehow modify dynamically the script.

This is the script I have

```<code>$(document).ready(function() {
var text_max = 400;

$('#textarea_feedback1').html('<span>'+text_max + '</span>');

$('#answer1').on('input click keyup', function() {
    var text_length = $('#answer1').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback1').html('<span>'+text_remaining + '</span>');
});

});
</code>```

Basically, what I think that it should happen is, that based on the areaid attr to also change the value of the span id="textarea_feedback" and textatea id="answer" to match the areaid value, so somehow the script would work separately to as many textareas I have.

Here is jsfiddle

答:
Wrap that span and the textarea in an element like div so you can access both easily.

;window.onload = function(){
  var text_max = 400;

  for(var tL=document.querySelectorAll('.dummy textarea'), i=0, j=tL.length; i<j; i++){
    $(tL[i]).on('input click keyup', function(){
        var text_length = this.value.length;
        var text_remaining = text_max - text_length;

        this.parentNode.querySelector('span').textContent = text_remaining
    })
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">

<div class = 'dummy'>
<span id="textarea_feedback1"></span>
<span> Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
</div>

<hr>

<div class = 'dummy'>
<span id="textarea_feedback2"></span>
<span> Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>
</div></code>```

Body:
I am having two textareas one under another

 Characters left

<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>

 Characters left

<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>

Both textareas are created dynamically and they have different id and name attr. At some point, they might be 2, 3, 4... and so on.
What I am trying to do is to create a char counter for each textarea that also applies dynamically.

It would have had been easy if the number of the textareas was fixed (i.e, always 2).

But I am having trouble finding a way to apply one and the same JQuery script to textareas with a different name and id attribute.

I was thinking about adding a unique attribute like areaid="" to each textarea, so I can somehow modify dynamically the script.

This is the script I have

$(document).ready(function() {
var text_max = 400;

$('#textarea_feedback1').html(''+text_max + '');

$('#answer1').on('input click keyup', function() {
    var text_length = $('#answer1').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback1').html(''+text_remaining + '');
});

});

Basically, what I think that it should happen is, that based on the areaid attr to also change the value of the span id="textarea_feedback" and textatea id="answer" to match the areaid value, so somehow the script would work separately to as many textareas I have.

Here is jsfiddle

Body:
Wrap that span and the textarea in an element like div so you can access both easily.

;window.onload = function(){
  var text_max = 400;

  for(var tL=document.querySelectorAll('.dummy textarea'), i=0, j=tL.length; i<j; i++){
    $(tL[i]).on('input click keyup', function(){
        var text_length = this.value.length;
        var text_remaining = text_max - text_length;

        this.parentNode.querySelector('span').textContent = text_remaining
    })
  }
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">

<div class = 'dummy'>
<span id="textarea_feedback1"></span>
<span> Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
</div>

<hr>

<div class = 'dummy'>
<span id="textarea_feedback2"></span>
<span> Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>
</div>


问:
How to parse XML with several Attributes and an options list
I have an XML file that looks something similar to this:

```<code><root>
    <data label="product data" min="0" max="10">
        <option>
            <id>1</id>
            <name>Name1</name>
        </option>
        <option>
            <id>2</id>
            <name>Name2</name>
        </option>
        <option>
            <id>3</id>
            <name>Name3</name>
        </option>
    </data>
</root>
</code>```

I need to retreive both data attributes and the option list.

I tried this:

```<code>[XmlRoot(ElementName = "root")]
public class Data
{
    // Retreive data attributes
    [XmlElement(ElementName = "data")]
    public Options Attributes { get; set; }

    // Retrieve option list
    [XmlArray("data")]
    [XmlArrayItem("option", Type = typeof(GeneralOptions))]
    public GeneralOptions[] Options { get; set; }
}
</code>```

Optional classes:

Options

```<code>public class Options
{
    [XmlAttribute("label")]
    public string Label{ get; set; }

    [XmlAttribute("min")]
    public string Min{ get; set; }

    [XmlAttribute("max")]
    public string Max{ get; set; }
}
</code>```

GeneralOptions

```<code>public class GeneralOptions
{
    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "name")]
    public string Name{ get; set; }
}
</code>```

But when I try to deserialize the object, it launches the following exception:

The XML element 'data' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

I imagine the problem is that I'm trying to retreive the same element "twice". But I need to retreive both things. I cannot use the [Attribute] thing because there are several Attributes to retreive, and I need to do this with several XML Elements with the same format and I want to reuse it.

So, how can I retreive both of them?

答:
I suggest using xmltocsharp or anyother tools to convert the XML to C# Models within seconds... (eliminates all manual mistakes)

As mentioned by @canton7, another easy method is using Visual Studio: Edit -> Paste Special -> Paste XML As Classes

```<code>[XmlRoot(ElementName="option")]
public class Option {
    [XmlElement(ElementName="id")]
    public string Id { get; set; }
    [XmlElement(ElementName="name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="option")]
    public List<Option> Option { get; set; }
    [XmlAttribute(AttributeName="label")]
    public string Label { get; set; }
    [XmlAttribute(AttributeName="min")]
    public string Min { get; set; }
    [XmlAttribute(AttributeName="max")]
    public string Max { get; set; }
}

[XmlRoot(ElementName="root")]
public class Root {
    [XmlElement(ElementName="data")]
    public Data Data { get; set; }
}
</code>```

Body:
I have an XML file that looks something similar to this:

<root>
    <data label="product data" min="0" max="10">
        <option>
            <id>1</id>
            <name>Name1</name>
        </option>
        <option>
            <id>2</id>
            <name>Name2</name>
        </option>
        <option>
            <id>3</id>
            <name>Name3</name>
        </option>
    </data>
</root>

I need to retreive both data attributes and the option list.

I tried this:

[XmlRoot(ElementName = "root")]
public class Data
{
    // Retreive data attributes
    [XmlElement(ElementName = "data")]
    public Options Attributes { get; set; }

    // Retrieve option list
    [XmlArray("data")]
    [XmlArrayItem("option", Type = typeof(GeneralOptions))]
    public GeneralOptions[] Options { get; set; }
}

Optional classes:

Options

public class Options
{
    [XmlAttribute("label")]
    public string Label{ get; set; }

    [XmlAttribute("min")]
    public string Min{ get; set; }

    [XmlAttribute("max")]
    public string Max{ get; set; }
}

GeneralOptions

public class GeneralOptions
{
    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "name")]
    public string Name{ get; set; }
}

But when I try to deserialize the object, it launches the following exception:

The XML element 'data' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

I imagine the problem is that I'm trying to retreive the same element "twice". But I need to retreive both things. I cannot use the [Attribute] thing because there are several Attributes to retreive, and I need to do this with several XML Elements with the same format and I want to reuse it.

So, how can I retreive both of them?

Body:
I suggest using xmltocsharp or anyother tools to convert the XML to C# Models within seconds... (eliminates all manual mistakes)

As mentioned by @canton7, another easy method is using Visual Studio: Edit -> Paste Special -> Paste XML As Classes

[XmlRoot(ElementName="option")]
public class Option {
    [XmlElement(ElementName="id")]
    public string Id { get; set; }
    [XmlElement(ElementName="name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="option")]
    public List<Option> Option { get; set; }
    [XmlAttribute(AttributeName="label")]
    public string Label { get; set; }
    [XmlAttribute(AttributeName="min")]
    public string Min { get; set; }
    [XmlAttribute(AttributeName="max")]
    public string Max { get; set; }
}

[XmlRoot(ElementName="root")]
public class Root {
    [XmlElement(ElementName="data")]
    public Data Data { get; set; }
}


问:
KeyError trying to multiply item in a tuple by item in a dictionary?
My python assignment asks me to make a list of tuples and multiply an item in each tuple by a value in a dictionary and I keep getting a KeyError, but I don't really know why or how to fix it. I might just be doing everything wrong.

shop_prices = {
    'eggs': 1.99,
    'milk': 0.99,
    'ham': 4.99,
}

cart = [('eggs', 2), ('milk', 4)]

itemprice = int(cart[0][1]) * shop_prices[item]
print(itemprice)
```

I also have to add all these values together at the end, so if you could help me with that too that would be so great.

Thank you!

答:
Does that answer the question?

for item, value in cart:
    print(shop_prices[item] * value)
```

<p>And if you want total price </p>

<pre class="lang-py prettyprint-override"><code>total = sum(shop_prices[item]* value for item, value in cart) # you may need to round up the value...
</code>```

Body:
My python assignment asks me to make a list of tuples and multiply an item in each tuple by a value in a dictionary and I keep getting a KeyError, but I don't really know why or how to fix it. I might just be doing everything wrong.

shop_prices = {
    'eggs': 1.99,
    'milk': 0.99,
    'ham': 4.99,
}

cart = [('eggs', 2), ('milk', 4)]

itemprice = int(cart[0][1]) * shop_prices[item]
print(itemprice)

I also have to add all these values together at the end, so if you could help me with that too that would be so great.

Thank you!

Body:
Does that answer the question?

for item, value in cart:
    print(shop_prices[item] * value)

And if you want total price

total = sum(shop_prices[item]* value for item, value in cart) # you may need to round up the value...


问:
Learning C# ASAP to get started with ASP.NET?
I have experience writing web apps in Django; scripting in Python; playing with PHP and I understand Object Oriented Programming. I need to get started ASAP with C# in order to start learning and using ASP.NET for a clients project.

Is there a way to get a working knowledge of C# without passing by the over-a-thousand-pages-books? How should I proceed to gain that knowledge?

Thanks.

答:
These are some of the good books for C# since you are already familiar with OOPS concept.

C# via CLR
C# in depth
C# in a nutshell


问:
How do we do Unit testing for AWS CDK code? And should we?
Based on the examples I see, the code assertions are expected json cf template versus the cdk synth generated template.

How do we setup expected json cf template?

If we manually create it, that defeats the purpose of using cdk.

If we just copy paste the cdk synth output, that defeats the purpose of unit testing it.

Having said that, is there a purpose on having unit tests for CDK code?
Maybe I'm missing the idea here. Please do point it out.

答:
An approach that I use, is to create a different project delegated to use the resources that i expect that have been created.

So, from the cdk-init-cluster project, i simply create all the necessary resources using cdk library. Than, after the DEPLOY phase, i run the cdk-init-cluster-test module that is delegated to populate/query/use the resources previously created from the cdk-init-cluster project.

This approach, can only help with few type of resources such as:

S3 bucket

Lambda

AppSync

DynamoDB table

The test project is in charge to:

Populate the DynamoDB table and retrieve the data.

Call the Lambda function with dummy data

Call the lambda function with correct data for verify permission behaviour

Call appsync (that wrap all the resources above) and verify the result

Then, i remove the data inserted for test. If no exceptions occurs, the test is passed.


问:
I am getting error for isDisplayed method?
if (driver.findElement(By.id(id)).isDisplayed()) {

}

Always execution is failed when element is not available?

Environment:

Appium 1.15.1

java Client 7.3.0

selenium-java 3.141.59

error logs:

Android Loding Problem Pages

org.openqa.selenium.NoSuchElementException: Can't locate an element by this strategy: By.chained({By.AccessibilityId: OK})
    at io.appium.java_client.pagefactory.AppiumElementLocator.findElement(AppiumElementLocator.java:126)
    at io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement.intercept(InterceptorOfASingleElement.java:59)
    at io.appium.java_client.ios.IOSElement$$EnhancerByCGLIB$$d311658.isDisplayed()
    at
    at ✽.And Verify the On Side Menu List are Navigating to correspont Screen with OnBoared User(:12)
Caused by: org.openqa.selenium.TimeoutException: Expected condition failed: waiting for io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction@66ba7e45 (tried for 1 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.FluentWait.timeoutException(FluentWait.java:304)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
    at io.appium.java_client.pagefactory.AppiumElementLocator.waitFor(AppiumElementLocator.java:99)
    at io.appium.java_client.pagefactory.AppiumElementLocator.findElement(AppiumElementLocator.java:119)
    at io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement.intercept(InterceptorOfASingleElement.java:59)
    at io.appium.java_client.ios.IOSElement$$EnhancerByCGLIB$$d311658.isDisplayed()
    at
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:39)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:79)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:70)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.chained({By.AccessibilityId: OK})
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'Elites-MacBook-Pro-4.local', ip: 'fe80:0:0:0:1c56:6e8a:fceb:a653%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.15.3', java.version: '1.8.0_201'
Driver info: driver.version: IOSDriver
    at io.appium.java_client.pagefactory.bys.builder.ByChained.findElement(ByChained.java:74)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:57)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.pagefactory.bys.ContentMappedBy.findElement(ContentMappedBy.java:50)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:57)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.pagefactory.AppiumElementLocator.lambda$0(AppiumElementLocator.java:120)
    at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:172)
    at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:1)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:249)
    ... 67 more

答:
If you are trying to verify element is displayed on the page, you can try out this:

```<code>List<WebElement> ele = driver.findElements(By.id(id));
</code>```

This would return the list of elements matching the id you provided. If the List size is more than 0 it means that the element is present on the page.

Body:
If you are trying to verify element is displayed on the page, you can try out this:

List<WebElement> ele = driver.findElements(By.id(id));

This would return the list of elements matching the id you provided. If the List size is more than 0 it means that the element is present on the page.


问:
How to produce an array with values in a specific shape?
I would like to create an array with values that range from 0.0 to 1.0 as shown here:
weighting matrix

Basically, the left and top edges should remain close to 1.0 but slowly decay to 0.5 in the corners.
The bottom and right edges should remain close to 0.0
The middle region should be mostly 0.5, and the values should be decaying diagonally from 1.0 to 0.0.

This is what I've tried but it doesn't give me exactly what I would like.

```<code>import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
  y = np.zeros(len(x))
  for i in range(len(x)):
    y[i] = 1 / (1 + math.exp(-x[i]))
  return y

sigmoid_ = sigmoid(np.linspace(20, 2.5, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(6, 3, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha1 = temp1 + temp2

sigmoid_ = sigmoid(np.linspace(-2.5, -20, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(-3, -6, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha2 = temp1 + temp2

alpha = alpha1 + alpha2
alpha = alpha - np.min(alpha)
alpha = alpha / np.max(alpha)

plt.matshow(alpha)
</code>```

Which gives me this: results

Can someone help me?

答:
I'd use the same function for all parts of the weighting matrix area, if not otherwise required. A sigmoid function (which changes rapidly near the center and slowly away from it) is indeed suitable after appropriate translation and scaling. For the sigmoid function's argument I'd choose the taxicab distance from a corner of the area.

```<code>import math
import numpy as np
import matplotlib.pyplot as plt

alpha = np.ndarray((10, 30))
ymax, xmax = alpha.shape[0]-1, alpha.shape[1]-1
for y in range(alpha.shape[0]):
    for x in range(alpha.shape[1]):
        M = x/xmax+y/ymax   # Manhattan distance, range [0;2]
        M -= 1              # make range [-1;1], so that inflection point is in the middle
        M *= 3.0            # the higher this factor, the steeper the sigmoid curve at the flex
        s = 1 / (1 + math.exp(-M))  # sigmoid function, range ]0;1[
        alpha[y, x] = 1-s   # decay from 1 to 0

plt.matshow(alpha)
plt.show()
# show the values close to 0.5
h = [(y, x) for y in range(alpha.shape[0])
            for x in range(alpha.shape[1]) if .4 < alpha[y, x] and alpha[y, x] < .6]
hy, hx = zip(*h)
plt.plot(hx, hy, 'o')
plt.gca().invert_yaxis()
plt.show()
</code>```

Illustration of values in center region close to 0.5, e. g. in ]0.4;0.6[:

Body:
I would like to create an array with values that range from 0.0 to 1.0 as shown here:
weighting matrix

Basically, the left and top edges should remain close to 1.0 but slowly decay to 0.5 in the corners.
The bottom and right edges should remain close to 0.0
The middle region should be mostly 0.5, and the values should be decaying diagonally from 1.0 to 0.0.

This is what I've tried but it doesn't give me exactly what I would like.

import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
  y = np.zeros(len(x))
  for i in range(len(x)):
    y[i] = 1 / (1 + math.exp(-x[i]))
  return y

sigmoid_ = sigmoid(np.linspace(20, 2.5, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(6, 3, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha1 = temp1 + temp2

sigmoid_ = sigmoid(np.linspace(-2.5, -20, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(-3, -6, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha2 = temp1 + temp2

alpha = alpha1 + alpha2
alpha = alpha - np.min(alpha)
alpha = alpha / np.max(alpha)

plt.matshow(alpha)

Which gives me this: results

Can someone help me?

Body:
I'd use the same function for all parts of the weighting matrix area, if not otherwise required. A sigmoid function (which changes rapidly near the center and slowly away from it) is indeed suitable after appropriate translation and scaling. For the sigmoid function's argument I'd choose the taxicab distance from a corner of the area.

import math
import numpy as np
import matplotlib.pyplot as plt

alpha = np.ndarray((10, 30))
ymax, xmax = alpha.shape[0]-1, alpha.shape[1]-1
for y in range(alpha.shape[0]):
    for x in range(alpha.shape[1]):
        M = x/xmax+y/ymax   # Manhattan distance, range [0;2]
        M -= 1              # make range [-1;1], so that inflection point is in the middle
        M *= 3.0            # the higher this factor, the steeper the sigmoid curve at the flex
        s = 1 / (1 + math.exp(-M))  # sigmoid function, range ]0;1[
        alpha[y, x] = 1-s   # decay from 1 to 0

plt.matshow(alpha)
plt.show()
# show the values close to 0.5
h = [(y, x) for y in range(alpha.shape[0])
            for x in range(alpha.shape[1]) if .4 < alpha[y, x] and alpha[y, x] < .6]
hy, hx = zip(*h)
plt.plot(hx, hy, 'o')
plt.gca().invert_yaxis()
plt.show()

Illustration of values in center region close to 0.5, e. g. in ]0.4;0.6[: