问:
Is there a way to create two Classes that needs each other in during their Initialization process?
I have a program where two classes need each other in their Initialization process, but so far all I get is Compilation Error and I have no idea how to make it work

in Class MainComponent

```<code>class MainComponent  : {
   private:
      PlaylistComponent playlistComponent{formatManager, *this};
}
</code>```

in Class PlaylistComponent

```<code>class PlaylistComponent :{
   private:
      MainComponent& mainComponent;
}
PlaylistComponent::PlaylistComponent(juce::AudioFormatManager &_formatManager, MainComponent &_mainComponent):
formatManager(_formatManager),
mainComponent(_mainComponent){
   //something else
}

</code>```

and here are the error messages:

```<code>error: ‘MainComponent’ has not been declared
   29 |     PlaylistComponent(juce::AudioFormatManager&, MainComponent&);
error: ‘MainComponent’ does not name a type; did you mean ‘Component’?
   74 |     MainComponent& mainComponent;
error: ‘PlaylistComponent’ does not name a type; did you mean ‘MainComponent’?
   49 |     PlaylistComponent playlistComponent{formatManager, *this};
error: ‘MainComponent’ has not been declared
   29 |     PlaylistComponent(juce::AudioFormatManager&, MainComponent&);

error: could not convert ‘{((MainComponent*)this)->MainComponent::formatManager, (*(MainComponent*)this)}’ from ‘<brace-enclosed initializer list>’ to ‘PlaylistComponent’
   49 |     PlaylistComponent playlistComponent{formatManager, *this};
      |                                                             ^
      |                                                             |
      |                                                             <brace-enclosed initializer list>

</code>```

So far I have tried different approach such as " forward declarations"(Two classes that refer to each other) but it did not work, and the error message was that playlistComponent has incomplete type PlaylistComponent

I know that it's because one Class needs to be initialized before the other, but how could I do this when both Classes need each other during the Initialization process?

答:
You need something like this(forward declaration: because you didn't show us how you used forward decleration I show that again here):

//in  A.h file
class B;
class A{
    B* b; // or anything else that dont need definition here and just need definition in cpp file.
}
```
<pre class="lang-cpp prettyprint-override"><code>//in  B.h file
class A;
class B{
    A* a; // or anything else that dont need definition here and just need definition in cpp file.
}
</code>```

// in A.cpp
include "A.h"
include "B.h"
```
<pre class="lang-cpp prettyprint-override"><code>// in B.cpp
include "B.h"
include "A.h"
</code>```

Note: always write the namespaces too if the class has namespace(in
forward decleration) for example:

```<code>namespace mine{
class A;
}
</code>```

Body:
I have a program where two classes need each other in their Initialization process, but so far all I get is Compilation Error and I have no idea how to make it work

in Class MainComponent

class MainComponent  : {
   private:
      PlaylistComponent playlistComponent{formatManager, *this};
}

in Class PlaylistComponent

class PlaylistComponent :{
   private:
      MainComponent& mainComponent;
}
PlaylistComponent::PlaylistComponent(juce::AudioFormatManager &_formatManager, MainComponent &_mainComponent):
formatManager(_formatManager),
mainComponent(_mainComponent){
   //something else
}

and here are the error messages:

error: ‘MainComponent’ has not been declared
   29 |     PlaylistComponent(juce::AudioFormatManager&, MainComponent&);
error: ‘MainComponent’ does not name a type; did you mean ‘Component’?
   74 |     MainComponent& mainComponent;
error: ‘PlaylistComponent’ does not name a type; did you mean ‘MainComponent’?
   49 |     PlaylistComponent playlistComponent{formatManager, *this};
error: ‘MainComponent’ has not been declared
   29 |     PlaylistComponent(juce::AudioFormatManager&, MainComponent&);

error: could not convert ‘{((MainComponent*)this)->MainComponent::formatManager, (*(MainComponent*)this)}’ from ‘<brace-enclosed initializer list>’ to ‘PlaylistComponent’
   49 |     PlaylistComponent playlistComponent{formatManager, *this};
      |                                                             ^
      |                                                             |
      |                                                             <brace-enclosed initializer list>

So far I have tried different approach such as " forward declarations"(Two classes that refer to each other) but it did not work, and the error message was that playlistComponent has incomplete type PlaylistComponent

I know that it's because one Class needs to be initialized before the other, but how could I do this when both Classes need each other during the Initialization process?

Body:
You need something like this(forward declaration: because you didn't show us how you used forward decleration I show that again here):

//in  A.h file
class B;
class A{
    B* b; // or anything else that dont need definition here and just need definition in cpp file.
}

//in  B.h file
class A;
class B{
    A* a; // or anything else that dont need definition here and just need definition in cpp file.
}

// in A.cpp
include "A.h"
include "B.h"

// in B.cpp
include "B.h"
include "A.h"

Note: always write the namespaces too if the class has namespace(in
forward decleration) for example:

namespace mine{
class A;
}


来源: stackexchange

问:
How to use react transition group after API loads?

I'm displaying a skeleton loader when the page loads.

When My API are done fetching, skeleton is removed from the DOM

Content is added to the DOM.

I would like to fade-out the skeleton when it goes away, and to fade-in the content when it comes in.

For that, I'm using react-transition-group, with the CSSTransition component.

Here is a simplified version of my code so far, please forgive me for the lack of a codepen, since replicating and mimicking API loading/ready states are quite tedious to me :

Homepage.tsx :

```<code>function HomePage() {

  const { data: dataAPI, error } = useAPI1();
  const { data: dataAPI2, error: error2 } = useAPI2();

  if (!dataAPI || !dataAPI2) return <SkeletonLoader isLoading={!dataAPI && !dataAPI2} />;

  if (error) return <Error customMessage="Error from API1" />;
  if (error2) return <Error customMessage="Error from API2" />;

  return (
    <>
      <p>My content !</p>
    </>
  );
}

export default HomePage;
</code>```

SkeletonLoader.tsx

```<code>const SkeletonLoader = ({ isLoading }: { isLoading: boolean }) => {
  const nodeRef = useRef(null);
  return (
    <CSSTransition timeout={1000} classNames="skeleton" in={!isLoading} nodeRef={nodeRef}>
      <Layout>
        <div className={styles.skeleton} ref={nodeRef}>
          <div className={styles.img} />
          <div className={styles.line} />
          <SkeletonProduct />
          <SkeletonProduct />
          <SkeletonProduct />
        </div>
      </Layout>
    </CSSTransition>
  );
};

export default SkeletonLoader;
</code>```

global.scss

```<code>.skeleton-enter {
  opacity: 0;
}

.skeleton-enter-active {
  opacity: 1;
  transform: translateX(0);
  transition: opacity 1000ms;
}

.skeleton-exit {
  opacity: 1;
}

.skeleton-exit-active {
  opacity: 0;
  transition: opacity 1000ms;
}
</code>```

I've tried different things but I can't see the fade-out when the skeleton is removed from the DOM.

Thank you for your help.

答:
You're unmounting the transition group before it has time to play your animation.

```<code>  if (!dataAPI || !dataAPI2) return <SkeletonLoader isLoading={!dataAPI && !dataAPI2} />;
</code>```

will stop rendering your transition group.

you could try to always render the transition group, and have it unmount itself with 'unmountOnExit` property:

```<code>function HomePage() {
  const { data: dataAPI, error } = useAPI1();
  const { data: dataAPI2, error: error2 } = useAPI2();

  const isLoading =  (!dataAPI || !dataAPI2)
  const shouldRenderContent = !error && !error2 && !isLoading;

  return (
    <>
      { error && <Error customMessage="Error from API1" /> }
      { error2 && <Error customMessage="Error from API2" /> }
      { isLoading && <SkeletonLoader isLoading={isLoading} />}
      {shouldRenderContent && <p>My content !</p> }
    </>
  );
}

export default HomePage;

....
    <CSSTransition
       unmountOnExit  // <-- this will remove the children when 'exit' ran.
       timeout={1000}
       classNames="skeleton"
       in={!isLoading}
       nodeRef={nodeRef}
       >
.....

</code>```

Code sandbox where the api call is replaced with simple button toggle

ContentLicense: CC BY-SA 4.0

Body:
I'm displaying a skeleton loader when the page loads.

When My API are done fetching, skeleton is removed from the DOM

Content is added to the DOM.

I would like to fade-out the skeleton when it goes away, and to fade-in the content when it comes in.

For that, I'm using react-transition-group, with the CSSTransition component.

Here is a simplified version of my code so far, please forgive me for the lack of a codepen, since replicating and mimicking API loading/ready states are quite tedious to me :

Homepage.tsx :

function HomePage() {

  const { data: dataAPI, error } = useAPI1();
  const { data: dataAPI2, error: error2 } = useAPI2();

  if (!dataAPI || !dataAPI2) return <SkeletonLoader isLoading={!dataAPI && !dataAPI2} />;

  if (error) return <Error customMessage="Error from API1" />;
  if (error2) return <Error customMessage="Error from API2" />;

  return (
    <>

My content !

    </>
  );
}

export default HomePage;

SkeletonLoader.tsx

const SkeletonLoader = ({ isLoading }: { isLoading: boolean }) => {
  const nodeRef = useRef(null);
  return (
    <CSSTransition timeout={1000} classNames="skeleton" in={!isLoading} nodeRef={nodeRef}>
      <Layout>

          <SkeletonProduct />
          <SkeletonProduct />
          <SkeletonProduct />

      </Layout>
    </CSSTransition>
  );
};

export default SkeletonLoader;

global.scss

.skeleton-enter {
  opacity: 0;
}

.skeleton-enter-active {
  opacity: 1;
  transform: translateX(0);
  transition: opacity 1000ms;
}

.skeleton-exit {
  opacity: 1;
}

.skeleton-exit-active {
  opacity: 0;
  transition: opacity 1000ms;
}

I've tried different things but I can't see the fade-out when the skeleton is removed from the DOM.

Thank you for your help.

Body:
You're unmounting the transition group before it has time to play your animation.

  if (!dataAPI || !dataAPI2) return <SkeletonLoader isLoading={!dataAPI && !dataAPI2} />;

will stop rendering your transition group.

you could try to always render the transition group, and have it unmount itself with 'unmountOnExit` property:

function HomePage() {
  const { data: dataAPI, error } = useAPI1();
  const { data: dataAPI2, error: error2 } = useAPI2();

  const isLoading =  (!dataAPI || !dataAPI2)
  const shouldRenderContent = !error && !error2 && !isLoading;

  return (
    <>
      { error && <Error customMessage="Error from API1" /> }
      { error2 && <Error customMessage="Error from API2" /> }
      { isLoading && <SkeletonLoader isLoading={isLoading} />}
      {shouldRenderContent && <p>My content !</p> }
    </>
  );
}

export default HomePage;

....
    <CSSTransition
       unmountOnExit  // <-- this will remove the children when 'exit' ran.
       timeout={1000}
       classNames="skeleton"
       in={!isLoading}
       nodeRef={nodeRef}
       >
.....

Code sandbox where the api call is replaced with simple button toggle


问:
How to webscrape with Python keeping meta-information in the text?
I am trying to webscrape this website. To do so,
I run the following code:

```<code>from bs4 import BeautifulSoup
import requests

url = "https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html"
soup = BeautifulSoup(requests.get(url).content)

data = []

for link in soup.select('div.title > a'):
    soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{link['href']}").content)
    data.append({
        'text':' '.join([p.text for p in soup.select('main .section p:not([class])')])
    })

print(data)

</code>```

This works fine. What is the issue? The problem is that the webscraped text comes without information on paragraphs split and on bold character. This is a problem since I would then need to make some calls on the basis of that.

Can anyone suggest how to maintain meta-information in the text?

Thanks a lot!

答:
A solution is to determine in the website code source what are the markers for paragraphs split and bold characters.

Then, the "soup" variable, you can localize what interests you using the markers as a string to be searched in "soup".

Looking briefly at the source code of your website, I think the answer relies in following markers (I needed to add ' otherwise the markers are hidden by stackoverflow):

"<'/a><'/div><'div class="subtitle">"

Body:
I am trying to webscrape this website. To do so,
I run the following code:

from bs4 import BeautifulSoup
import requests

url = "https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html"
soup = BeautifulSoup(requests.get(url).content)

data = []

for link in soup.select('div.title > a'):
    soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{link['href']}").content)
    data.append({
        'text':' '.join([p.text for p in soup.select('main .section p:not([class])')])
    })

print(data)

This works fine. What is the issue? The problem is that the webscraped text comes without information on paragraphs split and on bold character. This is a problem since I would then need to make some calls on the basis of that.

Can anyone suggest how to maintain meta-information in the text?

Thanks a lot!


问:
How to implement Pure DI with Razor Components
I am making an ASP.NET Core application using the Pure DI approach explained in the book Dependency Injection Principles, Practices, and Patterns (DIPP&P). Part of my application has a web API controller. To implement Pure DI with my controller, I was easily able to follow section 7.3.1 "Creating a custom controller activator" from DIPP&P to create a controller activator class, similar to the example found in DIPP&P. This was done by implementing IControllerActivator and composing my composition root within the create method.

My application will also feature Razor Components. I would like to continue using the Pure DI approach but I cannot find any examples on how to do this.

My questions are:

Is it possible to implement Pure DI with Razor Components?

If so, how does one go about this?

答:
It certainly is possible to apply Pure DI to a Razor application, but not through IRazorPageActivator but through the IComponentActivator abstraction. Here's an example based on the default Visual Studio (2019) Razor project template. Since that template builds around a weather forecast domain, let's use that for the example.

Let's start with the custom IComponentActivator, which acts as your Composer, which is part of your Composition Root.

public record WeatherComponentActivator(IServiceProvider Provider)
    : IComponentActivator
{
    public IComponent CreateInstance(Type componentType) => (IComponent)this.Create(componentType);

    private object Create(Type type)
    {
        switch (type.Name)
        {
            case nameof(FetchData):
                return new FetchData(new WeatherForecastService());

            case nameof(App): return new App();
            case nameof(Counter): return new Counter();
            case nameof(MainLayout): return new MainLayout();
            case nameof(NavMenu): return new NavMenu();
            case nameof(Pages.Index): return new Pages.Index();
            case nameof(SurveyPrompt): return new SurveyPrompt();

            default:
                return type.Namespace.StartsWith("Microsoft")
                    ? Activator.CreateInstance(type) // Default framework behavior
                    : throw new NotImplementedException(type.FullName);
        }
    }
}
```
<p>Notice a few things with this implementation:</p>
<ul>
<li>Constructor injection is used with the <code>FetchData</code> Razor page.</li>
<li>It falls back to using <code>Activator.CreateInstance</code> for framework components. <code>Activator.CreateInstance</code> is the behavior the framework uses for its default component activator implementation. Falling back is required, because there are quite some framework Razor components to be created. You don't want to list them all, and they are not yours to manage.</li>
<li>In the <code>WeatherComponentActivator</code> class, I injected an <code>IServiceProvider</code>. It's not needed right now, but it shows that it's possible to use it to pull in framework dependencies if you need. There will certainly be a time where your pages directly or indirectly need a dependency on some part of the framework. This is how to integrate the two. The framework is so tightly mangled with its DI infrastructure that it's impossible to <em>not</em> use the DI Container for its framework parts.</li>
</ul>
<p>Compared to the built-in behavior, using Pure DI has the nice advantage of being able to use constructor injection on your Razor Pages. For your <code>FetchData</code> component, this means it should be implemented as follows:</p>
```@page "/fetchdata"

@using AspNetCoreBlazor50PureDI.Data
@* "notice that there are no @inject attributes here" *@

Weather forecast

This component demonstrates fetching data from a service.

@if (forecasts == null)
{

Loading...

}
else
{

        Default template code removed for brevity

}

@code {
    private readonly WeatherForecastService forecastService;

    // Yeah! Constructor Injection!
    public FetchData(WeatherForecastService forecastService)
    {
        this.forecastService = forecastService;
    }

    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await this.forecastService.GetForecastAsync(DateTime.Now);
    }
}
```
<p>Please be aware that even though your <code>WeatherComponentActivator</code> is now in control over the creation of Razer Components, the Razor framework will still try to initialize them. That means that any properties on the page that are marked with <code>@inject</code> are pulled in from the built-in DI container. But since you will not register your own classes in the container (since you are applying Pure DI), this won't work and your page will break.</p>
<p>The last missing piece of infrastructure required is the registration of your <code>WeatherComponentActivator</code> into the framework's DI Container. This is done inside the <code>Startup</code> class:</p>
<pre class="lang-cs prettyprint-override"><code>public class Startup
{
    public Startup(IConfiguration configuration) => this.Configuration = configuration;

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();

        // Register your custom component activator here
        services.AddScoped<IComponentActivator, WeatherComponentActivator>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) ...
}
</code>```

Notice how the WeatherComponentActivator is registered as a Scoped component. This important in case you need to pull in framework components from the IServiceProvider, because it allows resolving Scoped framework components, which is impossible to do from within a Singleton class.

But this has some important consequences. The examples of controller activators and other classes that function as a Composition Root often contain private fields that are used to store Singletons in them. This won't work for the  WeatherComponentActivator when you register it as Scoped, because those private fields will be gone with the next scope. In that case you should either store singletons in private static fields, but that has the consequence that it becomes harder to create WeatherComponentActivator inside unit tests, where you rather want a unit test to run in isolation. So if that's an issue, you can extract the composition of dependencies out of the WeatherComponentActivator into its own class, for instance:

public record WeatherComponentActivator(WeatherComposer Composer, IServiceProvider Provider)
    : IComponentActivator
{
    // Activator delegates to WeatherComposer
    public IComponent CreateInstance(Type componentType) =>
        (IComponent)this.Composer.Create(componentType, this.Provider);

public class WeatherComposer
{
    // Singleton
    private readonly ILogger logger = new ConsoleLogger();

    public object Create(Type type, IServiceProvider provider)
    {
        switch (type.Name)
        {
            case nameof(FetchData):
                return new FetchData(new WeatherForecastService());
            ...
        }
    }
}
```
<p>This new <code>WeatherComposer</code> can now be registered as Singleton:</p>
<pre class="lang-cs prettyprint-override"><code>services.RegisterSingleton(new WeatherComposer());
</code>```

Body:
It certainly is possible to apply Pure DI to a Razor application, but not through IRazorPageActivator but through the IComponentActivator abstraction. Here's an example based on the default Visual Studio (2019) Razor project template. Since that template builds around a weather forecast domain, let's use that for the example.

Let's start with the custom IComponentActivator, which acts as your Composer, which is part of your Composition Root.

public record WeatherComponentActivator(IServiceProvider Provider)
    : IComponentActivator
{
    public IComponent CreateInstance(Type componentType) => (IComponent)this.Create(componentType);

    private object Create(Type type)
    {
        switch (type.Name)
        {
            case nameof(FetchData):
                return new FetchData(new WeatherForecastService());

            case nameof(App): return new App();
            case nameof(Counter): return new Counter();
            case nameof(MainLayout): return new MainLayout();
            case nameof(NavMenu): return new NavMenu();
            case nameof(Pages.Index): return new Pages.Index();
            case nameof(SurveyPrompt): return new SurveyPrompt();

            default:
                return type.Namespace.StartsWith("Microsoft")
                    ? Activator.CreateInstance(type) // Default framework behavior
                    : throw new NotImplementedException(type.FullName);
        }
    }
}

Notice a few things with this implementation:

Constructor injection is used with the FetchData Razor page.

It falls back to using Activator.CreateInstance for framework components. Activator.CreateInstance is the behavior the framework uses for its default component activator implementation. Falling back is required, because there are quite some framework Razor components to be created. You don't want to list them all, and they are not yours to manage.

In the WeatherComponentActivator class, I injected an IServiceProvider. It's not needed right now, but it shows that it's possible to use it to pull in framework dependencies if you need. There will certainly be a time where your pages directly or indirectly need a dependency on some part of the framework. This is how to integrate the two. The framework is so tightly mangled with its DI infrastructure that it's impossible to not use the DI Container for its framework parts.

Compared to the built-in behavior, using Pure DI has the nice advantage of being able to use constructor injection on your Razor Pages. For your FetchData component, this means it should be implemented as follows:

@page "/fetchdata"

@using AspNetCoreBlazor50PureDI.Data
@* "notice that there are no @inject attributes here" *@
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from a service.</p>
@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        Default template code removed for brevity
    </table>
}

@code {
    private readonly WeatherForecastService forecastService;

    // Yeah! Constructor Injection!
    public FetchData(WeatherForecastService forecastService)
    {
        this.forecastService = forecastService;
    }

    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await this.forecastService.GetForecastAsync(DateTime.Now);
    }
}

Please be aware that even though your WeatherComponentActivator is now in control over the creation of Razer Components, the Razor framework will still try to initialize them. That means that any properties on the page that are marked with @inject are pulled in from the built-in DI container. But since you will not register your own classes in the container (since you are applying Pure DI), this won't work and your page will break.

The last missing piece of infrastructure required is the registration of your WeatherComponentActivator into the framework's DI Container. This is done inside the Startup class:

public class Startup
{
    public Startup(IConfiguration configuration) => this.Configuration = configuration;

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();

        // Register your custom component activator here
        services.AddScoped<IComponentActivator, WeatherComponentActivator>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) ...
}

Notice how the WeatherComponentActivator is registered as a Scoped component. This important in case you need to pull in framework components from the IServiceProvider, because it allows resolving Scoped framework components, which is impossible to do from within a Singleton class.

But this has some important consequences. The examples of controller activators and other classes that function as a Composition Root often contain private fields that are used to store Singletons in them. This won't work for the  WeatherComponentActivator when you register it as Scoped, because those private fields will be gone with the next scope. In that case you should either store singletons in private static fields, but that has the consequence that it becomes harder to create WeatherComponentActivator inside unit tests, where you rather want a unit test to run in isolation. So if that's an issue, you can extract the composition of dependencies out of the WeatherComponentActivator into its own class, for instance:

public record WeatherComponentActivator(WeatherComposer Composer, IServiceProvider Provider)
    : IComponentActivator
{
    // Activator delegates to WeatherComposer
    public IComponent CreateInstance(Type componentType) =>
        (IComponent)this.Composer.Create(componentType, this.Provider);

public class WeatherComposer
{
    // Singleton
    private readonly ILogger logger = new ConsoleLogger();

    public object Create(Type type, IServiceProvider provider)
    {
        switch (type.Name)
        {
            case nameof(FetchData):
                return new FetchData(new WeatherForecastService());
            ...
        }
    }
}

This new WeatherComposer can now be registered as Singleton:

services.RegisterSingleton(new WeatherComposer());


问:
Theory of storing a number and text in same SQL field
I have a three tables

Results:
TestID
TestCode
Value

Tests:
TestID
TestType
SysCodeID

SystemCodes
SysCodeID
ParentSysCodeID
Description

The question I have is for when the user is entering data into the results table.

The formatting code when the row gets the focus changes the value field to a dropdown combobox if the testCode is of type SystemList.  The drop down has a list of all the system codes that have a parentsyscodeID of the test.SysCodeID.  When the user chooses a value in the list it translates into a number which goes into the value field.

The datatype of the Results.Value field is integer.  I made it an integer instead of a string because when reporting it is easier to do calculations and sorting if it is a number.  There are issues if you are putting integer/decimal value into a string field.  As well, when the system was being designed they only wanted numbers in there.

The users now want to put strings into the value field as well as numbers/values from a list and I'm wondering what the best way of doing that would be.

Would it be bad practice to convert the field over to a string and then store both strings and integers in the same field?  There are different issues related to this one but i'm not sure if any are a really big deal.

Should I add another column into the table of string datatype and  if the test is a string type then put the data the user enters into the different field.

Another option would be to create a 1-1 relationship to another table and if the user types in a string into the value field it adds it into the new table with a key of a number.

Anyone have any interesting ideas?

答:
Are you saying that they want to do free-form text entry? If that's the case, they will ruin the ability to do meaningful reporting on the field, because I can guarantee that they will not consistently enter the strings.

If they are going to be entering one of several preset strings (for example, grades of A, B, C, etc.) then make a lookup table for those strings which maps to numeric values for sorting, evaluating, averaging, etc.

If they really want to be able to start entering in free-form text and you can't dissuade them from it, add another column along the lines of other_entry. Have a predefined value that means "other" to put in your value column. That way, when you're doing reporting you can either roll up all of those random "other" values or you can simply ignore them. Make sure that you add the "other" into your SystemCodes table so that you can keep a foreign key between that and the Results table. If you don't already have one, then you should definitely consider adding one.

Good luck!

OwnerDisplayName: Jaydel Gluckie

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Tom H.


问:
variable connected to Interface builder not free memory when release it , how to fixed?
this view controller will consume memory when the view dealloc all that memory are not free
how to free that memory ??</p>

```<code>@interface Agro01ViewController : UIViewController<UIScrollViewDelegate> {

    NSInteger picIndex;
    BOOL isOverrideing;
    NSTimer *myTimer;
    NSInteger maxPicture;
}

@property (nonatomic, retain) IBOutlet UIScrollView *myscrollView;
@property (nonatomic, retain) IBOutlet UIScrollView *myscrollView3;
@property (nonatomic, retain) IBOutlet UIView *simgView;
@property (nonatomic, retain) IBOutlet UIView *simgView3;
@property (nonatomic, retain) IBOutlet UIView *imgView;
@property (nonatomic, retain) IBOutlet UIView *imgView2;
@property (nonatomic, retain) IBOutlet UIView *imgView3;
@property (nonatomic, retain) IBOutlet UIView *imgView4;
@property (nonatomic, retain) IBOutlet UIView *imgView5;
@property (nonatomic, retain) IBOutlet UIView *imgView6;
@property (nonatomic, retain) IBOutlet UIView *imgView7;
@property (nonatomic, retain) IBOutlet UIView *imgView8;
@property (nonatomic, retain) IBOutlet UIView *Portrait;
@property (nonatomic, retain) IBOutlet UIView *Landscape;
@property (nonatomic) NSInteger maxPicture;

- (IBAction) Closebutton:(id)sender;
- (void)updatepicture;
- (IBAction) SecondViewbutton:(id)sender;
@end

@implementation Agro01ViewController
@synthesize imgView = _imgView, imgView2 = _imgView2, imgView3 = _imgView3, imgView4 = _imgView4, imgView5 = _imgView5;
@synthesize imgView6 = _imgView6, imgView7 = _imgView7, imgView8 = _imgView8, Portrait = _Portrait, Landscape = _Landscape ;
@synthesize myscrollView = _myscrollView, myscrollView3 = _myscrollView3, simgView = _simgView, simgView3 = _simgView3, maxPicture;
- (void)dealloc {
    NSLog(@"dealloc");
    [_Landscape release];
    [_Portrait release];
    [_imgView release];
    [_imgView2 release];
    [_imgView3 release];
    [_imgView4 release];
    [_imgView5 release];
    [_imgView6 release];
    [_imgView7 release];
    [_imgView8 release];
    [_myscrollView release];
    [_myscrollView3 release];
    [_simgView release];
    [_simgView3 release];
    [super dealloc];

}
- (void)viewDidUnload {
    self.simgView = nil;
    self.simgView3 = nil;
    self.myscrollView = nil;
    self.myscrollView3 = nil;
    self.Landscape = nil;
    self.Portrait = nil;
    self.imgView = nil;
    self.imgView2 = nil;
    self.imgView3 = nil;
    self.imgView4 = nil;
    self.imgView5 = nil;
    self.imgView6 = nil;
    self.imgView7 = nil;
    self.imgView8 = nil;
    [super viewDidUnload];

}

- (void)viewDidLoad {
    if (([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight)) {
        self.Landscape.alpha = 1;
        self.Portrait.alpha = 0;
    }
    else {
        self.Landscape.alpha = 0;
        self.Portrait.alpha = 1;
    }
    [self.view addSubview:self.Landscape];
    [self.view addSubview:self.Portrait];

    self.myscrollView3.contentSize = CGSizeMake(self.simgView3.frame.size.width, self.simgView3.frame.size.height);
    self.myscrollView3.maximumZoomScale = 1.0;
    self.myscrollView3.minimumZoomScale = 1.0;
    self.myscrollView3.clipsToBounds = YES;
    self.myscrollView3.delegate = self;
    self.myscrollView3.showsHorizontalScrollIndicator = NO;
    self.myscrollView3.showsVerticalScrollIndicator = NO;
    [self.myscrollView3 addSubview:self.simgView3];

    self.myscrollView.contentSize = CGSizeMake(self.simgView.frame.size.width, self.simgView.frame.size.height);
    self.myscrollView.maximumZoomScale = 1.0;
    self.myscrollView.minimumZoomScale = 1.0;
    self.myscrollView.clipsToBounds = YES;
    self.myscrollView.delegate = self;
    self.myscrollView.showsHorizontalScrollIndicator = NO;
    self.myscrollView.showsVerticalScrollIndicator = NO;
    [self.myscrollView addSubview:self.simgView];
    isOverrideing = NO;
    picIndex = 0;

    [super viewDidLoad];
}
</code>```

答:
Get rid of:

```<code>- (void)viewDidUnload {
self.simgView = nil;
self.simgView3 = nil;
self.myscrollView = nil;
self.myscrollView3 = nil;
self.Landscape = nil;
self.Portrait = nil;
self.imgView = nil;
self.imgView2 = nil;
self.imgView3 = nil;
self.imgView4 = nil;
self.imgView5 = nil;
self.imgView6 = nil;
self.imgView7 = nil;
self.imgView8 = nil;
[super viewDidUnload];
}
</code>```

You're clearing out the pointers to the objects you want to get rid of, before the dealloc can take place.  Let the dealloc handle it.

joe

ContentLicense: CC BY-SA 3.0

Body:
this view controller will consume memory when the view dealloc all that memory are not free
how to free that memory ??

@interface Agro01ViewController : UIViewController<UIScrollViewDelegate> {

    NSInteger picIndex;
    BOOL isOverrideing;
    NSTimer *myTimer;
    NSInteger maxPicture;
}

@property (nonatomic, retain) IBOutlet UIScrollView *myscrollView;
@property (nonatomic, retain) IBOutlet UIScrollView *myscrollView3;
@property (nonatomic, retain) IBOutlet UIView *simgView;
@property (nonatomic, retain) IBOutlet UIView *simgView3;
@property (nonatomic, retain) IBOutlet UIView *imgView;
@property (nonatomic, retain) IBOutlet UIView *imgView2;
@property (nonatomic, retain) IBOutlet UIView *imgView3;
@property (nonatomic, retain) IBOutlet UIView *imgView4;
@property (nonatomic, retain) IBOutlet UIView *imgView5;
@property (nonatomic, retain) IBOutlet UIView *imgView6;
@property (nonatomic, retain) IBOutlet UIView *imgView7;
@property (nonatomic, retain) IBOutlet UIView *imgView8;
@property (nonatomic, retain) IBOutlet UIView *Portrait;
@property (nonatomic, retain) IBOutlet UIView *Landscape;
@property (nonatomic) NSInteger maxPicture;

- (IBAction) Closebutton:(id)sender;
- (void)updatepicture;
- (IBAction) SecondViewbutton:(id)sender;
@end

@implementation Agro01ViewController
@synthesize imgView = _imgView, imgView2 = _imgView2, imgView3 = _imgView3, imgView4 = _imgView4, imgView5 = _imgView5;
@synthesize imgView6 = _imgView6, imgView7 = _imgView7, imgView8 = _imgView8, Portrait = _Portrait, Landscape = _Landscape ;
@synthesize myscrollView = _myscrollView, myscrollView3 = _myscrollView3, simgView = _simgView, simgView3 = _simgView3, maxPicture;
- (void)dealloc {
    NSLog(@"dealloc");
    [_Landscape release];
    [_Portrait release];
    [_imgView release];
    [_imgView2 release];
    [_imgView3 release];
    [_imgView4 release];
    [_imgView5 release];
    [_imgView6 release];
    [_imgView7 release];
    [_imgView8 release];
    [_myscrollView release];
    [_myscrollView3 release];
    [_simgView release];
    [_simgView3 release];
    [super dealloc];

}
- (void)viewDidUnload {
    self.simgView = nil;
    self.simgView3 = nil;
    self.myscrollView = nil;
    self.myscrollView3 = nil;
    self.Landscape = nil;
    self.Portrait = nil;
    self.imgView = nil;
    self.imgView2 = nil;
    self.imgView3 = nil;
    self.imgView4 = nil;
    self.imgView5 = nil;
    self.imgView6 = nil;
    self.imgView7 = nil;
    self.imgView8 = nil;
    [super viewDidUnload];

}

- (void)viewDidLoad {
    if (([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight)) {
        self.Landscape.alpha = 1;
        self.Portrait.alpha = 0;
    }
    else {
        self.Landscape.alpha = 0;
        self.Portrait.alpha = 1;
    }
    [self.view addSubview:self.Landscape];
    [self.view addSubview:self.Portrait];

    self.myscrollView3.contentSize = CGSizeMake(self.simgView3.frame.size.width, self.simgView3.frame.size.height);
    self.myscrollView3.maximumZoomScale = 1.0;
    self.myscrollView3.minimumZoomScale = 1.0;
    self.myscrollView3.clipsToBounds = YES;
    self.myscrollView3.delegate = self;
    self.myscrollView3.showsHorizontalScrollIndicator = NO;
    self.myscrollView3.showsVerticalScrollIndicator = NO;
    [self.myscrollView3 addSubview:self.simgView3];

    self.myscrollView.contentSize = CGSizeMake(self.simgView.frame.size.width, self.simgView.frame.size.height);
    self.myscrollView.maximumZoomScale = 1.0;
    self.myscrollView.minimumZoomScale = 1.0;
    self.myscrollView.clipsToBounds = YES;
    self.myscrollView.delegate = self;
    self.myscrollView.showsHorizontalScrollIndicator = NO;
    self.myscrollView.showsVerticalScrollIndicator = NO;
    [self.myscrollView addSubview:self.simgView];
    isOverrideing = NO;
    picIndex = 0;

    [super viewDidLoad];
}

Body:
Get rid of:

- (void)viewDidUnload {
self.simgView = nil;
self.simgView3 = nil;
self.myscrollView = nil;
self.myscrollView3 = nil;
self.Landscape = nil;
self.Portrait = nil;
self.imgView = nil;
self.imgView2 = nil;
self.imgView3 = nil;
self.imgView4 = nil;
self.imgView5 = nil;
self.imgView6 = nil;
self.imgView7 = nil;
self.imgView8 = nil;
[super viewDidUnload];
}

You're clearing out the pointers to the objects you want to get rid of, before the dealloc can take place.  Let the dealloc handle it.

joe


问:
PHP is not updating the data in table (bindParam)
Below is the attached query that I am trying to run through a POST request.

I have checked (echo) the values on submit, I am getting the latest values which means no issue on the form side. I am not getting any errors. echo after the query is also working but the record is not getting updated in the table. I have double check typos in the query it seems fine to me. Below is the query (I have replaced table name here)

```<code>$sql="UPDATE table_name SET name = :name, email = :email, category = :category, mobile = :mobileno, description = :description, website = :website, address = :address, city = :city, state = :state, zip = :zip, image = :image  WHERE  id = :editid";
$query = $dbh->prepare($sql);
$query-> bindParam(':name', $name, PDO::PARAM_STR);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':category', $category, PDO::PARAM_STR);
$query-> bindParam(':mobileno', $mobileno, PDO::PARAM_STR);
$query-> bindParam(':description', $description, PDO::PARAM_STR);
$query-> bindParam(':website', $website, PDO::PARAM_STR);
$query-> bindParam(':address', $address, PDO::PARAM_STR);
$query-> bindParam(':city', $city, PDO::PARAM_STR);
$query-> bindParam(':state', $state, PDO::PARAM_STR);
$query-> bindParam(':zip', $zip, PDO::PARAM_STR);
$query-> bindParam(':image', $image, PDO::PARAM_STR);
$query-> bindParam(':editid', $editid, PDO::PARAM_STR);
$query->execute();
</code>```

答:
In MySQL there are a few reserved keywords that you cannot use without escaping the fields in a query. The complete list can be found in the MySQL-documentation.

Try the query below and check whether or not the query processes correctly now.

```<code>$sql="UPDATE `table_name` SET `name` = :name, `email` = :email, `category` = :category, `mobile` = :mobileno, `description` = :description, `website` = :website, `address` = :address, `city` = :city, `state` = :state, `zip` = :zip, `image` = :image  WHERE `id` = :editid";
$query = $dbh->prepare($sql);
$query-> bindParam(':name', $name, PDO::PARAM_STR);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':category', $category, PDO::PARAM_STR);
$query-> bindParam(':mobileno', $mobileno, PDO::PARAM_STR);
$query-> bindParam(':description', $description, PDO::PARAM_STR);
$query-> bindParam(':website', $website, PDO::PARAM_STR);
$query-> bindParam(':address', $address, PDO::PARAM_STR);
$query-> bindParam(':city', $city, PDO::PARAM_STR);
$query-> bindParam(':state', $state, PDO::PARAM_STR);
$query-> bindParam(':zip', $zip, PDO::PARAM_STR);
$query-> bindParam(':image', $image, PDO::PARAM_STR);
$query-> bindParam(':editid', $editid, PDO::PARAM_STR);
$query->execute();
</code>```

EDIT:
If all the inputs are strings, and the table fields are strings, this should work. Although I suspect that the fields that are being used aren't all strings... In that case the binding would fail and the query won't process.
I will update this answer should you provide more information about the table you're trying to update and some sample data.

Body:
Below is the attached query that I am trying to run through a POST request.

I have checked (echo) the values on submit, I am getting the latest values which means no issue on the form side. I am not getting any errors. echo after the query is also working but the record is not getting updated in the table. I have double check typos in the query it seems fine to me. Below is the query (I have replaced table name here)

$sql="UPDATE table_name SET name = :name, email = :email, category = :category, mobile = :mobileno, description = :description, website = :website, address = :address, city = :city, state = :state, zip = :zip, image = :image  WHERE  id = :editid";
$query = $dbh->prepare($sql);
$query-> bindParam(':name', $name, PDO::PARAM_STR);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':category', $category, PDO::PARAM_STR);
$query-> bindParam(':mobileno', $mobileno, PDO::PARAM_STR);
$query-> bindParam(':description', $description, PDO::PARAM_STR);
$query-> bindParam(':website', $website, PDO::PARAM_STR);
$query-> bindParam(':address', $address, PDO::PARAM_STR);
$query-> bindParam(':city', $city, PDO::PARAM_STR);
$query-> bindParam(':state', $state, PDO::PARAM_STR);
$query-> bindParam(':zip', $zip, PDO::PARAM_STR);
$query-> bindParam(':image', $image, PDO::PARAM_STR);
$query-> bindParam(':editid', $editid, PDO::PARAM_STR);
$query->execute();

Body:
In MySQL there are a few reserved keywords that you cannot use without escaping the fields in a query. The complete list can be found in the MySQL-documentation.

Try the query below and check whether or not the query processes correctly now.

$sql="UPDATE `table_name` SET `name` = :name, `email` = :email, `category` = :category, `mobile` = :mobileno, `description` = :description, `website` = :website, `address` = :address, `city` = :city, `state` = :state, `zip` = :zip, `image` = :image  WHERE `id` = :editid";
$query = $dbh->prepare($sql);
$query-> bindParam(':name', $name, PDO::PARAM_STR);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':category', $category, PDO::PARAM_STR);
$query-> bindParam(':mobileno', $mobileno, PDO::PARAM_STR);
$query-> bindParam(':description', $description, PDO::PARAM_STR);
$query-> bindParam(':website', $website, PDO::PARAM_STR);
$query-> bindParam(':address', $address, PDO::PARAM_STR);
$query-> bindParam(':city', $city, PDO::PARAM_STR);
$query-> bindParam(':state', $state, PDO::PARAM_STR);
$query-> bindParam(':zip', $zip, PDO::PARAM_STR);
$query-> bindParam(':image', $image, PDO::PARAM_STR);
$query-> bindParam(':editid', $editid, PDO::PARAM_STR);
$query->execute();

EDIT:
If all the inputs are strings, and the table fields are strings, this should work. Although I suspect that the fields that are being used aren't all strings... In that case the binding would fail and the query won't process.
I will update this answer should you provide more information about the table you're trying to update and some sample data.


问:
Generate values in separate dataframe
I trying to generate random data with Pandas.

Data is need to be stored in two columns. The first column needs to contain categorical variables (from Stratum_1 until Stratum_19) each of these stratums can contain a random number of values.

Second column needs to have data in the range between 1 to 180000000 with a standard deviation of 453210, a mean of 170000, and a number of rows 100000.

I try to

```<code>   categorical = {'name': ['Stratum_1','Stratum_2','Stratum_3','Stratum_4','Stratum_5','Stratum_6','Stratum_7','Stratum_8','Stratum_9',
    'Stratum_10','Stratum_11','Stratum_12','Stratum_13','Stratum_14','Stratum_15','Stratum_16','Stratum_17','Stratum_18','Stratum_19']}

desired_mean = 170000
desired_std_dev = 453210

df = pd.DataFrame(np.random.randint(0,180000000,size=(100000, 1)),columns=list('1'))
</code>```

I tried with this code above but don't know how to implement categorical and numerical values together with desired mean and standard deviation. So can anybody help how to solve this problem and generate?

答:
I decided to use the gamma distribution to generate your desired sample after thinking that the given parameters are not suitable for the normal distribution.

Code

import numpy as np
import pandas as pd

# desired parameters
n_rows = 100000
lower, upper = 1, 180000000
mu, sigma = 170000, 453210

# amount of shift
delta = lower

# parameters for the gamma distribution
shape = ((mu - delta) / sigma) ** 2
scale = sigma**2 / (mu - delta)

# Create a dataframe
categories = {'name': [f'Stratum_{i}' for i in range(1, 19 + 1)]}
df = pd.DataFrame(categories).sample(n=n_rows, replace=True).reset_index(drop=True)

# Generate samples along with your desired parameters
generator = np.random.default_rng()
while True:
    df['value'] = generator.gamma(shape=shape, scale=scale, size=n_rows) + delta
    if df.value.max() <= upper:
        break

# Show statistics
print(df.describe())
```

Output

value

count
100,000

mean
169,403 (Target: 170,000)

std
449,668 (Target: 453,210)

min
1

25%
39.4267

50%
5529.28

75%
105,748

max
9.45114e+06

Title: Generate values in separate dataframe

Body:
I trying to generate random data with Pandas.

Data is need to be stored in two columns. The first column needs to contain categorical variables (from Stratum_1 until Stratum_19) each of these stratums can contain a random number of values.

Second column needs to have data in the range between 1 to 180000000 with a standard deviation of 453210, a mean of 170000, and a number of rows 100000.

I try to

   categorical = {'name': ['Stratum_1','Stratum_2','Stratum_3','Stratum_4','Stratum_5','Stratum_6','Stratum_7','Stratum_8','Stratum_9',
    'Stratum_10','Stratum_11','Stratum_12','Stratum_13','Stratum_14','Stratum_15','Stratum_16','Stratum_17','Stratum_18','Stratum_19']}

desired_mean = 170000
desired_std_dev = 453210

df = pd.DataFrame(np.random.randint(0,180000000,size=(100000, 1)),columns=list('1'))

I tried with this code above but don't know how to implement categorical and numerical values together with desired mean and standard deviation. So can anybody help how to solve this problem and generate?

Body:
I decided to use the gamma distribution to generate your desired sample after thinking that the given parameters are not suitable for the normal distribution.

Code

import numpy as np
import pandas as pd

# desired parameters
n_rows = 100000
lower, upper = 1, 180000000
mu, sigma = 170000, 453210

# amount of shift
delta = lower

# parameters for the gamma distribution
shape = ((mu - delta) / sigma) ** 2
scale = sigma**2 / (mu - delta)

# Create a dataframe
categories = {'name': [f'Stratum_{i}' for i in range(1, 19 + 1)]}
df = pd.DataFrame(categories).sample(n=n_rows, replace=True).reset_index(drop=True)

# Generate samples along with your desired parameters
generator = np.random.default_rng()
while True:
    df['value'] = generator.gamma(shape=shape, scale=scale, size=n_rows) + delta
    if df.value.max() <= upper:
        break

# Show statistics
print(df.describe())

Output

value

count
100,000

mean
169,403 (Target: 170,000)

std
449,668 (Target: 453,210)

min
1

25%
39.4267

50%
5529.28

75%
105,748

max
9.45114e+06


问:
Dynamically building WHERE clauses in SQL statements
I have a question regarding SQL. I have the following SQL statement:

```<code>SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;
</code>```

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks

答:
Without dynamic SQL, this is probably your best bet:

```<code>SELECT
    id, first, last, email, notes
FROM
    My_Table
WHERE
    CASE @column_name_variable
        WHEN 'column_1' THEN column_1
        WHEN 'column_2' THEN column_2
        ...
        ELSE 'not null'
    END IS NOT NULL
</code>```

There might be some issues with data type conversions, so you might need to explicitly cast all of the columns to one data type (VARCHAR is probably the best bet). Also, there's a good chance that performance will be horrendous on this query. I'd test it thoroughly before even thinking about implementing something like this.

I mentioned this in my comment, but for completeness I'll put it here too... you can probably also accomplish this with dynamic SQL, but how you do that will depend on your database server (MS SQL Server, Oracle, mySQL, etc.) and there are usually some caveats to using dynamic SQL.

Body:
I have a question regarding SQL. I have the following SQL statement:

SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks

Body:
Without dynamic SQL, this is probably your best bet:

SELECT
    id, first, last, email, notes
FROM
    My_Table
WHERE
    CASE @column_name_variable
        WHEN 'column_1' THEN column_1
        WHEN 'column_2' THEN column_2
        ...
        ELSE 'not null'
    END IS NOT NULL

There might be some issues with data type conversions, so you might need to explicitly cast all of the columns to one data type (VARCHAR is probably the best bet). Also, there's a good chance that performance will be horrendous on this query. I'd test it thoroughly before even thinking about implementing something like this.

I mentioned this in my comment, but for completeness I'll put it here too... you can probably also accomplish this with dynamic SQL, but how you do that will depend on your database server (MS SQL Server, Oracle, mySQL, etc.) and there are usually some caveats to using dynamic SQL.


问:
Eureka client is failing to start up while Eureka server is successfully starting up
I am developing two micro services. One as Eureka Server and other one as Eureka Client. Eureka Server is starting successfully while for Eureka client it is failing to start up and giving error as below after I added Eureka client dependency in pom.xml.Thanks.

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.eurekaClient' defined in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:356) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:390) ~[spring-cloud-context-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:184) ~[spring-cloud-context-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:353) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.getTargetObject(EurekaRegistration.java:171) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.getEurekaClient(EurekaRegistration.java:160) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:246) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope$LockedScopedProxyFactoryBean.invoke(GenericScope.java:494) ~[spring-cloud-context-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration$$EnhancerBySpringCGLIB$$d0d8d24c.getEurekaClient(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.maybeInitializeClient(EurekaServiceRegistry.java:57) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(EurekaServiceRegistry.java:39) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:82) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:53) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:360) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:158) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:122) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:879) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:163) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at io.javabrains.ratingsdataservice.RatingsDataServiceApplication.main(RatingsDataServiceApplication.java:12) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 40 common frames omitted
Caused by: java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:411) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:269) ~[eureka-client-1.9.8.jar:1.9.8]
    at org.springframework.cloud.netflix.eureka.CloudEurekaClient.<init>(CloudEurekaClient.java:63) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.eurekaClient(EurekaClientAutoConfiguration.java:302) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$25bb903d.CGLIB$eurekaClient$0(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$25bb903d$$FastClassBySpringCGLIB$$74fcf26d.invoke(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$25bb903d.eurekaClient(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 41 common frames omitted
</code>```

Below is the pom.xml, I am using for Eureka client

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>io.javabrains</groupId>
    <artifactId>movie-info-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>movie-info-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>
</code>```

Below is the main class for Eureka client

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class RatingsDataServiceApplication {

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

}
</code>```

答:
Have you tried perform mvn clean install?

and add this dependency

```<code><dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-apache-client4</artifactId>
    <version>1.19.4</version>
</dependency>
</code>```

Body:
I am developing two micro services. One as Eureka Server and other one as Eureka Client. Eureka Server is starting successfully while for Eureka client it is failing to start up and giving error as below after I added Eureka client dependency in pom.xml.Thanks.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.eurekaClient' defined in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:356) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:390) ~[spring-cloud-context-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:184) ~[spring-cloud-context-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:353) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.getTargetObject(EurekaRegistration.java:171) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.getEurekaClient(EurekaRegistration.java:160) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:246) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope$LockedScopedProxyFactoryBean.invoke(GenericScope.java:494) ~[spring-cloud-context-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration$$EnhancerBySpringCGLIB$$d0d8d24c.getEurekaClient(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.maybeInitializeClient(EurekaServiceRegistry.java:57) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(EurekaServiceRegistry.java:39) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:82) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:53) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:360) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:158) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:122) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:879) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:163) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at io.javabrains.ratingsdataservice.RatingsDataServiceApplication.main(RatingsDataServiceApplication.java:12) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 40 common frames omitted
Caused by: java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:411) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:269) ~[eureka-client-1.9.8.jar:1.9.8]
    at org.springframework.cloud.netflix.eureka.CloudEurekaClient.<init>(CloudEurekaClient.java:63) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.eurekaClient(EurekaClientAutoConfiguration.java:302) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$25bb903d.CGLIB$eurekaClient$0(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$25bb903d$$FastClassBySpringCGLIB$$74fcf26d.invoke(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$25bb903d.eurekaClient(<generated>) ~[spring-cloud-netflix-eureka-client-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 41 common frames omitted

Below is the pom.xml, I am using for Eureka client

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>io.javabrains</groupId>
    <artifactId>movie-info-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>movie-info-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

Below is the main class for Eureka client

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class RatingsDataServiceApplication {

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

}

Body:
Have you tried perform mvn clean install?

and add this dependency

<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-apache-client4</artifactId>
    <version>1.19.4</version>
</dependency>


问:
Geoalchemy2 & ST_Within - type mismatch between point and polygon?
I want to run a query which returns every point which falls within a rectangle, where the points and the rectangle are based on real-world longitudes and latitudes.

This is the query which fails:

```<code>results = session.query(Store.id).filter(func.ST_Within(Store.location, func.ST_GeomFromEWKT('SRID=4326;POLYGON((150 -33, 152 -33, 152 -31, 150 -31, 150 -33))')))
</code>```

It runs without complaint, but when calling results.first(), I see the following errors and warnings:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) function st_within(geography, geometry) does not exist
  LINE 3: WHERE ST_Within(store.location, ST_GeomFromEWKT('SRID=4326;P...
                ^
  HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
   [SQL: 'SELECT store.id AS store_id \nFROM store \nWHERE ST_Within(store.location, ST_GeomFromEWKT(%(ST_GeomFromEWKT_1)s
  )) \n LIMIT %(param_1)s'] [parameters: {'ST_GeomFromEWKT_1': 'SRID=4326;POLYGON((150 -33, 152 -33, 152 -31, 150 -31, 150
   -33))', 'param_1': 1}]

I can make the query work, however, by creating a dummy point in the query (which causes every store to be matched):

```<code>results = session.query(Store.id).filter(func.ST_Within(func.ST_GeomFromEWKT('SRID=4326;POINT(151 -32)'), func.ST_GeomFromEWKT('SRID=4326;POLYGON((150 -33, 152 -33, 152 -31, 150 -31, 150 -33))')))
</code>```

This would indicate that the problem is my Store.location field, but nothing I've tried [including type_coerce(Store.location, Geoography)] has worked.

This is my SQLAlchemy definition for the location column:

```<code>location = Column(Geography(geometry_type='POINT', srid=4326))
</code>```

This is the code I ran to turn longitude & latitude into a location (and I've also tried using func.ST_GeomFromEWKT() to coerce the type):

```<code>stores = session.query(Store)
for store in stores:
    store.location = 'SRID=4326;POINT({} {})'.format(store.longitude, store.latitude)
session.commit()
</code>```

Python tells me that the type of Store.location is 'geoalchemy2.elements.WKBElement', which is what I'd expect from the documentation.

Does anyone have any suggestions on how to fix the query, please?

FYI I'm running:

PostgreSQL 9.6.1

psycopg2 2.6.2

SQLAlchemy 1.1.4, and

Geoalchemy2 0.4.0

答:
If you want to

return every point which falls within a rectangle, where the points and the rectangle are based on real-world longitudes and latitudes

using geography data type, you may use ST_Intersects and ST_Covers, because they support geography data type and give more accurate results.

PostGIS documentation: "Functions on geographies (areas, distances, lengths, intersections, etc) are calculated using arcs on the sphere. By taking the spheroidal shape of the world into account, the functions provide more accurate results."

On the other hand they "take more CPU time to execute" [1]

There is a list of PostGIS Geography Support Functions

Body:
I want to run a query which returns every point which falls within a rectangle, where the points and the rectangle are based on real-world longitudes and latitudes.

This is the query which fails:

results = session.query(Store.id).filter(func.ST_Within(Store.location, func.ST_GeomFromEWKT('SRID=4326;POLYGON((150 -33, 152 -33, 152 -31, 150 -31, 150 -33))')))

It runs without complaint, but when calling results.first(), I see the following errors and warnings:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) function st_within(geography, geometry) does not exist
  LINE 3: WHERE ST_Within(store.location, ST_GeomFromEWKT('SRID=4326;P...
                ^
  HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
   [SQL: 'SELECT store.id AS store_id \nFROM store \nWHERE ST_Within(store.location, ST_GeomFromEWKT(%(ST_GeomFromEWKT_1)s
  )) \n LIMIT %(param_1)s'] [parameters: {'ST_GeomFromEWKT_1': 'SRID=4326;POLYGON((150 -33, 152 -33, 152 -31, 150 -31, 150
   -33))', 'param_1': 1}]

I can make the query work, however, by creating a dummy point in the query (which causes every store to be matched):

results = session.query(Store.id).filter(func.ST_Within(func.ST_GeomFromEWKT('SRID=4326;POINT(151 -32)'), func.ST_GeomFromEWKT('SRID=4326;POLYGON((150 -33, 152 -33, 152 -31, 150 -31, 150 -33))')))

This would indicate that the problem is my Store.location field, but nothing I've tried [including type_coerce(Store.location, Geoography)] has worked.

This is my SQLAlchemy definition for the location column:

location = Column(Geography(geometry_type='POINT', srid=4326))

This is the code I ran to turn longitude & latitude into a location (and I've also tried using func.ST_GeomFromEWKT() to coerce the type):

stores = session.query(Store)
for store in stores:
    store.location = 'SRID=4326;POINT({} {})'.format(store.longitude, store.latitude)
session.commit()

Python tells me that the type of Store.location is 'geoalchemy2.elements.WKBElement', which is what I'd expect from the documentation.

Does anyone have any suggestions on how to fix the query, please?

FYI I'm running:

PostgreSQL 9.6.1

psycopg2 2.6.2

SQLAlchemy 1.1.4, and

Geoalchemy2 0.4.0


问:
EXPECT_THROW - Actual: it throws a different type, google tests
Hi guys so i have this constructor

```<code>Matrix::Matrix(size_t row, size_t col)
{
  if(row < 1 || col < 1)
    throw new std::runtime_error("Minimalni velikost matice je 1x1");
  matrix = std::vector<std::vector< double > >(row,std::vector<double>(col, 0));
}
</code>```

and this test

```<code>Matrix *TestedMatrix;
EXPECT_THROW(TestedMatrix = new Matrix(-2,3),std::runtime_error );
</code>```

but im still getting that exepction is of different type. I also tried std::runtime_error* but result is the same. I wanted use EXPECT_ANY_THROW at first but it was not displayed in my code coverage. Thanks for help ! :)

答:
Assuming that size_t is an alias for std::size_t, you're seeing signed-to-unsigned conversion here (and your compiler should be warning you about that; check that you've enabled sufficient warnings in your build).

-2 gets converted to a very large positive value (very nearly SIZE_MAX), so the likelihood is that the constructor is throwing std::bad_alloc.

You need to pass 0 to the constructor to exercise the code path that throws std::runtime_error*.  (And you can simplify the check to if (!row || !col), since 0 is the only unsigned value less than 1).

```<code>EXPECT_THROW(Matrix(0,3), std::runtime_error*);
EXPECT_THROW(Matrix(3,0), std::runtime_error*);
</code>```

As an aside, I recommend that you throw by value rather than using new.

Body:
Hi guys so i have this constructor

Matrix::Matrix(size_t row, size_t col)
{
  if(row < 1 || col < 1)
    throw new std::runtime_error("Minimalni velikost matice je 1x1");
  matrix = std::vector<std::vector< double > >(row,std::vector<double>(col, 0));
}

and this test

Matrix *TestedMatrix;
EXPECT_THROW(TestedMatrix = new Matrix(-2,3),std::runtime_error );

but im still getting that exepction is of different type. I also tried std::runtime_error* but result is the same. I wanted use EXPECT_ANY_THROW at first but it was not displayed in my code coverage. Thanks for help ! :)

Body:
Assuming that size_t is an alias for std::size_t, you're seeing signed-to-unsigned conversion here (and your compiler should be warning you about that; check that you've enabled sufficient warnings in your build).

-2 gets converted to a very large positive value (very nearly SIZE_MAX), so the likelihood is that the constructor is throwing std::bad_alloc.

You need to pass 0 to the constructor to exercise the code path that throws std::runtime_error*.  (And you can simplify the check to if (!row || !col), since 0 is the only unsigned value less than 1).

EXPECT_THROW(Matrix(0,3), std::runtime_error*);
EXPECT_THROW(Matrix(3,0), std::runtime_error*);

As an aside, I recommend that you throw by value rather than using new.


问:
SwiftUI Text Markdown dynamic string not working
I want to dynamically deliver content and display hyperlinks, but it can’t be delivered dynamically and doesn’t work</p>
```<code>let linkTitle = "Apple Link"
let linkURL = "http://www.apple.com"
let string = "[Apple Link](http://www.apple.com)"

Text(string)        // Not working

Text("[Apple Link](http://www.apple.com)")  // Working

Text("[\(linkTitle)](http://www.apple.com)")    // Working

Text("[\(linkTitle)](\(linkURL))")  // Not working

</code>```

答:
Add another .init in text.

```<code>struct ContentView: View {

    let linkTitle = "Apple Link"
    let linkURL = "http://www.apple.com"
    let string = "[Apple Link](http://www.apple.com)"

    var body: some View {

        Text(.init(string))     // <== Here!

        Text("[Apple Link](http://www.apple.com)")  // Working

        Text("[\(linkTitle)](http://www.apple.com)")    // Working

        Text(.init("[\(linkTitle)](\(linkURL))"))  // <== Here!
    }
}
</code>```

Body:
I want to dynamically deliver content and display hyperlinks, but it can’t be delivered dynamically and doesn’t work

let linkTitle = "Apple Link"
let linkURL = "http://www.apple.com"
let string = "[Apple Link](http://www.apple.com)"

Text(string)        // Not working

Text("[Apple Link](http://www.apple.com)")  // Working

Text("[\(linkTitle)](http://www.apple.com)")    // Working

Text("[\(linkTitle)](\(linkURL))")  // Not working

Body:
Add another .init in text.

struct ContentView: View {

    let linkTitle = "Apple Link"
    let linkURL = "http://www.apple.com"
    let string = "[Apple Link](http://www.apple.com)"

    var body: some View {

        Text(.init(string))     // <== Here!

        Text("[Apple Link](http://www.apple.com)")  // Working

        Text("[\(linkTitle)](http://www.apple.com)")    // Working

        Text(.init("[\(linkTitle)](\(linkURL))"))  // <== Here!
    }
}


问:
Is there a maximum limit to a python array? How to handle large data?
I'm using a simple python array to store words fetched from a file.

```<code>words=[]
words.append(new_word)
</code>```

This code snippet works perfectly for files with small word counts. However when running the script for larger files, it hangs after some time.(when the array length is around 111166 and the letter count inside the array is high)

Is there a maximum limit for a python array?
Is there a workaround to for this?

Thanks in advance.

答:
You may consider using a database if your data gets too big.
a viable option is SQLite which is a simple file-based database.

First create a table for your words

```<code>try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute('''
        CREATE TABLE "words" (
            "id"    INTEGER,
            "word"  TEXT NOT NULL UNIQUE,
            PRIMARY KEY("id" AUTOINCREMENT)
        );
    ''')
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()

</code>```

Now you can start adding words to the table

```<code>my_word = cat

try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute("INSERT INTO words(word) VALUES(?)", [my_word])
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()
</code>```

Now to fetch the word from list do

```<code>search_word = "cat"

try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM words WHERE word=?", [search_word])
    print(cursor.fetchall())
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()
</code>```

Body:
I'm using a simple python array to store words fetched from a file.

words=[]
words.append(new_word)

This code snippet works perfectly for files with small word counts. However when running the script for larger files, it hangs after some time.(when the array length is around 111166 and the letter count inside the array is high)

Is there a maximum limit for a python array?
Is there a workaround to for this?

Thanks in advance.

Body:
You may consider using a database if your data gets too big.
a viable option is SQLite which is a simple file-based database.

First create a table for your words

try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute('''
        CREATE TABLE "words" (
            "id"    INTEGER,
            "word"  TEXT NOT NULL UNIQUE,
            PRIMARY KEY("id" AUTOINCREMENT)
        );
    ''')
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()

Now you can start adding words to the table

my_word = cat

try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute("INSERT INTO words(word) VALUES(?)", [my_word])
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()

Now to fetch the word from list do

search_word = "cat"

try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM words WHERE word=?", [search_word])
    print(cursor.fetchall())
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()


问:
Counter and call duration combination in flutter
```<code>int score = 0;
score += 1;
</code>```

I wish to add 1 (+= 1) to score when call duration reach 30 seconds just once and reset the score to 0 when call duration is less than 30 seconds.

```<code>Text('$score')
</code>```

and show it like this

```<code>import 'package:permission_handler/permission_handler.dart';
import 'package:call_log/call_log.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
</code>```

I have imported 3 packages above

```<code>void callLogs() async {
  Iterable<CallLogEntry> entries = await CallLog.get();
  for (var item in entries) {
    print(Duration());   <--- Use Duration & if statement to solve but duration not printing
   }
 }
</code>```

and code I wrote above is not working as I imagined to even start with. What changes can I make for adding and resetting score to work? Please help and thanks in advance

答:
if you variable score is inside of a widget or in the build method then i think that it set it to the begin value any time you run setState because setState builds the build again and also the widgets that is inside the build.

if that is so then try to make the variable global.

PS: global means that you the variable is outside of your class.

Body:
int score = 0;
score += 1;

I wish to add 1 (+= 1) to score when call duration reach 30 seconds just once and reset the score to 0 when call duration is less than 30 seconds.

Text('$score')

and show it like this

import 'package:permission_handler/permission_handler.dart';
import 'package:call_log/call_log.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';

I have imported 3 packages above

void callLogs() async {
  Iterable<CallLogEntry> entries = await CallLog.get();
  for (var item in entries) {
    print(Duration());   <--- Use Duration & if statement to solve but duration not printing
   }
 }

and code I wrote above is not working as I imagined to even start with. What changes can I make for adding and resetting score to work? Please help and thanks in advance


问:
Java add new functions to library class
The problem:
application uses some library. Like:

```<code>ClassA a=new ClassA();
</code>```

In this library classA uses classB - e.g. call some method from classB.
I need to change how this method works.
Is it possible do without using AOP?
Thanks.

答:
There are two options:

a) modify the source

b) modify the byte code

a) means: download the source, change it, build and use your own version. Drawback: for every new version of the library, you'll need to create a new  patched version

b) For this, AOP (probably using AspectJ) is the easiest way. Other options would be to do it programmatically using commons / bcel or cglib. AOP is easier because you only have to implement the behaviour you want, whereas using byte code manipulation, you would also have to do lots of infrastructure programming (e.g. providing a custom ClassLoader or Java Agent that runs your patch).

Alternative c) is often the best: contact the developer of the library and ask him to provide the functionality you need.

Title: Java add new functions to library class

Body:
The problem:
application uses some library. Like:

ClassA a=new ClassA();

In this library classA uses classB - e.g. call some method from classB.
I need to change how this method works.
Is it possible do without using AOP?
Thanks.