问:
How can I create new array from this JSON response?
I am really struggling to create a new array from this response, I don't know where and how to start or to do it:

```<code>{
    "fruits": [
        {
            "name": "Bananas",
            "pieces": 2469429
        },
        {
            "name": "Oranges",
            "pieces": 1576890
        },
        {
            "name": "Lemons",
            "pieces": 5645318
        }
    ],
    "size": [
        {
            "size": "5000-10,000 eaters",
            "pieces": 17008533
        },
        {
            "size": "100-500 eaters",
            "pieces": 23473914
        },
        {
            "size": "10,001+ eaters",
            "pieces": 68086139
        }
    ],
    "SizeAndFruit": [
        {
            "size": "100-500 eaters",
            "pieces": 226636,
            "name": "Bananas"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 249004,
            "name": "Bananas"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 727829,
            "name": "Bananas"
        },
        {
            "size": "100-500 eaters",
            "pieces": 416310,
            "name": "Lemons"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 488711,
            "name": "Lemons"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 2340652,
            "name": "Lemons"
        },
        {
            "size": "100-500 eaters",
            "pieces": 217037,
            "name": "Oranges"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 71779,
            "name": "Oranges"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 201729,
            "name": "Oranges"
        }
    ]
}
</code>```

I want to get this new structure/array:

```<code>{
    "newArray": [
    {
        "name": "Bananas",
        "totalResults": 2469429,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 226636
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 249004
            },
            {
                "size": "10,001+ eaters",
                "pieces": 727829
            }
        ]
    },
    {
        "name": "Oranges",
        "totalResults": 1576890,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 217037
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 71779
            },
            {
                "size": "10,001+ eaters",
                "pieces": 201729
            }
        ]
    },
    {
        "name": "Lemons",
        "totalResults": 5645318,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 416310
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 488711
            },
            {
                "size": "10,001+ eaters",
                "pieces": 2340652
            }
        ]
    }
]
}
</code>```

How can I make for each fruit to add all sizes as subarray from the sizeAndFruit as the example above? After that each fruit has to be row in a table, that's why I need to get this new array? Please let me know if you have any suggestions or any extra questions I will be glad to explain more if needed. Thank you very much!

Edit for David:
How about if we always order them by size?
Here is the snippet: pastecode.io/s/t82n19x4 so when the order is like this. So, to order them by size as it is now on David's reply, because if these are mixed then they order as they go instead by 100-500 5001-10000 10,000+ they go 10.000+ 100-500 5001-1000, etc.
Thank you!

答:
The below codes reads your inputs and turns it into your desired output (including sorting by size):

<?php

$inputContents = file_get_contents(__DIR__ . '/input.json');
$inputJson = json_decode($inputContents);

$out = [];

foreach ($inputJson->fruits as $fruit) {
    $out[] = [
        'name' => $fruit->name,
        'totalResults' => $fruit->pieces,
        'sortedResults' => [],
    ];
}

foreach ($inputJson->SizeAndFruit as $entry) {
    $newEntry = [
        'size' => $entry->size,
        'pieces' => $entry->pieces,
    ];

    foreach ($out as &$fruit) {
        if ($fruit['name'] === $entry->name) {
            $fruit['sortedResults'][] = $newEntry;
        }
    }
}

/**
 * Get a number of the size from the provided string.
 *
 * @param string $size
 *
 * @return int|null
 */
function sizeStringToNumber(string $size): ?int
{
    $sizes = [
        '100-500 eaters' => 100,
        '5000-10,000 eaters' => 5000,
        '10,001+ eaters' => 10000,
    ];

    if (isset($sizes[$size])) {
        return $sizes[$size];
    }

    throw new \Exception('Unknown size: ' . $size);
}

/**
 * Sort the `sortedResults` array by `size` in ascending order.
 */
foreach ($out as &$fruit) {
    usort($fruit['sortedResults'], function ($a, $b) {
        $aSize = sizeStringToNumber($a['size']);
        $bSize = sizeStringToNumber($b['size']);
        return $aSize <=> $bSize;
    });
}

$outArray = [
    'newArray' => $out,
];
$outJson = json_encode($outArray, JSON_PRETTY_PRINT);

print_r($outJson);
```
<p>Prints as:</p>
<pre class="lang-json prettyprint-override"><code>{
    "newArray": [
        {
            "name": "Bananas",
            "totalResults": 2469429,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 226636
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 249004
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 727829
                }
            ]
        },
        {
            "name": "Oranges",
            "totalResults": 1576890,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 217037
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 71779
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 201729
                }
            ]
        },
        {
            "name": "Lemons",
            "totalResults": 5645318,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 416310
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 488711
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 2340652
                }
            ]
        }
    ]
}
</code>```

Body:
I am really struggling to create a new array from this response, I don't know where and how to start or to do it:

{
    "fruits": [
        {
            "name": "Bananas",
            "pieces": 2469429
        },
        {
            "name": "Oranges",
            "pieces": 1576890
        },
        {
            "name": "Lemons",
            "pieces": 5645318
        }
    ],
    "size": [
        {
            "size": "5000-10,000 eaters",
            "pieces": 17008533
        },
        {
            "size": "100-500 eaters",
            "pieces": 23473914
        },
        {
            "size": "10,001+ eaters",
            "pieces": 68086139
        }
    ],
    "SizeAndFruit": [
        {
            "size": "100-500 eaters",
            "pieces": 226636,
            "name": "Bananas"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 249004,
            "name": "Bananas"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 727829,
            "name": "Bananas"
        },
        {
            "size": "100-500 eaters",
            "pieces": 416310,
            "name": "Lemons"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 488711,
            "name": "Lemons"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 2340652,
            "name": "Lemons"
        },
        {
            "size": "100-500 eaters",
            "pieces": 217037,
            "name": "Oranges"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 71779,
            "name": "Oranges"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 201729,
            "name": "Oranges"
        }
    ]
}

I want to get this new structure/array:

{
    "newArray": [
    {
        "name": "Bananas",
        "totalResults": 2469429,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 226636
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 249004
            },
            {
                "size": "10,001+ eaters",
                "pieces": 727829
            }
        ]
    },
    {
        "name": "Oranges",
        "totalResults": 1576890,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 217037
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 71779
            },
            {
                "size": "10,001+ eaters",
                "pieces": 201729
            }
        ]
    },
    {
        "name": "Lemons",
        "totalResults": 5645318,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 416310
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 488711
            },
            {
                "size": "10,001+ eaters",
                "pieces": 2340652
            }
        ]
    }
]
}

How can I make for each fruit to add all sizes as subarray from the sizeAndFruit as the example above? After that each fruit has to be row in a table, that's why I need to get this new array? Please let me know if you have any suggestions or any extra questions I will be glad to explain more if needed. Thank you very much!

Edit for David:
How about if we always order them by size?
Here is the snippet: pastecode.io/s/t82n19x4 so when the order is like this. So, to order them by size as it is now on David's reply, because if these are mixed then they order as they go instead by 100-500 5001-10000 10,000+ they go 10.000+ 100-500 5001-1000, etc.
Thank you!

Body:
The below codes reads your inputs and turns it into your desired output (including sorting by size):

<?php

$inputContents = file_get_contents(__DIR__ . '/input.json');
$inputJson = json_decode($inputContents);

$out = [];

foreach ($inputJson->fruits as $fruit) {
    $out[] = [
        'name' => $fruit->name,
        'totalResults' => $fruit->pieces,
        'sortedResults' => [],
    ];
}

foreach ($inputJson->SizeAndFruit as $entry) {
    $newEntry = [
        'size' => $entry->size,
        'pieces' => $entry->pieces,
    ];

    foreach ($out as &$fruit) {
        if ($fruit['name'] === $entry->name) {
            $fruit['sortedResults'][] = $newEntry;
        }
    }
}

/**
 * Get a number of the size from the provided string.
 *
 * @param string $size
 *
 * @return int|null
 */
function sizeStringToNumber(string $size): ?int
{
    $sizes = [
        '100-500 eaters' => 100,
        '5000-10,000 eaters' => 5000,
        '10,001+ eaters' => 10000,
    ];

    if (isset($sizes[$size])) {
        return $sizes[$size];
    }

    throw new \Exception('Unknown size: ' . $size);
}

/**
 * Sort the `sortedResults` array by `size` in ascending order.
 */
foreach ($out as &$fruit) {
    usort($fruit['sortedResults'], function ($a, $b) {
        $aSize = sizeStringToNumber($a['size']);
        $bSize = sizeStringToNumber($b['size']);
        return $aSize <=> $bSize;
    });
}

$outArray = [
    'newArray' => $out,
];
$outJson = json_encode($outArray, JSON_PRETTY_PRINT);

print_r($outJson);

Prints as:

{
    "newArray": [
        {
            "name": "Bananas",
            "totalResults": 2469429,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 226636
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 249004
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 727829
                }
            ]
        },
        {
            "name": "Oranges",
            "totalResults": 1576890,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 217037
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 71779
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 201729
                }
            ]
        },
        {
            "name": "Lemons",
            "totalResults": 5645318,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 416310
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 488711
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 2340652
                }
            ]
        }
    ]
}


来源: stackexchange

问:
Is there a hook similar to Class#inherited that's triggered only after a Ruby class definition?
#inherited is called right after the class Foo statement. I want something that'll run only after the end statement that closes the class declaration.

Here's some code to exemplify what I need:

```<code>class Class
  def inherited m
    puts "In #inherited for #{m}"
  end
end

class Foo
  puts "In Foo"
end
puts "I really wanted to have #inherited tiggered here."

### Output:
# In #inherited for Foo
# In Foo
# I really wanted to have #inherited tiggered here.
</code>```

Does anything like that exist? Can it be created? Am I totally out of luck?

答:
I am late, but I think I have an answer (to anyone who visit here).

You can trace until you find the end of the class definition. I did it in a method which I called after_inherited:

```<code>class Class
  def after_inherited child = nil, &blk
    line_class = nil
    set_trace_func(lambda do |event, file, line, id, binding, classname|
      unless line_class
        # save the line of the inherited class entry
        line_class = line if event == 'class'
      else
        # check the end of inherited class
        if line == line_class && event == 'end'
          # if so, turn off the trace and call the block
          set_trace_func nil
          blk.call child
        end
      end
    end)
  end
end

# testing...

class A
  def self.inherited(child)
    after_inherited do
      puts "XXX"
    end
  end
end

class B < A
  puts "YYY"
  # .... code here can include class << self, etc.
end
</code>```

Output:

```<code>YYY
XXX
</code>```

ContentLicense: CC BY-SA 3.0

Body:
#inherited is called right after the class Foo statement. I want something that'll run only after the end statement that closes the class declaration.

Here's some code to exemplify what I need:

class Class
  def inherited m
    puts "In #inherited for #{m}"
  end
end

class Foo
  puts "In Foo"
end
puts "I really wanted to have #inherited tiggered here."

### Output:
# In #inherited for Foo
# In Foo
# I really wanted to have #inherited tiggered here.

Does anything like that exist? Can it be created? Am I totally out of luck?

Body:
I am late, but I think I have an answer (to anyone who visit here).

You can trace until you find the end of the class definition. I did it in a method which I called after_inherited:

class Class
  def after_inherited child = nil, &blk
    line_class = nil
    set_trace_func(lambda do |event, file, line, id, binding, classname|
      unless line_class
        # save the line of the inherited class entry
        line_class = line if event == 'class'
      else
        # check the end of inherited class
        if line == line_class && event == 'end'
          # if so, turn off the trace and call the block
          set_trace_func nil
          blk.call child
        end
      end
    end)
  end
end

# testing...

class A
  def self.inherited(child)
    after_inherited do
      puts "XXX"
    end
  end
end

class B < A
  puts "YYY"
  # .... code here can include class << self, etc.
end

Output:

YYY
XXX


问:
JSON writer doesn't include properties on classes derived from ObservableCollection
I have the following classes:

```<code>public class Goal : ObservableCollection<Activity>
{

  public string Name { get; set; }

  // constructors
  public Goal() { }
  public Goal(string name)
  {

    Name = name;

  }

}

public class Activity
{

  // properties
  public string Name { get; set; }
  public string Details { get; set; }
  public bool FilterMe { get; set; }

  // constructors
  public Activity() { }
  public Activity(string name)
  {

    Name = name;

  }

}
</code>```

When I write this out as JSON, the Activity list with all public Activity properties is output correctly, but the Name property for the Goal is not included. What am I doing wrong?

```<code>// create a goal
Goal goal = new("Goal 1");
for (int a = 0; a < 5; a++)
{
  Activity activity = new($"Activity {a + 1}");
  if (a % 2 == 0) { activity.FilterMe = true; }
  goal.Add(activity);
}

// write the output file
using FileStream fsWrite = File.Create("C:\\Users\\me\\Desktop\\Test.json");
JsonSerializer.Serialize<Goal>(new Utf8JsonWriter(fsWrite, new JsonWriterOptions() { Indented = true }), goal, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, IgnoreReadOnlyProperties = true });
</code>```

Here is sample output:

```<code>{
  "Goal": [
    {
      "Name": "Activity 1",
      "Details": "",
      "FilterMe": true
    },
    {
      "Name": "Activity 2",
      "Details": "",
      "FilterMe": false
    },
    {
      "Name": "Activity 3",
      "Details": "",
      "FilterMe": true
    },
    {
      "Name": "Activity 4",
      "Details": "",
      "FilterMe": false
    },
    {
      "Name": "Activity 5",
      "Details": "",
      "FilterMe": true
    }
  ]
}
</code>```

As you can see in the output above, the Name property for the Goal is missing. It's a public property, so I assumed that the Serializer would pick it up.

答:
it will never be working the way you want, and it is not a serializer problem, it is the way C# creates objects. Even if you try to create json the way you want manually using a text editor,  it will be an invalid json. You will not be able to use it. So the only thing I can recommed you , to change your class to this

```<code>public class Goal
{
    public ObservableCollection<Activity> Goals {get; set;} = new();

  public string Name { get; set; }
   public void Add (Activity activity)
   {
    Goals.Add(activity);
   }

  // constructors
  public Goal() { }
  public Goal(string name)
  {
    Name = name;
  }
}
</code>```

and all your code will be working without any problem

PS.

I would be extremely interested to see a json you want after serialization, please fix json you posted  manually the way you want and show us.

ContentLicense: CC BY-SA 4.0

Body:
I have the following classes:

public class Goal : ObservableCollection<Activity>
{

  public string Name { get; set; }

  // constructors
  public Goal() { }
  public Goal(string name)
  {

    Name = name;

  }

}

public class Activity
{

  // properties
  public string Name { get; set; }
  public string Details { get; set; }
  public bool FilterMe { get; set; }

  // constructors
  public Activity() { }
  public Activity(string name)
  {

    Name = name;

  }

}

When I write this out as JSON, the Activity list with all public Activity properties is output correctly, but the Name property for the Goal is not included. What am I doing wrong?

// create a goal
Goal goal = new("Goal 1");
for (int a = 0; a < 5; a++)
{
  Activity activity = new($"Activity {a + 1}");
  if (a % 2 == 0) { activity.FilterMe = true; }
  goal.Add(activity);
}

// write the output file
using FileStream fsWrite = File.Create("C:\\Users\\me\\Desktop\\Test.json");
JsonSerializer.Serialize<Goal>(new Utf8JsonWriter(fsWrite, new JsonWriterOptions() { Indented = true }), goal, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, IgnoreReadOnlyProperties = true });

Here is sample output:

{
  "Goal": [
    {
      "Name": "Activity 1",
      "Details": "",
      "FilterMe": true
    },
    {
      "Name": "Activity 2",
      "Details": "",
      "FilterMe": false
    },
    {
      "Name": "Activity 3",
      "Details": "",
      "FilterMe": true
    },
    {
      "Name": "Activity 4",
      "Details": "",
      "FilterMe": false
    },
    {
      "Name": "Activity 5",
      "Details": "",
      "FilterMe": true
    }
  ]
}

As you can see in the output above, the Name property for the Goal is missing. It's a public property, so I assumed that the Serializer would pick it up.

Body:
it will never be working the way you want, and it is not a serializer problem, it is the way C# creates objects. Even if you try to create json the way you want manually using a text editor,  it will be an invalid json. You will not be able to use it. So the only thing I can recommed you , to change your class to this

public class Goal
{
    public ObservableCollection<Activity> Goals {get; set;} = new();

  public string Name { get; set; }
   public void Add (Activity activity)
   {
    Goals.Add(activity);
   }

  // constructors
  public Goal() { }
  public Goal(string name)
  {
    Name = name;
  }
}

and all your code will be working without any problem

PS.

I would be extremely interested to see a json you want after serialization, please fix json you posted  manually the way you want and show us.


问:
Difference between pem, crt, key files
I'm having problems understanding the difference between files produced by openssl and how to detect them.

For example I'm trying to generate Self-signed cert with private key and generate JKS file from p12
format. I'm googling like a madman but I still don't know how to generate it correctly to be able to use following commands.

openssl pkcs12 -export -in user.pem -inkey user.key -certfile user.pem -out testkeystore.p12
keytool -importkeystore -srckeystore testkeystore.p12 -srcstoretype pkcs12 -destkeystore wso2carbon.jks -deststoretype JKS
```
<p>Source: https://www.ibm.com/support/pages/how-generate-jks-keystore-existing-private-key</p>
<p>I found a couple of different commands to generate Self-signed cert and private key but I don't know how to map resulting files to the commands above and whats worse I don't understand what those commands do.
I mean I see what files they generate and understand that certificate and private key used to sign it ( or maybe the other way around :| ) but what is the difference between those commands and is cert.pem === certificate.crt - Those file extensions are driving me crazy.</p>
<pre class="lang-bash prettyprint-override"><code>openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
</code>```

This is yet another situation where I'm having similar issues with the openssl command. At this point I'm even ready to read some RFC ( I hope it won't come to this :) )

Thanks in advance for help

答:
.key is the private key. This is accessible the key owner and no one else.

.csr is the certificate request. This is a request for a certificate authority to sign the key. (The key itself is not included.)

.crt is the certificate produced by the certificate authority that verifies the authenticity of the key. (The key itself is not included.) This is given to other parties, e.g. HTTPS client.

.pem is a text-based container using base-64 encoding. It could be any of the above files.

```<code>-----BEGIN EXAMPLE-----
...
-----END EXAMPLE-----
</code>```

.p12 is a PKCS12 file, which is a container format usually used to combine the private key and certificate.

There isn't only one extension. For example you may see certificates with either the .crt or a .pem extension.

Title: Difference between pem, crt, key files

Body:
I'm having problems understanding the difference between files produced by openssl and how to detect them.

For example I'm trying to generate Self-signed cert with private key and generate JKS file from p12
format. I'm googling like a madman but I still don't know how to generate it correctly to be able to use following commands.

openssl pkcs12 -export -in user.pem -inkey user.key -certfile user.pem -out testkeystore.p12
keytool -importkeystore -srckeystore testkeystore.p12 -srcstoretype pkcs12 -destkeystore wso2carbon.jks -deststoretype JKS

Source: https://www.ibm.com/support/pages/how-generate-jks-keystore-existing-private-key

I found a couple of different commands to generate Self-signed cert and private key but I don't know how to map resulting files to the commands above and whats worse I don't understand what those commands do.
I mean I see what files they generate and understand that certificate and private key used to sign it ( or maybe the other way around :| ) but what is the difference between those commands and is cert.pem === certificate.crt - Those file extensions are driving me crazy.

openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

This is yet another situation where I'm having similar issues with the openssl command. At this point I'm even ready to read some RFC ( I hope it won't come to this :) )

Thanks in advance for help

Body:
.key is the private key. This is accessible the key owner and no one else.

.csr is the certificate request. This is a request for a certificate authority to sign the key. (The key itself is not included.)

.crt is the certificate produced by the certificate authority that verifies the authenticity of the key. (The key itself is not included.) This is given to other parties, e.g. HTTPS client.

.pem is a text-based container using base-64 encoding. It could be any of the above files.

-----BEGIN EXAMPLE-----
...
-----END EXAMPLE-----

.p12 is a PKCS12 file, which is a container format usually used to combine the private key and certificate.

There isn't only one extension. For example you may see certificates with either the .crt or a .pem extension.


问:
Is it still loose coupling if we use @qualifier
we use interface for autowiring service into controller

this is for loose coupling , coz the interface can hold object of any of its implementations. so no need to write the implementation name and create tight coupling.

however when we have more than one implementations for an interface, we write the @qualifier .

my question is if we have to write qualifier to tell which implementation needs to be injected, then should we still call it loose coupling??

```<code>class ServiceInterface {
interfaceMethod();
}

implementation 1:
    @component("service1")
    class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){

    }
    }
implementation 2:
    @component("service2")
    class ServiceImpl2 implements ServiceInterface {
    interfaceMethod(){

    }

   now  only instead of directly creating Object of ServiceImpl1() using new
   ServiceImpl1 obj = new ServiceImpl1();
    we write in
    class Controller {
    @autowired
    @qualifier("service1")
    ServiceInterface se;

    sc.interfaceMethod();

    }
</code>```

答:
Even though you are using the @Qualifier annotation you are still using inversion of control to let the framework manage your dependencies.

Furthermore, lets say you wouldn't autowire this implementation but use 'new' to create your object.

When the implementation changes you would need to update all the places where this is created. However, with dependency injection you wouldn't need to do so. Therefore you still have the advantages of dependency injection with regards to loose coupling.

If you would like to have your implementation less coupled with your target class then you could do a few things

Use @Primary for a bean to determine the default implementation.

Autowire your implementations into a List<ServiceInterface>

Use Spring's ObjectFactory to determine which bean to use at runtime

Use Profiles to determine which bean to autowire

Body:
we use interface for autowiring service into controller

this is for loose coupling , coz the interface can hold object of any of its implementations. so no need to write the implementation name and create tight coupling.

however when we have more than one implementations for an interface, we write the @qualifier .

my question is if we have to write qualifier to tell which implementation needs to be injected, then should we still call it loose coupling??

class ServiceInterface {
interfaceMethod();
}

implementation 1:
    @component("service1")
    class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){

    }
    }
implementation 2:
    @component("service2")
    class ServiceImpl2 implements ServiceInterface {
    interfaceMethod(){

    }

   now  only instead of directly creating Object of ServiceImpl1() using new
   ServiceImpl1 obj = new ServiceImpl1();
    we write in
    class Controller {
    @autowired
    @qualifier("service1")
    ServiceInterface se;

    sc.interfaceMethod();

    }


问:
why can't maven find the artifact?
I added a new dependency to my project:

```<code><dependency>
    <groupId>org.jboss.ejb3</groupId>
    <artifactId>jboss-ejb3-ext-api</artifactId>
    <version>2.3.0.Final</version>
</dependency>
</code>```

but I get following error:

```<code>[ERROR] Failed to execute goal on project myproject-ejb: Could not resolve dependencies for project com.myproject.site:myproject-ejb:ejb:2.14.0: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project myproject-ejb: Could not resolve dependencies for project com.myproject.site:myproject-ejb:ejb:2.14.0: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:269)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project com.myproject.site:myproject-ejb:ejb:2.14.0: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:208)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.eclipse.aether.resolution.DependencyResolutionException: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies (DefaultRepositorySystem.java:342)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:202)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve (DefaultArtifactResolver.java:413)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts (DefaultArtifactResolver.java:215)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies (DefaultRepositorySystem.java:325)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:202)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException (DefaultUpdateCheckManager.java:217)
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact (DefaultUpdateCheckManager.java:192)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads (DefaultArtifactResolver.java:554)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads (DefaultArtifactResolver.java:472)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve (DefaultArtifactResolver.java:390)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts (DefaultArtifactResolver.java:215)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies (DefaultRepositorySystem.java:325)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:202)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
</code>```

when I manually look at https://repo.maven.apache.org/maven2/org/jboss/ejb3/jboss-ejb3-ext-api/2.3.0.Final/ then I can find it.

What's with the exception message about "cached in the local repository"? I hoped maven would download it from the central repository.

I don't understand how maven finds everything else, just not this artifact. Any Help?

答: That is based on an earlier trial which has failed possible based on network issues etc. which results in having some partial artifacts in your local cache ($HOME/.m2/repository). Just try mvn -U package

Title: why can't maven find the artifact?

Body:
I added a new dependency to my project:

<dependency>
    <groupId>org.jboss.ejb3</groupId>
    <artifactId>jboss-ejb3-ext-api</artifactId>
    <version>2.3.0.Final</version>
</dependency>

but I get following error:

[ERROR] Failed to execute goal on project myproject-ejb: Could not resolve dependencies for project com.myproject.site:myproject-ejb:ejb:2.14.0: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project myproject-ejb: Could not resolve dependencies for project com.myproject.site:myproject-ejb:ejb:2.14.0: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:269)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project com.myproject.site:myproject-ejb:ejb:2.14.0: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:208)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.eclipse.aether.resolution.DependencyResolutionException: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies (DefaultRepositorySystem.java:342)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:202)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve (DefaultArtifactResolver.java:413)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts (DefaultArtifactResolver.java:215)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies (DefaultRepositorySystem.java:325)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:202)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Failure to find org.jboss.ejb3:jboss-ejb3-ext-api:jar:2.3.0.Final in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException (DefaultUpdateCheckManager.java:217)
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact (DefaultUpdateCheckManager.java:192)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads (DefaultArtifactResolver.java:554)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads (DefaultArtifactResolver.java:472)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve (DefaultArtifactResolver.java:390)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts (DefaultArtifactResolver.java:215)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies (DefaultRepositorySystem.java:325)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:202)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:243)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:147)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:248)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:202)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:64)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)

when I manually look at https://repo.maven.apache.org/maven2/org/jboss/ejb3/jboss-ejb3-ext-api/2.3.0.Final/ then I can find it.

What's with the exception message about "cached in the local repository"? I hoped maven would download it from the central repository.

I don't understand how maven finds everything else, just not this artifact. Any Help?


问:
Replace external jar dependency with local intellij project
So I have an intellij IDEA project (project A) which includes a bunch of external jar libraries. I am currently working on one of those external jar libraries (project B) and I want to replace it with the local project (project B) on my computer.

So, in short:
I have Project A which depends on jar B
I want to replace jar B with my local project (project B)

That way, when I run project A, it uses Project B local rather than Jar B external. Anyone know any good easy ways of doing this?

答:
Since you have the tag "gradle", I'm assuming you are using it for both projects. Run "gradle publishToMavenLocal" in project B and then refresh the dependencies of project A.

Just make sure you remember you did this and delete project B from your local repository when you are done with it.


问:
Efficient way to get closest pay day to a given date
I'm trying to figure out the most efficient way to find the closest payday from a given date.

Let's say we know payday are every 14 days and that January 6, 2022 was one of them. What is the most efficient way to find the next payday for a given date (the date is the beginning of a week actually) from a known payday?

Here is a current working ugly implementation

```<code>    def payday_first_date
      # TODO: Very reliable, but very inefficient
      @payday_first_date ||= begin
        date = known_pay_day
        date -= 14.days until date < given_date
        date += 14.days until date > given_date
        date
      end
    end

    def known_pay_day
      # Thursday January 6, 2022 was a payday
      @known_pay_day ||= Date.new(2022, 2, 17)
    end
</code>```

The given_date could be in the future and also in the past. It can be a date from another year aswell.

Thanks in advance!

答:
First define the known pay date and two helper methods.

```<code>require 'date'
</code>```

```<code>def date_str_to_date_obj(date_str)
  DateTime.strptime(date_str, "%B %d, %Y").to_date
end
</code>```

```<code>known_date = date_str_to_date_obj("January 6, 2022")
  #=> #<Date: 2022-01-06 ((2459586j,0s,0n),+0s,2299161j)>
</code>```

For presentation only:

```<code>def date_obj_to_date_str(date_obj)
  date_obj.strftime("%B %d, %Y, %A")
end
</code>```

```<code>date_obj_to_date_str(known_date)
  #=> "January 06, 2022, Thursday"
</code>```

The main method follows.

```<code>def closest_pay_day(known_date, target_date)
  nbr_pay_dates    = (target_date - known_date)/14.0
  last_pay_date    = known_date + nbr_pay_dates.floor * 14
  next_pay_date    = last_pay_date + 14
  (next_pay_date - target_date < target_date - last_pay_date) ?
  next_pay_date : last_pay_date
end
</code>```

Suppose the target date is after the known pay date.

```<code>target_date_str = "March 26, 2022"
</code>```

Then

```<code>target_date = date_str_to_date_obj(target_date_str)
  #=> #<Date: 2022-03-26 ((2459665j,0s,0n),+0s,2299161j)>
date_obj_to_date_str(target_date)
  #=> "March 26, 2022, Saturday"
</code>```

The closest pay period to the target date is therefore

```<code>closest = closest_pay_day(known_date, target_date)
  #=> #<Date: 2022-03-31 ((2459670j,0s,0n),+0s,2299161j)>
date_obj_to_date_str(closest)
  #=> "March 31, 2022, Thursday"
</code>```

which is

```<code>(target_date- closest).to_i
  #=> -5
</code>```

days before the target date, meaning 5 days after the target date.

Now suppose the target date is before the known pay date.

```<code>target_date_str = "October 19, 2021"
</code>```

Then

```<code>target_date = date_str_to_date_obj(target_date_str)
  #=> #<Date: 2021-10-19 ((2459507j,0s,0n),+0s,2299161j)>
date_obj_to_date_str(target_date)
  #=> "October 19, 2021, Tuesday"
</code>```

```<code>date_obj_to_date_str(closest_pay_day(known_date, target_date))
  #=> "October 14, 2021, Thursday"
</code>```

Body:
I'm trying to figure out the most efficient way to find the closest payday from a given date.

Let's say we know payday are every 14 days and that January 6, 2022 was one of them. What is the most efficient way to find the next payday for a given date (the date is the beginning of a week actually) from a known payday?

Here is a current working ugly implementation

    def payday_first_date
      # TODO: Very reliable, but very inefficient
      @payday_first_date ||= begin
        date = known_pay_day
        date -= 14.days until date < given_date
        date += 14.days until date > given_date
        date
      end
    end

    def known_pay_day
      # Thursday January 6, 2022 was a payday
      @known_pay_day ||= Date.new(2022, 2, 17)
    end

The given_date could be in the future and also in the past. It can be a date from another year aswell.

Thanks in advance!

Body:
First define the known pay date and two helper methods.

require 'date'

def date_str_to_date_obj(date_str)
  DateTime.strptime(date_str, "%B %d, %Y").to_date
end

known_date = date_str_to_date_obj("January 6, 2022")
  #=> #<Date: 2022-01-06 ((2459586j,0s,0n),+0s,2299161j)>

For presentation only:

def date_obj_to_date_str(date_obj)
  date_obj.strftime("%B %d, %Y, %A")
end

date_obj_to_date_str(known_date)
  #=> "January 06, 2022, Thursday"

The main method follows.

def closest_pay_day(known_date, target_date)
  nbr_pay_dates    = (target_date - known_date)/14.0
  last_pay_date    = known_date + nbr_pay_dates.floor * 14
  next_pay_date    = last_pay_date + 14
  (next_pay_date - target_date < target_date - last_pay_date) ?
  next_pay_date : last_pay_date
end

Suppose the target date is after the known pay date.

target_date_str = "March 26, 2022"

Then

target_date = date_str_to_date_obj(target_date_str)
  #=> #<Date: 2022-03-26 ((2459665j,0s,0n),+0s,2299161j)>
date_obj_to_date_str(target_date)
  #=> "March 26, 2022, Saturday"

The closest pay period to the target date is therefore

closest = closest_pay_day(known_date, target_date)
  #=> #<Date: 2022-03-31 ((2459670j,0s,0n),+0s,2299161j)>
date_obj_to_date_str(closest)
  #=> "March 31, 2022, Thursday"

which is

(target_date- closest).to_i
  #=> -5

days before the target date, meaning 5 days after the target date.

Now suppose the target date is before the known pay date.

target_date_str = "October 19, 2021"

Then

target_date = date_str_to_date_obj(target_date_str)
  #=> #<Date: 2021-10-19 ((2459507j,0s,0n),+0s,2299161j)>
date_obj_to_date_str(target_date)
  #=> "October 19, 2021, Tuesday"

date_obj_to_date_str(closest_pay_day(known_date, target_date))
  #=> "October 14, 2021, Thursday"


问:
Error when installing and loading libraries from list in R
I have a function that loads libraries from a list, and installs packages if required:

```<code># List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
    if (!require(x, character.only = T)) {
        install.packages(x)
        library(x)
    }
}

# Load packages
invisible(lapply(lib_List, loadLibrary))
</code>```

For example, in this case library "caret" is not installed. Running the loadLibrary function, the package gets downloaded and installed but this is followed by an error and the library is not loaded. Below the output from the R console:

```<code>Load required package: caret
--- Please select a CRAN mirror for use in this session ---
# Now download notifications follow
The downloaded binary packages are in
    /var/folders/8p/b3t6spn133z5s69hpj1hf4hc0000gn/T//Rtmp8VNEII/downloaded_packages

Error in library(x) : there is no package called ‘x’
In addition: Warning:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘caret’

sessionInfo()
other attached packages:
[1] scales_1.1.1   ggplot2_3.3.5   dplyr_1.0.7
</code>```

If I now run the loadLibrary function again, the new installed package gets loaded:

```<code>invisible(lapply(lib_List, loadLibrary))
Load package: caret

sessionInfo()
other attached packages:
[1] caret_6.0-90   lattice_0.20-45   scales_1.1.1    ggplot2_3.3.5   dplyr_1.0.7
</code>```

Why is the package not loaded the first time I run the loadLibrary function?

答:
Consider using pacman. You can achieve the same outcome with one line using p_load:

```<code>pacman::p_load(dplyr, ggplot2, scales, caret, install = TRUE)
</code>```

Body:
I have a function that loads libraries from a list, and installs packages if required:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
    if (!require(x, character.only = T)) {
        install.packages(x)
        library(x)
    }
}

# Load packages
invisible(lapply(lib_List, loadLibrary))

For example, in this case library "caret" is not installed. Running the loadLibrary function, the package gets downloaded and installed but this is followed by an error and the library is not loaded. Below the output from the R console:

Load required package: caret
--- Please select a CRAN mirror for use in this session ---
# Now download notifications follow
The downloaded binary packages are in
    /var/folders/8p/b3t6spn133z5s69hpj1hf4hc0000gn/T//Rtmp8VNEII/downloaded_packages

Error in library(x) : there is no package called ‘x’
In addition: Warning:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘caret’

sessionInfo()
other attached packages:
[1] scales_1.1.1   ggplot2_3.3.5   dplyr_1.0.7

If I now run the loadLibrary function again, the new installed package gets loaded:

invisible(lapply(lib_List, loadLibrary))
Load package: caret

sessionInfo()
other attached packages:
[1] caret_6.0-90   lattice_0.20-45   scales_1.1.1    ggplot2_3.3.5   dplyr_1.0.7

Why is the package not loaded the first time I run the loadLibrary function?

Body:
Consider using pacman. You can achieve the same outcome with one line using p_load:

pacman::p_load(dplyr, ggplot2, scales, caret, install = TRUE)


问:
how to show stars based on user rating?
i woud like to show star based on rating . i can only show one product with rating stars and the other products don't show any star only show rating number. could help to check which part need to change ?

```<code><%- include ('_layouts/header'); -%>
<h1>......Exciting Books.....</h1>
 <hr size="100" width="100%" align="center" color="black">
    <br>
 <div class="row products">

    <% savedexcit.forEach(function(products){ %>
            <div class="col-xs-12 col-md-4 p shop-item">
                 <a class="pa" href="/products/<%= products.category %>/<%= products.slug %>">
                    <img class="pimage" src="/product_images/<%= products.id %>/<%= products.image %>" alt="">
                    </a>
                <h3><%= products.title %></h3>
                <b>Rating: <span id=stars></span><%= products.rating %>/5</b>
                <a class="vd" href="/products/<%= products.category %>/<%= products.slug %>">View Details</a>
            </div>
        <% }); %>
</div>
<script>
 <% savedexcit.forEach(function(products){ %>
document.getElementById("stars").innerHTML = getStars(<%= products.rating %>);

function getStars(rating) {

  // Round to nearest half
  rating = Math.round(rating * 2) / 2;
  let output = [];

  // Append all the filled whole stars
  for (var i = rating; i >= 1; i--)
    output.push('<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i> ');

  // If there is a half a star, append it
  if (i == .5) output.push('<i class="fa fa-star-half-o" aria-hidden="true" style="color: gold;"></i> ');

  // Fill the empty stars
  for (let i = (5 - rating); i >= 1; i--)
    output.push('<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i> ');

  return output.join('');

}
<% }); %>
</script>
    <%- include ('_layouts/footer'); -%>
</code>```

output result:

答:
Edit: I have edited the answer to be more specific. Also, I believe this to be ejs template just to be more clear.

Id in html is used for identifying individual element and Checking your code there are two places where ID is wrongly declared, that is you are declaring it multiple times.

In the Creation section for row

```<code><h3><%= products.title %></h3>
                <b>Rating: <span id=stars></span><%= products.rating %>/5</b>
</code>```

In the script tag where you are accessing id

```<code> <% savedexcit.forEach(function(products){ %>
document.getElementById("stars").innerHTML = getStars(<%= products.rating %>);
</code>```

To solve this issue you either need to add different ids, which you can do simply by adding a counter to it or you need to add a class on the star and use it to access the elements or just access it by using class. You can try to do the following changes and this should solve the issue hopefully

Access the index for it by including a variable(index) in the callback function.

```<code><% savedexcit.forEach(function(products, index){ %>
           <div class="col-xs-12 col-md-4 p shop-item">
                <a class="pa" href="/products/<%= products.category %>/<%= products.slug %>">
                   <img class="pimage" src="/product_images/<%= products.id %>/<%= products.image %>" alt="">
                   </a>
               <h3><%= products.title %></h3>
               <b>Rating: <span id="stars<%= index %>">></span><%= products.rating %>/5</b>

</code>```

Then make the same change inside the script tag as below

```<code> <% savedexcit.forEach(function(products,index){ %>
document.getElementById("stars<%= index %>").innerHTML = getStars(<%= products.rating %>);

</code>```

This should change target the specific element id.

Title: how to show stars based on user rating?

Body:
i woud like to show star based on rating . i can only show one product with rating stars and the other products don't show any star only show rating number. could help to check which part need to change ?

<%- include ('_layouts/header'); -%>

......Exciting Books.....

    <% savedexcit.forEach(function(products){ %>

                 <a class="pa" href="/products/<%= products.category %>/<%= products.slug %>">
                    <img class="pimage" src="/product_images/<%= products.id %>/<%= products.image %>" alt="">

<%= products.title %>

                Rating: <%= products.rating %>/5
                <a class="vd" href="/products/<%= products.category %>/<%= products.slug %>">View Details

        <% }); %>

    <%- include ('_layouts/footer'); -%>

output result:

Body:
Edit: I have edited the answer to be more specific. Also, I believe this to be ejs template just to be more clear.

Id in html is used for identifying individual element and Checking your code there are two places where ID is wrongly declared, that is you are declaring it multiple times.

In the Creation section for row

<h3><%= products.title %></h3>
                <b>Rating: <span id=stars></span><%= products.rating %>/5</b>

In the script tag where you are accessing id

 <% savedexcit.forEach(function(products){ %>
document.getElementById("stars").innerHTML = getStars(<%= products.rating %>);

To solve this issue you either need to add different ids, which you can do simply by adding a counter to it or you need to add a class on the star and use it to access the elements or just access it by using class. You can try to do the following changes and this should solve the issue hopefully

Access the index for it by including a variable(index) in the callback function.

<% savedexcit.forEach(function(products, index){ %>
           <div class="col-xs-12 col-md-4 p shop-item">
                <a class="pa" href="/products/<%= products.category %>/<%= products.slug %>">
                   <img class="pimage" src="/product_images/<%= products.id %>/<%= products.image %>" alt="">
                   </a>
               <h3><%= products.title %></h3>
               <b>Rating: <span id="stars<%= index %>">></span><%= products.rating %>/5</b>

Then make the same change inside the script tag as below

 <% savedexcit.forEach(function(products,index){ %>
document.getElementById("stars<%= index %>").innerHTML = getStars(<%= products.rating %>);

This should change target the specific element id.


问:
Magento: Problem in getting custom attribute value of a grouped product in IE and Chrome in Magento
$_product->getData doesn't work for grouped product image custom attribute :(

```<code>$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
echo $_product->getData('item_front_view');
</code>```

This code works for FF, Opera & Safari.
But doesn't working in IE and Chrome

I am using Magento 1.5.1.0
Here i am facing a strange problem.
Can anyone please help me?

答:
The problem solved automatically after i come back to office on this day. May be its browser cache problem.

If anyone have the same problem try restarting the pc.

Body:
$_product->getData doesn't work for grouped product image custom attribute :(

$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
echo $_product->getData('item_front_view');

This code works for FF, Opera & Safari.
But doesn't working in IE and Chrome

I am using Magento 1.5.1.0
Here i am facing a strange problem.
Can anyone please help me?


问:
if typeOf f == io then f else return . f in Haskell?
Related to

https://stackoverflow.com/a/71020780/17053359

We can lift non-IO functions : f to IO ones with return, as in

```<code>return . f
</code>```

and now, I want to make this f generic including IO

```<code>f :: A -> IO A -- not IO to IO
f :: IO a -> IO a -- (no change, `id` instead of `return`)
</code>```

in other words:

if typeOf f == io then f

else return . f

What would the code be in Haskell?

EDIT:

console.log(
 Object(1)
);

console.log(
 Object(Object(1))
);

console.log(
 Object(Object(Object(1)))
);```

答:
Answered by myself.

I totally have no idea what's wrong with my question, perhaps my way to ask is not sufficient. At least, I have mentioned idempotency and with my sample snippet JS. but here is my simple solution.

```<code>(+++) :: (a -> b) -> (b -> c) -> a -> c
(+++) = flip (.)

infixl 9 +++

someFunctor :: Show a => (a -> IO b) -> IO (R a) -> IO (R b)
someFunctor = \f -> \ioA -> do
  print "-- someFunctor"

  val <- ioA >>= _val

  b <- (f +++ return +++ join) val

  io b
</code>```

based on the code of my previous Q&A:

https://stackoverflow.com/a/71020780/17053359

Body:
Related to

https://stackoverflow.com/a/71020780/17053359

We can lift non-IO functions : f to IO ones with return, as in

return . f

and now, I want to make this f generic including IO

f :: A -> IO A -- not IO to IO
f :: IO a -> IO a -- (no change, `id` instead of `return`)

in other words:

if typeOf f == io then f

else return . f

What would the code be in Haskell?

EDIT:

console.log(
 Object(1)
);

console.log(
 Object(Object(1))
);

console.log(
 Object(Object(Object(1)))
);

Body:
Answered by myself.

I totally have no idea what's wrong with my question, perhaps my way to ask is not sufficient. At least, I have mentioned idempotency and with my sample snippet JS. but here is my simple solution.

(+++) :: (a -> b) -> (b -> c) -> a -> c
(+++) = flip (.)

infixl 9 +++

someFunctor :: Show a => (a -> IO b) -> IO (R a) -> IO (R b)
someFunctor = \f -> \ioA -> do
  print "-- someFunctor"

  val <- ioA >>= _val

  b <- (f +++ return +++ join) val

  io b

based on the code of my previous Q&A:

https://stackoverflow.com/a/71020780/17053359


问:
Skip irelevant text from some of bars in plotly bar chart
I create a simple plotly bar chart but inside the first columns I get a weird text that I need to delete.</p>
```<code>library(plotly)
sum2<-structure(list(month = structure(c(1451606400, 1454284800, 1456790400,
1459468800, 1462060800, 1464739200, 1467331200, 1470009600, 1472688000,
1475280000), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    Monthly = c(14236.895, 4519.892, 55691.009, 28295.345, 23648.287,
    34595.1276, 33946.393, 27909.4685, 81777.3508, 31453.393)), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

fig <- plot_ly(sum2, x = ~month, y = ~Monthly, type = 'bar', text = text,
               marker = list(color = 'rgb(158,202,225)',
                             line = list(color = 'rgb(8,48,107)',
                                         width = 1.5))
)
fig <- fig %>% layout( width=1800,height=600
)

fig
</code>```

答:
Not sure what you were doing with text = text but just remove that line and it looks fine.

plot_ly(
  sum2,
  x = ~ month,
  y = ~ Monthly,
  type = 'bar',
  # text = text,
  marker = list(
    color = 'rgb(158,202,225)',
    line = list(color = 'rgb(8,48,107)',
                width = 1.5)
  )
)
```
<p><img src="https://i.stack.imgur.com/Dnyx2.png" alt="enter image description here" /></p>
<hr />
<p>This happens because <code>text</code> is referring to the function <code>graphics::text()</code> and when called without parentheses it just gives the report of that object with that name. Try just running <code>text</code> at the console (without parentheses) and you'll see what was getting passed as labels to your plot.</p>
<pre class="lang-r prettyprint-override"><code>text
#> function (x, ...)
#> UseMethod("text")
#> <bytecode: 0x0000000013994f20>
#> <environment: namespace:graphics>
</code>```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
I create a simple plotly bar chart but inside the first columns I get a weird text that I need to delete.

library(plotly)
sum2<-structure(list(month = structure(c(1451606400, 1454284800, 1456790400,
1459468800, 1462060800, 1464739200, 1467331200, 1470009600, 1472688000,
1475280000), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    Monthly = c(14236.895, 4519.892, 55691.009, 28295.345, 23648.287,
    34595.1276, 33946.393, 27909.4685, 81777.3508, 31453.393)), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

fig <- plot_ly(sum2, x = ~month, y = ~Monthly, type = 'bar', text = text,
               marker = list(color = 'rgb(158,202,225)',
                             line = list(color = 'rgb(8,48,107)',
                                         width = 1.5))
)
fig <- fig %>% layout( width=1800,height=600
)

fig

Body:
Not sure what you were doing with text = text but just remove that line and it looks fine.

plot_ly(
  sum2,
  x = ~ month,
  y = ~ Monthly,
  type = 'bar',
  # text = text,
  marker = list(
    color = 'rgb(158,202,225)',
    line = list(color = 'rgb(8,48,107)',
                width = 1.5)
  )
)

This happens because text is referring to the function graphics::text() and when called without parentheses it just gives the report of that object with that name. Try just running text at the console (without parentheses) and you'll see what was getting passed as labels to your plot.

text
#> function (x, ...)
#> UseMethod("text")
#> <bytecode: 0x0000000013994f20>
#> <environment: namespace:graphics>

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Imagemagick, windows cmd (or similar windows console app) equivalent of "Head", piping line 1, specific characters to a .ppm file
First time posting to stackoverflow. Thanks for the help.

I need to create a .ppm file based off the most dominant color in an image's color histogram. I'm using imagemagick. I need it to work in windows.

To do so, I need a windows command equivalent of sort, head, sed: (eg: | sort -n -k 4 | head -n 1 | sed 's/.*(//' | sed 's/,/ /g' | sed 's/ 0)//g')

Main command for imagemagick (works in bash / windows git-bash.exe, needs to work in windows native):

```<code>magick convert 'BMW_logo_(gray).png' -colors 5 -depth 8 -format "%c" histogram:info: | sort -n -k 4 | head -n 1 | sed 's/.*(//' | sed 's/,/ /g' | sed 's/ 0)//g'
</code>```

Output (most dominant color):

```<code>107 116 122
</code>```

These results need piped to a file and then prepended with the PPM file prerequisites of P3 1 1 255 , in windows via cmd or other process that can be automated.

Eg: P3 1 1 255 107 116 122 in a ppm file would produce a 1x1 pixel, with 255 max levels, of gray color (rgb 107 116 122).

File to pipe results to:

```<code>results.ppm
</code>```

And then perform

```<code>&& del ppmsetup.ppm && echo P3 1 1 255 >ppmsetup.ppm && type results.ppm>>ppmsetup.ppm
</code>```

Which would:

1.) Delete old ppmsetup.ppm file

2.) Write ppm prerequisites to ppmsetup.ppm

3.) Prepend ppm prerequisites (ppmsetup.ppm) to results.ppm

This .ppm file will be linked in a photoshop document as a linked smart object. I'm making an artificially intelligent designer, this is one portion.

Any help on this would be greatly appreciated and likely a great contribution to this community (because it's so fun).

Additional notes, please stop reading unless the above is not possible:
Alternatively, doing all the same operations in git-bash.exe may work... the process starts with a user passing the file variable through windows command (QtTabBar UI shortcut passes file variable to a command line), and the file lands in a hot folder, where a hotfolder.sh script invokes runhotfolder.cmd (launches photoshop and other programs) which could run in parallel with the magick command if it was possible to pass the file variable to runhotfolder.sh, immediately before . ../functions/"$FUNCTION".cmd on line ~39:

```<code>#!/bin/bash
FUNCTION=runhotfolder
# Finding path to itself
RELPATH=$(dirname "$0")
# cd into it
cd "$RELPATH"
#make 3 new directories
mkdir in out processing
# mechanism to restart converting videos if script was aborted(computer shutdown)
FOLDERSIZE=`du -s processing | cut -f1`
# find processing/ -type f -iname *_converted* -exec rm -f {} \;
find processing/ -type f \( -name '*_converted*' -or -name '*_compressed*' \) -exec rm -f {} \;
mv processing/* in
#open a loop
while :
do
if ! [ "$(ls -A in)" ]; then
    echo 'The "in" Folder is Empty'
    # to reduce processing load lets wait some seconds till we check again.
    sleep 5
else
    echo 'Oh something is in the "in" Folder let us watch it more closely'
    #check the size of folder in, wait 5 second check again.
    FOLDERSIZE1=`du -s in | cut -f1`
    echo $FOLDERSIZE1
    sleep 2
    FOLDERSIZE2=`du -s in | cut -f1`
    echo $FOLDERSIZE2
    sleep 2
        # if the first and secod time the foldersize didn't change and is grater than 0 start processing (we then assume that the copying into the in folder is finished)
        if [ "$FOLDERSIZE1" -eq "$FOLDERSIZE2" ] && [ "$FOLDERSIZE2" -gt 0 ]; then
            # Start Processing > Enter your code here
            # move content from in folder to processing folder
            mv in/* processing
            # go into processing folder / make it current path
            cd ./processing
            # load a script from functions / here it actually starts the processing of the data
            # replaced source with . for bigger compatibility
            . ../functions/"$FUNCTION".cmd
            # go up one level (because in the rest of the script we assume to be at the base level of our folderstructure)
            cd ..
        else
            # this is somehow obsolete now but if there was a file with size 0 placed in the in folder this is where we would land.
            echo Size of in is still changing we assume someone is still copying their data into it.
            echo OR someone placed a file with size 0 in the in folder
        fi
fi
done
</code>```

答:
Correct answer:

```<code>magick convert 'BMW_logo_(gray).png' -colors 5 -depth 8 -format "%c" histogram:info: | Sort-Object | Select -First 1 | Foreach-Object {$_ -replace ",", " "} | Foreach-Object {$_ -replace "^.*?\("} | Foreach-Object {$_ -replace '0\).*'}
</code>```

CMD is built for managing basic files. To have custom outputs etc. you'll need to use powershell. Powershell equivalents for sort, head and sed are above.

Full answer, writing to a ppm file:

```<code>magick convert 'BMW_logo_(gray).png' -colors 5 -depth 8 -format "%c" histogram:info: | Sort-Object | Select -First 1 | Foreach-Object {$_ -replace ",", " "} | Foreach-Object {$_ -replace "^.*?\("} | Foreach-Object {$_ -replace '0\).*'} | Out-File -Path results.ppm && "P3 1 1 255 " + (Get-Content results.ppm -Raw) | Set-Content results.ppm
</code>```

Body:
First time posting to stackoverflow. Thanks for the help.

I need to create a .ppm file based off the most dominant color in an image's color histogram. I'm using imagemagick. I need it to work in windows.

To do so, I need a windows command equivalent of sort, head, sed: (eg: | sort -n -k 4 | head -n 1 | sed 's/.*(//' | sed 's/,/ /g' | sed 's/ 0)//g')

Main command for imagemagick (works in bash / windows git-bash.exe, needs to work in windows native):

magick convert 'BMW_logo_(gray).png' -colors 5 -depth 8 -format "%c" histogram:info: | sort -n -k 4 | head -n 1 | sed 's/.*(//' | sed 's/,/ /g' | sed 's/ 0)//g'

Output (most dominant color):

107 116 122

These results need piped to a file and then prepended with the PPM file prerequisites of P3 1 1 255 , in windows via cmd or other process that can be automated.

Eg: P3 1 1 255 107 116 122 in a ppm file would produce a 1x1 pixel, with 255 max levels, of gray color (rgb 107 116 122).

File to pipe results to:

results.ppm

And then perform

&& del ppmsetup.ppm && echo P3 1 1 255 >ppmsetup.ppm && type results.ppm>>ppmsetup.ppm

Which would:

1.) Delete old ppmsetup.ppm file

2.) Write ppm prerequisites to ppmsetup.ppm

3.) Prepend ppm prerequisites (ppmsetup.ppm) to results.ppm

This .ppm file will be linked in a photoshop document as a linked smart object. I'm making an artificially intelligent designer, this is one portion.

Any help on this would be greatly appreciated and likely a great contribution to this community (because it's so fun).

Additional notes, please stop reading unless the above is not possible:
Alternatively, doing all the same operations in git-bash.exe may work... the process starts with a user passing the file variable through windows command (QtTabBar UI shortcut passes file variable to a command line), and the file lands in a hot folder, where a hotfolder.sh script invokes runhotfolder.cmd (launches photoshop and other programs) which could run in parallel with the magick command if it was possible to pass the file variable to runhotfolder.sh, immediately before . ../functions/"$FUNCTION".cmd on line ~39:

#!/bin/bash
FUNCTION=runhotfolder
# Finding path to itself
RELPATH=$(dirname "$0")
# cd into it
cd "$RELPATH"
#make 3 new directories
mkdir in out processing
# mechanism to restart converting videos if script was aborted(computer shutdown)
FOLDERSIZE=`du -s processing | cut -f1`
# find processing/ -type f -iname *_converted* -exec rm -f {} \;
find processing/ -type f \( -name '*_converted*' -or -name '*_compressed*' \) -exec rm -f {} \;
mv processing/* in
#open a loop
while :
do
if ! [ "$(ls -A in)" ]; then
    echo 'The "in" Folder is Empty'
    # to reduce processing load lets wait some seconds till we check again.
    sleep 5
else
    echo 'Oh something is in the "in" Folder let us watch it more closely'
    #check the size of folder in, wait 5 second check again.
    FOLDERSIZE1=`du -s in | cut -f1`
    echo $FOLDERSIZE1
    sleep 2
    FOLDERSIZE2=`du -s in | cut -f1`
    echo $FOLDERSIZE2
    sleep 2
        # if the first and secod time the foldersize didn't change and is grater than 0 start processing (we then assume that the copying into the in folder is finished)
        if [ "$FOLDERSIZE1" -eq "$FOLDERSIZE2" ] && [ "$FOLDERSIZE2" -gt 0 ]; then
            # Start Processing > Enter your code here
            # move content from in folder to processing folder
            mv in/* processing
            # go into processing folder / make it current path
            cd ./processing
            # load a script from functions / here it actually starts the processing of the data
            # replaced source with . for bigger compatibility
            . ../functions/"$FUNCTION".cmd
            # go up one level (because in the rest of the script we assume to be at the base level of our folderstructure)
            cd ..
        else
            # this is somehow obsolete now but if there was a file with size 0 placed in the in folder this is where we would land.
            echo Size of in is still changing we assume someone is still copying their data into it.
            echo OR someone placed a file with size 0 in the in folder
        fi
fi
done

Body:
Correct answer:

magick convert 'BMW_logo_(gray).png' -colors 5 -depth 8 -format "%c" histogram:info: | Sort-Object | Select -First 1 | Foreach-Object {$_ -replace ",", " "} | Foreach-Object {$_ -replace "^.*?\("} | Foreach-Object {$_ -replace '0\).*'}

CMD is built for managing basic files. To have custom outputs etc. you'll need to use powershell. Powershell equivalents for sort, head and sed are above.

Full answer, writing to a ppm file:

magick convert 'BMW_logo_(gray).png' -colors 5 -depth 8 -format "%c" histogram:info: | Sort-Object | Select -First 1 | Foreach-Object {$_ -replace ",", " "} | Foreach-Object {$_ -replace "^.*?\("} | Foreach-Object {$_ -replace '0\).*'} | Out-File -Path results.ppm && "P3 1 1 255 " + (Get-Content results.ppm -Raw) | Set-Content results.ppm


问:
Radio button and saving the state values in iphone
I need to create two radio buttons and I want to store there state values (enabled or disabled) in an array. can anybody share the code?</p>

答:
This is the complete code for using the Radio Button : (You need to use the custom button to perform this task)

In .h file:

```<code>//Option Menu Buttons
IBOutlet UIButton *option1;
IBOutlet UIButton *option2;

 -(IBAction)MyCustomRadioButtons:(id)sender; // Give connection to this method through Xib/code .
</code>```

.m file

```<code>-(IBAction)MyCustomRadioButtons:(id)sender
{
    if(sender==option1)
    {
        if([option1 isSelected]==TRUE)
        {
            [option1 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option1.selected=FALSE;

            [option2 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option2.selected=TRUE;

        }
        else {

            [option1 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option1.selected=TRUE;

            [option2 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option2.selected=FALSE;
        }

    }

    if(sender==option2)
    {
        if([option2 isSelected]==TRUE)
        {
            [option2 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option2.selected=FALSE;

            [option1 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option1.selected=TRUE;

        }
        else {

            [option2 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option2.selected=TRUE;
            [self ShowActionSheetWithPicker:sender];
            [option1 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option1.selected=FALSE;

        }
    }
}
</code>```

Below are the images to use :

AS far as storing is concerned, you can use the Dictionary to store the values through key Values.

Hope that would help to do it with coding.

Body:
This is the complete code for using the Radio Button : (You need to use the custom button to perform this task)

In .h file:

//Option Menu Buttons
IBOutlet UIButton *option1;
IBOutlet UIButton *option2;

 -(IBAction)MyCustomRadioButtons:(id)sender; // Give connection to this method through Xib/code .

.m file

-(IBAction)MyCustomRadioButtons:(id)sender
{
    if(sender==option1)
    {
        if([option1 isSelected]==TRUE)
        {
            [option1 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option1.selected=FALSE;

            [option2 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option2.selected=TRUE;

        }
        else {

            [option1 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option1.selected=TRUE;

            [option2 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option2.selected=FALSE;
        }

    }

    if(sender==option2)
    {
        if([option2 isSelected]==TRUE)
        {
            [option2 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option2.selected=FALSE;

            [option1 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option1.selected=TRUE;

        }
        else {

            [option2 setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
            option2.selected=TRUE;
            [self ShowActionSheetWithPicker:sender];
            [option1 setImage:[UIImage imageNamed:@"deselected.png"] forState:UIControlStateNormal];
            option1.selected=FALSE;

        }
    }
}

Below are the images to use :

AS far as storing is concerned, you can use the Dictionary to store the values through key Values.

Hope that would help to do it with coding.


问:
How to apply a user defined function to a range of values in KQL
I have a function that outputs a table:

```<code>let my_function = (InputDate: datetime){....}
</code>```

What I would like to do is apply this function on a range and combine the result as in:

```<code>range date_X from ago(7d) to now() step 1d
| project my_function (date_X)
</code>```

Any ideas? I tried many things but ended up with only code errors

答:
The function should take a table as a parameter, then you can use "invoke" to call it. Here is an example from the docs</p>
```<code>let MyFilter = (T:(x:long), v:long) {
  T | where x >= v
};
MyFilter((range x from 1 to 10 step 1), 9)
</code>```

Body:
I have a function that outputs a table:

let my_function = (InputDate: datetime){....}

What I would like to do is apply this function on a range and combine the result as in:

range date_X from ago(7d) to now() step 1d
| project my_function (date_X)

Any ideas? I tried many things but ended up with only code errors

Body:
The function should take a table as a parameter, then you can use "invoke" to call it. Here is an example from the docs

let MyFilter = (T:(x:long), v:long) {
  T | where x >= v
};
MyFilter((range x from 1 to 10 step 1), 9)