问:
convert a number or string to binary number in python?
sample input:
B15
sample output:
B15 in binary = 1011000010101

I've tried

```<code>a = input()
print(bin(a))
</code>```

答:
The hexadecimal number 0xB15 = 2837 has the binary representation 0b101100010101. So if your input is a hexadecimal number, you need to tell Python to convert the string "B15" which comes out of input() into the hexadecimal number 0xB15, also known as the decimal number 2837, before you can convert it into binary for output.

```<code>BASE = 16
a = int(input(), BASE)
print(bin(a)[2:]) # Cut of the first two characters '0b'
</code>```

Body:
sample input:
B15
sample output:
B15 in binary = 1011000010101

I've tried

a = input()
print(bin(a))

Body:
The hexadecimal number 0xB15 = 2837 has the binary representation 0b101100010101. So if your input is a hexadecimal number, you need to tell Python to convert the string "B15" which comes out of input() into the hexadecimal number 0xB15, also known as the decimal number 2837, before you can convert it into binary for output.

BASE = 16
a = int(input(), BASE)
print(bin(a)[2:]) # Cut of the first two characters '0b'


来源: stackexchange

问:
Layer-specific learning rate in Keras Model
In a keras model, It's possible to set the learning rate for the model when compiling, like this,

```<code>model.compile(optimizer=Adam(learning_rate=0.001), loss=...)
</code>```

This sets the same learning rate for all the layers in the model, but how do I set different learning rates for each layer of my model?

like this,

layer 1 : 0.001

layer 2 : 0.05

layer 3 : 0.02

etc.

How do I do this in keras? or in tf.keras?

答:
You can use tfa.optimizers.MultiOptimizer from the tensorflow_addons package.

See directly from the docs:

```<code>import tensorflow as tf
import tensorflow_addons as tfa

model = tf.keras.Sequential([
    tf.keras.Input(shape=(4,)),
    tf.keras.layers.Dense(8),
    tf.keras.layers.Dense(16),
    tf.keras.layers.Dense(32),
])
optimizers = [
    tf.keras.optimizers.Adam(learning_rate=1e-4),
    tf.keras.optimizers.Adam(learning_rate=1e-2)
]
optimizers_and_layers = [(optimizers[0], model.layers[0]), (optimizers[1], model.layers[1:])]
optimizer = tfa.optimizers.MultiOptimizer(optimizers_and_layers)
model.compile(optimizer=optimizer, loss="mse")
</code>```

Note "Each optimizer will optimize only the weights associated with its paired layer."

ContentLicense: CC BY-SA 4.0

Body:
In a keras model, It's possible to set the learning rate for the model when compiling, like this,

model.compile(optimizer=Adam(learning_rate=0.001), loss=...)

This sets the same learning rate for all the layers in the model, but how do I set different learning rates for each layer of my model?

like this,

layer 1 : 0.001

layer 2 : 0.05

layer 3 : 0.02

etc.

How do I do this in keras? or in tf.keras?

Body:
You can use tfa.optimizers.MultiOptimizer from the tensorflow_addons package.

See directly from the docs:

import tensorflow as tf
import tensorflow_addons as tfa

model = tf.keras.Sequential([
    tf.keras.Input(shape=(4,)),
    tf.keras.layers.Dense(8),
    tf.keras.layers.Dense(16),
    tf.keras.layers.Dense(32),
])
optimizers = [
    tf.keras.optimizers.Adam(learning_rate=1e-4),
    tf.keras.optimizers.Adam(learning_rate=1e-2)
]
optimizers_and_layers = [(optimizers[0], model.layers[0]), (optimizers[1], model.layers[1:])]
optimizer = tfa.optimizers.MultiOptimizer(optimizers_and_layers)
model.compile(optimizer=optimizer, loss="mse")

Note "Each optimizer will optimize only the weights associated with its paired layer."


问:
Extract child key and flatten into parent object output in JQ
I'm trying to simplify a nested JSON structure using JQ

Input

[
  {
    "defaultBranchRef": {
      "name": "main"
    },
    "nameWithOwner": "KyleMit/stack-posts"
  },
  {
    "defaultBranchRef": {
      "name": "master"
    },
    "nameWithOwner": "KyleMit/HelloSERN"
  }
]
```
<h3>Desired Output</h3>
<pre class="lang-json prettyprint-override"><code>[
  {
    "nameWithOwner": "KyleMit/stack-posts",
    "defaultBranchName": "main"
  },
  {
    "nameWithOwner": "KyleMit/HelloSERN",
    "defaultBranchName": "master"
  }
]
</code>```

Attempted Solution

I can retrieve each of the individual fields at any depth

Get nameWithOwner

[.[]|.nameWithOwner] // ["KyleMit/stack-posts","KyleMit/HelloSERN"]
```
</li>
<li><p>Get <code>defaultBranchRef.name</code></p>
<pre class="lang-js prettyprint-override"><code>[.[]|.defaultBranchRef.name] // ["main","master"]
</code>```

But can't quite get how to combine fields / selectors to return mulitple values

答:
Open to other solutions, but one way to combine is to use Object Construction like

[.[]|{nameWithOwner, defaultBranchName: .defaultBranchRef.name}]
```
<p>Which results in the following output:</p>
```  {
    "nameWithOwner": "KyleMit/stack-posts",
    "defaultBranchName": "main"
  },
  {
    "nameWithOwner": "KyleMit/HelloSERN",
    "defaultBranchName": "master"
  }
]
```

Body:
I'm trying to simplify a nested JSON structure using JQ

Input

[
  {
    "defaultBranchRef": {
      "name": "main"
    },
    "nameWithOwner": "KyleMit/stack-posts"
  },
  {
    "defaultBranchRef": {
      "name": "master"
    },
    "nameWithOwner": "KyleMit/HelloSERN"
  }
]

Desired Output

[
  {
    "nameWithOwner": "KyleMit/stack-posts",
    "defaultBranchName": "main"
  },
  {
    "nameWithOwner": "KyleMit/HelloSERN",
    "defaultBranchName": "master"
  }
]

Attempted Solution

I can retrieve each of the individual fields at any depth

Get nameWithOwner

[.[]|.nameWithOwner] // ["KyleMit/stack-posts","KyleMit/HelloSERN"]

Get defaultBranchRef.name

[.[]|.defaultBranchRef.name] // ["main","master"]

But can't quite get how to combine fields / selectors to return mulitple values

Body:
Open to other solutions, but one way to combine is to use Object Construction like

[.[]|{nameWithOwner, defaultBranchName: .defaultBranchRef.name}]

Which results in the following output:

  {
    "nameWithOwner": "KyleMit/stack-posts",
    "defaultBranchName": "main"
  },
  {
    "nameWithOwner": "KyleMit/HelloSERN",
    "defaultBranchName": "master"
  }
]


问:
Image resizing not working with Intervention image Package
The photo is saved, but without resizing, the original photo is actually saved</p>
```<code>protected function uploadImage($images = '') {
    $path = 'upload/images';
    if (request()->hasFile('image') && $files = request()->file('image'))
        $images = Image::make($files->store($path, 'public_files'))->resize(320, 240);
    return $images;
}
</code>```
```<code>public function store(CreateGalleryRequest $request, Job $job) {
    $image = $this->uploadImage();
    if ($request->hasFile('image')) {
        $data['image'] = $image . $image->dirname . '/' . $image->basename;
    } else
        $data['image'] = null;
    $job->gallery()->create($data);
    return redirect(route('jobs.gallery.index' , ['job' => $job->id]));
}
</code>```

答:
You need to call save() function to save image

...
$images = Image::make($files->store($path, 'public_files'))->resize(320, 240)->save('image path');
...
```

Body:
The photo is saved, but without resizing, the original photo is actually saved

protected function uploadImage($images = '') {
    $path = 'upload/images';
    if (request()->hasFile('image') && $files = request()->file('image'))
        $images = Image::make($files->store($path, 'public_files'))->resize(320, 240);
    return $images;
}

public function store(CreateGalleryRequest $request, Job $job) {
    $image = $this->uploadImage();
    if ($request->hasFile('image')) {
        $data['image'] = $image . $image->dirname . '/' . $image->basename;
    } else
        $data['image'] = null;
    $job->gallery()->create($data);
    return redirect(route('jobs.gallery.index' , ['job' => $job->id]));
}


问:
Sort Function Excel Visual Basic
I am trying to do a Excel Function with order data with Visual Basic

```<code>Function DobleMax(rgn As range)

DobleMax = Application.WorksheetFunction.Sort(rgn)

End Function
</code>```

The function does not work, return the same array.

答:
As a comment:
This works fine using Office 365 using the above-mentioned function

Title: Sort Function Excel Visual Basic

Body:
I am trying to do a Excel Function with order data with Visual Basic

Function DobleMax(rgn As range)

DobleMax = Application.WorksheetFunction.Sort(rgn)

End Function

The function does not work, return the same array.


问:
Parallel tree traversal in C#
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

```<code>   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }
</code>```

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).

答:
The most direct way would be to create a Task for each child node and then wait for all of them:

```<code>public void Traverse(Node root)
{
    if (node.Property == someValue)
        DoSomething(node);

    var tasks = new List<Task>();

    foreach (var node in node.Children)
    {
        // tmp is necessary because of the way closures close over loop variables
        var tmp = node;
        tasks.Add(Task.Factory.StartNew(() => Traverse(tmp)));
    }

    Task.WaitAll(tasks.ToArray());
}
</code>```

Task is fairly light-weight, so creating lots of them works reasonably well. But they do have some overhead, so doing something more complicated like having a few tasks that share a queue is probably going to be faster. If that's the way you're going to go, don't forget that empty queue doesn't mean all work is done. Classes from the System.Collections.Concurrent namespace are going to come handy if you went this way.

EDIT: Because of the shape of the tree (the root has about 500 children), processing just the first level in parallel should give good performance:

```<code>public void Traverse(Node root, bool parallel = true)
{
    if (node.Property == someValue)
        DoSomething(node);

    if (parallel)
    {
        Parallel.ForEach(node.Children, node =>
        {
            Traverse(node, false);
        });
    }
    else
    {
        foreach (var node in node.Children)
        {
            Traverse(node, false);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parallel tree traversal in C#

Body:
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).

Body:
The most direct way would be to create a Task for each child node and then wait for all of them:

public void Traverse(Node root)
{
    if (node.Property == someValue)
        DoSomething(node);

    var tasks = new List<Task>();

    foreach (var node in node.Children)
    {
        // tmp is necessary because of the way closures close over loop variables
        var tmp = node;
        tasks.Add(Task.Factory.StartNew(() => Traverse(tmp)));
    }

    Task.WaitAll(tasks.ToArray());
}

Task is fairly light-weight, so creating lots of them works reasonably well. But they do have some overhead, so doing something more complicated like having a few tasks that share a queue is probably going to be faster. If that's the way you're going to go, don't forget that empty queue doesn't mean all work is done. Classes from the System.Collections.Concurrent namespace are going to come handy if you went this way.

EDIT: Because of the shape of the tree (the root has about 500 children), processing just the first level in parallel should give good performance:

public void Traverse(Node root, bool parallel = true)
{
    if (node.Property == someValue)
        DoSomething(node);

    if (parallel)
    {
        Parallel.ForEach(node.Children, node =>
        {
            Traverse(node, false);
        });
    }
    else
    {
        foreach (var node in node.Children)
        {
            Traverse(node, false);
        }
    }
}


问:
Hyderate the Nodes
Recently I gave a coding interview test at a company. This was one of the problem I was unable to solve. I tried on my own and came with approach but I'm not sure if it's correct, please help me rectify my mistake in approach if any.

This was the problem statement :-

Hydrate the nodes There is a tree with n nodes. The tree is rooted at node with number 0. As usually in computer science, the tree grows upside down comparing to trees existing in nature. Apples grow on nodes of this tree. Some of these apples are underhydrated, some are overhydrated, and others are neither. You know that for each overhydrated apple you'll get overhydratedPenalty cents and for every underhydrated you'll get underhydratedPenalty cents. Now, you want to pour water on exactly one node of the tree. When you pour water on node v, all apples that are in v's subtree, i.e. vitself and all descendants of v, will be hydrated and in consequence, each hydrated apple that was almost overhydrated becomes overhydrated. Moreover, every apple in the whole tree that was almost underhydrated and no water was poured on it gets underhydrated. Calculate the minimum total penalty you can get from pouring water on exactly one node of the tree.

Function Description Complete the function minimumPouringWaterPenalty(vector parent, vector waterLevel, int overhydratedPenalty, int underhydratedPenalty)

minimumPouringWaterPenalty has the following parameter(s): 1. An integer array, parent, of size n, where parenti, denotes the parent of the ith node. 2. An integer array, waterLevel, of size n, where waterLevel denotes the level of the water in the apple on node i. It's either -1, 0 or 1 where -1 stands for almost underhydrated, O stands for neither almost underhydrated nor almost overhydrated and 1 stands for almost overhydrated. 3. An integer, overhydratedPenalty, denoting the penalty for each overhydrated apple. 4. An integer, underhydrated Penalty, denoting the penalty for each underhydrated apple.

The function must return the minimum penalty that you can get by pouring water on exactly one node of the tree.

Text taken from : https://codeforces.com/blog/entry/86512

My approach :

Make Graph with parent[i] -> i (g)

Do dfs traversal to check penalty at each node if that node is given water. In this just checking if any value is 1 then increase count penalty of overhyderate for that node and store in array(h_penalty) for each node what is penalty if water is given.

Traverse again this time check if water is not given then what is penalty for underhyderate. In this just checking if any value is -1, then increase count of penalty of underhyderate for that node and store in array(u_penalty) for each node what is penalty if water is given.

Now, I have penalty of each node if water is given and if water is not given. Then I will traverse h_penalty and and for each node I will take minimum of h_penalty[i] + (u_penalty[0]-u_penalty[i]).

Here is my code for approach :

```<code>from collections import defaultdict

def hyderatedtheNode(parent, waterLevel, overHyderatd, underHyderated):
    g = defaultdict(list)

    h_penalty = [0] * len(waterLevel)
    u_penalty = [0] * len(waterLevel)

    createGraph(parent, g)
    dfs(0, waterLevel, overHyderatd, underHyderated, 1, h_penalty, g)
    dfs(0, waterLevel, underHyderated, overHyderatd, - 1, u_penalty, g)
    # print(h_penalty)
    # print(u_penalty)
    # print(g)
    # print(list(enumerate(waterLevel)))
    ans = float('inf')
    p = u_penalty[0]
    for i, h in enumerate(h_penalty):
        ans = min(ans, h + (p - u_penalty[i]))
    print(ans)

def createGraph(parent, g):
    for i in range(1, len(parent)):
        g[parent[i]].append(i)

def dfs(src, waterLeve, oH, uH, apple, val, g):
    if not g.get(src, None):
        if waterLeve[src] == apple:
            val[src] = oH
            return oH
        return 0

    if g.get(src, None):
        penalty = 0
        if waterLeve[src] == apple:
            penalty = oH
        for t in g[src]:
            penalty += dfs(t, waterLeve, oH, uH, apple, val, g)
            # print(src, t, penalty)
    val[src] = penalty
    return penalty

hyderatedtheNode([-1, 0, 1], [1, 1, 1], 3, 5)  # 0
hyderatedtheNode([-1, 0, 0], [1, -1, -1], 10, 15)   # 10
hyderatedtheNode([-1, 0, 0, 1], [0, 0, 0, 0], 10, 15)  # 0
hyderatedtheNode([-1, 0, 1, 0, 1, 2, 2, 2, 5, 5], [-1, -1, 0, -1, 0, 0, 1, 0, 0, 1], 2, 3)  # 4
</code>```

Please let me know if this approach is fine or any thing else is needed ?

答:
@pkd Your solution works. For bigger test cases, Just increase the recursion limit as you may exceed recursion depth.</p>
```<code>import sys
sys.setrecursionlimit(10**6)
</code>```

Title: Hyderate the Nodes

Body:
Recently I gave a coding interview test at a company. This was one of the problem I was unable to solve. I tried on my own and came with approach but I'm not sure if it's correct, please help me rectify my mistake in approach if any.

This was the problem statement :-

Hydrate the nodes There is a tree with n nodes. The tree is rooted at node with number 0. As usually in computer science, the tree grows upside down comparing to trees existing in nature. Apples grow on nodes of this tree. Some of these apples are underhydrated, some are overhydrated, and others are neither. You know that for each overhydrated apple you'll get overhydratedPenalty cents and for every underhydrated you'll get underhydratedPenalty cents. Now, you want to pour water on exactly one node of the tree. When you pour water on node v, all apples that are in v's subtree, i.e. vitself and all descendants of v, will be hydrated and in consequence, each hydrated apple that was almost overhydrated becomes overhydrated. Moreover, every apple in the whole tree that was almost underhydrated and no water was poured on it gets underhydrated. Calculate the minimum total penalty you can get from pouring water on exactly one node of the tree.

Function Description Complete the function minimumPouringWaterPenalty(vector parent, vector waterLevel, int overhydratedPenalty, int underhydratedPenalty)

minimumPouringWaterPenalty has the following parameter(s): 1. An integer array, parent, of size n, where parenti, denotes the parent of the ith node. 2. An integer array, waterLevel, of size n, where waterLevel denotes the level of the water in the apple on node i. It's either -1, 0 or 1 where -1 stands for almost underhydrated, O stands for neither almost underhydrated nor almost overhydrated and 1 stands for almost overhydrated. 3. An integer, overhydratedPenalty, denoting the penalty for each overhydrated apple. 4. An integer, underhydrated Penalty, denoting the penalty for each underhydrated apple.

The function must return the minimum penalty that you can get by pouring water on exactly one node of the tree.

Text taken from : https://codeforces.com/blog/entry/86512

My approach :

Make Graph with parent[i] -> i (g)

Do dfs traversal to check penalty at each node if that node is given water. In this just checking if any value is 1 then increase count penalty of overhyderate for that node and store in array(h_penalty) for each node what is penalty if water is given.

Traverse again this time check if water is not given then what is penalty for underhyderate. In this just checking if any value is -1, then increase count of penalty of underhyderate for that node and store in array(u_penalty) for each node what is penalty if water is given.

Now, I have penalty of each node if water is given and if water is not given. Then I will traverse h_penalty and and for each node I will take minimum of h_penalty[i] + (u_penalty[0]-u_penalty[i]).

Here is my code for approach :

from collections import defaultdict

def hyderatedtheNode(parent, waterLevel, overHyderatd, underHyderated):
    g = defaultdict(list)

    h_penalty = [0] * len(waterLevel)
    u_penalty = [0] * len(waterLevel)

    createGraph(parent, g)
    dfs(0, waterLevel, overHyderatd, underHyderated, 1, h_penalty, g)
    dfs(0, waterLevel, underHyderated, overHyderatd, - 1, u_penalty, g)
    # print(h_penalty)
    # print(u_penalty)
    # print(g)
    # print(list(enumerate(waterLevel)))
    ans = float('inf')
    p = u_penalty[0]
    for i, h in enumerate(h_penalty):
        ans = min(ans, h + (p - u_penalty[i]))
    print(ans)

def createGraph(parent, g):
    for i in range(1, len(parent)):
        g[parent[i]].append(i)

def dfs(src, waterLeve, oH, uH, apple, val, g):
    if not g.get(src, None):
        if waterLeve[src] == apple:
            val[src] = oH
            return oH
        return 0

    if g.get(src, None):
        penalty = 0
        if waterLeve[src] == apple:
            penalty = oH
        for t in g[src]:
            penalty += dfs(t, waterLeve, oH, uH, apple, val, g)
            # print(src, t, penalty)
    val[src] = penalty
    return penalty

hyderatedtheNode([-1, 0, 1], [1, 1, 1], 3, 5)  # 0
hyderatedtheNode([-1, 0, 0], [1, -1, -1], 10, 15)   # 10
hyderatedtheNode([-1, 0, 0, 1], [0, 0, 0, 0], 10, 15)  # 0
hyderatedtheNode([-1, 0, 1, 0, 1, 2, 2, 2, 5, 5], [-1, -1, 0, -1, 0, 0, 1, 0, 0, 1], 2, 3)  # 4

Please let me know if this approach is fine or any thing else is needed ?

Body:
@pkd Your solution works. For bigger test cases, Just increase the recursion limit as you may exceed recursion depth.

import sys
sys.setrecursionlimit(10**6)


问:
LDAP python 3 (not working) but in PHP (working) where is the problem?
Python 3 code - not working:

import ldap3 as ldap

SERVER_NAME = 'serverip'
DN = 'dc=mydomain,dc=com,dc=br,ou=people'
USERNAME = 'no-reply'
PASSWORD = 'mypassword'

server = ldap.Server(SERVER_NAME,port=389, get_info='ALL')
connection = ldap.Connection(server, user='{}\\{}'.format(DN, USERNAME), password=PASSWORD)
connection.open()
if connection.bind():
    print('Authenticated!')
else:
    print('Not Authenticated')
    print(connection.result)
```
<p><strong>This is print result</strong></p>
<blockquote>
<p>Not Authenticated
{'result': 34, 'description': 'invalidDNSyntax', 'dn': '', 'message': >'invalid DN', 'referrals': None, 'saslCreds': None, 'type': 'bindResponse'}</p>
</blockquote>
<p>PHP code - working:</p>
<pre class="lang-php prettyprint-override"><code><?php
$username="no-reply";
$pass="mypassword";

$ldapconfig['host'] = 'serverip';
$ldapconfig['port'] = '389';
$ldapconfig['basedn'] = 'dc=mydomain,dc=com,dc=br';
$ldapconfig['usersdn'] = 'ou=people';
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$dn="uid=".$username.",".$ldapconfig['usersdn'].",".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $pass)) {
  $ldap_result = @ldap_search($ds, $dn, "uid=".$username);
  $result = ldap_get_entries($ds, $ldap_result);
  print_r($result);
} else {
  print_r(new Exception("Error"));
}
?>
</code>```

I'm writing Python 3 code to use LDAP, but authentication is not working. However, my old code written in PHP works successfully. Where is the problem in my Python code?

答:
The key words in the error message is 'invalid DN'. It's complaining about the format of the username in the call to ldap.Connection. You're doing:

```<code>user='{}\\{}'.format(DN, USERNAME)
</code>```

Which would result in this string:

```<code>"dc=mydomain,dc=com,dc=br,ou=people\no-reply"
</code>```

But that's not a valid format. Because you're using the distinguished name (DN) of the domain, it's assuming the whole string is a DN, but then the \no-reply at the end throws it off.

Your PHP code is doing this:

$dn = "uid=" . $username . "," . $ldapconfig['usersdn'] . "," . $ldapconfig['basedn'];
```
<p>Which will result in this string:</p>
```"uid=no-reply,ou=people,dc=mydomain,dc=com,dc=br"
```
<p>So modify your Python code to use the same value for the username.</p>
<p>You may even get away with passing just the username (<code>"no-reply"</code>), depending on what your LDAP server is. It may or may not work:</p>
```connection = ldap.Connection(server, user=USERNAME, password=PASSWORD)
```

Body:
Python 3 code - not working:

import ldap3 as ldap

SERVER_NAME = 'serverip'
DN = 'dc=mydomain,dc=com,dc=br,ou=people'
USERNAME = 'no-reply'
PASSWORD = 'mypassword'

server = ldap.Server(SERVER_NAME,port=389, get_info='ALL')
connection = ldap.Connection(server, user='{}\\{}'.format(DN, USERNAME), password=PASSWORD)
connection.open()
if connection.bind():
    print('Authenticated!')
else:
    print('Not Authenticated')
    print(connection.result)

This is print result

Not Authenticated
{'result': 34, 'description': 'invalidDNSyntax', 'dn': '', 'message': >'invalid DN', 'referrals': None, 'saslCreds': None, 'type': 'bindResponse'}

PHP code - working:

<?php
$username="no-reply";
$pass="mypassword";

$ldapconfig['host'] = 'serverip';
$ldapconfig['port'] = '389';
$ldapconfig['basedn'] = 'dc=mydomain,dc=com,dc=br';
$ldapconfig['usersdn'] = 'ou=people';
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$dn="uid=".$username.",".$ldapconfig['usersdn'].",".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $pass)) {
  $ldap_result = @ldap_search($ds, $dn, "uid=".$username);
  $result = ldap_get_entries($ds, $ldap_result);
  print_r($result);
} else {
  print_r(new Exception("Error"));
}
?>

I'm writing Python 3 code to use LDAP, but authentication is not working. However, my old code written in PHP works successfully. Where is the problem in my Python code?

Body:
The key words in the error message is 'invalid DN'. It's complaining about the format of the username in the call to ldap.Connection. You're doing:

user='{}\\{}'.format(DN, USERNAME)

Which would result in this string:

"dc=mydomain,dc=com,dc=br,ou=people\no-reply"

But that's not a valid format. Because you're using the distinguished name (DN) of the domain, it's assuming the whole string is a DN, but then the \no-reply at the end throws it off.

Your PHP code is doing this:

$dn = "uid=" . $username . "," . $ldapconfig['usersdn'] . "," . $ldapconfig['basedn'];

Which will result in this string:

"uid=no-reply,ou=people,dc=mydomain,dc=com,dc=br"

So modify your Python code to use the same value for the username.

You may even get away with passing just the username ("no-reply"), depending on what your LDAP server is. It may or may not work:

connection = ldap.Connection(server, user=USERNAME, password=PASSWORD)


问:
Virtual Environment's Activate Does not work
I tried to install VirtualEnv on the latest version of Python. Even though it is successfully installed, when I create a new virtual environment and try to activate it, it switches to a new line as nothing has happened.

I checked the folder, I'm entering the right path, it's not in "bin" folder. I'm not sure what's causing the problem.

I'm on Windows and I'm not using PowerShell.

答:
1)Run Powershell as Administrator

Run the following command in powershell: Set-ExecutionPolicy Unrestricted

Rerun the activation command: > venv\Scripts\activate.ps1


问:
Backend Call to SAP Commerce is not triggering From My New Spartacus Setup
I am new to Spartacus and I am trying to do end-to-end integration by creating one feature in myAccount Navigation. I am able to render the page and map the CMS Component to Angular Component and it displays correctly.

Now I want to call a new occ API from this component to Commerce. I have written a service where it calls the API. But I don't see the request getting triggered in the Web Browser Console. Is there any extra setup that has to be done for this

I am using Spartacus 4.3 and Hybris 2011

Below is component

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { BuyAgain } from 'src/app/model/buyAgain-model';
import { BuyAgainService } from 'src/app/service/buyAgain.service';

@Component({
  selector: 'app-buyAgain',
  templateUrl: './buyAgain.component.html',
  styleUrls: ['./buyAgain.component.scss']
})
export class BuyAgainComponent implements OnInit {

  productList$: any;
  constructor(protected buyAgainService: BuyAgainService) { }
  ngOnInit(): void {
    this.productList$ = this.getAllProductsForCustomer();
  }

  getAllProductsForCustomer(): Observable<BuyAgain> {

    return this.buyAgainService.getCustomerOrderedProducts();
  }

}```
</div>
</div>
</p>
<p>Below is the BuyAgain Service</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { OccEndpointsService } from '@spartacus/core';
import { Observable } from 'rxjs';
import { BuyAgain } from '../model/buyAgain-model';

@Injectable({
  providedIn: 'root'
})
export class BuyAgainService {

  constructor(protected http: HttpClient,
    protected occEndpoints: OccEndpointsService) { }

getCustomerOrderedProducts(): Observable<BuyAgain> {
  console.log("In Service")
  return this.http.get<BuyAgain>(
    this.getBuyAgainEndpoint()
  );
}

  protected getBuyAgainEndpoint(): string {

    return this.occEndpoints.buildUrl('buyAgainProducts');
  }

}</code>```

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { translationChunksConfig, translations } from "@spartacus/assets";
import { FeaturesConfig, I18nConfig, OccConfig, provideConfig, SiteContextConfig } from "@spartacus/core";
import { defaultCmsContentProviders,layoutConfig, mediaConfig } from "@spartacus/storefront";
import { BuyAgainModule } from '../component/buyAgain/buyAgain.module';
import { LayoutConfigurationModule } from '../confiuration/layout/layout.module';
import { ExtendServices } from '../service/extend-services.service';

@NgModule({
  declarations: [],
  imports: [
    LayoutConfigurationModule,
    ExtendServices,
    BuyAgainModule,
    HttpClientModule
  ],
  providers: [provideConfig(mediaConfig), ...defaultCmsContentProviders, provideConfig(<OccConfig>{
    backend: {
      occ: {
        baseUrl: 'https://localhost:9002/',
      }
    },
  }), provideConfig(<SiteContextConfig>{
    context: {
      currency: ['GBP', 'USD'],
      language: ['en','de'],
      baseSite: ['apparel-uk-spa', 'electronics-spa'],
      urlParameters: ['baseSite', 'language', 'currency']
    },
  }),
  provideConfig(<I18nConfig>{
    i18n: {
      resources: translations,
      chunks: translationChunksConfig,
      fallbackLang: 'en'
    },
  }),

  //***** How to Override i18n*****/
  // provideConfig({
  //   i18n: {
  //     backend: {
  //       loadPath: 'assets/i18n-assets/{{lng}}/{{ns}}.json',
  //     },
  //     chunks: translationChunksConfig,
  //   },
  // }),
  provideConfig(<FeaturesConfig>{
    features: {
      level: '4.3'
    }
  })]
})
export class SpartacusConfigurationModule { }```

答:
Does your call to this.occEndpoints.buildUrl call actually return something? You need to have the endpoint provided with corresponding fields in your config.

Another problem could be that the subscription to the observable of your productList might not be started? Are you using something like the async pipe in the html of the component to subscribe to the productList$ attribute?

Body:
I am new to Spartacus and I am trying to do end-to-end integration by creating one feature in myAccount Navigation. I am able to render the page and map the CMS Component to Angular Component and it displays correctly.

Now I want to call a new occ API from this component to Commerce. I have written a service where it calls the API. But I don't see the request getting triggered in the Web Browser Console. Is there any extra setup that has to be done for this

I am using Spartacus 4.3 and Hybris 2011

Below is component

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { BuyAgain } from 'src/app/model/buyAgain-model';
import { BuyAgainService } from 'src/app/service/buyAgain.service';

@Component({
  selector: 'app-buyAgain',
  templateUrl: './buyAgain.component.html',
  styleUrls: ['./buyAgain.component.scss']
})
export class BuyAgainComponent implements OnInit {

  productList$: any;
  constructor(protected buyAgainService: BuyAgainService) { }
  ngOnInit(): void {
    this.productList$ = this.getAllProductsForCustomer();
  }

  getAllProductsForCustomer(): Observable<BuyAgain> {

    return this.buyAgainService.getCustomerOrderedProducts();
  }

}

Below is the BuyAgain Service

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { OccEndpointsService } from '@spartacus/core';
import { Observable } from 'rxjs';
import { BuyAgain } from '../model/buyAgain-model';

@Injectable({
  providedIn: 'root'
})
export class BuyAgainService {

  constructor(protected http: HttpClient,
    protected occEndpoints: OccEndpointsService) { }

getCustomerOrderedProducts(): Observable<BuyAgain> {
  console.log("In Service")
  return this.http.get<BuyAgain>(
    this.getBuyAgainEndpoint()
  );
}

  protected getBuyAgainEndpoint(): string {

    return this.occEndpoints.buildUrl('buyAgainProducts');
  }

}

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { translationChunksConfig, translations } from "@spartacus/assets";
import { FeaturesConfig, I18nConfig, OccConfig, provideConfig, SiteContextConfig } from "@spartacus/core";
import { defaultCmsContentProviders,layoutConfig, mediaConfig } from "@spartacus/storefront";
import { BuyAgainModule } from '../component/buyAgain/buyAgain.module';
import { LayoutConfigurationModule } from '../confiuration/layout/layout.module';
import { ExtendServices } from '../service/extend-services.service';

@NgModule({
  declarations: [],
  imports: [
    LayoutConfigurationModule,
    ExtendServices,
    BuyAgainModule,
    HttpClientModule
  ],
  providers: [provideConfig(mediaConfig), ...defaultCmsContentProviders, provideConfig(<OccConfig>{
    backend: {
      occ: {
        baseUrl: 'https://localhost:9002/',
      }
    },
  }), provideConfig(<SiteContextConfig>{
    context: {
      currency: ['GBP', 'USD'],
      language: ['en','de'],
      baseSite: ['apparel-uk-spa', 'electronics-spa'],
      urlParameters: ['baseSite', 'language', 'currency']
    },
  }),
  provideConfig(<I18nConfig>{
    i18n: {
      resources: translations,
      chunks: translationChunksConfig,
      fallbackLang: 'en'
    },
  }),

  //***** How to Override i18n*****/
  // provideConfig({
  //   i18n: {
  //     backend: {
  //       loadPath: 'assets/i18n-assets/{{lng}}/{{ns}}.json',
  //     },
  //     chunks: translationChunksConfig,
  //   },
  // }),
  provideConfig(<FeaturesConfig>{
    features: {
      level: '4.3'
    }
  })]
})
export class SpartacusConfigurationModule { }


问:
Recursive Use of ReadDirectoryChanges
I want to watch all changes in a directory recursively, i.e. if watching C:\ I want to receive notifications for

```<code>C:\1.txt
C:\A\1.txt
</code>```

If I use ReadDirectoryChanges with watchSubtree option enabled, it reports only

```<code>C:\1.txt
C:\A
</code>```

It does not work recursively.

How can I make it work recursively? Do I really need to call ReadDirectoryChangesfor each subdirectory recusively? What if new subdirectories are created / subdirectories get deleted?

Thanks for any help.

答: You probably want change journals if you're trying to watch the whole disk.</p>

Title: Recursive Use of ReadDirectoryChanges

Body:
I want to watch all changes in a directory recursively, i.e. if watching C:\ I want to receive notifications for

C:\1.txt
C:\A\1.txt

If I use ReadDirectoryChanges with watchSubtree option enabled, it reports only

C:\1.txt
C:\A

It does not work recursively.

How can I make it work recursively? Do I really need to call ReadDirectoryChangesfor each subdirectory recusively? What if new subdirectories are created / subdirectories get deleted?

Thanks for any help.


答:
Just update |= the defaultBranchRef field to the content of its name subfield:

jq '.[].defaultBranchRef |= .name'
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "defaultBranchRef": "main",
    "nameWithOwner": "KyleMit/stack-posts"
  },
  {
    "defaultBranchRef": "master",
    "nameWithOwner": "KyleMit/HelloSERN"
  }
]
</code>```

Demo

Title: Extract child key and flatten into parent object output in JQ

Body:
Just update |= the defaultBranchRef field to the content of its name subfield:

jq '.[].defaultBranchRef |= .name'

[
  {
    "defaultBranchRef": "main",
    "nameWithOwner": "KyleMit/stack-posts"
  },
  {
    "defaultBranchRef": "master",
    "nameWithOwner": "KyleMit/HelloSERN"
  }
]

Demo


问:
Is there a RegEx to extract semicolon separated values from a string... possibly containing string with semicolon
I would like to extract values from a string semicolon separated values that could also contains semicolon but not as separator. The RegEx I found on this website (I lost the post) is almost complete because it separates the key and it's value.

Example:
my.parameter 10; the.foo "Procedural Map"; pve; server.description "This; is \"my\", my description,.\n"

Current result with [^; "]+|"(?:\\"|[^"])*"/g

```<code>[
  'server.seed',
  '10',
  'pve',
  'server.level',
  '"Procedural Map"',
  'server.description',
  '"This; is \\"my\\", server; description,."'
]
</code>```

Desired result

```<code>[
  'my.parameter 10',
  'the.foo "Procedural Map"',
  'pve',
  'server.description "This; is \"my\", server; description,.\n"'
]
</code>```

Can you help me to improve the RegEx to group the parameter and it's value?

答:
I found a workaround by replacing separator by the ASCII separator (␟) then splitting the result.

const separatorPattern = /; (?=([^"]*"[^"]*")*[^"]*$)/g;

const myRawString = "server.seed 10; server.pve, server.level \"Procedural Map\"; server.description \"This; is \\\"my\\\", server; description,.\"";
const replacedSeparator = myRawString.replace(separatorPattern, "␟");
const parameters = replacedSeparator.split("␟");

console.log(parameters);
/*[
  'server.seed 10',
  'server.pve, server.level "Procedural Map"',
  'server.description "This; is \\"my\\", server; description,."'
]*/
```

Body:
I would like to extract values from a string semicolon separated values that could also contains semicolon but not as separator. The RegEx I found on this website (I lost the post) is almost complete because it separates the key and it's value.

Example:
my.parameter 10; the.foo "Procedural Map"; pve; server.description "This; is \"my\", my description,.\n"

Current result with [^; "]+|"(?:\\"|[^"])*"/g

[
  'server.seed',
  '10',
  'pve',
  'server.level',
  '"Procedural Map"',
  'server.description',
  '"This; is \\"my\\", server; description,."'
]

Desired result

[
  'my.parameter 10',
  'the.foo "Procedural Map"',
  'pve',
  'server.description "This; is \"my\", server; description,.\n"'
]

Can you help me to improve the RegEx to group the parameter and it's value?


问:
React router not working //Even after following the documentation
So i was trying react for first time, i followed the documentation and at router dom i got stuck
When i use Switch is says "export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'" So in short my router isn't working and i want a way to make it work, also it is the latest version of react as i just made this project yesterday</p>
```<code>import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import Form from './components/Form';
import Sus from './components/Sus';
import React from "react";
import {
  BrowserRouter as Router,
  // Switch,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <Router>
    <div className="">
      <Navbar title="Sus" main="SusHome" about="SusAbout"/>
      <div className="container my-5">

      <Routes>
          <Route path="/" component={Form}/>
          <Route path="/sus" component={Sus} />
        </Routes>
      </div>
    </div>
    </Router>
  );
}

export default App;
</code>```

答:
Upgrading React Router V5 to V6

If you have ever used React Router you know that we need to wrap our routes into this <Switch> component that makes sure that only one of these routes is loaded at the same time, instead of all matching routes. Something like this

```<code>export function App() {
  return (
    <div>
      <Switch>
        <Route path="/">
          <Home />
        </Route>
      </Switch>
    </div>
  )
}
</code>```

Now with V6 we changed the name from Switch to Routes and now the Routes component has a new prop called element, where you pass the component it needs to render inside this component and be like this

```<code>export function App() {
  return (
    <div>
      <Routes>
        <Route path="/" element={<Home />} />
      </Routes>
    </div>
  )
}
</code>```

Body:
So i was trying react for first time, i followed the documentation and at router dom i got stuck
When i use Switch is says "export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'" So in short my router isn't working and i want a way to make it work, also it is the latest version of react as i just made this project yesterday

import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import Form from './components/Form';
import Sus from './components/Sus';
import React from "react";
import {
  BrowserRouter as Router,
  // Switch,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <Router>

      <Navbar title="Sus" main="SusHome" about="SusAbout"/>

      <Routes>
          <Route path="/" component={Form}/>
          <Route path="/sus" component={Sus} />
        </Routes>

    </Router>
  );
}

export default App;

Body:
Upgrading React Router V5 to V6

If you have ever used React Router you know that we need to wrap our routes into this <Switch> component that makes sure that only one of these routes is loaded at the same time, instead of all matching routes. Something like this

export function App() {
  return (
    <div>
      <Switch>
        <Route path="/">
          <Home />
        </Route>
      </Switch>
    </div>
  )
}

Now with V6 we changed the name from Switch to Routes and now the Routes component has a new prop called element, where you pass the component it needs to render inside this component and be like this

export function App() {
  return (
    <div>
      <Routes>
        <Route path="/" element={<Home />} />
      </Routes>
    </div>
  )
}


问:
Leetcode Problem First Unique Character In a string
I am struggling to understand how the leetcode solution for the above problem works. If any help on how the post increment operator is working on the value of the array it would be great.

```<code>class Solution {
    public int firstUniqChar(String s) {
        int [] charArr = new int[26];
        for(int i=0;i<s.length();i++){
          charArr[s.charAt(i)-'a']++;
        }

        for(int i=0;i<s.length();i++){
            if(charArr[s.charAt(i)-'a']==1) return i;
        }
        return -1;
    }
</code>```

The problem  link here https://leetcode.com/problems/first-unique-character-in-a-string/submissions/!

答:
First, you need to understand there are 26 letters in the English alphabet. So the code creates an array of 26 integers that will hold the count of each letter in the string.

```<code>int [] charArr = new int[26];
</code>```

The count of all a's will be at index 0, the cound of all b's at index 1, etc. The default value for int is 0, so this gives an array of 26 zeros to start with.

Each letter has two character codes; one for upper case and one for lower case. The function String.charAt() returns a char but char is an integral type so you can do math on it. When doing math on a char, it uses the char code. So for example:

```<code>char c = 'B';
c -= 'A';
System.out.println((int)c);  // Will print 1 since char code of 'A' = 65, 'B' = 66
</code>```

So this line:

```<code>charArr[s.charAt(i)-'a']++;
</code>```

Takes the char at i and subtracts 'a' from it. The range of lower case codes are 97-122. Subtracting 'a' shifts those values to 0-25 - which gives the indexes into the array. (Note this code only checks lower case letters).

After converting the character to an index, it increments the value at that index. So each item in the array represents the character count of the corresponding letter.

For example, the string "aabbee" will give the array {2, 2, 0, 0, 2, 0, 0....0}

Body:
I am struggling to understand how the leetcode solution for the above problem works. If any help on how the post increment operator is working on the value of the array it would be great.

class Solution {
    public int firstUniqChar(String s) {
        int [] charArr = new int[26];
        for(int i=0;i<s.length();i++){
          charArr[s.charAt(i)-'a']++;
        }

        for(int i=0;i<s.length();i++){
            if(charArr[s.charAt(i)-'a']==1) return i;
        }
        return -1;
    }

The problem  link here https://leetcode.com/problems/first-unique-character-in-a-string/submissions/!

Body:
First, you need to understand there are 26 letters in the English alphabet. So the code creates an array of 26 integers that will hold the count of each letter in the string.

int [] charArr = new int[26];

The count of all a's will be at index 0, the cound of all b's at index 1, etc. The default value for int is 0, so this gives an array of 26 zeros to start with.

Each letter has two character codes; one for upper case and one for lower case. The function String.charAt() returns a char but char is an integral type so you can do math on it. When doing math on a char, it uses the char code. So for example:

char c = 'B';
c -= 'A';
System.out.println((int)c);  // Will print 1 since char code of 'A' = 65, 'B' = 66

So this line:

charArr[s.charAt(i)-'a']++;

Takes the char at i and subtracts 'a' from it. The range of lower case codes are 97-122. Subtracting 'a' shifts those values to 0-25 - which gives the indexes into the array. (Note this code only checks lower case letters).

After converting the character to an index, it increments the value at that index. So each item in the array represents the character count of the corresponding letter.

For example, the string "aabbee" will give the array {2, 2, 0, 0, 2, 0, 0....0}


问:
Unable to build Kotlin Multiplatform mobile project on MacBook M1 chip
I am unable to build KMM project for iOS app. I am following KMM get started.I have below setup

Android studio Artic Fox Beta 3

Kotlin 1.5.10 plugin

KMM plugin 0.2.6

Xcode 12.5

JDK 11 (Tried on AS embedded and JDK 11 from azul)

I am getting below error when I run iosApp from android studio (Android app able to run successfully in same project)

```<code>    Task :shared:linkDebugFrameworkIos FAILED
e: Compilation failed: Could not initialize class llvm.llvm

 * Source files:
 * Compiler version info: Konan: 1.5.10 / Kotlin: 1.5.10
 * Output kind: FRAMEWORK

e: java.lang.NoClassDefFoundError: Could not initialize class llvm.llvm
    at org.jetbrains.kotlin.backend.konan.llvm.BitcodePhasesKt$contextLLVMSetupPhase$1.invoke(BitcodePhases.kt:34)
    at org.jetbrains.kotlin.backend.konan.llvm.BitcodePhasesKt$contextLLVMSetupPhase$1.invoke(BitcodePhases.kt:28)
    at org.jetbrains.kotlin.backend.konan.KonanLoweringPhasesKt$makeKonanModuleOpPhase$1.invoke(KonanLoweringPhases.kt:63)
    at org.jetbrains.kotlin.backend.konan.KonanLoweringPhasesKt$makeKonanModuleOpPhase$1.invoke(KonanLoweringPhases.kt:61)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:23)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:30)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:23)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:30)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.invokeToplevel(CompilerPhase.kt:41)
    at org.jetbrains.kotlin.backend.konan.KonanDriverKt.runTopLevelPhases(KonanDriver.kt:29)
    at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:78)
    at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:35)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:88)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:76)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:45)
    at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMainNoExit(CLITool.kt:227)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion$mainNoExitWithGradleRenderer$1.invoke(K2Native.kt:286)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion$mainNoExitWithGradleRenderer$1.invoke(K2Native.kt:285)
    at org.jetbrains.kotlin.util.UtilKt.profileIf(Util.kt:27)
    at org.jetbrains.kotlin.util.UtilKt.profile(Util.kt:21)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion.mainNoExitWithGradleRenderer(K2Native.kt:285)
    at org.jetbrains.kotlin.cli.bc.K2NativeKt.mainNoExitWithGradleRenderer(K2Native.kt:485)
    at org.jetbrains.kotlin.cli.utilities.MainKt$daemonMain$1.invoke(main.kt:62)
    at org.jetbrains.kotlin.cli.utilities.MainKt$daemonMain$1.invoke(main.kt:62)
    at org.jetbrains.kotlin.cli.utilities.MainKt.mainImpl(main.kt:17)
    at org.jetbrains.kotlin.cli.utilities.MainKt.daemonMain(main.kt:62)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.jetbrains.kotlin.compilerRunner.KotlinToolRunner.runInProcess(KotlinToolRunner.kt:124)
    at org.jetbrains.kotlin.compilerRunner.KotlinToolRunner.run(KotlinToolRunner.kt:73)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinNativeCompile.compile(KotlinNativeTasks.kt:336)
    at org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink.compile(KotlinNativeTasks.kt:659)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:104)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:58)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:51)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:29)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.run(ExecuteActionsTaskExecuter.java:498)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:56)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$run$1(DefaultBuildOperationExecutor.java:71)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.runWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:45)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:71)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:483)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:466)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:105)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:270)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:248)
    at org.gradle.internal.execution.steps.ExecuteStep.executeInternal(ExecuteStep.java:83)
    at org.gradle.internal.execution.steps.ExecuteStep.access$000(ExecuteStep.java:37)
    at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:50)
    at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:47)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:47)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:37)
    at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:68)
    at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:38)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:50)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:36)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:41)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:74)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:55)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:29)
    at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:54)
    at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:35)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:60)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:27)
    at org.gradle.internal.execution.steps.BuildCacheStep.executeWithoutCache(BuildCacheStep.java:174)
    at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:74)
    at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:45)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:40)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:29)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:36)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:22)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:99)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:92)
    at java.base/java.util.Optional.map(Optional.java:265)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:84)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:41)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:27)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:91)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:49)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:78)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:49)
    at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:105)
    at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:50)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:86)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:86)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:32)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:38)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:43)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:31)
    at org.gradle.internal.execution.steps.AssignWorkspaceStep.lambda$execute$0(AssignWorkspaceStep.java:40)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution$2.withWorkspace(ExecuteActionsTaskExecuter.java:283)
    at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:40)
    at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:30)
    at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:37)
    at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:27)
    at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:49)
    at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:35)
    at org.gradle.internal.execution.impl.DefaultExecutionEngine$1.execute(DefaultExecutionEngine.java:76)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:184)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:173)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:408)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:395)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:388)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:374)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':shared:linkDebugFrameworkIos'.
> Compilation finished with errors

</code>```

Is anybudy builded on Mac M1?

答:
Just open build.gradle.kts in shared module and uncomment all occurances of iosSimulatorArm64, at minimum your shared/build.gradle.kts should look like this

```<code>    plugins {
    kotlin("multiplatform")
    id("com.android.library")
}

kotlin {
    android()

    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64() // sure all ios dependencies support this target
    ).forEach {
        it.binaries.framework {
            baseName = "shared"
        }
    }

    sourceSets {
        val commonMain by getting
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test-common"))
                implementation(kotlin("test-annotations-common"))
            }
        }
        val androidMain by getting
        val androidTest by getting {
            dependencies {
                implementation(kotlin("test-junit"))
                implementation("junit:junit:4.13.2")
            }
        }
        val iosX64Main by getting
        val iosArm64Main by getting
        val iosSimulatorArm64Main by getting
        val iosMain by creating {
            dependsOn(commonMain)
            iosX64Main.dependsOn(this)
            iosArm64Main.dependsOn(this)
            iosSimulatorArm64Main.dependsOn(this)
        }
        val iosX64Test by getting
        val iosArm64Test by getting
        val iosSimulatorArm64Test by getting
        val iosTest by creating {
            dependsOn(commonTest)
            iosX64Test.dependsOn(this)
            iosArm64Test.dependsOn(this)
            iosSimulatorArm64Test.dependsOn(this)
        }
    }
}

android {
    compileSdk = 32
    sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
    defaultConfig {
        minSdk = 21
        targetSdk = 32
    }
}
</code>```

Body:
I am unable to build KMM project for iOS app. I am following KMM get started.I have below setup

Android studio Artic Fox Beta 3

Kotlin 1.5.10 plugin

KMM plugin 0.2.6

Xcode 12.5

JDK 11 (Tried on AS embedded and JDK 11 from azul)

I am getting below error when I run iosApp from android studio (Android app able to run successfully in same project)

    Task :shared:linkDebugFrameworkIos FAILED
e: Compilation failed: Could not initialize class llvm.llvm

 * Source files:
 * Compiler version info: Konan: 1.5.10 / Kotlin: 1.5.10
 * Output kind: FRAMEWORK

e: java.lang.NoClassDefFoundError: Could not initialize class llvm.llvm
    at org.jetbrains.kotlin.backend.konan.llvm.BitcodePhasesKt$contextLLVMSetupPhase$1.invoke(BitcodePhases.kt:34)
    at org.jetbrains.kotlin.backend.konan.llvm.BitcodePhasesKt$contextLLVMSetupPhase$1.invoke(BitcodePhases.kt:28)
    at org.jetbrains.kotlin.backend.konan.KonanLoweringPhasesKt$makeKonanModuleOpPhase$1.invoke(KonanLoweringPhases.kt:63)
    at org.jetbrains.kotlin.backend.konan.KonanLoweringPhasesKt$makeKonanModuleOpPhase$1.invoke(KonanLoweringPhases.kt:61)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:23)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:30)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:23)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:30)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
    at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.invokeToplevel(CompilerPhase.kt:41)
    at org.jetbrains.kotlin.backend.konan.KonanDriverKt.runTopLevelPhases(KonanDriver.kt:29)
    at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:78)
    at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:35)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:88)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:76)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:45)
    at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMainNoExit(CLITool.kt:227)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion$mainNoExitWithGradleRenderer$1.invoke(K2Native.kt:286)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion$mainNoExitWithGradleRenderer$1.invoke(K2Native.kt:285)
    at org.jetbrains.kotlin.util.UtilKt.profileIf(Util.kt:27)
    at org.jetbrains.kotlin.util.UtilKt.profile(Util.kt:21)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion.mainNoExitWithGradleRenderer(K2Native.kt:285)
    at org.jetbrains.kotlin.cli.bc.K2NativeKt.mainNoExitWithGradleRenderer(K2Native.kt:485)
    at org.jetbrains.kotlin.cli.utilities.MainKt$daemonMain$1.invoke(main.kt:62)
    at org.jetbrains.kotlin.cli.utilities.MainKt$daemonMain$1.invoke(main.kt:62)
    at org.jetbrains.kotlin.cli.utilities.MainKt.mainImpl(main.kt:17)
    at org.jetbrains.kotlin.cli.utilities.MainKt.daemonMain(main.kt:62)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.jetbrains.kotlin.compilerRunner.KotlinToolRunner.runInProcess(KotlinToolRunner.kt:124)
    at org.jetbrains.kotlin.compilerRunner.KotlinToolRunner.run(KotlinToolRunner.kt:73)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinNativeCompile.compile(KotlinNativeTasks.kt:336)
    at org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink.compile(KotlinNativeTasks.kt:659)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:104)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:58)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:51)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:29)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.run(ExecuteActionsTaskExecuter.java:498)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:56)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$run$1(DefaultBuildOperationExecutor.java:71)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.runWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:45)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:71)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:483)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:466)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:105)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:270)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:248)
    at org.gradle.internal.execution.steps.ExecuteStep.executeInternal(ExecuteStep.java:83)
    at org.gradle.internal.execution.steps.ExecuteStep.access$000(ExecuteStep.java:37)
    at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:50)
    at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:47)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:47)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:37)
    at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:68)
    at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:38)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:50)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:36)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:41)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:74)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:55)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:29)
    at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:54)
    at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:35)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:60)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:27)
    at org.gradle.internal.execution.steps.BuildCacheStep.executeWithoutCache(BuildCacheStep.java:174)
    at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:74)
    at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:45)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:40)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:29)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:36)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:22)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:99)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:92)
    at java.base/java.util.Optional.map(Optional.java:265)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:84)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:41)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:27)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:91)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:49)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:78)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:49)
    at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:105)
    at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:50)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:86)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:86)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:32)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:38)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:43)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:31)
    at org.gradle.internal.execution.steps.AssignWorkspaceStep.lambda$execute$0(AssignWorkspaceStep.java:40)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution$2.withWorkspace(ExecuteActionsTaskExecuter.java:283)
    at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:40)
    at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:30)
    at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:37)
    at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:27)
    at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:49)
    at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:35)
    at org.gradle.internal.execution.impl.DefaultExecutionEngine$1.execute(DefaultExecutionEngine.java:76)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:184)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:173)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:408)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:395)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:388)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:374)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':shared:linkDebugFrameworkIos'.
> Compilation finished with errors

Is anybudy builded on Mac M1?

Body:
Just open build.gradle.kts in shared module and uncomment all occurances of iosSimulatorArm64, at minimum your shared/build.gradle.kts should look like this

    plugins {
    kotlin("multiplatform")
    id("com.android.library")
}

kotlin {
    android()

    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64() // sure all ios dependencies support this target
    ).forEach {
        it.binaries.framework {
            baseName = "shared"
        }
    }

    sourceSets {
        val commonMain by getting
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test-common"))
                implementation(kotlin("test-annotations-common"))
            }
        }
        val androidMain by getting
        val androidTest by getting {
            dependencies {
                implementation(kotlin("test-junit"))
                implementation("junit:junit:4.13.2")
            }
        }
        val iosX64Main by getting
        val iosArm64Main by getting
        val iosSimulatorArm64Main by getting
        val iosMain by creating {
            dependsOn(commonMain)
            iosX64Main.dependsOn(this)
            iosArm64Main.dependsOn(this)
            iosSimulatorArm64Main.dependsOn(this)
        }
        val iosX64Test by getting
        val iosArm64Test by getting
        val iosSimulatorArm64Test by getting
        val iosTest by creating {
            dependsOn(commonTest)
            iosX64Test.dependsOn(this)
            iosArm64Test.dependsOn(this)
            iosSimulatorArm64Test.dependsOn(this)
        }
    }
}

android {
    compileSdk = 32
    sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
    defaultConfig {
        minSdk = 21
        targetSdk = 32
    }
}