问:
Python DFS (CS 188 Berkeley Pacman)
I am not a Berkeley student, I'm just taking this course for fun (so you aren't helping me cheat).  I've implemented their project 1, but I am failing the autograder for Question 1 (DFS) and only question 1.  I'm always skeptical of the "it's the grader that's wrong!" statements, but in this case... I think there is a mistake in the autograder :)

The following is my implementation, which fails the autograder:

def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:
    """
    start = problem.getStartState()
    frontier = util.Stack()
    frontier.push([(start,None)])
    visited = {start}
    while frontier:
        path = frontier.pop() # path = [(pt1,dir1),(pt2,dir2)...]
        pt0, dir0 = state = path[-1]
        if problem.isGoalState(pt0):
            p = [p[1] for p in path if p[1]] # return dirs only, not points, first dir is "None" so filter that out
            return p
        for pt1,dir1,cost1 in problem.getSuccessors(pt0):
            if pt1 not in visited:
                visited.add(pt1)
                frontier.push(path + [(pt1,dir1)])
```
<p>And this code passes (identical except for the two lines marked added/removed):</p>
<pre class="lang-py prettyprint-override"><code>def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:
    """
    start = problem.getStartState()
    frontier = util.Stack()
    frontier.push([(start,None)])
    visited = {start}
    while frontier:
        path = frontier.pop() # path = [(pt1,dir1),(pt2,dir2)...]
        pt0, dir0 = state = path[-1]
        if problem.isGoalState(pt0):
            p = [p[1] for p in path if p[1]] # return dirs only, not points, first dir is "None" so filter that out
            return p
        visited.add(p0) # ADDED
        for pt1,dir1,cost1 in problem.getSuccessors(pt0):
            if pt1 not in visited:
                # visited.add(pt1) # REMOVED
                frontier.push(path + [(pt1,dir1)])
</code>```

The only difference between the two is when you mark a node as visited.  In the latter version, you mark upon popping from the stack, then you generate neighbors, adding them to the frontier if you haven't already visited them.  In the latter, you generate neighbors first, and then for each neighbor you check if they've been visited, adding them to the visited set and frontier if not.

Both versions will find the same path, and both versions are correct as I understand it.  If anything, the first version is actually a better implementation because it avoids re-queuing already visited states as outlined in this answer to a similar question.  You could avoid the re-queuing issue inherent in the second implementation by also checking that a state is not on the frontier before enqueuing, but that's a lot of wasted work to scan the frontier for every neighbor.

Is there some conceptual misunderstanding I've made here, or is my skepticism warranted?  I've tried to dissect the autograder testcases but there is a lot of magic going on and it's tough to follow the evaluate function in autograder.py. From what I can tell though, this is the test that fails:

```<code># Graph where BFS finds the optimal solution but DFS does not
class: "GraphSearchTest"
algorithm: "depthFirstSearch"

diagram: """
/-- B
|   ^
|   |
|  *A -->[G]
|   |     ^
|   V     |
\-->D ----/

A is the start state, G is the goal.  Arrows
mark possible transitions
"""
# The following section specifies the search problem and the solution.
# The graph is specified by first the set of start states, followed by
# the set of goal states, and lastly by the state transitions which are
# of the form:
#      <start state> <actions> <end state> <cost>
graph: """
start_state: A
goal_states: G
A 0:A->B B 1.0
A 1:A->G G 2.0
A 2:A->D D 4.0
B 0:B->D D 8.0
D 0:D->G G 16.0
"""
</code>```

and the reason it fails is that the path I find is just going straight from A->G whereas the grader wants to see A->D->G (in both cases {A,D} is the visited set).  To me this would be entirely dependent on the order the neighbors are added to the fringe.  If G is the final neighbor of A added to the fringe (stack here), my solution makes sense.  If not it doesn't.  This is where I got stuck, I couldn't tell from the test cases what order neighbors were being added in due to the metaprogramming magic.

 EDIT

Shortly after posting this I found a file that allowed me to inspect the test-case that was failing, after some modification.  For future learners, it's in `graphProblem.py`.  After loading up the graph mentioned above using this file, and adding some print statements to my DFS, here are the results:

My version:

```<code>Step 1: Frontier = [A], Visited = {A}
Step 2: Frontier = [A->B,A->G,A->D], Visited = {A,G,D,B}
Step 3: Frontier = [A->B,A->G], Visited = {A,G,D,B}
Step 4: Goal
</code>```

Between steps 2 and 3 is the critical difference.  Ending Step 2 we have A->D at the top of the stack, so starting step 3 we are in State D.  However, since we've recorded all of the nodes as visited as soon as we generate them as successors (in step 2), we do not add any additional paths to the frontier, and then on step 4 we pop A->G and arrive at the goal.

Contrast this with the "correct" sequence of actions the autograder requires:

```<code>Step 1: Frontier = [A], Visited = {A}
Step 2: Frontier = [A->B,A->G,A->D], Visited = {A}
Step 3: Frontier = [A->B,A->G,A->D->G], Visited = {A,D}
Step 4: Goal
</code>```

Here, since we do not add G to the visited set upon generating successors in step 2 (only when de-queing do we add items to the visited set), we are able to extend path A->D to add G despite the fact that G is already on the frontier.

So, the autograder is wrong.

Title: Python DFS (CS 188 Berkeley Pacman)

Body:
I am not a Berkeley student, I'm just taking this course for fun (so you aren't helping me cheat).  I've implemented their project 1, but I am failing the autograder for Question 1 (DFS) and only question 1.  I'm always skeptical of the "it's the grader that's wrong!" statements, but in this case... I think there is a mistake in the autograder :)

The following is my implementation, which fails the autograder:

def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:
    """
    start = problem.getStartState()
    frontier = util.Stack()
    frontier.push([(start,None)])
    visited = {start}
    while frontier:
        path = frontier.pop() # path = [(pt1,dir1),(pt2,dir2)...]
        pt0, dir0 = state = path[-1]
        if problem.isGoalState(pt0):
            p = [p[1] for p in path if p[1]] # return dirs only, not points, first dir is "None" so filter that out
            return p
        for pt1,dir1,cost1 in problem.getSuccessors(pt0):
            if pt1 not in visited:
                visited.add(pt1)
                frontier.push(path + [(pt1,dir1)])

And this code passes (identical except for the two lines marked added/removed):

def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:
    """
    start = problem.getStartState()
    frontier = util.Stack()
    frontier.push([(start,None)])
    visited = {start}
    while frontier:
        path = frontier.pop() # path = [(pt1,dir1),(pt2,dir2)...]
        pt0, dir0 = state = path[-1]
        if problem.isGoalState(pt0):
            p = [p[1] for p in path if p[1]] # return dirs only, not points, first dir is "None" so filter that out
            return p
        visited.add(p0) # ADDED
        for pt1,dir1,cost1 in problem.getSuccessors(pt0):
            if pt1 not in visited:
                # visited.add(pt1) # REMOVED
                frontier.push(path + [(pt1,dir1)])

The only difference between the two is when you mark a node as visited.  In the latter version, you mark upon popping from the stack, then you generate neighbors, adding them to the frontier if you haven't already visited them.  In the latter, you generate neighbors first, and then for each neighbor you check if they've been visited, adding them to the visited set and frontier if not.

Both versions will find the same path, and both versions are correct as I understand it.  If anything, the first version is actually a better implementation because it avoids re-queuing already visited states as outlined in this answer to a similar question.  You could avoid the re-queuing issue inherent in the second implementation by also checking that a state is not on the frontier before enqueuing, but that's a lot of wasted work to scan the frontier for every neighbor.

Is there some conceptual misunderstanding I've made here, or is my skepticism warranted?  I've tried to dissect the autograder testcases but there is a lot of magic going on and it's tough to follow the evaluate function in autograder.py. From what I can tell though, this is the test that fails:

# Graph where BFS finds the optimal solution but DFS does not
class: "GraphSearchTest"
algorithm: "depthFirstSearch"

diagram: """
/-- B
|   ^
|   |
|  *A -->[G]
|   |     ^
|   V     |
\-->D ----/

A is the start state, G is the goal.  Arrows
mark possible transitions
"""
# The following section specifies the search problem and the solution.
# The graph is specified by first the set of start states, followed by
# the set of goal states, and lastly by the state transitions which are
# of the form:
#      <start state> <actions> <end state> <cost>
graph: """
start_state: A
goal_states: G
A 0:A->B B 1.0
A 1:A->G G 2.0
A 2:A->D D 4.0
B 0:B->D D 8.0
D 0:D->G G 16.0
"""

and the reason it fails is that the path I find is just going straight from A->G whereas the grader wants to see A->D->G (in both cases {A,D} is the visited set).  To me this would be entirely dependent on the order the neighbors are added to the fringe.  If G is the final neighbor of A added to the fringe (stack here), my solution makes sense.  If not it doesn't.  This is where I got stuck, I couldn't tell from the test cases what order neighbors were being added in due to the metaprogramming magic.

 EDIT

Shortly after posting this I found a file that allowed me to inspect the test-case that was failing, after some modification.  For future learners, it's in `graphProblem.py`.  After loading up the graph mentioned above using this file, and adding some print statements to my DFS, here are the results:

My version:

Step 1: Frontier = [A], Visited = {A}
Step 2: Frontier = [A->B,A->G,A->D], Visited = {A,G,D,B}
Step 3: Frontier = [A->B,A->G], Visited = {A,G,D,B}
Step 4: Goal

Between steps 2 and 3 is the critical difference.  Ending Step 2 we have A->D at the top of the stack, so starting step 3 we are in State D.  However, since we've recorded all of the nodes as visited as soon as we generate them as successors (in step 2), we do not add any additional paths to the frontier, and then on step 4 we pop A->G and arrive at the goal.

Contrast this with the "correct" sequence of actions the autograder requires:

Step 1: Frontier = [A], Visited = {A}
Step 2: Frontier = [A->B,A->G,A->D], Visited = {A}
Step 3: Frontier = [A->B,A->G,A->D->G], Visited = {A,D}
Step 4: Goal

Here, since we do not add G to the visited set upon generating successors in step 2 (only when de-queing do we add items to the visited set), we are able to extend path A->D to add G despite the fact that G is already on the frontier.

So, the autograder is wrong.


来源: stackexchange

问:
How to access the items array in a JSON file
I want to access the JSON data for my YouTube channel and here is what I got

```<code>    {
  "version": "https://jsonfeed.org/version/1",
  "title": "Academy",
  "home_page_url": "https://www.youtube.com/channel/UCm814Any5c0GvOrRCUE3z8g",
  "author": {
    "name": "Academy"
  },
  "items": [{
      "guid": "yt:video:im1kHs3dBlQ",
      "url": "https://www.youtube.com/watch?v=im1kHs3dBlQ",
      "title": "TCP/IP Explained The Easy Way | Academy",
      "date_published": "2022-02-28T22:19:59.000Z",
      "author": {
        "name": "Academy"
      }
    },
    {
      "guid": "yt:video:q2U7Rg9KNG8",
      "url": "https://www.youtube.com/watch?v=q2U7Rg9KNG8",
      "title": "How Do You Know If A MAC Address is Unicast, Multicast or Broadcast | Academy",
      "date_published": "2022-02-28T05:37:30.000Z",
      "author": {
        "name": "Academy"
      }
    }
  ]
}
</code>```

But the problem is that I am unable to because the data I want to loop is inside the items:[....].

One way i know to do this is to remove it from the file but i want to access it remotely using Hugo, so it is difficult for me to access it.

ContentLicense: CC BY-SA 4.0

Body:
I want to access the JSON data for my YouTube channel and here is what I got

    {
  "version": "https://jsonfeed.org/version/1",
  "title": "Academy",
  "home_page_url": "https://www.youtube.com/channel/UCm814Any5c0GvOrRCUE3z8g",
  "author": {
    "name": "Academy"
  },
  "items": [{
      "guid": "yt:video:im1kHs3dBlQ",
      "url": "https://www.youtube.com/watch?v=im1kHs3dBlQ",
      "title": "TCP/IP Explained The Easy Way | Academy",
      "date_published": "2022-02-28T22:19:59.000Z",
      "author": {
        "name": "Academy"
      }
    },
    {
      "guid": "yt:video:q2U7Rg9KNG8",
      "url": "https://www.youtube.com/watch?v=q2U7Rg9KNG8",
      "title": "How Do You Know If A MAC Address is Unicast, Multicast or Broadcast | Academy",
      "date_published": "2022-02-28T05:37:30.000Z",
      "author": {
        "name": "Academy"
      }
    }
  ]
}

But the problem is that I am unable to because the data I want to loop is inside the items:[....].

One way i know to do this is to remove it from the file but i want to access it remotely using Hugo, so it is difficult for me to access it.


问:
How to change limit of messages when i scroll to top?
I have a chat with total of 20 messages displayed, and i want to make when user scroll to top to change that value from 20 to 30 and to update the chat. So, it is one time scroll, you scroll one time to top and you get in total 30 messages instead of 20. Here is what i have so far:

So this is global/default value:

let limit = 20;

This is how i print messages:

```<code>function print_msg() {

        var output = [];
        // console.log(limit);
        console.log('messages:', messages);
        for(var i=0; i<limit && i<messages.length; i++){ // here is where i use that limit
            var msg = messages[i];

            output.push(
                `
                <div class="row chat-strip">
                    // chat messages
                </div>

                `);
        }
        $("#chat-ul").html(output.reverse().join(''));
    }
</code>```

Here i have scroll detector that i fixed position to -492 because when i have default 20 messages, my scrollbar will be at -492 position when i scroll to top and it's working.

```<code>    const chatContainer = $('#chatbox');
    chatContainer.scroll(function() {
        if(chatContainer[0].scrollTop === -492 && !isLoading){
            isLoading = true;
            limit = 30;
            print_msg();
        }
    });
</code>```

As you can see it has limit = 30; that's the new limit when i scroll to top and function print_msg(); to load the chat.

This is how i get data:

```<code>    function loadOrSend(q, data) {
        return $.ajax({
            type: "POST",
            url: "../includes/data/chat.php",
            data: {q: q, data: data, limit: limit},
            dataType: "json",
            success: function(retr){
                if( q == 'load' ){
                    console.log(limit);
                    curr_id = retr.id;
                    messages = [...retr.data, ...messages];
                    if( retr.data.length > 0 ){
                        print_msg();
                    }
                    isLoading = false;
                }
                if( q == 'send' ){
                    playSound();
                }
            },
        }).fail(function () {
            alert("error: chat can't be loaded!");
        });
    }
setInterval(() => loadOrSend('load', curr_id), 3000);
</code>```

I put console.log there and it is showing the limit of 30, but just need to make that limit go to print_msg(); i guess.

And this is DB and all the stuff where it gets everything:

```<code>$q = $_POST["q"];
        $data = $_POST["data"];
        $retr = ["data"=>array(), "id"=>0];
        $limit = $_POST['limit'];

        if($q == "load") {
            $load = DB::getInstance()->query("SELECT * FROM chat WHERE id > $data ORDER BY id DESC LIMIT $limit");
            if($load->count()){
                $retr["data"] = $load->results();
                $retr["id"]   = max(array_column($retr["data"], 'id')); // get the last chat id
            }else{
                $retr["data"] = array();
                $retr["id"]   = $data;
            }
        } elseif ($q == "send") {
            $insert = DB::getInstance()->insert('chat', array(
                'text' => parseSmiley(badWords(escape(preg_replace( '/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '', showBBcodes(trim($data)))))),
                'username' => escape($user->data()->username),
                'avatar' => escape($user->getAvatar())
            ));
        }

        echo json_encode($retr);
</code>```

I hope you guys can help me because i feel like im really close...

Body:
I have a chat with total of 20 messages displayed, and i want to make when user scroll to top to change that value from 20 to 30 and to update the chat. So, it is one time scroll, you scroll one time to top and you get in total 30 messages instead of 20. Here is what i have so far:

So this is global/default value:

let limit = 20;

This is how i print messages:

function print_msg() {

        var output = [];
        // console.log(limit);
        console.log('messages:', messages);
        for(var i=0; i<limit && i<messages.length; i++){ // here is where i use that limit
            var msg = messages[i];

            output.push(
                `

                    // chat messages

                `);
        }
        $("#chat-ul").html(output.reverse().join(''));
    }

Here i have scroll detector that i fixed position to -492 because when i have default 20 messages, my scrollbar will be at -492 position when i scroll to top and it's working.

    const chatContainer = $('#chatbox');
    chatContainer.scroll(function() {
        if(chatContainer[0].scrollTop === -492 && !isLoading){
            isLoading = true;
            limit = 30;
            print_msg();
        }
    });

As you can see it has limit = 30; that's the new limit when i scroll to top and function print_msg(); to load the chat.

This is how i get data:

    function loadOrSend(q, data) {
        return $.ajax({
            type: "POST",
            url: "../includes/data/chat.php",
            data: {q: q, data: data, limit: limit},
            dataType: "json",
            success: function(retr){
                if( q == 'load' ){
                    console.log(limit);
                    curr_id = retr.id;
                    messages = [...retr.data, ...messages];
                    if( retr.data.length > 0 ){
                        print_msg();
                    }
                    isLoading = false;
                }
                if( q == 'send' ){
                    playSound();
                }
            },
        }).fail(function () {
            alert("error: chat can't be loaded!");
        });
    }
setInterval(() => loadOrSend('load', curr_id), 3000);

I put console.log there and it is showing the limit of 30, but just need to make that limit go to print_msg(); i guess.

And this is DB and all the stuff where it gets everything:

$q = $_POST["q"];
        $data = $_POST["data"];
        $retr = ["data"=>array(), "id"=>0];
        $limit = $_POST['limit'];

        if($q == "load") {
            $load = DB::getInstance()->query("SELECT * FROM chat WHERE id > $data ORDER BY id DESC LIMIT $limit");
            if($load->count()){
                $retr["data"] = $load->results();
                $retr["id"]   = max(array_column($retr["data"], 'id')); // get the last chat id
            }else{
                $retr["data"] = array();
                $retr["id"]   = $data;
            }
        } elseif ($q == "send") {
            $insert = DB::getInstance()->insert('chat', array(
                'text' => parseSmiley(badWords(escape(preg_replace( '/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '', showBBcodes(trim($data)))))),
                'username' => escape($user->data()->username),
                'avatar' => escape($user->getAvatar())
            ));
        }

        echo json_encode($retr);

I hope you guys can help me because i feel like im really close...


问:
Appium-python: Scrolling scrolls the window but not placing the specified element to the centre of the screen
I'm automating the android native app. I have a set of cards and each card has a set of information. To access the card, I'm using android_uiautomator to scroll, it is able to find the element by text but it is not moving the card to the centre screen (where I can access all the information), but sometimes it stops by text where the rest of the card is under the view. I have tried different ways but have not been able to figure this out.

I have used below code for scrolling

```<code>browser.driver.find_element_by_android_uiautomator(
            'new UiScrollable(new UiSelector().scrollable(true).instance(0)).setSwipeDeadZonePercentage(0.25).scrollIntoView(new UiSelector().text("' + LocatorText + '"));')

</code>```

I'm using LocatorText, cards will change their order every time. Any help is highly appreciated

Body:
I'm automating the android native app. I have a set of cards and each card has a set of information. To access the card, I'm using android_uiautomator to scroll, it is able to find the element by text but it is not moving the card to the centre screen (where I can access all the information), but sometimes it stops by text where the rest of the card is under the view. I have tried different ways but have not been able to figure this out.

I have used below code for scrolling

browser.driver.find_element_by_android_uiautomator(
            'new UiScrollable(new UiSelector().scrollable(true).instance(0)).setSwipeDeadZonePercentage(0.25).scrollIntoView(new UiSelector().text("' + LocatorText + '"));')

I'm using LocatorText, cards will change their order every time. Any help is highly appreciated


问:
Install `System.ComponentModel.DataAnnotations.dll` to a MacOS Unity project
I need System.ComponentModel.DataAnnotations.dll as a dependency for openapi-generate, but I can't seem to get a valid dll.

I've tried using

NuGet for Unity (silently fails to install, other packages do work)

Installing with VisualStudio (indicates that it's installed, but doesn't resolve the reference errors)

Directly copying the dll from Mono.framework (says that .dll doesn't contain valid CIL)

I'm using Unity 2021.3.6f1 what are my options here as far as diagnosing, understanding and fixing dependency problems like this?


问:
Dapper - how to apply a transformation to selected object fields?
The problem I am trying to solve is pretty simple: I need to make sure my timestamps are stored in the database as UTC. I use DateTime in my model objects, which maps to timespamp column in Postgres DB.

I'd like to do 2 things:

When a value is saved to the database, I want to check the DateTime.Kind field and throw up if it is not UTC. This will help me to capture errors if I try to feed a non-UTC time to a timestamp field. I do not want to do any transformations, just assert.

When loading from DB, I need those DateTime instances come out with DateTime.Kind set to UTC, so the rest of my application can recognize they are UTC and convert to local or whatever, as needed.

I only need to apply this logic to selected timestamp fields, not to all DateTime-s, because I have other DateTime values in my model, which need to be stored as they are.

I've tried this:

```<code>public class UtcTimestampMapper: SqlMapper.TypeHandler<DateTime>
{
    public override void SetValue(IDbDataParameter parameter, DateTime dt)
    {
        if (dt.Kind == DateTimeKind.Utc)
            parameter.Value = dt;
        else
            throw new InvalidOperationException("UTC timestamp expected");
    }

    public override DateTime Parse(object value)
    {
        return DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
    }
}
</code>```

This solution has 2 issues:

It applies to all DateTime values. With SetValue I can do the trick checking the column name in IDbDataParameter, maybe... But Parse method just gets a naked value, there is nothing I can do to determine where it goes.

The SetValue method won't be called at all, unless I remove the standard handler for DateTime. See this SO answer for details: Dapper TypeHandler.SetValue() not being called Again, if I replace the handler, I replace it globally, there is no way to choose where it applies.

So, is there a way to solve my problem with the facilities Dapper provides to customize mappings?

Body:
The problem I am trying to solve is pretty simple: I need to make sure my timestamps are stored in the database as UTC. I use DateTime in my model objects, which maps to timespamp column in Postgres DB.

I'd like to do 2 things:

When a value is saved to the database, I want to check the DateTime.Kind field and throw up if it is not UTC. This will help me to capture errors if I try to feed a non-UTC time to a timestamp field. I do not want to do any transformations, just assert.

When loading from DB, I need those DateTime instances come out with DateTime.Kind set to UTC, so the rest of my application can recognize they are UTC and convert to local or whatever, as needed.

I only need to apply this logic to selected timestamp fields, not to all DateTime-s, because I have other DateTime values in my model, which need to be stored as they are.

I've tried this:

public class UtcTimestampMapper: SqlMapper.TypeHandler<DateTime>
{
    public override void SetValue(IDbDataParameter parameter, DateTime dt)
    {
        if (dt.Kind == DateTimeKind.Utc)
            parameter.Value = dt;
        else
            throw new InvalidOperationException("UTC timestamp expected");
    }

    public override DateTime Parse(object value)
    {
        return DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
    }
}

This solution has 2 issues:

It applies to all DateTime values. With SetValue I can do the trick checking the column name in IDbDataParameter, maybe... But Parse method just gets a naked value, there is nothing I can do to determine where it goes.

The SetValue method won't be called at all, unless I remove the standard handler for DateTime. See this SO answer for details: Dapper TypeHandler.SetValue() not being called Again, if I replace the handler, I replace it globally, there is no way to choose where it applies.

So, is there a way to solve my problem with the facilities Dapper provides to customize mappings?


问:
terratest receive error (variable of type *string) as type string in argument while read the cloudwatch log stream
I'm very new to golang, so I'm trying to follow: terratest_code-base while buidling my test to read the cw log stream.

```<code>terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
            // The path to where our Terraform code is located to give the folder name
            TerraformDir: "../../",

            // Variables to pass to our Terraform code using -var options
            Vars: map[string]interface{}{
                "dynamo_db_table_name": expectedTableName,
                "token": token,
                "aws_region": awsRegion,
                "access_key": accessKey,
                "secret_key": secretKey,
                "environment": environment,
            },

            // Environment variables to set when running Terraform
            EnvVars: map[string]string{
                "AWS_DEFAULT_REGION": awsRegion,
                "AWS_ACCESS_KEY_ID": accessKey,
                "AWS_SECRET_ACCESS_KEY": secretKey,
                "AWS_SESSION_TOKEN": token,
            },
            // Backend config to create state file in S3
            BackendConfig: map[string]interface{}{
                "bucket": bucketName,
                "key":    key,
                "region": awsRegion,
            },
        })
    // At the end of the test, run `terraform destroy` to clean up any resources that were created
    defer terraform.Destroy(t, terraformOptions)

    // This will run `terraform init` and `terraform apply` and fail the test if there are any errors
    terraform.InitAndApply(t, terraformOptions)

client := aws.NewCloudWatchLogsClient(t, awsRegion)
    cw_main_log_group_prefix := terraform.Output(t, terraformOptions, "main_cloudwatch_log_name")

    groups, err := client.DescribeLogGroups(&cloudwatchlogs.DescribeLogGroupsInput{LogGroupNamePrefix: &cw_main_log_group_prefix})
    // cw_prefix_not_exist_msg := fmt.Sprintf("CW Log group %s does not exists", cw_main_log_group_prefix)
    if err != nil {
        assert.Error(t, errors.New("Error in "))
    }

    if len(groups.LogGroups) < 1 {
             assert.Error(t, errors.New(fmt.Sprintf("No log group found for %s", cw_main_log_group_prefix)))
    }

    group := groups.LogGroups[0]
    fmt.Println(group)
    streams, err := client.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
            LogGroupName: group.LogGroupName,
            Descending:   awsSDK.Bool(true),
            OrderBy:      awsSDK.String("LastEventTime"),
    })

    if len(streams.LogStreams) < 1 {
          assert.Error(t, errors.New(fmt.Sprintf("No log streams found for %s", cw_main_log_group_prefix)))
    }

    stream := streams.LogStreams[0]
     message, err := aws.GetCloudWatchLogEntriesE(t, awsRegion, stream.LogStreamName, cw_main_log_group_prefix)
</code>```

I'm getting below error:

```<code>cannot use stream.LogStreamName (variable of type *string) as type string in argument to aws.GetCloudWatchLogEntriesE
</code>```

as the response from describeLogstream has string attribute called LogStreamName

My question is how to fix this?

can anyone suggest me how to follow carry out the test?
only thing it prints is fmt.Println(group)

Body:
I'm very new to golang, so I'm trying to follow: terratest_code-base while buidling my test to read the cw log stream.

terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
            // The path to where our Terraform code is located to give the folder name
            TerraformDir: "../../",

            // Variables to pass to our Terraform code using -var options
            Vars: map[string]interface{}{
                "dynamo_db_table_name": expectedTableName,
                "token": token,
                "aws_region": awsRegion,
                "access_key": accessKey,
                "secret_key": secretKey,
                "environment": environment,
            },

            // Environment variables to set when running Terraform
            EnvVars: map[string]string{
                "AWS_DEFAULT_REGION": awsRegion,
                "AWS_ACCESS_KEY_ID": accessKey,
                "AWS_SECRET_ACCESS_KEY": secretKey,
                "AWS_SESSION_TOKEN": token,
            },
            // Backend config to create state file in S3
            BackendConfig: map[string]interface{}{
                "bucket": bucketName,
                "key":    key,
                "region": awsRegion,
            },
        })
    // At the end of the test, run `terraform destroy` to clean up any resources that were created
    defer terraform.Destroy(t, terraformOptions)

    // This will run `terraform init` and `terraform apply` and fail the test if there are any errors
    terraform.InitAndApply(t, terraformOptions)

client := aws.NewCloudWatchLogsClient(t, awsRegion)
    cw_main_log_group_prefix := terraform.Output(t, terraformOptions, "main_cloudwatch_log_name")

    groups, err := client.DescribeLogGroups(&cloudwatchlogs.DescribeLogGroupsInput{LogGroupNamePrefix: &cw_main_log_group_prefix})
    // cw_prefix_not_exist_msg := fmt.Sprintf("CW Log group %s does not exists", cw_main_log_group_prefix)
    if err != nil {
        assert.Error(t, errors.New("Error in "))
    }

    if len(groups.LogGroups) < 1 {
             assert.Error(t, errors.New(fmt.Sprintf("No log group found for %s", cw_main_log_group_prefix)))
    }

    group := groups.LogGroups[0]
    fmt.Println(group)
    streams, err := client.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
            LogGroupName: group.LogGroupName,
            Descending:   awsSDK.Bool(true),
            OrderBy:      awsSDK.String("LastEventTime"),
    })

    if len(streams.LogStreams) < 1 {
          assert.Error(t, errors.New(fmt.Sprintf("No log streams found for %s", cw_main_log_group_prefix)))
    }

    stream := streams.LogStreams[0]
     message, err := aws.GetCloudWatchLogEntriesE(t, awsRegion, stream.LogStreamName, cw_main_log_group_prefix)

I'm getting below error:

cannot use stream.LogStreamName (variable of type *string) as type string in argument to aws.GetCloudWatchLogEntriesE

as the response from describeLogstream has string attribute called LogStreamName

My question is how to fix this?

can anyone suggest me how to follow carry out the test?
only thing it prints is fmt.Println(group)


问:
Google Cal API - Sending invites that insert calendar event automatically on attendees calendars
I'm using:

POST https://www.googleapis.com/calendar/v3/calendars/calendarId/events

To create and post a google calendar event on attendees calendars.

It worked when I was using my personal gmail account. However, when I switched to a Google workspace business account it did not auto insert the calendar invite on the attendees calendar.

I've checked permissions for both accounts, but I cannot figure out why it worked for my gmail during testing but won't operate the same with a Google workspace email. Example:

michael@gmail.com = it worked.
michael@google.com = it did not work.

Anyone experienced with adding g cal invites onto attendees calendars? Do I need an additional parameter like visibility when using this API?

Thank you !

I was able to try this and it succeeded using my personal gmail address as the calendarId. But when I changed the calendarId to a business account it failed. And the calendar invites did not automatically appear on attendees calendars like they did with my personal gmail account as the calendarId.


问:
quicksort Iterative + animation
I wanted to create a quicksort  iterative sorting algorithm that will show me the progress of an animation. I use matplotlib.animation for this purpose. The problem arises when after passing the first sort and setting new pivot points, the program stops working showing an error:

for rect, val in zip(rects, A):
TypeError: zip argument #2 must support iteration

Code with a sorting function:

```<code>def partition(a, l, r):
    i = (l - 1)
    x = a[r]

    for j in range(l, r):
        if a[j] <= x:
            # increment index of smaller element
            i = i + 1
            a[i], a[j] = a[j], a[i]

    a[i + 1], a[r] = a[r], a[i + 1]
    return (i + 1)

def quickSortIterative(a, l, r):
    # Create an auxiliary stack
    size = r - l + 1
    stack = [0] * (size)

    # initialize top of stack
    top = -1

    # push initial values of l and h to stack
    top = top + 1
    stack[top] = l
    top = top + 1
    stack[top] = r

    # Keep popping from stack while is not empty
    while top >= 0:

        # Pop h and l
        r = stack[top]
        top = top - 1
        l = stack[top]
        top = top - 1

        # Set pivot element at its correct position in
        # sorted array
        if l >= r:
            return
        x = a[l]
        j = l
        for i in range(l + 1, r + 1):
            if a[i] <= x:
                j += 1
                a[j], a[i] = a[i], a[j]
            yield a
        a[l], a[j] = a[j], a[l]
        yield a
        # If there are elements on left side of pivot,
        # then push left side to stack
        for i in a:
            if i - 1 > l:
                top = top + 1
                stack[top] = l
                top = top + 1
                stack[top] = i - 1
                yield stack[top]

            # If there are elements on right side of pivot,
            # then push right side to stack

            if i + 1 < r:
                top = top + 1
                stack[top] = i + 1
                top = top + 1
                stack[top] = r
                yield stack[top]

</code>```

Drawing a graph:

```<code>def draw2(n=None):
    n = int(n)
    a = [x + 1 for x in range(n)]
    random.shuffle(a)
    datasetName = 'Random'

    # generator object returned by the function
    generator = quickSortIterative(a, 0, n - 1)
    algoName = 'Quick Sort2'

    # style of the chart
    plt.style.use('fivethirtyeight')

    fig, ax = plt.subplots()

    # bar container
    bar_rects = ax.bar(range(len(a)), a, align="edge",
                       color='Blue')

    # setting the limits of x and y axes
    ax.set_xlim(0, len(a))
    ax.set_ylim(0, int(1.1 * len(a)))
    ax.set_title("ALGORITHM : " + algoName + "\n" + "DATA SET : " +
                 datasetName)

    text = ax.text(0.01, 0.95, "", transform=ax.transAxes, color="#E4365D")
    iteration2 = [0]

    def animate(A, rects, iteration2):
        for rect, val in zip(rects, A):
            # setting the size of each bar equal to the value of the elements
            rect.set_height(val)
        iteration2[0] += 1
        text.set_text("iterations : {}".format(iteration2[0]))

    # call animate function repeatedly
    anim = FuncAnimation(fig, func=animate,
                         fargs=(bar_rects, iteration2), frames=generator, interval=50,
                         repeat=False)
    plt.show()

</code>```

How can I fix the error so that the program sorts all the elements?

Title: quicksort Iterative + animation

Body:
I wanted to create a quicksort  iterative sorting algorithm that will show me the progress of an animation. I use matplotlib.animation for this purpose. The problem arises when after passing the first sort and setting new pivot points, the program stops working showing an error:

for rect, val in zip(rects, A):
TypeError: zip argument #2 must support iteration

Code with a sorting function:

def partition(a, l, r):
    i = (l - 1)
    x = a[r]

    for j in range(l, r):
        if a[j] <= x:
            # increment index of smaller element
            i = i + 1
            a[i], a[j] = a[j], a[i]

    a[i + 1], a[r] = a[r], a[i + 1]
    return (i + 1)

def quickSortIterative(a, l, r):
    # Create an auxiliary stack
    size = r - l + 1
    stack = [0] * (size)

    # initialize top of stack
    top = -1

    # push initial values of l and h to stack
    top = top + 1
    stack[top] = l
    top = top + 1
    stack[top] = r

    # Keep popping from stack while is not empty
    while top >= 0:

        # Pop h and l
        r = stack[top]
        top = top - 1
        l = stack[top]
        top = top - 1

        # Set pivot element at its correct position in
        # sorted array
        if l >= r:
            return
        x = a[l]
        j = l
        for i in range(l + 1, r + 1):
            if a[i] <= x:
                j += 1
                a[j], a[i] = a[i], a[j]
            yield a
        a[l], a[j] = a[j], a[l]
        yield a
        # If there are elements on left side of pivot,
        # then push left side to stack
        for i in a:
            if i - 1 > l:
                top = top + 1
                stack[top] = l
                top = top + 1
                stack[top] = i - 1
                yield stack[top]

            # If there are elements on right side of pivot,
            # then push right side to stack

            if i + 1 < r:
                top = top + 1
                stack[top] = i + 1
                top = top + 1
                stack[top] = r
                yield stack[top]

Drawing a graph:

def draw2(n=None):
    n = int(n)
    a = [x + 1 for x in range(n)]
    random.shuffle(a)
    datasetName = 'Random'

    # generator object returned by the function
    generator = quickSortIterative(a, 0, n - 1)
    algoName = 'Quick Sort2'

    # style of the chart
    plt.style.use('fivethirtyeight')

    fig, ax = plt.subplots()

    # bar container
    bar_rects = ax.bar(range(len(a)), a, align="edge",
                       color='Blue')

    # setting the limits of x and y axes
    ax.set_xlim(0, len(a))
    ax.set_ylim(0, int(1.1 * len(a)))
    ax.set_title("ALGORITHM : " + algoName + "\n" + "DATA SET : " +
                 datasetName)

    text = ax.text(0.01, 0.95, "", transform=ax.transAxes, color="#E4365D")
    iteration2 = [0]

    def animate(A, rects, iteration2):
        for rect, val in zip(rects, A):
            # setting the size of each bar equal to the value of the elements
            rect.set_height(val)
        iteration2[0] += 1
        text.set_text("iterations : {}".format(iteration2[0]))

    # call animate function repeatedly
    anim = FuncAnimation(fig, func=animate,
                         fargs=(bar_rects, iteration2), frames=generator, interval=50,
                         repeat=False)
    plt.show()

How can I fix the error so that the program sorts all the elements?


问:
Adding nuget package in C# Interactive fails
I am trying to add a nuget package in C# Interactive in Visual Studio Code. Seems pretty straight forward, but it always fails.

```<code>#r "nuget:Newtonsoft.Json"
</code>```

I always get back:

```<code>Error: PackageManagement Error 3217 Invalid URI: The format of the URI could not be determined.
</code>```

Same response for multiple packages.

Body:
I am trying to add a nuget package in C# Interactive in Visual Studio Code. Seems pretty straight forward, but it always fails.

#r "nuget:Newtonsoft.Json"

I always get back:

Error: PackageManagement Error 3217 Invalid URI: The format of the URI could not be determined.

Same response for multiple packages.


问:
How to send notification when the app is closed? (android java)
Im making a reminder app that's based on location.
One of it's main features is to send the user a notification when he is close to one of the locations he set.

I've tried and searched the web, but still couldn't find a way to send a notification - when the app is closed (e.g. the user force closed it (not force stopped!)).

I've come across the idea of foreground service - which isn't bad, but has one problem - it HAS to send a notification when it is started.

I want the notifications to be like most apps' notification - for example, instagram just sends a notification that a message has been received. There's no notification saying that a service has started.

If someone knows a way - please, tell me. I'm lost :)

Im sorry for not including code. Everything i've tried so far isn't relevant - I need ideas.


问:
Keeping orders from closing if conditions are met & multiple orders
First time coding - trying to set up a bot that creates multiple buy orders every time the buying signal is met and closed once the short signal is triggered - and vice versa. It seems to be working in TradingView when I add the strategy to the chart however when I connect it to 3 commas it only takes in one buy order (paper trading account) - and it closes it specifically when the condition to keep the position from closing is triggered.

I think I've set up the strategy correctly to take up to six positions with pyramiding.

```<code>strategy("DEMA CROSS STRATEGY", shorttitle = "DEMAC-S", overlay = true, initial_capital = 4000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20, commission_type = strategy.commission.percent, commission_value = 0.03, pyramiding = 6)
</code>```

The conditions to keep a position from closing if longAction or shortAction are true, then keep the opened positions from closing, otherwise close all positions and open a long/short.

```<code>positionState = volume < valueThreshold and ADXsignal < adxThreshold

//logic

longCondition = ta.crossover(DEMA1, DEMA2) and supertrend_X_min < close and mfi+rsi/1.8 > 40 and close > WMA
shortCondition = ta.crossunder(DEMA1, DEMA2)  and supertrend_X_min > close and mfi+rsi/1.8 < 60 and close < WMA and atr < .05

longAction = (longCondition and positionState)
shortAction = (shortCondition and positionState)

if (shortAction or longAction)
    false

else

    if (longCondition)
        strategy.entry("Enter Long", strategy.long)
        strategy.exit("Exit Short", stop=na)

    if (shortCondition)
        strategy.entry("Enter Short", strategy.short)
        strategy.exit("Exit Long", stop=na)
//

//Buy and sell alerts

buyAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXX
exitAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXXX

if longAction ? na : longCondition
    alert(buyAlert, alert.freq_once_per_bar)
if shortAction ? na : shortCondition
    alert(exitAlert, alert.freq_once_per_bar)
</code>```

I've tried multiple different if then statements but honestly I'm not sure if I'm just doing it plain wrong at this stage.

Like I've stated, the code works in TradingView - not in 3Commas

Body:
First time coding - trying to set up a bot that creates multiple buy orders every time the buying signal is met and closed once the short signal is triggered - and vice versa. It seems to be working in TradingView when I add the strategy to the chart however when I connect it to 3 commas it only takes in one buy order (paper trading account) - and it closes it specifically when the condition to keep the position from closing is triggered.

I think I've set up the strategy correctly to take up to six positions with pyramiding.

strategy("DEMA CROSS STRATEGY", shorttitle = "DEMAC-S", overlay = true, initial_capital = 4000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20, commission_type = strategy.commission.percent, commission_value = 0.03, pyramiding = 6)

The conditions to keep a position from closing if longAction or shortAction are true, then keep the opened positions from closing, otherwise close all positions and open a long/short.

positionState = volume < valueThreshold and ADXsignal < adxThreshold

//logic

longCondition = ta.crossover(DEMA1, DEMA2) and supertrend_X_min < close and mfi+rsi/1.8 > 40 and close > WMA
shortCondition = ta.crossunder(DEMA1, DEMA2)  and supertrend_X_min > close and mfi+rsi/1.8 < 60 and close < WMA and atr < .05

longAction = (longCondition and positionState)
shortAction = (shortCondition and positionState)

if (shortAction or longAction)
    false

else

    if (longCondition)
        strategy.entry("Enter Long", strategy.long)
        strategy.exit("Exit Short", stop=na)

    if (shortCondition)
        strategy.entry("Enter Short", strategy.short)
        strategy.exit("Exit Long", stop=na)
//

//Buy and sell alerts

buyAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXX
exitAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXXX

if longAction ? na : longCondition
    alert(buyAlert, alert.freq_once_per_bar)
if shortAction ? na : shortCondition
    alert(exitAlert, alert.freq_once_per_bar)

I've tried multiple different if then statements but honestly I'm not sure if I'm just doing it plain wrong at this stage.

Like I've stated, the code works in TradingView - not in 3Commas


问:
foreach array in SQL, print as json
Hello i want to load all user programs by fecthing all the rows in the programs table then foreach row, create a array then print it

current code:

```<code>$programs = $con->query("SELECT * FROM programs");
$json = array(
  "Programs" => array(
    // here, foreach row i want to make a new array and assign it. does not work.
    while ($row = $programs->fetch_assoc())
    {
      print_r($row);
    }
  )
);
</code>```

but doesnt work because of while loop.

please help!

i tried searching all over the internet

Title: foreach array in SQL, print as json

Body:
Hello i want to load all user programs by fecthing all the rows in the programs table then foreach row, create a array then print it

current code:

$programs = $con->query("SELECT * FROM programs");
$json = array(
  "Programs" => array(
    // here, foreach row i want to make a new array and assign it. does not work.
    while ($row = $programs->fetch_assoc())
    {
      print_r($row);
    }
  )
);

but doesnt work because of while loop.

please help!

i tried searching all over the internet


Title: How to extract forecasted vals from BVAR R package?

Body:
I need to extract as df from list of forecasted values in BVAR R package.

Following the https://search.r-project.org/CRAN/refmans/BVAR/html/bvar.html, I tried without success:

library(BVAR)

# Access a subset of the fred_qd dataset
data <- fred_qd[, c("CPIAUCSL", "UNRATE", "FEDFUNDS")]
# Transform it to be stationary
data <- fred_transform(data, codes = c(5, 5, 1), lag = 4)

# Estimate a BVAR using one lag, default settings and very few draws
x <- bvar(data, lags = 1, n_draw = 1000L, n_burn = 200L, verbose = FALSE)

# Calculate and store forecasts and impulse responses
predict(x) <- predict(x, horizon = 8)

By using the predict for the model...

> str(predict(x)$quants)
 num [1:3, 1:8, 1:3] 2.77 5.3 7.93 3.01 5.89 ...
 - attr(*, "dimnames")=List of 3
  ..$ : chr [1:3] "16%" "50%" "84%"
  ..$ : NULL
  ..$ : NULL

And the respective values:

> predict(x)$quants
, , 1

        [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]
16% 2.774658 3.007596 2.844906 3.171022 3.120042 3.280207 3.280711 3.340406
50% 5.295416 5.894685 5.598136 5.936070 5.914653 5.929794 6.015413 6.115462
84% 7.934775 8.441216 8.545498 8.609100 8.635386 8.639450 8.642212 8.743854

, , 2

          [,1]       [,2]       [,3]       [,4]       [,5]        [,6]        [,7]       [,8]
16% -198.35421 -202.46336 -193.93925 -183.83362 -172.58724 -163.328015 -176.077664 -171.85801
50%  -32.86254  -49.75918  -12.30155  -22.73606  -12.29385   -8.360729   -8.124497  -10.49748
84%  108.91752  128.27793  149.10568  139.07234  149.74230  150.878742  146.331703  138.11896

, , 3

          [,1]      [,2]      [,3]       [,4]       [,5]       [,6]      [,7]        [,8]
16% -2.0800047 -1.351935 -1.399585 -0.7301408 -0.5417815 -0.2849631 0.0266887 -0.09101401
50%  0.6846143  1.568261  1.518127  2.2271754  2.3772251  2.6740493 2.9952527  3.31705293
84%  3.3500116  4.367114  4.933579  5.1953887  5.3821811  5.5352213 6.1401906  6.18692133

I need to extract the forecasted values as 50% for each variable listed above by the numbers , , 1 then , , 2 and so on...

How can I extract df from each number of that list ?


问:
Discard invalid objects validation time using Yup
I have a Yup schema, that has a value that is a array of objects.

Like so:

```<code>    export const fooSchema = yup.object({
        bar: yup.string().required(),
        someValue: yup.string().required(),
    }).required();

    export const ArrayOfFooSchema = yup.array().of(fooSchema).required();

    export const someSchema = yup.object({
        foofoo: yup.object({
            someDate: yup.object({
                time: yup.date().required(),
            }).required(),
            foos: ArrayOfFooSchema.required(),
        });
</code>```

My issue is that if one of objects in "foos" does not pass the validation, then the whole "someSchema"s validation fails.

In my use case i need to filter out the objects in the array that does not pass the validation.

I tried to use the .test() function to perform this, but i didnt manage to. Also i looked in a similar thread in Stackoverflow, and i couldnt solve my issue using the answer.

Body:
I have a Yup schema, that has a value that is a array of objects.

Like so:

    export const fooSchema = yup.object({
        bar: yup.string().required(),
        someValue: yup.string().required(),
    }).required();

    export const ArrayOfFooSchema = yup.array().of(fooSchema).required();

    export const someSchema = yup.object({
        foofoo: yup.object({
            someDate: yup.object({
                time: yup.date().required(),
            }).required(),
            foos: ArrayOfFooSchema.required(),
        });

My issue is that if one of objects in "foos" does not pass the validation, then the whole "someSchema"s validation fails.

In my use case i need to filter out the objects in the array that does not pass the validation.

I tried to use the .test() function to perform this, but i didnt manage to. Also i looked in a similar thread in Stackoverflow, and i couldnt solve my issue using the answer.


问:
PHP Unable to Return curl response
I cannot return the response. I successfully tried this request with Postman. The result is in JSON format already, I want to return JSON. If I mess with the header, the error message returned by the api is successfully displayed. The whole point is simply to return the JSON-data, it is retrieved of an API, but the app that I want to display the data in does not support headers, so I'm trying to build an URL which displays the data without any headers needed.

EDIT Solved

Following Phil I've updated my code to:

```<code>$url = "https://api.com/data";
$headers = array(
    "accept-encoding: gzip",
    "cache-control: no-cache",
    "connection: keep-alive",
    "content-type: application/json",
    "Authorization: Bearer superlongkey"
);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_ENCODING, "gzip");

$resp = curl_exec($curl);
curl_close($curl);

$response->getBody()->write($resp);
return $response

</code>```

Additionally, I had to include the line

```<code>    curl_setopt($curl, CURLOPT_ENCODING, "gzip");
</code>```

to decode the data from gzip

```<code>$url = "https://api.com/data";
$headers = array(
    "accept-encoding: gzip",
    "cache-control: no-cache",
    "connection: keep-alive",
    "content-type: application/json",
    "Authorization: Bearer superlongkey"
);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$resp = curl_exec($curl);
curl_close($curl);

$response->getBody()->write(json_encode($resp));
return $response

</code>```

The error I get is

```<code>fwrite() expects parameter 2 to be string, boolean given
</code>```

I've also tried to leave out the fwrite line, but then I get the following error:

```<code>Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must implement interface Psr\Http\Message\ResponseInterface, string returned
</code>```

Title: PHP Unable to Return curl response

Body:
I cannot return the response. I successfully tried this request with Postman. The result is in JSON format already, I want to return JSON. If I mess with the header, the error message returned by the api is successfully displayed. The whole point is simply to return the JSON-data, it is retrieved of an API, but the app that I want to display the data in does not support headers, so I'm trying to build an URL which displays the data without any headers needed.

EDIT Solved

Following Phil I've updated my code to:

$url = "https://api.com/data";
$headers = array(
    "accept-encoding: gzip",
    "cache-control: no-cache",
    "connection: keep-alive",
    "content-type: application/json",
    "Authorization: Bearer superlongkey"
);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_ENCODING, "gzip");

$resp = curl_exec($curl);
curl_close($curl);

$response->getBody()->write($resp);
return $response

Additionally, I had to include the line

    curl_setopt($curl, CURLOPT_ENCODING, "gzip");

to decode the data from gzip

$url = "https://api.com/data";
$headers = array(
    "accept-encoding: gzip",
    "cache-control: no-cache",
    "connection: keep-alive",
    "content-type: application/json",
    "Authorization: Bearer superlongkey"
);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$resp = curl_exec($curl);
curl_close($curl);

$response->getBody()->write(json_encode($resp));
return $response

The error I get is

fwrite() expects parameter 2 to be string, boolean given

I've also tried to leave out the fwrite line, but then I get the following error:

Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must implement interface Psr\Http\Message\ResponseInterface, string returned


问:
Looking for Jacobi elliptic functions in Sympy
I’m trying to solve a Sturm-Liouville problem involving elliptic functions, using pre-existing code, that requires symbolic arguments for these functions.

I found numerical routines for elliptic functions in Scipy and mpmath. I found reference to jcn and jdn in Sympy 2009, but could not import them from Sympy version 1.6.2.


问:
VBA - How to Have OLEObjects.Add work properly with Microsoft Office files when using DisplayAsIcon?
I have a sub-routine to insert file objects onto a worksheet in Excel using the DisplayAsIcon option of OLEObjects.Add. It works perfectly for all files EXCEPT those related to Microsoft Office (Excel file, Word file, etc). For these documents, the code is seemingly not able to detect a default icon or label; is there a way to have this automatically detected? If not, how could I refer to these default icons?

The sub-routine's code is below:

```<code>Public Sub InsertObjectFromFileName(filename As String, k As Double, j As Double)

Dim ws As Worksheet
Set ws = ActiveSheet
ws.OLEObjects.Add filename:=filename, IconLabel:=filename, DisplayAsIcon:=True, Top:=k, left:=j

End Sub
</code>```

When given a Microsoft Office file (.xls, .docx, etc.), the code fails to detect the file's label and icon; otherwise, the code works fine.
I have attempted using IconFileName and setting it equal to the filename parameter as well, but got the same result.

Body:
I have a sub-routine to insert file objects onto a worksheet in Excel using the DisplayAsIcon option of OLEObjects.Add. It works perfectly for all files EXCEPT those related to Microsoft Office (Excel file, Word file, etc). For these documents, the code is seemingly not able to detect a default icon or label; is there a way to have this automatically detected? If not, how could I refer to these default icons?

The sub-routine's code is below:

Public Sub InsertObjectFromFileName(filename As String, k As Double, j As Double)

Dim ws As Worksheet
Set ws = ActiveSheet
ws.OLEObjects.Add filename:=filename, IconLabel:=filename, DisplayAsIcon:=True, Top:=k, left:=j

End Sub

When given a Microsoft Office file (.xls, .docx, etc.), the code fails to detect the file's label and icon; otherwise, the code works fine.
I have attempted using IconFileName and setting it equal to the filename parameter as well, but got the same result.


问:
How to set canva borders for moving object with key_press?
so I've been trying to solve this problem: I need to set window borders so the ship that's moving can't go out of them.

if I put if statement the function key_down doesn't stop running if player doesn't release the key.

```<code>from tkinter import *

LENGHT = 500
WIDTH = 800
window = Tk()
window.title('Ship moving')

a = Canvas(window, width=WIDTH, height=LENGHT, bg = 'red')
a.pack()

background = PhotoImage(file = 'path..')
fons = a.create_image(402,110, image = background)

img = PhotoImage(file = 'path..')
spongijs = a.create_image(50,50, image = img, tags = 'ship')

VID_X = WIDTH / 2
VID_Y = LENGHT / 2

a.move(spongijs, VID_X, VID_Y)

velx = 0
vely = 0
global x
global y
x, y = VID_X, VID_Y

def move():
    global x
    global y
    x += velx
    y += vely
    a.delete("ship") #here it deletes the ship from canvas
    global spongijs
    spongijs = a.create_image(x, y, image = img, tags = 'ship') #and here it adds a new one it different position
    kord = a.coords(spongijs)

def key_press(event):
    global velx
    global vely
    pr = event.char
    if(pr == "a" ):
    #     if kord[1] < 30:       this works only if a player realeses the key and tries to press again when already out of the border
    #         a.bind('<KeyPress-w>', i)
    # else:
    #     a.unbind('<KeyPress-w>', i)
    #     velx = -0.1
        velx = -0.1
    if(pr == "d"):
        velx = 0.1
    if(pr == "w"):
        vely = -0.1
    if(pr == "s"):
        vely = 0.1
def key_release(event):
    global velx
    global vely
    velx = 0
    vely = 0
a.focus_set()
a.bind("<KeyPress>", key_press)
a.bind("<KeyRelease>", key_release)

while True:
    move()
    window.update()
</code>```

so I was thinking maybe there is a way to stop the key_down function or unbind button if one coordinate reaches border

Body:
so I've been trying to solve this problem: I need to set window borders so the ship that's moving can't go out of them.

if I put if statement the function key_down doesn't stop running if player doesn't release the key.

from tkinter import *

LENGHT = 500
WIDTH = 800
window = Tk()
window.title('Ship moving')

a = Canvas(window, width=WIDTH, height=LENGHT, bg = 'red')
a.pack()

background = PhotoImage(file = 'path..')
fons = a.create_image(402,110, image = background)

img = PhotoImage(file = 'path..')
spongijs = a.create_image(50,50, image = img, tags = 'ship')

VID_X = WIDTH / 2
VID_Y = LENGHT / 2

a.move(spongijs, VID_X, VID_Y)

velx = 0
vely = 0
global x
global y
x, y = VID_X, VID_Y

def move():
    global x
    global y
    x += velx
    y += vely
    a.delete("ship") #here it deletes the ship from canvas
    global spongijs
    spongijs = a.create_image(x, y, image = img, tags = 'ship') #and here it adds a new one it different position
    kord = a.coords(spongijs)

def key_press(event):
    global velx
    global vely
    pr = event.char
    if(pr == "a" ):
    #     if kord[1] < 30:       this works only if a player realeses the key and tries to press again when already out of the border
    #         a.bind('<KeyPress-w>', i)
    # else:
    #     a.unbind('<KeyPress-w>', i)
    #     velx = -0.1
        velx = -0.1
    if(pr == "d"):
        velx = 0.1
    if(pr == "w"):
        vely = -0.1
    if(pr == "s"):
        vely = 0.1
def key_release(event):
    global velx
    global vely
    velx = 0
    vely = 0
a.focus_set()
a.bind("<KeyPress>", key_press)
a.bind("<KeyRelease>", key_release)

while True:
    move()
    window.update()

so I was thinking maybe there is a way to stop the key_down function or unbind button if one coordinate reaches border


问:
Where do I save the log4j.properties file so that RedhawkSDR will automatically find it
I've compiled RedhawkSDR v3.0.0 within a Docker container and tried to implement the Basic Sandbox Example from RedhawkSDR's manual (Manual for v3.0.0 & v3.0.1). However, I've encountered  this problem, as shown below:

```<code>$ docker run -it docker-redhawk3.0.0-src

[root@2c65bf0659d7 Redhawk_User]# python3
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ossie.utils import sb
>>> sb.catalog()
['rh.AmFmPmBasebandDemod', 'rh.ArbitraryRateResampler', 'rh.DataConverter', 'rh.FileReader', 'rh.FileWriter', 'rh.HardLimit', 'rh.RBDSDecoder', 'rh.SigGen', 'rh.SinkSDDS', 'rh.SinkVITA49', 'rh.SourceSDDS', 'rh.SourceVITA49', 'rh.TuneFilterDecimate', 'rh.agc', 'rh.autocorrelate', 'rh.fastfilter', 'rh.fcalc', 'rh.psd', 'rh.psk_soft', 'rh.sinksocket', 'rh.sourcesocket']
>>> sigGen = sb.launch("rh.SigGen")
>>> hardLimit = sb.launch("rh.HardLimit")
>>> sb.IDELocation("/eclipse")
>>> plot = sb.Plot()
>>> sigGen.connect(hardLimit)
>>> hardLimit.connect(plot)
>>> log4j:WARN No appenders could be found for logger (jacorb.config).
log4j:WARN Please initialize the log4j system properly.
Plotter: Cannot open display:
</code>```

(Note: The error takes about 5 sec to appear, which is why the >>> prompt appears before the error message.)

I've Googled this error and found a relevant StackOverflow entry(No appenders could be found for logger(log4j)?). I also looked at the section on logging in the Redhawk Manual(RedhawkSDR-LoggingConfig). I got the impression that if I created a file called log4j.properties and either indicated where it was by including it in the Java CLASSPATH environment variable, or placed it in the directory with the log4j jar files, then this error would be resolved.

A reasonable default for this file was given as: (Note: Multiple answers in StackOverflow had the bottom formatted string without quotes, but the Redhawk version used quotes. I tried with & without, but without success):

```<code># Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
</code>```

However, adding this file in both locations did not solve the problem. I also tried adding the directory with log4j jar files to the CLASSPATH variable, but without success.

logAt this point, I don't know what to do. How can I fix the log4j errors? How can I open the plotter? Is the plotter not opening a function of the log4j errors or does it have something to do with my use of Docker?

Body:
I've compiled RedhawkSDR v3.0.0 within a Docker container and tried to implement the Basic Sandbox Example from RedhawkSDR's manual (Manual for v3.0.0 & v3.0.1). However, I've encountered  this problem, as shown below:

$ docker run -it docker-redhawk3.0.0-src

[root@2c65bf0659d7 Redhawk_User]# python3
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ossie.utils import sb
>>> sb.catalog()
['rh.AmFmPmBasebandDemod', 'rh.ArbitraryRateResampler', 'rh.DataConverter', 'rh.FileReader', 'rh.FileWriter', 'rh.HardLimit', 'rh.RBDSDecoder', 'rh.SigGen', 'rh.SinkSDDS', 'rh.SinkVITA49', 'rh.SourceSDDS', 'rh.SourceVITA49', 'rh.TuneFilterDecimate', 'rh.agc', 'rh.autocorrelate', 'rh.fastfilter', 'rh.fcalc', 'rh.psd', 'rh.psk_soft', 'rh.sinksocket', 'rh.sourcesocket']
>>> sigGen = sb.launch("rh.SigGen")
>>> hardLimit = sb.launch("rh.HardLimit")
>>> sb.IDELocation("/eclipse")
>>> plot = sb.Plot()
>>> sigGen.connect(hardLimit)
>>> hardLimit.connect(plot)
>>> log4j:WARN No appenders could be found for logger (jacorb.config).
log4j:WARN Please initialize the log4j system properly.
Plotter: Cannot open display:

(Note: The error takes about 5 sec to appear, which is why the >>> prompt appears before the error message.)

I've Googled this error and found a relevant StackOverflow entry(No appenders could be found for logger(log4j)?). I also looked at the section on logging in the Redhawk Manual(RedhawkSDR-LoggingConfig). I got the impression that if I created a file called log4j.properties and either indicated where it was by including it in the Java CLASSPATH environment variable, or placed it in the directory with the log4j jar files, then this error would be resolved.

A reasonable default for this file was given as: (Note: Multiple answers in StackOverflow had the bottom formatted string without quotes, but the Redhawk version used quotes. I tried with & without, but without success):

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

However, adding this file in both locations did not solve the problem. I also tried adding the directory with log4j jar files to the CLASSPATH variable, but without success.

logAt this point, I don't know what to do. How can I fix the log4j errors? How can I open the plotter? Is the plotter not opening a function of the log4j errors or does it have something to do with my use of Docker?


问:
Can json schema references have a template?
I'm working on reducing json schema, to try and make it easier to follow.  Many of my nodes are of the same general form:

```<code>{
   "[$PassedName]": {
       "type": "object",
       "properties": {
           "current": {
               "type": "object",
               "[$PassedName]" : {"$ref": "#/definitions/Objects/[$PassedName]"}
           },
           "history": {
               "type": "array",
               "[$PassedName]" : {"$ref": "#/definitions/Objects/[$PassedName]"}
           }
       }
    }
}
</code>```

What I'd like to do is to pass a string to a reference, so the reference could use that string in the given locations.  For example, giving the reference the string value "SSN" would have a resultant schema of the following:

```<code>{
   "SSN": {
       "type": "object",
       "properties": {
           "current": {
               "type": "object",
               "SSN": "#/definitions/Objects/SSN"
           },
           "history": {
               "type": "array",
               "SSN": "#/definitions/Objects/SSN"
           }
       }
    }
}
</code>```

Is this at all possible with json schemas?  I've more than a dozen of basically the same node, so I'd like to simplify, if possible.

Body:
I'm working on reducing json schema, to try and make it easier to follow.  Many of my nodes are of the same general form:

{
   "[$PassedName]": {
       "type": "object",
       "properties": {
           "current": {
               "type": "object",
               "[$PassedName]" : {"$ref": "#/definitions/Objects/[$PassedName]"}
           },
           "history": {
               "type": "array",
               "[$PassedName]" : {"$ref": "#/definitions/Objects/[$PassedName]"}
           }
       }
    }
}

What I'd like to do is to pass a string to a reference, so the reference could use that string in the given locations.  For example, giving the reference the string value "SSN" would have a resultant schema of the following:

{
   "SSN": {
       "type": "object",
       "properties": {
           "current": {
               "type": "object",
               "SSN": "#/definitions/Objects/SSN"
           },
           "history": {
               "type": "array",
               "SSN": "#/definitions/Objects/SSN"
           }
       }
    }
}

Is this at all possible with json schemas?  I've more than a dozen of basically the same node, so I'd like to simplify, if possible.


问:
PIT mutation testing in Jenkin s ignores some classes
I have upwardes of 200 classes in a Maven java application and I use Jenkin to manage the test and build.
Jenkins continued to report a nice high coverage figure but when I dig into the report I notioced some classed hadf not been analysed.

These classes all took data from a source, did some work created a message and then added it to a database table via a sertvice and JPA repository. I am testing using a mixture of mocking and argument capture.

I found that it I added a "simple method" to the class (add two numbers and return the sum) then PIT analysed and reported on all the methods in the class.

I tried with and without an interface, in different folder and made minor changes to the methods and the mocks.
Switching on verbose loggion in PIT did not help.


问:
main.js:149 Uncaught TypeError: L.easyButton is not a function, Leaflet Button not working?
I have currently a map and am trying to create a Leaflet Easy button that toggles if the info__container shows or not. I have also tried display = 'none' but nothing happens.

Currently getting this issue

Uncaught TypeError: L.easyButton is not a function

I have also made sure that the L.easy Button files are after the main leaflet.js

```<code>        <!--map required links-->
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
        <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>

        <!--map plugin to locate user-->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol@0.79.0/dist/L.Control.Locate.min.css" />
        <script src="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol@0.79.0/dist/L.Control.Locate.min.js" charset="utf-8"></script>

        <!--easy button plugin-->
        <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
        <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>

</code>```

This is my JS

```<code>var informationBar = document.getElementById(info__container);

var toggle = L.easyButton({
    states: [{
    stateName: 'add-markers',
    icon: '<span class="star">≡</span>',
    title: 'Menu',
    onClick: function(control) {
        map.addLayer(informationBar);
        control.state('remove-markers');
    }
    }, {
    icon: 'fa-undo',
    stateName: 'remove-markers',
    onClick: function(control) {
        map.removeLayer(informationBar);
        control.state('add-markers');
    },
    title: 'remove markers'
    }]
});
toggle.addTo(map);
</code>```

my HTML div start

```<code><div id="info__container">
    <table class="tableContainer">
        <tbody>
         <!--Title-->
</code>```

my css

```<code>#info__container{
    position: absolute;
    z-index: 800;
    margin-top: 10%; /*change for mobile*/
    margin-left: 5rem;
    align-items: center;
    display: inline-flex;
    flex-direction: column;
    width: 250px;
}
</code>```

I'm a newbie so please bear with me

I have tried different types of functions using map methods or just normal function onclick:

this said I have also tried .toggle()

Body:
I have currently a map and am trying to create a Leaflet Easy button that toggles if the info__container shows or not. I have also tried display = 'none' but nothing happens.

Currently getting this issue

Uncaught TypeError: L.easyButton is not a function

I have also made sure that the L.easy Button files are after the main leaflet.js

        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol@0.79.0/dist/L.Control.Locate.min.css" />

        <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />

This is my JS

var informationBar = document.getElementById(info__container);

var toggle = L.easyButton({
    states: [{
    stateName: 'add-markers',
    icon: '≡',
    title: 'Menu',
    onClick: function(control) {
        map.addLayer(informationBar);
        control.state('remove-markers');
    }
    }, {
    icon: 'fa-undo',
    stateName: 'remove-markers',
    onClick: function(control) {
        map.removeLayer(informationBar);
        control.state('add-markers');
    },
    title: 'remove markers'
    }]
});
toggle.addTo(map);

my HTML div start

my css

#info__container{
    position: absolute;
    z-index: 800;
    margin-top: 10%; /*change for mobile*/
    margin-left: 5rem;
    align-items: center;
    display: inline-flex;
    flex-direction: column;
    width: 250px;
}

I'm a newbie so please bear with me

I have tried different types of functions using map methods or just normal function onclick:

this said I have also tried .toggle()


问:
How to use binding redirects when dynamically loading assembly with MEF
I have a .NET 4.8 library that is loaded as a plugin via MEF. That library has automatically generated binding redirects for some of its dependencies:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Channels" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
```
<p>My main application (.NET 4.8) loads the library assembly dynamically via MEF. When the main application loads the library (e.g. <code>MyLibrary.dll</code>), it appears to ignore the binding redirects that are defined in the config file (<code>MyLibrary.dll.config</code>) that sits alongside the library assembly, and I get a composition exception because the assembly fails to load:</p>
<pre class="lang-none prettyprint-override"><code>Unhandled Exception: System.ComponentModel.Composition.CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Could not load file or assembly 'Microsoft.Bcl.AsyncInterfaces, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Resulting in: An exception occurred while trying to create an instance of type 'MyLibrary.MyType'.
Resulting in: Cannot activate part 'MyLibrary.MyType'.
Element: MyLibrary.MyType -->  MyLibrary.MyType -->  AssemblyCatalog (Assembly="MyLibrary, Version=3.9.0.0, Culture=neutral, PublicKeyToken=null")
Resulting in: Cannot get export 'MyLibrary.MyType (ContractName="LibraryBaseType")' from part 'MyLibrary.MyType'.
Element: MyLibrary.MyType (ContractName="LibraryBaseType") -->  MyLibrary.MyType -->  AssemblyCatalog (Assembly="MyLibrary, Version=3.9.0.0, Culture=neutral, PublicKeyToken=null")
   at System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
   at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart)
   at System.ComponentModel.Composition.Primitives.Export.get_Value()
   at System.ComponentModel.Composition.ExportServices.GetCastedExportedValue[T](Export export)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at MainApplication.Start(String[] args) in ...\MainApplication.cs:line 65
   at MainApplication.Main(String[] args) in ...\MainApplication.cs:line 31
</code>```

Is there any way for my application to respect the binding redirects for a dynamically loaded library, if the binding redirects are defined alongside the library assembly? Or am I stuck copy-pasting all of the binding redirects into the app.config of the main application?

Body:
I have a .NET 4.8 library that is loaded as a plugin via MEF. That library has automatically generated binding redirects for some of its dependencies:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Channels" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

My main application (.NET 4.8) loads the library assembly dynamically via MEF. When the main application loads the library (e.g. MyLibrary.dll), it appears to ignore the binding redirects that are defined in the config file (MyLibrary.dll.config) that sits alongside the library assembly, and I get a composition exception because the assembly fails to load:

Unhandled Exception: System.ComponentModel.Composition.CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Could not load file or assembly 'Microsoft.Bcl.AsyncInterfaces, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Resulting in: An exception occurred while trying to create an instance of type 'MyLibrary.MyType'.
Resulting in: Cannot activate part 'MyLibrary.MyType'.
Element: MyLibrary.MyType -->  MyLibrary.MyType -->  AssemblyCatalog (Assembly="MyLibrary, Version=3.9.0.0, Culture=neutral, PublicKeyToken=null")
Resulting in: Cannot get export 'MyLibrary.MyType (ContractName="LibraryBaseType")' from part 'MyLibrary.MyType'.
Element: MyLibrary.MyType (ContractName="LibraryBaseType") -->  MyLibrary.MyType -->  AssemblyCatalog (Assembly="MyLibrary, Version=3.9.0.0, Culture=neutral, PublicKeyToken=null")
   at System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
   at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart)
   at System.ComponentModel.Composition.Primitives.Export.get_Value()
   at System.ComponentModel.Composition.ExportServices.GetCastedExportedValue[T](Export export)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at MainApplication.Start(String[] args) in ...\MainApplication.cs:line 65
   at MainApplication.Main(String[] args) in ...\MainApplication.cs:line 31

Is there any way for my application to respect the binding redirects for a dynamically loaded library, if the binding redirects are defined alongside the library assembly? Or am I stuck copy-pasting all of the binding redirects into the app.config of the main application?


Title: How to replace the rownames of a dataframe with information from another dataframe based on a column?

Body:
I want to rename the index of METcancer.filtered with the rownames of cpg.symbol if the GENE_SYMBOL column value matches the existing rownames of METcancer.filtered.

My code below returned "NULL".

rownames(METcancer.filtered) <- rownames(cpg.symbol[cpg.symbol$GENE_SYMBOL %in% rownames(METcancer.filtered),])

Data:

METcancer.filtered

> dput(METcancer.filtered[1:5,1:5])
structure(c(0.936065885072034, 0.760063272526672, 0.849664612215924,
0.307465252710058, 0.0806540288779055, 0.905611840347474, 0.589167124893843,
0.678726685812101, 0.137120205681178, 0.0588078725188056, 0.914721280502537,
0.74140669028999, 0.864305433550123, 0.268585708286729, 0.227311388507558,
0.937877051432322, 0.704027552497729, 0.680150780394169, 0.132336313766774,
0.399603073219686, 0.923913298905444, 0.796189700820243, 0.810224634062211,
0.236114867806732, 0.0803320327165197), dim = c(5L, 5L), dimnames = list(
    c("A2ML1", "ABCA4", "ABCB5", "ABHD1", "ACRBP"), c("TCGA-2K-A9WE",
    "TCGA-2Z-A9J1", "TCGA-2Z-A9J2", "TCGA-2Z-A9J3", "TCGA-2Z-A9J5"
    )))

cpg.symbol

> dput(cpg.symbol[1:100,])
c("RBL2", "VDAC3", "ACTN1", "ATP2A1", "SFRP1", "NIPA2", "MAN1B1",
"LRRC16A", "CNBP", "DDX55", "FAM81A", "KCNQ1;KCNQ1OT1", "NPHP4",
"MRPS25", "MAEL", "PROX1", "ELOVL1", "LILRA6", "LOC283050;ZMIZ1",
"NR5A2", "CDK10", "TMEM182", "DNAJA2", "ATOH7", "LRFN1", "MRPL12",
"COL6A3", "C8orf31", "RTTN", "CD2BP2", "SLMAP", "NOV", "MXD4",
"SND1;MIR593", "MUSTN1", "TAS1R3", "ITGAD", "SMARCC2", "C1orf114",
"C1orf65", "DNAH17", "DAB1", "SLBP", "CHCHD4;TMEM43", "TNNT2",
"CASZ1", "CASZ1", "C3orf16", "WFIKKN2", "CCDC45;DDX5", "MEOX2",
"CKLF", "TRANK1", "ZFP36", "SLC2A9", "MXRA7", "LOXL4", "P2RX6P",
"SFRS7", "EHMT1", "AGPAT3", "CDSN;PSORS1C1", "AGA", "LDHD", "C14orf181",
"LOC729176;C6orf103", "SH2B3", "MTMR7", "MT1F", "RSPO3", "ANKRD11",
"TDRD6", "WWP2", "OR1F2P", "SERPINB12", "DOK7", "SRCAP", "AMDHD2;ATP6V0C",
"DRG2;MYO15A", "TCTE3;C6orf70", "EFNB1", "FAM180B", "MTHFD2L",
"HOXD3", "GPHN", "HMX2", "C12orf44", "TDRD10", "OTOF", "NHLH1",
"NUP210L", "IL1RAPL2", "CCDC126", "MTUS2", "ZNF362", "LHX6",
"RRS1", "PTPRF", "PACS2", "C4orf39;TRIM61")


问:
Unclear route "pathMatch" breaking change upgrading to Angular 14
One of the Angular upgrade notes at https://update.angular.io/?l=3&v=13.0-14.0 about moving to Angular 14 reads "If you are defining routes with pathMatch, you may have to cast it to Route or Routes explicitly. Route.pathMatch is no longer compatible with string type." I may have to cast what?

The second sentence contradicts the interface declaration at https://angular.io/api/router/Route, which is:

pathMatch?: 'prefix' | 'full'

So, it's still a string type. How do you cast that to Route or Routes?

More specifically, if my existing definition of routes begins

```<code>const routes: Routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },
</code>```

then what is the upgrade note telling me I have to do? Maybe "it" in the note refers to the route, and I need to cast

  { path: '', pathMatch: 'full', component: HomeComponent }

to a Route, but what does that have to do with being "no longer compatible with a string type"? I mean, 'full' is a string and it matches the type spec 'prefix' | 'full', so what's the issue here?

Body:
One of the Angular upgrade notes at https://update.angular.io/?l=3&v=13.0-14.0 about moving to Angular 14 reads "If you are defining routes with pathMatch, you may have to cast it to Route or Routes explicitly. Route.pathMatch is no longer compatible with string type." I may have to cast what?

The second sentence contradicts the interface declaration at https://angular.io/api/router/Route, which is:

pathMatch?: 'prefix' | 'full'

So, it's still a string type. How do you cast that to Route or Routes?

More specifically, if my existing definition of routes begins

const routes: Routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },

then what is the upgrade note telling me I have to do? Maybe "it" in the note refers to the route, and I need to cast

  { path: '', pathMatch: 'full', component: HomeComponent }

to a Route, but what does that have to do with being "no longer compatible with a string type"? I mean, 'full' is a string and it matches the type spec 'prefix' | 'full', so what's the issue here?