问:
Python can properly be executed in IDEA, but when executing the executable file, following error appears: ModuleNotFoundError: No module named 'PIL'
I wrote a small Python script which takes all .jpeg img-files from a given "./Input" folder, creates a thumbnail from these images and saves them in a "./Output" file. It works perfectly fine when executed in an IDEA (In my case PyCharm), but when I created the executable with pyinstaller and tried to execute it, the following error appeared:

Traceback (most recent call last):
  File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
[84693] Failed to execute script 'image_resizer' due to unhandled exception: No module named 'PIL'
[84693] Traceback:
Traceback (most recent call last):
  File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'

logout

Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
```
<p>Here is my code:</p>
```import shutil

from PIL import Image
import glob, os
import time

output_directory = "./Output"

def photo_picker():
    pictures = []
    try:
        for filename in glob.iglob("./Input/*.jpg"):
            pictures.append(filename)
    except FileNotFoundError:
        print("could not execute")

    return pictures

def create_output_folder():
    if os.path.exists(output_directory):
        shutil.rmtree(output_directory)
    try:
        os.mkdir(path=output_directory, mode=777)
    except FileExistsError:
        print("Could not execute")

def crop_image(img, new_name):
    size = (2000, 2000)
    with Image.open(img) as im:
        im.thumbnail(size)
        print(im.info)
        img_name = f"{new_name}"
        im.save(output_directory + "/" + img_name, "JPEG")

def main():
    photos = photo_picker()
    create_output_folder()
    time.sleep(2)
    for f in photos:
        img_name_splitted = f.split("/")
        img_name = img_name_splitted[len(img_name_splitted) - 1]
        print(img_name)
        crop_image(f, img_name)
    return 0

if __name__ == "__main__":
    main()
```

I installed the module Pillow, uninstalled it ,tried to install PIL (which didn't work). But as I mentioned before, when executing it in an IDEA it works.

Body:
I wrote a small Python script which takes all .jpeg img-files from a given "./Input" folder, creates a thumbnail from these images and saves them in a "./Output" file. It works perfectly fine when executed in an IDEA (In my case PyCharm), but when I created the executable with pyinstaller and tried to execute it, the following error appeared:

Traceback (most recent call last):
  File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
[84693] Failed to execute script 'image_resizer' due to unhandled exception: No module named 'PIL'
[84693] Traceback:
Traceback (most recent call last):
  File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'

logout

Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

Here is my code:

import shutil

from PIL import Image
import glob, os
import time

output_directory = "./Output"

def photo_picker():
    pictures = []
    try:
        for filename in glob.iglob("./Input/*.jpg"):
            pictures.append(filename)
    except FileNotFoundError:
        print("could not execute")

    return pictures

def create_output_folder():
    if os.path.exists(output_directory):
        shutil.rmtree(output_directory)
    try:
        os.mkdir(path=output_directory, mode=777)
    except FileExistsError:
        print("Could not execute")

def crop_image(img, new_name):
    size = (2000, 2000)
    with Image.open(img) as im:
        im.thumbnail(size)
        print(im.info)
        img_name = f"{new_name}"
        im.save(output_directory + "/" + img_name, "JPEG")

def main():
    photos = photo_picker()
    create_output_folder()
    time.sleep(2)
    for f in photos:
        img_name_splitted = f.split("/")
        img_name = img_name_splitted[len(img_name_splitted) - 1]
        print(img_name)
        crop_image(f, img_name)
    return 0

if __name__ == "__main__":
    main()

I installed the module Pillow, uninstalled it ,tried to install PIL (which didn't work). But as I mentioned before, when executing it in an IDEA it works.


来源: stackexchange

问:
Ninject exception when using named, lazy-loaded bindings
I've been using Ninject to handle my dependency injection needs, and it works quite well for my purposes. But now I'm running into a problem. Some of my bindings contain circular dependencies, so I get around that by replacing the injected parameter with a Lazy<T> -- the Ninject Factory extension handles lazy-loaded bindings automatically, so no problem there. However, the underlying service type (T) also has multiple implementation classes bound to it, which means I need to use named bindings to specify which one I want. And therein lies the problem: Ninject can handle either named bindings or lazy-loaded parameters, but it throws an exception ("No matching bindings are available") if I try to use both at once.

The only way I've found to get around this issue is to explicitly declare a binding for Lazy<T>. But since the Ninject Factory extension claims to automatically and transparently resolve lazy-loaded bindings, it seems like this shouldn't be necessary. Does anyone have a better way of solving this?

Note: These examples require the "Ninject" and "Ninject.Extensions.Factory" NuGet packages to be installed.

This works:

using System;
using Ninject;

namespace NinjectNamedTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IService>().To<ServiceImpl>().Named("ABC");
            kernel.Bind<TargetWithNamedBinding>().ToSelf();

            var target = kernel.Get<TargetWithNamedBinding>();
            target.Run();
        }
    }

    public class TargetWithNamedBinding
    {
        private readonly IService service;

        public TargetWithNamedBinding([Named("ABC")] IService service)
        {
            this.service = service;
        }

        public void Run()
        {
            service.SayHello();
        }
    }

    public interface IService
    {
        void SayHello();
    }

    public class ServiceImpl : IService
    {
        public void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
}
```
<p>And this works:</p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using Ninject;

namespace NinjectLazyTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IService>().To<ServiceImpl>();
            kernel.Bind<TargetWithLazyBinding>().ToSelf();

            var target = kernel.Get<TargetWithLazyBinding>();
            target.Run();
        }
    }

    public class TargetWithLazyBinding
    {
        private readonly Lazy<IService> serviceLazy;

        public TargetWithLazyBinding(Lazy<IService> serviceLazy)
        {
            this.serviceLazy = serviceLazy;
        }

        public void Run()
        {
            serviceLazy.Value.SayHello();
        }
    }

    public interface IService
    {
        void SayHello();
    }

    public class ServiceImpl : IService
    {
        public void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
}
</code>```

But this doesn't:

using System;
using Ninject;

namespace NinjectLazyNamedTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IService>().To<ServiceImpl>().Named("ABC");
            kernel.Bind<TargetWithNamedLazyBinding>().ToSelf();

            // This WOULD fix the issue, but is it really the best way?
            //kernel.Bind<Lazy<IService>>()
            //    .ToMethod(ctx => new Lazy<IService>(() => ctx.Kernel.Get<ServiceImpl>()))
            //    .Named("ABC");

            var target = kernel.Get<TargetWithNamedLazyBinding>(); // Throws exception
            target.Run();
        }
    }

    public class TargetWithNamedLazyBinding
    {
        private readonly Lazy<IService> serviceLazy;

        public TargetWithNamedLazyBinding([Named("ABC")] Lazy<IService> serviceLazy)
        {
            this.serviceLazy = serviceLazy;
        }

        public void Run()
        {
            serviceLazy.Value.SayHello();
        }
    }

    public interface IService
    {
        void SayHello();
    }

    public class ServiceImpl : IService
    {
        public void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
}
```
<p>Exception stack trace:</p>
<pre class="lang-plaintext prettyprint-override"><code>Ninject.ActivationException
  HResult=0x80131500
  Message=Error activating Lazy{IService}
No matching bindings are available, and the type is not self-bindable.
Activation path:
  2) Injection of dependency Lazy{IService} into parameter serviceLazy of constructor of type TargetWithNamedLazyBinding
  1) Request for TargetWithNamedLazyBinding

Suggestions:
  1) Ensure that you have defined a binding for Lazy{IService}.
  2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
  3) Ensure you have not accidentally created more than one kernel.
  4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
  5) If you are using automatic module loading, ensure the search path and filters are correct.

  Source=Ninject
  StackTrace:
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings, Boolean filterImplicitBindings)
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings, Boolean filterImplicitBindings)
   at Ninject.KernelBase.Resolve(IRequest request)
   at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
   at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
   at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass15_0.<Create>b__0(ITarget target)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
   at Ninject.Activation.Context.ResolveInternal(Object scope)
   at Ninject.Activation.Context.Resolve()
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings, Boolean filterImplicitBindings)
   at Ninject.KernelBase.Resolve(IRequest request)
   at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique)
   at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters)
   at NinjectLazyNamedTest.Program.Main(String[] args) in C:\Users\[REDACTED]\Documents\Visual Studio 2022\Projects\NinjectLazyNamedTest\NinjectLazyNamedTest\Program.cs:line 19

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been using Ninject to handle my dependency injection needs, and it works quite well for my purposes. But now I'm running into a problem. Some of my bindings contain circular dependencies, so I get around that by replacing the injected parameter with a Lazy<T> -- the Ninject Factory extension handles lazy-loaded bindings automatically, so no problem there. However, the underlying service type (T) also has multiple implementation classes bound to it, which means I need to use named bindings to specify which one I want. And therein lies the problem: Ninject can handle either named bindings or lazy-loaded parameters, but it throws an exception ("No matching bindings are available") if I try to use both at once.

The only way I've found to get around this issue is to explicitly declare a binding for Lazy<T>. But since the Ninject Factory extension claims to automatically and transparently resolve lazy-loaded bindings, it seems like this shouldn't be necessary. Does anyone have a better way of solving this?

Note: These examples require the "Ninject" and "Ninject.Extensions.Factory" NuGet packages to be installed.

This works:

using System;
using Ninject;

namespace NinjectNamedTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IService>().To<ServiceImpl>().Named("ABC");
            kernel.Bind<TargetWithNamedBinding>().ToSelf();

            var target = kernel.Get<TargetWithNamedBinding>();
            target.Run();
        }
    }

    public class TargetWithNamedBinding
    {
        private readonly IService service;

        public TargetWithNamedBinding([Named("ABC")] IService service)
        {
            this.service = service;
        }

        public void Run()
        {
            service.SayHello();
        }
    }

    public interface IService
    {
        void SayHello();
    }

    public class ServiceImpl : IService
    {
        public void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

And this works:

using System;
using Ninject;

namespace NinjectLazyTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IService>().To<ServiceImpl>();
            kernel.Bind<TargetWithLazyBinding>().ToSelf();

            var target = kernel.Get<TargetWithLazyBinding>();
            target.Run();
        }
    }

    public class TargetWithLazyBinding
    {
        private readonly Lazy<IService> serviceLazy;

        public TargetWithLazyBinding(Lazy<IService> serviceLazy)
        {
            this.serviceLazy = serviceLazy;
        }

        public void Run()
        {
            serviceLazy.Value.SayHello();
        }
    }

    public interface IService
    {
        void SayHello();
    }

    public class ServiceImpl : IService
    {
        public void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

But this doesn't:

using System;
using Ninject;

namespace NinjectLazyNamedTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IService>().To<ServiceImpl>().Named("ABC");
            kernel.Bind<TargetWithNamedLazyBinding>().ToSelf();

            // This WOULD fix the issue, but is it really the best way?
            //kernel.Bind<Lazy<IService>>()
            //    .ToMethod(ctx => new Lazy<IService>(() => ctx.Kernel.Get<ServiceImpl>()))
            //    .Named("ABC");

            var target = kernel.Get<TargetWithNamedLazyBinding>(); // Throws exception
            target.Run();
        }
    }

    public class TargetWithNamedLazyBinding
    {
        private readonly Lazy<IService> serviceLazy;

        public TargetWithNamedLazyBinding([Named("ABC")] Lazy<IService> serviceLazy)
        {
            this.serviceLazy = serviceLazy;
        }

        public void Run()
        {
            serviceLazy.Value.SayHello();
        }
    }

    public interface IService
    {
        void SayHello();
    }

    public class ServiceImpl : IService
    {
        public void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Exception stack trace:

Ninject.ActivationException
  HResult=0x80131500
  Message=Error activating Lazy{IService}
No matching bindings are available, and the type is not self-bindable.
Activation path:
  2) Injection of dependency Lazy{IService} into parameter serviceLazy of constructor of type TargetWithNamedLazyBinding
  1) Request for TargetWithNamedLazyBinding

Suggestions:
  1) Ensure that you have defined a binding for Lazy{IService}.
  2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
  3) Ensure you have not accidentally created more than one kernel.
  4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
  5) If you are using automatic module loading, ensure the search path and filters are correct.

  Source=Ninject
  StackTrace:
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings, Boolean filterImplicitBindings)
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings, Boolean filterImplicitBindings)
   at Ninject.KernelBase.Resolve(IRequest request)
   at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
   at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
   at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass15_0.<Create>b__0(ITarget target)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
   at Ninject.Activation.Context.ResolveInternal(Object scope)
   at Ninject.Activation.Context.Resolve()
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings, Boolean filterImplicitBindings)
   at Ninject.KernelBase.Resolve(IRequest request)
   at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique)
   at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters)
   at NinjectLazyNamedTest.Program.Main(String[] args) in C:\Users\[REDACTED]\Documents\Visual Studio 2022\Projects\NinjectLazyNamedTest\NinjectLazyNamedTest\Program.cs:line 19


问:
Get Visitor IP or a Custom header in Jaeger docker behind docker traefik (v2,x)
we are experimenting with JAEGER as a tracing-tool for our traefik routing environment. We also use an ecapsulated docker network .
The goal is to accumulate requests on our api's per department and also some other monitoring.
We are using traefik 2.8 as a docker service. Also all our services run behind this traefik instance.

We added basic tracing configuration to our .toml file and startet a jaeger-instance, also as docker service. On our websecure endpoint we added forwardedHeaders.insecure = true

Jaeger is working fine, but we only get the docker internal host ip of the service, not the visitor ip from the user accessing a client with the browser or app.

I googled around and I am not sure, but it seems that this is a problem due to our setup and can't be fixed -  except by using network="host". But unfortunately thats not an option.
But I want to be sure, so I hope someone here has a tip for us to configure docker/jaeger correctly or knows if it is even possible.

A different tracing tool suggestion (for example like tideways, but more python and wasm and c++ compatible) is also appreciated.

Thanks


问:
spring micrometer metric to send one of values to datadog
Im trying to understand what type of metric i should be sending to Datadog, form my spring boot application. I only want to send a single value daily.

Example i send 100-200 emails daily, i want to publish this in a metric daily in Datadog, its not really a counter is it, but is it a gauge? not sure as its not going to be computed every time.

So how could i do this? What kind of metric would be best suited to accomplish this.

A gauge is set up as follows:

```<code>    registry.gauge("totalemail", email.size());
</code>```

But this doesnt work, and i can see why, as last requested value would be 0?

Body:
Im trying to understand what type of metric i should be sending to Datadog, form my spring boot application. I only want to send a single value daily.

Example i send 100-200 emails daily, i want to publish this in a metric daily in Datadog, its not really a counter is it, but is it a gauge? not sure as its not going to be computed every time.

So how could i do this? What kind of metric would be best suited to accomplish this.

A gauge is set up as follows:

    registry.gauge("totalemail", email.size());

But this doesnt work, and i can see why, as last requested value would be 0?


问:
I need to create an animation with bezier curve, where the dot follows the line and all the control points are shown, user has to enter control points
`

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

print("PLease input values in range of 0 to 500")
x0coord = int(input("Enter first x coordinate "))
y0coord = int(input("Enter first y coordinate "))
x1coord = int(input("Enter second x coordinate "))
y1coord = int(input("Enter second y coordinate "))
x2coord = int(input("Enter third x coordinate "))
y2coord = int(input("Enter third y coordinate "))
x3coord = int(input("Enter fourth x coordinate "))
y3coord = int(input("Enter fourth y coordinate "))

img = np.ones((500,500,3))
dot, = ax.plot([], [], 'o', color='red', markersize=10)
def DrawBezier(x0,y0, x1,y1, x2,y2, x3,y3):
    dot.set_data(100,200)
    x = x0
    y = y0
    t = 0
    ts = 0.001
    while t <= 1.0:
        B0 = 1*(1-t) * (1-t)
        B1 = 2* (1-t) * t
        B2 = 1* t * t
        x = int(x0*B0 + x1*B1 + x2*B2)
        y = int(y0*B0 + y1*B1 + y2*B2)
        img[y,x] = (1,0,0)
        t=t+ts
    return

DrawBezier(x0coord, y0coord,     x1coord, y1coord,    x2coord, y2coord,   x3coord, y3coord)
%matplotlib notebook
plt.figure(figsize=(10,8), dpi = 100, facecolor='w')
plt.imshow(img)
plt.show()
</code>```

`
this is how it is supposed to look
I need to make control points visible, animation should start at the starting point and flow into the ending point, the control point coordinates have to be entered by user with either text box or mouse, has to be at least 3 control points (including start and end points)

Body:
`

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

print("PLease input values in range of 0 to 500")
x0coord = int(input("Enter first x coordinate "))
y0coord = int(input("Enter first y coordinate "))
x1coord = int(input("Enter second x coordinate "))
y1coord = int(input("Enter second y coordinate "))
x2coord = int(input("Enter third x coordinate "))
y2coord = int(input("Enter third y coordinate "))
x3coord = int(input("Enter fourth x coordinate "))
y3coord = int(input("Enter fourth y coordinate "))

img = np.ones((500,500,3))
dot, = ax.plot([], [], 'o', color='red', markersize=10)
def DrawBezier(x0,y0, x1,y1, x2,y2, x3,y3):
    dot.set_data(100,200)
    x = x0
    y = y0
    t = 0
    ts = 0.001
    while t <= 1.0:
        B0 = 1*(1-t) * (1-t)
        B1 = 2* (1-t) * t
        B2 = 1* t * t
        x = int(x0*B0 + x1*B1 + x2*B2)
        y = int(y0*B0 + y1*B1 + y2*B2)
        img[y,x] = (1,0,0)
        t=t+ts
    return

DrawBezier(x0coord, y0coord,     x1coord, y1coord,    x2coord, y2coord,   x3coord, y3coord)
%matplotlib notebook
plt.figure(figsize=(10,8), dpi = 100, facecolor='w')
plt.imshow(img)
plt.show()

`
this is how it is supposed to look
I need to make control points visible, animation should start at the starting point and flow into the ending point, the control point coordinates have to be entered by user with either text box or mouse, has to be at least 3 control points (including start and end points)


问:
Firemonkey IOS Deploy
I am deploy a new simple app to my Iphone and getting the error:

[PAClient Error] Error: E0264 Warning: unable to build chain to self-signed root for signer "Apple Distribution: TECHTRS (JZMVX4928T)"

Platform: Delphi 11.2, Macbook air IOS 16.2, XCode Last version,
Certificate inslalled on mac, Provisioning profile install on mac,
Delphi provisioning status correct

p.s - Compiling directly Mac and IPhone works normally.

Title: Firemonkey IOS Deploy


问:
Failed to execute 'createObjectStore' on 'IDBDatabase'
I am trying to store a JSON object (100MB size) in google chrome indexedDB and getting this error:

```<code>error: SyntaxError: Failed to execute 'createObjectStore' on 'IDBDatabase': The keyPath option is not a valid key path.
</code>```

code:

```<code>    var db = new Dexie ("TheList",);
    db.version(1).stores({
      list1: "++id,name",
      list2: this.Items.toString()
      });

    db.open().then(result => {
    // Success
    }).catch(e => {
    console.log("error: " + e);
    });
</code>```

What didn't work:

Setting 'KeyPath' with:

```<code>db.createObjectStore("instruments", { keyPath: "My_Watchlist"});
</code>```

This code throws error Property 'createObjectStore' does not exist on type 'Dexie'.ts

How to fix?

Body:
I am trying to store a JSON object (100MB size) in google chrome indexedDB and getting this error:

error: SyntaxError: Failed to execute 'createObjectStore' on 'IDBDatabase': The keyPath option is not a valid key path.

code:

    var db = new Dexie ("TheList",);
    db.version(1).stores({
      list1: "++id,name",
      list2: this.Items.toString()
      });

    db.open().then(result => {
    // Success
    }).catch(e => {
    console.log("error: " + e);
    });

What didn't work:

Setting 'KeyPath' with:

db.createObjectStore("instruments", { keyPath: "My_Watchlist"});

This code throws error Property 'createObjectStore' does not exist on type 'Dexie'.ts

How to fix?


问:
Remove the invalid records from JSON after validation with schema?
I've stumbled upon this problem and after doing a bit of research here I am.

I have a json file which I want to validate against *Json-Schema. Now most of the libraries developed for this purpose in java, which are listed here, do a great a job in validating the file and provide well formatted reasons for it. But there's no feature of removing the invalid records completely. I tried ever-it/org package and couldn't find anything that pertains to the requirement.

For example if I'm having array inside a json object then its possible for one of the array elements to be invalid and the same I want to remove.

```<code>{   "key1" : "value1",
    "key2" : [
                {
                    "key3":"temp",
                    "key4":12
                },
                {                            --> this object invalid for some reason hence should be removed
                    "key3":"temp",
                    "key4":"dsds"
                },
                {
                    "key3":"temp",
                    "key4":"anything"
                }
             ]
}
</code>```

Except Of Course manually removing the invalid records/objects from file by tracking the object from start with the help of error messages upon validation, Is there any already implemented solution for this?

*Json-Schema : It is basically a standard way of representing the data format and its structure for json files. There are few versions in it, draft-07 and draft-06 for instance. Read more about it here.

Body:
I've stumbled upon this problem and after doing a bit of research here I am.

I have a json file which I want to validate against *Json-Schema. Now most of the libraries developed for this purpose in java, which are listed here, do a great a job in validating the file and provide well formatted reasons for it. But there's no feature of removing the invalid records completely. I tried ever-it/org package and couldn't find anything that pertains to the requirement.

For example if I'm having array inside a json object then its possible for one of the array elements to be invalid and the same I want to remove.

{   "key1" : "value1",
    "key2" : [
                {
                    "key3":"temp",
                    "key4":12
                },
                {                            --> this object invalid for some reason hence should be removed
                    "key3":"temp",
                    "key4":"dsds"
                },
                {
                    "key3":"temp",
                    "key4":"anything"
                }
             ]
}

Except Of Course manually removing the invalid records/objects from file by tracking the object from start with the help of error messages upon validation, Is there any already implemented solution for this?

*Json-Schema : It is basically a standard way of representing the data format and its structure for json files. There are few versions in it, draft-07 and draft-06 for instance. Read more about it here.


问:
Bicep variable creation from module output
I-m trying to create multiple app services with bicep using a for loop on a module.
The module has the following output:

```<code>output id string = appServiceAppResource.id
output name string = appServiceAppResource.name
output vnetIntegrationOn bool = allowVnetIntegration[appServicePlan.sku.name]
output principalId string = appServiceAppResource.identity.principalId   // <-- important
</code>```

After this, i want to create a key vault, and provide "get" access to all the app services previously created using an access policy:

```<code>...

param appServices object

...

module appServicePlanModules 'modules/appServicePlan.bicep' = [for appServicesConfig in appServicePlans.appServicesConfig: {
  name: '${appServicesConfig.name}-appserviceplan-module'
  params: {
    location: location
    name: appServicesConfig.name
    sku: appServicesConfig.sku
  }
}]

...
var accessPolicy = [ for i in range(0, appServices.instanceCount) : {
    objectId: appServiceModule[i].outputs.principalId
    permissions: {
      secrets: ['get']
    }
    tenantId: subscription().tenantId
  }]

module keyValutModule  'modules/keyvault.bicep' = {
  name: 'key-valut-module'
  dependsOn: [appServiceModule]
  params: {
    location: location
    accessPolicies: accessPolicy
    publicNetworkAccess: keyvault.publicNetworkAccess
    keyVaultName: keyvault.name
  }
}

</code>```

The problem is that when i try to create that access policy, it fails

What puzzles me is that, this is working:

```<code>var accessPolicy = [{
    objectId: appServiceModule[0].outputs.principalId
    permissions: {
      secrets: ['get']
    }
    tenantId: subscription().tenantId
}
{
  objectId: appServiceModule[1].outputs.principalId
  permissions: {
    secrets: ['get']
  }
  tenantId: subscription().tenantId
}]
</code>```

And also this:

```<code>var accessPolicies = [ for i in range(0,1):{
    objectId: '52xxxxxx-25xx-4xxf-axxx-xxdxx3axxdff'
    permissions: {
      secrets: ['get']
    }
    tenantId: subscription().tenantId
}]
</code>```

Since I want to use this template for multiple env, I want it to be more generic (so that i can have 1 or 5 service apps), so that for loop wold be very useful for me.
I'm not sure why, if I use a for loop in combination of a module output this is not working.

Do you have any idea why, or of there is a workaround on this.
Thank you!

Best regards,
Dorin

Body:
I-m trying to create multiple app services with bicep using a for loop on a module.
The module has the following output:

output id string = appServiceAppResource.id
output name string = appServiceAppResource.name
output vnetIntegrationOn bool = allowVnetIntegration[appServicePlan.sku.name]
output principalId string = appServiceAppResource.identity.principalId   // <-- important

After this, i want to create a key vault, and provide "get" access to all the app services previously created using an access policy:

...

param appServices object

...

module appServicePlanModules 'modules/appServicePlan.bicep' = [for appServicesConfig in appServicePlans.appServicesConfig: {
  name: '${appServicesConfig.name}-appserviceplan-module'
  params: {
    location: location
    name: appServicesConfig.name
    sku: appServicesConfig.sku
  }
}]

...
var accessPolicy = [ for i in range(0, appServices.instanceCount) : {
    objectId: appServiceModule[i].outputs.principalId
    permissions: {
      secrets: ['get']
    }
    tenantId: subscription().tenantId
  }]

module keyValutModule  'modules/keyvault.bicep' = {
  name: 'key-valut-module'
  dependsOn: [appServiceModule]
  params: {
    location: location
    accessPolicies: accessPolicy
    publicNetworkAccess: keyvault.publicNetworkAccess
    keyVaultName: keyvault.name
  }
}

The problem is that when i try to create that access policy, it fails

What puzzles me is that, this is working:

var accessPolicy = [{
    objectId: appServiceModule[0].outputs.principalId
    permissions: {
      secrets: ['get']
    }
    tenantId: subscription().tenantId
}
{
  objectId: appServiceModule[1].outputs.principalId
  permissions: {
    secrets: ['get']
  }
  tenantId: subscription().tenantId
}]

And also this:

var accessPolicies = [ for i in range(0,1):{
    objectId: '52xxxxxx-25xx-4xxf-axxx-xxdxx3axxdff'
    permissions: {
      secrets: ['get']
    }
    tenantId: subscription().tenantId
}]

Since I want to use this template for multiple env, I want it to be more generic (so that i can have 1 or 5 service apps), so that for loop wold be very useful for me.
I'm not sure why, if I use a for loop in combination of a module output this is not working.

Do you have any idea why, or of there is a workaround on this.
Thank you!

Best regards,
Dorin


问:
Trying to find out for which hyperlinks, Iframe is not present with the PDF
I am trying to click on individual hyperlinks and check whether PDF is present inside the iframe of those hyperlinks
Every time when the iframe is not present inside that hyperlink, my code get stuck there and do not proceed to further steps, I tried using try catch block also but it didn't work either.

Below is my code:

for (WebElement td : tr) {
    List<WebElement> div = driver.findElements(By.xpath("//*[@id=\"root\"]/div/main/div/div/div[5]/div/div/div/table/tbody/tr/td[3]/div"));
    for (WebElement divs : div) {
        divs.click();
        try {
            WebElement pdf = driver.findElement(By.xpath("//div[@class='MuiGrid-root MuiGrid-item MuiGrid-grid-md-6 MuiGrid-grid-lg-8 css-1tulejt']"));

            Thread.sleep(2000);
            WebElement iframe = driver.findElement(By.xpath("/html/body/div[4]/div[3]/div/div[1]/div/div[1]/iframe"));

            // pdf.click();
            WebElement PONo = divs.findElement(By.xpath("//h4[@class = contains(text(), 'PI')]"));

            System.out.println("pdf is present"
                + " PONumber=" + PONo.getText());

        } catch (NoSuchElementException e) {
            WebElement PONo = divs.findElement(By.xpath("//h4[@class = contains(text(), 'PI')]"));
            System.out.println("pdf is not present"
                + "PONumber = " + PONo.getText());

            continue;
        }
        Thread.sleep(2000);
        driver
            .findElement(
                By.xpath("//button[@class=\"MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root  css-kclo8i\"]"))
            .click();
    }
}
```

I want the loop to be continued till last link & get me the result of how many links does not have PDF

Body:
I am trying to click on individual hyperlinks and check whether PDF is present inside the iframe of those hyperlinks
Every time when the iframe is not present inside that hyperlink, my code get stuck there and do not proceed to further steps, I tried using try catch block also but it didn't work either.

Below is my code:

for (WebElement td : tr) {
    List<WebElement> div = driver.findElements(By.xpath("//*[@id=\"root\"]/div/main/div/div/div[5]/div/div/div/table/tbody/tr/td[3]/div"));
    for (WebElement divs : div) {
        divs.click();
        try {
            WebElement pdf = driver.findElement(By.xpath("//div[@class='MuiGrid-root MuiGrid-item MuiGrid-grid-md-6 MuiGrid-grid-lg-8 css-1tulejt']"));

            Thread.sleep(2000);
            WebElement iframe = driver.findElement(By.xpath("/html/body/div[4]/div[3]/div/div[1]/div/div[1]/iframe"));

            // pdf.click();
            WebElement PONo = divs.findElement(By.xpath("//h4[@class = contains(text(), 'PI')]"));

            System.out.println("pdf is present"
                + " PONumber=" + PONo.getText());

        } catch (NoSuchElementException e) {
            WebElement PONo = divs.findElement(By.xpath("//h4[@class = contains(text(), 'PI')]"));
            System.out.println("pdf is not present"
                + "PONumber = " + PONo.getText());

            continue;
        }
        Thread.sleep(2000);
        driver
            .findElement(
                By.xpath("//button[@class=\"MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root  css-kclo8i\"]"))
            .click();
    }
}

I want the loop to be continued till last link & get me the result of how many links does not have PDF


问:
Xlookup with panda in Python
I am very new to Python and i would like to use xlookup in order to look for values in different columns (column"Debt", column "Liquidity" etc..) in a database

And fill the value in the cells (C17, C18, c19....) of a number of destination files which have the same format

```<code>path_source= r"C:\Test source.xlsx"

destination_file= r"C:Stress Test Q4 2022\test.xlsx"

df1 = pd.read_excel(path_source)
df2= pd.read_excel(destination_file)
</code>```
```<code>def xlookup(lookup_value, lookup_array, return_array, if_not_found:str = ''):
    match_value = return_array.loc[lookup_array == lookup_value]
    if match_value.empty:
        return f'"{lookup_value}" not found!' if if_not_found == '' else if_not_found

    else:
        return match_value.tolist()[0]
</code>```
```<code>

df2.iloc[2,17]= df1["debt"].apply(xlookup, args = (main_df1["Fund name"],main_df1["fund_A"] ))

</code>```

NameError: name 'main_df1' is not defined

can anyone help correct the code ?
thanks a lot

Title: Xlookup with panda in Python

Body:
I am very new to Python and i would like to use xlookup in order to look for values in different columns (column"Debt", column "Liquidity" etc..) in a database

And fill the value in the cells (C17, C18, c19....) of a number of destination files which have the same format

path_source= r"C:\Test source.xlsx"

destination_file= r"C:Stress Test Q4 2022\test.xlsx"

df1 = pd.read_excel(path_source)
df2= pd.read_excel(destination_file)

def xlookup(lookup_value, lookup_array, return_array, if_not_found:str = ''):
    match_value = return_array.loc[lookup_array == lookup_value]
    if match_value.empty:
        return f'"{lookup_value}" not found!' if if_not_found == '' else if_not_found

    else:
        return match_value.tolist()[0]

df2.iloc[2,17]= df1["debt"].apply(xlookup, args = (main_df1["Fund name"],main_df1["fund_A"] ))

NameError: name 'main_df1' is not defined

can anyone help correct the code ?
thanks a lot


问:
C# WPF MVVM Changes in TextBox is not reflected in ListBox
I have a ListBox that shows a collection of Person objects with their full name.
I also have 4 TextBoxes that shows all info (FirstName, LastName, Age, Phone) from a Person object  when I click on a Person in the Listbox. This works fine.

I can change the values in the TextBoxes and they will be saved in the TexBoxes but it is not updating the name in the ListBox.

Iv´e tried to change the Binding property in Label Content From FullName to SelectedPerson.FullName but the Path for Label Content is PersonViewModel.

```<code><ListBox ItemsSource="{Binding PersonCollectionVM}"
               SelectedItem="{Binding SelectedPerson}"
               Grid.Row="0">
        <ListBox.ItemTemplate>
          <DataTemplate>
            <StackPanel Orientation="Horizontal">
              <Label Content="{Binding FullName}" />
            </StackPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>

<Grid Grid.Column="2">
      <TextBox Text="{Binding SelectedPerson.FirstName, UpdateSourceTrigger=PropertyChanged}"

</code>```
```<code>public class MainViewModel
    {
        private PersonRepository _personRepo;
        private List<PersonViewModel> _personCollectionVM;

        public MainViewModel()
        {
            _personRepo = new PersonRepository();
            _personCollectionVM = new List<PersonViewModel>();

            foreach (Person person in _personRepo.GetAll())
            {
                _personCollectionVM.Add(new PersonViewModel(person));
            }
        }

        public List<PersonViewModel> PersonCollectionVM => _personCollectionVM;

        public PersonViewModel SelectedPerson { get; set; }
    }
</code>```
```<code>public class PersonViewModel
    {
        private Person _person;

        public PersonViewModel(Person person)
        {
            _person = person;
        }
        public string FirstName
        {
            get => _person.FirstName;
            set => _person.FirstName = value;
        }

        public string LastName
        {
            get => _person.LastName;
            set=> _person.FirstName = value;
        }

        public int Age
        {
            get => _person.Age;
            set => _person.Age = value;
        }

        public string Phone
        {
            get => _person.Phone;
            set => _person.Phone = value;
        }

        public string FullName => _person.FirstName + " " + _person.LastName;

    }
</code>```

Body:
I have a ListBox that shows a collection of Person objects with their full name.
I also have 4 TextBoxes that shows all info (FirstName, LastName, Age, Phone) from a Person object  when I click on a Person in the Listbox. This works fine.

I can change the values in the TextBoxes and they will be saved in the TexBoxes but it is not updating the name in the ListBox.

Iv´e tried to change the Binding property in Label Content From FullName to SelectedPerson.FullName but the Path for Label Content is PersonViewModel.

<ListBox ItemsSource="{Binding PersonCollectionVM}"
               SelectedItem="{Binding SelectedPerson}"
               Grid.Row="0">
        <ListBox.ItemTemplate>
          <DataTemplate>
            <StackPanel Orientation="Horizontal">

            </StackPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>

<Grid Grid.Column="2">
      <TextBox Text="{Binding SelectedPerson.FirstName, UpdateSourceTrigger=PropertyChanged}"

public class MainViewModel
    {
        private PersonRepository _personRepo;
        private List<PersonViewModel> _personCollectionVM;

        public MainViewModel()
        {
            _personRepo = new PersonRepository();
            _personCollectionVM = new List<PersonViewModel>();

            foreach (Person person in _personRepo.GetAll())
            {
                _personCollectionVM.Add(new PersonViewModel(person));
            }
        }

        public List<PersonViewModel> PersonCollectionVM => _personCollectionVM;

        public PersonViewModel SelectedPerson { get; set; }
    }

public class PersonViewModel
    {
        private Person _person;

        public PersonViewModel(Person person)
        {
            _person = person;
        }
        public string FirstName
        {
            get => _person.FirstName;
            set => _person.FirstName = value;
        }

        public string LastName
        {
            get => _person.LastName;
            set=> _person.FirstName = value;
        }

        public int Age
        {
            get => _person.Age;
            set => _person.Age = value;
        }

        public string Phone
        {
            get => _person.Phone;
            set => _person.Phone = value;
        }

        public string FullName => _person.FirstName + " " + _person.LastName;

    }


问:
AVPlayer Not Able to Handle Relative Path URL in HLS Streams
We are running into an issue that seems unique to AVPlayer. We've built a new architecture for our HLS streams which makes use of relative URLs. We can play these channels on a number of other players just fine, but when trying to build using AVPlayer, the channel gets 400 errors requesting either child manifests/segments with relative URLs.

Using curl, we are able to get a 200 success by getting to a url like: something.com/segmentfolder/../../abcd1234/videosegment_01.mp4

Curl is smart enough to get rid of the ../../ and create a valid path so the actual request (which can be seen using curl -v) looks something like: something.com/abcd1234/videosegment_01.mp4

Great. But AVPlayer doesn't do this. So it makes the request as is, which leads to a 400 error and it can't download the segment.

We were able to simulate this problem with Swift playground fairly easily with this code:

```<code>let hlsurl = URL(string: "website.com/segmentfolder/../../abc1234/videosegment.mp4")!
print(hlsurl)
print(hlsurl.standardized)
</code>```

The first print shows the URL as is. Trying to GET that URL leads to a 400. The second print properly handles it by adding .standardized to the URL. This leads to a 200. The problem is, this only works for the top level/initial manifest, it doesn't work for all the child manifests and segments.

```<code>let url = URL(string: "website.com/segmentfolder/../../abc1234/videosegment.mp4")!

let task = URLSession.shared.dataTask(with: url.standardized) {(data, response, error) in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8)!)
}
</code>```

So question, does AVPlayer support relative URLs? If so, why can't it handle the ../../ in the URL path like other players and curl can? Is there a special way to get it to trigger standardizing ALL URL requests?

Any help would be appreciated.

Body:
We are running into an issue that seems unique to AVPlayer. We've built a new architecture for our HLS streams which makes use of relative URLs. We can play these channels on a number of other players just fine, but when trying to build using AVPlayer, the channel gets 400 errors requesting either child manifests/segments with relative URLs.

Using curl, we are able to get a 200 success by getting to a url like: something.com/segmentfolder/../../abcd1234/videosegment_01.mp4

Curl is smart enough to get rid of the ../../ and create a valid path so the actual request (which can be seen using curl -v) looks something like: something.com/abcd1234/videosegment_01.mp4

Great. But AVPlayer doesn't do this. So it makes the request as is, which leads to a 400 error and it can't download the segment.

We were able to simulate this problem with Swift playground fairly easily with this code:

let hlsurl = URL(string: "website.com/segmentfolder/../../abc1234/videosegment.mp4")!
print(hlsurl)
print(hlsurl.standardized)

The first print shows the URL as is. Trying to GET that URL leads to a 400. The second print properly handles it by adding .standardized to the URL. This leads to a 200. The problem is, this only works for the top level/initial manifest, it doesn't work for all the child manifests and segments.

let url = URL(string: "website.com/segmentfolder/../../abc1234/videosegment.mp4")!

let task = URLSession.shared.dataTask(with: url.standardized) {(data, response, error) in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8)!)
}

So question, does AVPlayer support relative URLs? If so, why can't it handle the ../../ in the URL path like other players and curl can? Is there a special way to get it to trigger standardizing ALL URL requests?

Any help would be appreciated.


Title: reshape multiple torch tensor

Body:
I am working with the outputs from an intermediate layer of inference and get it that:

tensor([[[[-0.2795, -0.8954,  0.0632,  ...,  0.1969, -0.1018, -0.0072],
      [-0.1998, -0.6809,  0.1348,  ...,  0.4048, -0.3689, -0.4339],
      [-0.3200, -0.6621,  0.4148,  ...,  0.1803,  0.3725, -0.1429],
      ...,
      [-0.1348,  1.0158, -0.0042,  ..., -0.4221, -0.2093, -0.0418],
      [-0.0110,  0.5780,  0.2478,  ..., -0.1673, -0.4187, -0.3328],
      [-0.0056,  0.7725,  0.5572,  ...,  0.0400,  0.2226, -0.5018]]]],
   grad_fn=<UnsqueezeBackward0>)

When I print the size of each tensor:

torch.Size([1, 154, 1024])
torch.Size([1, 122, 1024])
torch.Size([1, 107, 1024])
torch.Size([1, 141, 1024])
torch.Size([1, 72, 1024])
torch.Size([1, 86, 1024])
torch.Size([1, 180, 1024])
torch.Size([1, 113, 1024])
torch.Size([1, 145, 1024])
torch.Size([1, 76, 1024])
torch.Size([1, 106, 1024])
torch.Size([1, 107, 1024])
torch.Size([1, 121, 1024])
torch.Size([1, 97, 1024]
....

How could I reshape for getting the same size in each one? Because I would like to use that information for applying a Decision Tree Classifier.


问:
Fallback appender for Logback
Let's assume that we are using an Appender that relies on a network connection. For instance, we may be using one of the following:

https://logback.qos.ch/apidocs/ch/qos/logback/classic/net/server/ServerSocketAppender.html

https://javadoc.io/static/net.logstash.logback/logstash-logback-encoder/6.2/net/logstash/logback/appender/AbstractLogstashTcpSocketAppender.html

Since socket-based Appenders rely on the network, they are less reliable than a Console or File Appender.

Consider the scenario whereby the Socket-based Appender gets N errors or timeouts.

It would be awesome if Logback could automatically switch to a File Appender until the network outage is resolved.

Does the native XML-based configuration of Logback allow us to define such a fallback policy or we have to implement something custom (e.g. https://www.baeldung.com/custom-logback-appender) ?

Title: Fallback appender for Logback