问:
Parallelization of multiple numpy.linalg.multi_dot calls
I'm trying to parallelize this function:

```<code>def update_G_left(self):
    num = np.linalg.multi_dot([self.association_matrix,
                               self.G_right, self.S.transpose()])
    den = np.linalg.multi_dot([self.G_left, self.S, self.G_right.transpose(),
                               self.G_right, self.S.transpose()])

    for am in self.dep_own_left_other_left:
        num += np.linalg.multi_dot([am.association_matrix,
                                    am.G_right, am.S.transpose()])
        den += np.linalg.multi_dot([self.G_left, am.S, am.G_right.transpose(),
                                    am.G_right, am.S.transpose()])
    for am in self.dep_own_left_other_right:
        num += np.linalg.multi_dot([am.association_matrix.transpose(),
                                    am.G_left, am.S])
        den += np.linalg.multi_dot([self.G_left, am.S.transpose(),
                                    am.G_left.transpose(), am.G_left, am.S])
    div = np.divide(num, den + sys.float_info.min)
    return np.multiply(self.G_left, div)
</code>```

The function is working well, but when I use pools:

```<code>def update_G_left(self):
    num = np.linalg.multi_dot([self.association_matrix, self.G_right, self.S.transpose()])
    den = np.linalg.multi_dot([self.G_left, self.S, self.G_right.transpose(), self.G_right, self.S.transpose()])
    with multiprocessing.Pool(6) as pool:
        for x in pool.map(np.linalg.multi_dot,
                          [[am.association_matrix, am.G_right, am.S.transpose()]
                           for am in self.dep_own_right_other_left]):
            num += x
        for x in pool.map(np.linalg.multi_dot,
                          [[self.G_left, am.S,
                            am.G_right.transpose(), am.G_right, am.S.transpose()]
                           for am in self.dep_own_right_other_left]):
            den += x
        for x in pool.map(np.linalg.multi_dot,
                          [[am.association_matrix.transpose(), am.G_left, am.S]
                           for am in self.dep_own_right_other_right]):
            num += x
        for x in pool.map(np.linalg.multi_dot,
                          [[self.G_left, am.S.transpose(),
                            am.G_left.transpose(), am.G_left, am.S]
                           for am in self.dep_own_right_other_right]):
            den += x
    div = np.divide(num, den + sys.float_info.min)
    return np.multiply(self.G_left, div)
</code>```

Now it is no more working.

I get the error ValueError: operands could not be broadcast together with shapes (10,6) (7,6) (10,6) at the second num += x .
I'm wondering why because i don't see any differences in the code.
There are other patterns to parallelize my function?

Body:
I'm trying to parallelize this function:

def update_G_left(self):
    num = np.linalg.multi_dot([self.association_matrix,
                               self.G_right, self.S.transpose()])
    den = np.linalg.multi_dot([self.G_left, self.S, self.G_right.transpose(),
                               self.G_right, self.S.transpose()])

    for am in self.dep_own_left_other_left:
        num += np.linalg.multi_dot([am.association_matrix,
                                    am.G_right, am.S.transpose()])
        den += np.linalg.multi_dot([self.G_left, am.S, am.G_right.transpose(),
                                    am.G_right, am.S.transpose()])
    for am in self.dep_own_left_other_right:
        num += np.linalg.multi_dot([am.association_matrix.transpose(),
                                    am.G_left, am.S])
        den += np.linalg.multi_dot([self.G_left, am.S.transpose(),
                                    am.G_left.transpose(), am.G_left, am.S])
    div = np.divide(num, den + sys.float_info.min)
    return np.multiply(self.G_left, div)

The function is working well, but when I use pools:

def update_G_left(self):
    num = np.linalg.multi_dot([self.association_matrix, self.G_right, self.S.transpose()])
    den = np.linalg.multi_dot([self.G_left, self.S, self.G_right.transpose(), self.G_right, self.S.transpose()])
    with multiprocessing.Pool(6) as pool:
        for x in pool.map(np.linalg.multi_dot,
                          [[am.association_matrix, am.G_right, am.S.transpose()]
                           for am in self.dep_own_right_other_left]):
            num += x
        for x in pool.map(np.linalg.multi_dot,
                          [[self.G_left, am.S,
                            am.G_right.transpose(), am.G_right, am.S.transpose()]
                           for am in self.dep_own_right_other_left]):
            den += x
        for x in pool.map(np.linalg.multi_dot,
                          [[am.association_matrix.transpose(), am.G_left, am.S]
                           for am in self.dep_own_right_other_right]):
            num += x
        for x in pool.map(np.linalg.multi_dot,
                          [[self.G_left, am.S.transpose(),
                            am.G_left.transpose(), am.G_left, am.S]
                           for am in self.dep_own_right_other_right]):
            den += x
    div = np.divide(num, den + sys.float_info.min)
    return np.multiply(self.G_left, div)

Now it is no more working.

I get the error ValueError: operands could not be broadcast together with shapes (10,6) (7,6) (10,6) at the second num += x .
I'm wondering why because i don't see any differences in the code.
There are other patterns to parallelize my function?


来源: stackexchange

问:
Why msgrcv does not save recieved values in structure?
I have two programs: server.c, and c1.c.
Server should be running infinitely, and other programs, like c1.c, should send the number to the server, and get the square of that number as a server answer. The problem with my two programs is that server calculates number correctlly, c1 reads from the message queue without errors, but it does not save the number to the struct.

server.c:

```<code>#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define LAST_MESSAGE 255
int main()
{
    int msqid;
    char pathname[] = "server.c";
    key_t key;
    int len, maxlen;
    struct mymsgbuf
    {
        long mtype;
        int pid;
        int num;
    } mybuf;
    if((key = ftok(pathname,0)) < 0){
        printf("Can\'t generate key\n");
        exit(-1);
    }
    if((msqid = msgget(key, 0666 | IPC_CREAT)) < 0){
        printf("Can\'t get msqid\n");
        exit(-1);
    }

    //SERVER

    while(1){
        maxlen = sizeof(mybuf.num) + sizeof(mybuf.pid);
        if( len = msgrcv(msqid, (struct msgbuf *) &mybuf, maxlen, 1, 0) < 0){
            printf("Can\'t receive message from queue\n");
            exit(-1);
        }
        printf("Got number from process (#%d): '%d'", mybuf.pid, mybuf.num);

        mybuf.mtype=mybuf.pid;
        int answer = (mybuf.num * mybuf.num);
        printf("Calculating... %d*%d = %d\n", mybuf.num, mybuf.num, answer);
        mybuf.num = answer;
        printf("mybuf.num=%d\n", mybuf.num);
        printf("Sending answer to process (#%d).\n", mybuf.pid);
        if (msgsnd(msqid, (struct msgbuf *) &mybuf, len, 0) < 0){
            printf("Can\'t send message to queue\n");
            msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL);
            exit(-1);
        }
        printf("Sent answer to process (#%d).\n", mybuf.pid);
    }
    return 0;
}
</code>```

c1.c:

```<code>#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define LAST_MESSAGE 255
int main()
{
    int msqid;
    char pathname[] = "server.c";
    key_t key;
    int len, maxlen;
    struct mymsgbuf
    {
        long mtype;
        int pid;
        int num;
    } mybuf;

    int c1_pid = getpid();
    mybuf.pid = c1_pid;

    if((key = ftok(pathname,0)) < 0){
        printf("Can\'t generate key\n");
        exit(-1);
    }
    if((msqid = msgget(key, 0666 | IPC_CREAT)) < 0){
        printf("Can\'t get msqid\n");
        exit(-1);
    }

    for (int i=1; i<=5; i++)
    {
        mybuf.num = i;
        mybuf.mtype = 1;
        maxlen = sizeof(mybuf.num) + sizeof(mybuf.pid);
        if (msgsnd(msqid, (struct msgbuf *) &mybuf, maxlen, 0) < 0){
            printf("Can\'t send message to queue\n");
            msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL);
            exit(-1);
        }
        printf("Process with pid=%d sent the message to the server. number = %d \n", c1_pid, i);
        printf("num=%d pid=%d\n", mybuf.num, mybuf.pid);
        if( len = msgrcv(msqid, (struct msgbuf *) &mybuf, maxlen, c1_pid, 0) < 0){
            printf("Can\'t receive message from queue\n");
            exit(-1);
        }
        printf("Process with pid=%d recieved answer from server. Answer=%d \n", c1_pid, mybuf.num);
        sleep(0.4);
    }

}
</code>```

server.c results:

c1.c results:

What am i doing wrong, and how should i prevent this from happening?
Thanks in advance!

ContentLicense: CC BY-SA 4.0

Body:
I have two programs: server.c, and c1.c.
Server should be running infinitely, and other programs, like c1.c, should send the number to the server, and get the square of that number as a server answer. The problem with my two programs is that server calculates number correctlly, c1 reads from the message queue without errors, but it does not save the number to the struct.

server.c:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define LAST_MESSAGE 255
int main()
{
    int msqid;
    char pathname[] = "server.c";
    key_t key;
    int len, maxlen;
    struct mymsgbuf
    {
        long mtype;
        int pid;
        int num;
    } mybuf;
    if((key = ftok(pathname,0)) < 0){
        printf("Can\'t generate key\n");
        exit(-1);
    }
    if((msqid = msgget(key, 0666 | IPC_CREAT)) < 0){
        printf("Can\'t get msqid\n");
        exit(-1);
    }

    //SERVER

    while(1){
        maxlen = sizeof(mybuf.num) + sizeof(mybuf.pid);
        if( len = msgrcv(msqid, (struct msgbuf *) &mybuf, maxlen, 1, 0) < 0){
            printf("Can\'t receive message from queue\n");
            exit(-1);
        }
        printf("Got number from process (#%d): '%d'", mybuf.pid, mybuf.num);

        mybuf.mtype=mybuf.pid;
        int answer = (mybuf.num * mybuf.num);
        printf("Calculating... %d*%d = %d\n", mybuf.num, mybuf.num, answer);
        mybuf.num = answer;
        printf("mybuf.num=%d\n", mybuf.num);
        printf("Sending answer to process (#%d).\n", mybuf.pid);
        if (msgsnd(msqid, (struct msgbuf *) &mybuf, len, 0) < 0){
            printf("Can\'t send message to queue\n");
            msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL);
            exit(-1);
        }
        printf("Sent answer to process (#%d).\n", mybuf.pid);
    }
    return 0;
}

c1.c:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define LAST_MESSAGE 255
int main()
{
    int msqid;
    char pathname[] = "server.c";
    key_t key;
    int len, maxlen;
    struct mymsgbuf
    {
        long mtype;
        int pid;
        int num;
    } mybuf;

    int c1_pid = getpid();
    mybuf.pid = c1_pid;

    if((key = ftok(pathname,0)) < 0){
        printf("Can\'t generate key\n");
        exit(-1);
    }
    if((msqid = msgget(key, 0666 | IPC_CREAT)) < 0){
        printf("Can\'t get msqid\n");
        exit(-1);
    }

    for (int i=1; i<=5; i++)
    {
        mybuf.num = i;
        mybuf.mtype = 1;
        maxlen = sizeof(mybuf.num) + sizeof(mybuf.pid);
        if (msgsnd(msqid, (struct msgbuf *) &mybuf, maxlen, 0) < 0){
            printf("Can\'t send message to queue\n");
            msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL);
            exit(-1);
        }
        printf("Process with pid=%d sent the message to the server. number = %d \n", c1_pid, i);
        printf("num=%d pid=%d\n", mybuf.num, mybuf.pid);
        if( len = msgrcv(msqid, (struct msgbuf *) &mybuf, maxlen, c1_pid, 0) < 0){
            printf("Can\'t receive message from queue\n");
            exit(-1);
        }
        printf("Process with pid=%d recieved answer from server. Answer=%d \n", c1_pid, mybuf.num);
        sleep(0.4);
    }

}

server.c results:

c1.c results:

What am i doing wrong, and how should i prevent this from happening?
Thanks in advance!


问:
react keyboard event in the boxes, display a particular character in the boxes
I am trying to learn react, so I followed the below youtube video and building a small app
https://www.youtube.com/watch?v=5xf4_Kx7azg&t=1895

but for some reason when I type a letter in the boxes letters are not showing up in the boxes.
I debugged and put console .log and saw this when I type a.
can you let me know how to fix it.
providing my code snippet below.

https://codesandbox.io/s/exciting-noyce-zeckps?file=/src/App.js

```<code><!-- language: lang-or-tag-here -->

</code>```
```<code>// another prop isFinal
function Line(guess, isFinal, solution) {
  console.log("type here", guess );
  const tiles = [];
  //for each guess I am creating a tile
  // since guess can be null I am using for loop
  // we need for loop since empty strings can't be length 5
  for (let i = 0; i < WORD_LENGTH; i++) {
    let className = "tile";

    const char = guess[i];

    //const char = "";
    tiles.push(
      <div key={i} className="tile">
        {char}
      </div>
    );
  }
  return <div className="line">{tiles}</div>;
}
</code>```

Body:
I am trying to learn react, so I followed the below youtube video and building a small app
https://www.youtube.com/watch?v=5xf4_Kx7azg&t=1895

but for some reason when I type a letter in the boxes letters are not showing up in the boxes.
I debugged and put console .log and saw this when I type a.
can you let me know how to fix it.
providing my code snippet below.

https://codesandbox.io/s/exciting-noyce-zeckps?file=/src/App.js

// another prop isFinal
function Line(guess, isFinal, solution) {
  console.log("type here", guess );
  const tiles = [];
  //for each guess I am creating a tile
  // since guess can be null I am using for loop
  // we need for loop since empty strings can't be length 5
  for (let i = 0; i < WORD_LENGTH; i++) {
    let className = "tile";

    const char = guess[i];

    //const char = "";
    tiles.push(

        {char}

    );
  }
  return
{tiles}
;
}


问:
mutable variable locally reassigned in python recursion
I wrote some code wrong and found my bug, which is that I reassigned a mutable variable locally. However, the observed behavior confused me.

Here is a minimal example:

```<code>import numpy as np
n = 138

MQ = np.zeros((n, 0))

def calc(v):
  print(v)

  #do some complicated math
  if v % 16 == 3:
    q = np.random.random((n, 1))
    MQ = np.hstack((MQ, q))
  else:
    #do some complicated math and eventually call function recursively
    pass

  calc(v-1)

calc(700)
</code>```

As you can see, MQ is bound to a numpy array initially of size (138, 0) and the recursive function stacks some (138,1) arrays onto it when some complicated math things happen, the intention being to find some valid 138 dimensional vectors that solve the complicated math problem.

Of course, the bug here is that MQ is reassigned each recursion and will never mutate correctly because nothing in the code actually mutates it.

However, the behavior that I would expect from this example is, that on every recursion, the calc() function does not have the new incarnation of the variable MQ, instead it has the version of MQ that it closed over, which is an 138x0 array that was reassigned in the previous recursive call, but the original was never touched.

Instead, the behavior observed when running this example is UnboundLocalError: local variable 'MQ' referenced before assignment. Why is this? Clearly the recursive function closes over MQ, how can it be unbound?

Body:
I wrote some code wrong and found my bug, which is that I reassigned a mutable variable locally. However, the observed behavior confused me.

Here is a minimal example:

import numpy as np
n = 138

MQ = np.zeros((n, 0))

def calc(v):
  print(v)

  #do some complicated math
  if v % 16 == 3:
    q = np.random.random((n, 1))
    MQ = np.hstack((MQ, q))
  else:
    #do some complicated math and eventually call function recursively
    pass

  calc(v-1)

calc(700)

As you can see, MQ is bound to a numpy array initially of size (138, 0) and the recursive function stacks some (138,1) arrays onto it when some complicated math things happen, the intention being to find some valid 138 dimensional vectors that solve the complicated math problem.

Of course, the bug here is that MQ is reassigned each recursion and will never mutate correctly because nothing in the code actually mutates it.

However, the behavior that I would expect from this example is, that on every recursion, the calc() function does not have the new incarnation of the variable MQ, instead it has the version of MQ that it closed over, which is an 138x0 array that was reassigned in the previous recursive call, but the original was never touched.

Instead, the behavior observed when running this example is UnboundLocalError: local variable 'MQ' referenced before assignment. Why is this? Clearly the recursive function closes over MQ, how can it be unbound?


问:
PowerShell Classifier with File Server Resource Manager
I'm trying to use the Windows PowerShell Classifier in FSRM on Server 2019. I need it to look for files that start with "~$" and classify them with a Yes or No property I created.

I would also be fine with a REGEX code as well.

This is what I have but it's not working:

```<code># Global variables available:
# $ModuleDefinition  (IFsrmPipelineModuleDefinition)
# $Rule  (IFsrmClassificationRule)
# $PropertyDefinition  (IFsrmPropertyDefinition)
#
# And (optionally) any parameters you provide in the Script parameters box below,
# i.e. "$a = 1; $b = 2" . The string you enter is treated as a script and executed so the
# variables you define become globally available

# optional function to specify when the behavior of this script was last modified
# if it consumes additional files. emit one value of type DateTime
#
# function LastModified
# {
# }

# required function that outputs a value to be assigned to the specified property for each file classified
# emitting no value is allowed, which causes no value to be assigned for the property
# emitting more than one value will result in errors during classification
# begin and end are optional; process is required
#
function GetPropertyValueToApply
{
    # this parameter is of type IFsrmPropertyBag
    # it also has an additional method, GetStream, which returns a IO.Stream object to use for
    # reading the contents of the file. Make sure to close the stream after you are done reading
    # from the file
    param
    (
        [Parameter(Position = 0)] $PropertyBag
    )
Process
   {
$FileName = $_.Name
If($FileName -like "~$*")
{
$True
}
Else
{
$False
}
   }
</code>```

Body:
I'm trying to use the Windows PowerShell Classifier in FSRM on Server 2019. I need it to look for files that start with "~$" and classify them with a Yes or No property I created.

I would also be fine with a REGEX code as well.

This is what I have but it's not working:

# Global variables available:
# $ModuleDefinition  (IFsrmPipelineModuleDefinition)
# $Rule  (IFsrmClassificationRule)
# $PropertyDefinition  (IFsrmPropertyDefinition)
#
# And (optionally) any parameters you provide in the Script parameters box below,
# i.e. "$a = 1; $b = 2" . The string you enter is treated as a script and executed so the
# variables you define become globally available

# optional function to specify when the behavior of this script was last modified
# if it consumes additional files. emit one value of type DateTime
#
# function LastModified
# {
# }

# required function that outputs a value to be assigned to the specified property for each file classified
# emitting no value is allowed, which causes no value to be assigned for the property
# emitting more than one value will result in errors during classification
# begin and end are optional; process is required
#
function GetPropertyValueToApply
{
    # this parameter is of type IFsrmPropertyBag
    # it also has an additional method, GetStream, which returns a IO.Stream object to use for
    # reading the contents of the file. Make sure to close the stream after you are done reading
    # from the file
    param
    (
        [Parameter(Position = 0)] $PropertyBag
    )
Process
   {
$FileName = $_.Name
If($FileName -like "~$*")
{
$True
}
Else
{
$False
}
   }


问:
Excel: Automate formatting from generated table
I am trying to create a workflow to make the lives of my project managers easier.
I have financial profile of a client emailed to me automatically every month. The table lists the overall project information and then individual information for each phase of each project. the information is organized like below:

(Information starts at cell C7, headers are above that)

Snapshot of Table

I want to create an environment where project managers can guess the percent completion of each phase for upcoming months to build a financial outlook plan for the client. Then the totals for each phase is summed and shown on the line for the overall project.

I wanted to automate the formatting process for this file. I could use some guidance or direction?

I have created a general format but do not know the best way to automate this.

Desired Output

Edit:

I came up with some ugly work arounds. But am hoping to clean this up a bit. And I still need a solution for automating the process of bringing in data.

Working Solution V1

I've done the following:
Column K is used to calculate each rows % completion.
Total Contract $$$ / JTD Billed $$$ (columns I/G) =IF(G7>0,I7/G7,)

Columns L, M, N are inputs for the project manager to estimate the completion percentage of each phase by month.

Columns O, P, Q are the outputs calculating the projected billable by month.

(delta % Complete) * Total Contract $$$ (Columns delta(K-N) * G)

However, because I wanted to sum the total billable amounts for each project in the project line, I needed a way to separate the project lines and phase lines.
So, I created Column R with a Boleen value (true/false) to determine if a line was a project overview or a phase. It compares the project number (column C) to the row above it. =IF(C7=C6,TRUE)

Then I needed a way to know how many rows (phases) below a project line belong to the project. I used column S to calculate with =MATCH(1,--(R8:R100=FALSE),0)-1 which counts the number of columns to the next 'False' value.

I then used Columns T, U, V to sum the projected billable per phase per month for the project. =IF(NOT($R7),SUM(O8:INDEX(O8:O1000,$S7,1)),0)

I don't like this formula because its messy. I can't figure out how to write O8:O (like O:O).

And I showed the projected billables with this formula: =IF($R7,IF(AND((L7-K7)*$G7>0,(L7-K7)<1),(L7-K7)*$G7,0),T7). If column R identifies a project row, columns O, P, Q show the sums of the phases. If column R identifies a phase row, columns O, P, Q calculate the billable amount.

Additionally, I used conditional formation using column R to visually distinguish between projects and phases.


问:
Is there a way to store data in JavaScript/EcmaScript in Minecraft?
I'm trying to make a Private Minecraft Bedrock Edition Realm/Server and want to store the users data so i can access it even when the Server is offline for rework or changes but I don't know how, can anyone help me?

To clarify my question, is there a way to save something like a object or array in my case that got modified while the code was running so when i reolaunch the code it still has the state it had when i modified it and not the state it has default

Here is a Example to how i mean this

import {world} from '@minecraft/server' // The minecraft Module
let players = []; // This is where i want to store the players data

world.events.tick.subscribe((data) => { // This function gets executed 20 times a second (every minecraft tick)
    let onlinePlayers = Array.from(world.getPlayers()) // All Online Players

    onlinePlayers.forEach((onlinePlayer) => { // Pushes every Player to the array

        let player = { // This is the stored Player
            name: onlinePlayer.name, // Player Name
            data: {
                location: onlinePlayer.location, // Location
                dimension: onlinePlayer.dimension, // Dimension
                tags: onlinePlayer.getTags() // Players Ranks and Tags
            }
        }
        players.push() // Pushes the Player to the Array
    })
})

// Filters old Player data and sets it to the new one so no duplicates get created
const filteredPlayers = [...new Map(players.map((m) => [m.name, m])).values()];
players = filteredPlayers
```

So i want the ${players} Array to have the Players that got stored inside even when i close the Server or Restart it

Edit: for everyone who didn't relize that i tagged es6 and that this code is obviously not node.js. This code does NOT support any kind of node.js modules, node.js syntax or any node.js only feature

Body:
I'm trying to make a Private Minecraft Bedrock Edition Realm/Server and want to store the users data so i can access it even when the Server is offline for rework or changes but I don't know how, can anyone help me?

To clarify my question, is there a way to save something like a object or array in my case that got modified while the code was running so when i reolaunch the code it still has the state it had when i modified it and not the state it has default

Here is a Example to how i mean this

import {world} from '@minecraft/server' // The minecraft Module
let players = []; // This is where i want to store the players data

world.events.tick.subscribe((data) => { // This function gets executed 20 times a second (every minecraft tick)
    let onlinePlayers = Array.from(world.getPlayers()) // All Online Players

    onlinePlayers.forEach((onlinePlayer) => { // Pushes every Player to the array

        let player = { // This is the stored Player
            name: onlinePlayer.name, // Player Name
            data: {
                location: onlinePlayer.location, // Location
                dimension: onlinePlayer.dimension, // Dimension
                tags: onlinePlayer.getTags() // Players Ranks and Tags
            }
        }
        players.push() // Pushes the Player to the Array
    })
})

// Filters old Player data and sets it to the new one so no duplicates get created
const filteredPlayers = [...new Map(players.map((m) => [m.name, m])).values()];
players = filteredPlayers

So i want the ${players} Array to have the Players that got stored inside even when i close the Server or Restart it

Edit: for everyone who didn't relize that i tagged es6 and that this code is obviously not node.js. This code does NOT support any kind of node.js modules, node.js syntax or any node.js only feature


问:
Turning multiple values in a column into multiple records
]Im trying to turn all the values in the 'Data' column into multiple records. The Interval and Count represent how many readings after the initial reading. So 8 readings after 23:30 (1130 pm) at 30 mins each. I need to incorporate the correct time for that reading into its own record. So I need a record at 11:30 with a value of 10, 0.09045, I need a record for 12am with a value of 10, 0.08595, 1230 am with a value of 10, 0.08865 etc. All while maintaining the same data other than the fields mentioned.

Ive tried explode but cant seem to get the results Im looking for.

EDIT:

The Data is set up like this:

R Type,R Version, Time Stamp, Eid, Units, Interval, Count, FirstInt, Data

MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 10-31-2022 23:30:00Z, (Data Field)10, 0.095, 10,0.88,10,0.075,10,0.0918,10,0.0945,10,0.09495,10,0.0945, 10, .1008

The Data field has 8 readings starting at 23:30:00z with a value of 10,0.095.

I need to turn that into below:

R Type,R Version, Time Stamp, Eid, Units, Interval, Count, FirstInt, Data

1: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 10-31-2022 23:30:00Z, 10, 0.095

2: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022 12:00:00Z, 10,0.88

3: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022  12:30:00Z, 10,0.075

3: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022 1:00:00Z, 10,0.0918

4: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022  1:30:00Z, 10,0.918

5: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022  2:00:00Z, 10,0.0945

6: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022  2:30:00Z, 10,0.09495

7: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022 3:00:00Z, 10,0.0945

3: MEID, 2000, 700016565, Dollar General, kwh, 30, 8, 11-1-2022  3:30:00Z, 10,0.1008


问:
Dynamically positioning of elements in pyFPDF
I am using pyFPDF to automate reports (trying at least), and I am having problems dynamically adjusting the positions of multi_cells and graphs after page 01.

I tried two things:

I was using fixed distances between each graph and text, using something like:

```<code>pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', style = 'B', size = 12)

position_y = 100
position_x = (A4_size_x)/2

text = 80

var = [0,1,2,3,4,5]
for i in var:

   pdf.image(f'1. Gráficos/{cpf}-{fator}.png', #Graphs that were dynamically generated
           x = position_x - 25,
           y = position_y + (text * var),
           w = 50,
           h = 50)

   pdf.set_xy(position_x - 50, ((position_y + (text * var)) - 45))

   pdf.multi_cell(w = 100,
                h = 5,
                txt = 'Some Dynamic Text',
                align='C')

pdf.output(f'2. Reports/{cpf}.pdf', 'F')
</code>```

The problem here is that when it reaches a page break, the position values calculate from the new page and they break the whole document.

I also tried disabling page break:

```<code>pdf.set_auto_page_break(auto = False, margin = 0.0)
</code>```

But then there is only one page in the document.

The question here is, how to keep adding objects in the same intervals across multiple pages?

Thank you!

Body:
I am using pyFPDF to automate reports (trying at least), and I am having problems dynamically adjusting the positions of multi_cells and graphs after page 01.

I tried two things:

I was using fixed distances between each graph and text, using something like:

pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', style = 'B', size = 12)

position_y = 100
position_x = (A4_size_x)/2

text = 80

var = [0,1,2,3,4,5]
for i in var:

   pdf.image(f'1. Gráficos/{cpf}-{fator}.png', #Graphs that were dynamically generated
           x = position_x - 25,
           y = position_y + (text * var),
           w = 50,
           h = 50)

   pdf.set_xy(position_x - 50, ((position_y + (text * var)) - 45))

   pdf.multi_cell(w = 100,
                h = 5,
                txt = 'Some Dynamic Text',
                align='C')

pdf.output(f'2. Reports/{cpf}.pdf', 'F')

The problem here is that when it reaches a page break, the position values calculate from the new page and they break the whole document.

I also tried disabling page break:

pdf.set_auto_page_break(auto = False, margin = 0.0)

But then there is only one page in the document.

The question here is, how to keep adding objects in the same intervals across multiple pages?

Thank you!


问:
Is there a way to access data from a Nuxt 3 server api route inside of another server route?
I'm working on a Nuxt 3 application where I need to generate a sitemap dynamically from a CMS using the method described for Nuxt Content. I'm using the built in /server/api/ directory to get this data for the rest of the app. My sitemap.xml.js file is in /server/routes/.

I'd like to be able to make $fetch requests from my sitemap file to the apis instead of rewriting all of that code (making the $fetch requests to the CMS again).

sitemap.xml.js

export default defineEventHandler(async (event) => {
  const { auth, posts } = useRuntimeConfig()

//[...]

  const { records: postList } = await $fetch(`${posts}?api_key=${auth}`)

  postList.forEach((post) => {
    if(post.fields.Status){
      sitemap.write({
        url: 'posts/' + post.fields.Slug + '/',
        lastmod: post.lastMod
      })
    }
  })

//[...]

}
```
<h4>What I would like to do</h4>
<pre class="lang-js prettyprint-override"><code>export default defineEventHandler(async (event) => {

//[...]

  const { records: postList } = await $fetch('/api/posts')

  postList.forEach((post) => {
    sitemap.write({
      url: 'posts/' + post.fields.Slug + '/',
      lastmod: post.lastMod
    })
  })

//[...]

}
</code>```

My sitemap code all works fine, I just can't get the data from my other server routes. Does anyone know if this is possible/how to do it?

Body:
I'm working on a Nuxt 3 application where I need to generate a sitemap dynamically from a CMS using the method described for Nuxt Content. I'm using the built in /server/api/ directory to get this data for the rest of the app. My sitemap.xml.js file is in /server/routes/.

I'd like to be able to make $fetch requests from my sitemap file to the apis instead of rewriting all of that code (making the $fetch requests to the CMS again).

sitemap.xml.js

export default defineEventHandler(async (event) => {
  const { auth, posts } = useRuntimeConfig()

//[...]

  const { records: postList } = await $fetch(`${posts}?api_key=${auth}`)

  postList.forEach((post) => {
    if(post.fields.Status){
      sitemap.write({
        url: 'posts/' + post.fields.Slug + '/',
        lastmod: post.lastMod
      })
    }
  })

//[...]

}

What I would like to do

export default defineEventHandler(async (event) => {

//[...]

  const { records: postList } = await $fetch('/api/posts')

  postList.forEach((post) => {
    sitemap.write({
      url: 'posts/' + post.fields.Slug + '/',
      lastmod: post.lastMod
    })
  })

//[...]

}

My sitemap code all works fine, I just can't get the data from my other server routes. Does anyone know if this is possible/how to do it?


问:
Force page breaks and text containers using NSLayoutManager
I'm trying to implement pagination using NSLayoutManager and multiple text containers. Creating NSTextView/UITextView instances works as expected, and the text flows from text view to another.

However, I'd like to force a page break, ie. determine myself where to break onto the next container. I'm working with parsed content, so I can't insert any additional ASCII control characters into the text.

I tried subclassing NSLayoutManager and overriding textContainer(glyphIndex:, effectiveRange:), and here's a very brute-force example:

override func textContainer(forGlyphAt glyphIndex: Int, effectiveRange effectiveGlyphRange: NSRangePointer?) -> NSTextContainer? {
    if glyphIndex > 100 {
        return self.textContainers[1]
    } else {
        return super.textContainer(forGlyphAt: glyphIndex, effectiveRange: effectiveGlyphRange)
    }
}
```
<p>I'd expect this to move any glyphs after 100th index onto the second container, but the results are weird:
<img src="https://i.stack.imgur.com/1zsZW.png" alt="enter image description here" /></p>
<p>I suppose I'd have to subclass <code>NSTextContainer</code> and tell the layout manager that it's already full of text. It has a method called <code>lineFragmentRect(forProposedRect:at:writingDirection:remaining:)</code> but the documentation is <strong>very</strong> sparse, and I can't find any working examples.</p>
<p>Existing documentation around displaying text is very outdated, so any ideas or hints are welcome. I'm very confused about this, but still hopeful there is a simple way of telling the layout manager where to cut off content in each container.</p>
<h2>One possible solution</h2>
<p><code>NSTextContainer.exclusionPaths</code> could be used to rule out the rest of the possible space in containers.</p>
<pre class="lang-swift prettyprint-override"><code>let glyphIndex = layoutManager.glyphIndexForCharacter(at: 100)
var rect = layoutManager.lineFragmentRect(forGlyphAt: glyphIndex, effectiveRange: nil)

// Get the line range and used rect
var lineRange = NSMakeRange(NSNotFound, 0)
var usedRect = layoutManager.lineFragmentUsedRect(forGlyphAt: gi, effectiveRange: NSRangePointer(&lineRange))

// Calculate the remainder of the line
let remainder = NSRange(location: glyphIndex, length: NSMaxRange(lineRange) - glyphIndex)

var rectCount:Int = 0
var breakRects = layoutManager.rectArray(forGlyphRange: remainder, withinSelectedGlyphRange: remainder, in: textContainer1, rectCount: UnsafeMutablePointer(&rectCount))

// Create the rect for the remainder of the line
var lineRect = breakRect!.pointee
lineRect.size.width = textContainer1.size.width - lineRect.origin.x
// Then create a rect to cover up the rest
var coverRest = NSMakeRect(0, lineRect.origin.y + lineRect.height, textContainer1.size.width, CGFloat.greatestFiniteMagnitude)

// Add exclusion paths
textContainer1.exclusionPaths = [NSBezierPath(rect: lineRect), NSBezierPath(rect: coverRest)]
</code>```

This results in expected behavior:

This requires a ton of calculations, and text containers with exclusion paths are noticeably slower. The app could potentially have hundreds of text views, which makes this quite inefficient.

Body:
I'm trying to implement pagination using NSLayoutManager and multiple text containers. Creating NSTextView/UITextView instances works as expected, and the text flows from text view to another.

However, I'd like to force a page break, ie. determine myself where to break onto the next container. I'm working with parsed content, so I can't insert any additional ASCII control characters into the text.

I tried subclassing NSLayoutManager and overriding textContainer(glyphIndex:, effectiveRange:), and here's a very brute-force example:

override func textContainer(forGlyphAt glyphIndex: Int, effectiveRange effectiveGlyphRange: NSRangePointer?) -> NSTextContainer? {
    if glyphIndex > 100 {
        return self.textContainers[1]
    } else {
        return super.textContainer(forGlyphAt: glyphIndex, effectiveRange: effectiveGlyphRange)
    }
}

I'd expect this to move any glyphs after 100th index onto the second container, but the results are weird:

I suppose I'd have to subclass NSTextContainer and tell the layout manager that it's already full of text. It has a method called lineFragmentRect(forProposedRect:at:writingDirection:remaining:) but the documentation is very sparse, and I can't find any working examples.

Existing documentation around displaying text is very outdated, so any ideas or hints are welcome. I'm very confused about this, but still hopeful there is a simple way of telling the layout manager where to cut off content in each container.

One possible solution

NSTextContainer.exclusionPaths could be used to rule out the rest of the possible space in containers.

let glyphIndex = layoutManager.glyphIndexForCharacter(at: 100)
var rect = layoutManager.lineFragmentRect(forGlyphAt: glyphIndex, effectiveRange: nil)

// Get the line range and used rect
var lineRange = NSMakeRange(NSNotFound, 0)
var usedRect = layoutManager.lineFragmentUsedRect(forGlyphAt: gi, effectiveRange: NSRangePointer(&lineRange))

// Calculate the remainder of the line
let remainder = NSRange(location: glyphIndex, length: NSMaxRange(lineRange) - glyphIndex)

var rectCount:Int = 0
var breakRects = layoutManager.rectArray(forGlyphRange: remainder, withinSelectedGlyphRange: remainder, in: textContainer1, rectCount: UnsafeMutablePointer(&rectCount))

// Create the rect for the remainder of the line
var lineRect = breakRect!.pointee
lineRect.size.width = textContainer1.size.width - lineRect.origin.x
// Then create a rect to cover up the rest
var coverRest = NSMakeRect(0, lineRect.origin.y + lineRect.height, textContainer1.size.width, CGFloat.greatestFiniteMagnitude)

// Add exclusion paths
textContainer1.exclusionPaths = [NSBezierPath(rect: lineRect), NSBezierPath(rect: coverRest)]

This results in expected behavior:

This requires a ton of calculations, and text containers with exclusion paths are noticeably slower. The app could potentially have hundreds of text views, which makes this quite inefficient.


问:
ERR_UNKNOWN_URL_SCHEME in WebView flutter plus
I'm trying to build a mobile app from local HTML, CSS and JS files. using flutter plugin (webView flutter plus).

There is contact links in my index.html page such as:

```<code><a href='tel:99999999999'>Click here to call</a><br>
<a href='sms:99999999999'>Click here to message</a><br>
<a href='mailto:example@mail.com'>Click here to mail</a><br>
<a href='geo:51.5074,0.1278'>Click here to show location</a><br>
</code>```

But when viewed through the application on mobile, its doesn't work and shows message contain:

ERR_UNKNOWN_URL_SCHEME

how can i solve it?

trying to use  ‘tel:’, ‘sms:’, and ‘mailto:’ and others on webViewFutterPlus

Body:
I'm trying to build a mobile app from local HTML, CSS and JS files. using flutter plugin (webView flutter plus).

There is contact links in my index.html page such as:

Click here to call

Click here to message

Click here to mail

Click here to show location

But when viewed through the application on mobile, its doesn't work and shows message contain:

ERR_UNKNOWN_URL_SCHEME

how can i solve it?

trying to use  ‘tel:’, ‘sms:’, and ‘mailto:’ and others on webViewFutterPlus


问:
How do I create a digital passport program using WordPress plugins (ideally)?
I'm trying to recreate this, ideally using WordPress plugins if possible. I need the program to texts users a link (not a mobile app) that they use to check in to local businesses via their phone GPS.

this is what I'm trying to build: https://www.visitcumberlandvalley.com/cumberland-valley-beer-trail/locations/#get-the-passport

See example flow
https://www.visitalbuquerque.org/things-to-do/passport/#venues

Or like this, but as a website and not as an app: https://acton.simpleviewinc.com/acton/attachment/32124/f-0389/1/-/-/-/-/VisitApps%20Passport%20Simpleguide.pdf?_ga=2.24775422.596590586.1670450247-1406770011.1670450247

I've been searching geolocation and loyalty program plugins but nothing seems to match what I'm trying to accomplish


问:
Your debugged process might be corrupted and restaring it is recommended
I'm developing a .NET MAUI App using DevExpress.  It was working nicely and Hot Reload was fine but for some odd reason I keep getting this error message:

This happens only on C# and nothing else.  If add/edit code on XAML files it works fine and no problems at all.  Any workaround with this issue?


问:
Make part of text dark when overlapping SVG shape
I have an H1 tag and want to make everything in the H1 tag that's overlapping my SVG shape dark like the image below. I considered just using an image, but the problem is that the text will be moving across the webpage so different parts of the H1 will overlap every time. I have also tried to use mix-blend-mode: difference; but i am not satisfied with the result

The SVG path is too long to include here, but its similar to what's shown below. Any help would be appreciated.


问:
How do I create a Timeline Slicer using win32com on Excel
I have created a Pivot Table and was able to add a Slicer, now I am trying to figure out how to add a Timeline Slicer to the work sheet, but no luck.

I have tried:
wb.SlicerCaches.Add2(ws_ccpivot.PivotTables("PivotTable2"), "Impact Restore Time").Slicers.Add(SlicerDestination=ws_ccpivot, Name="Impact Restore Time", Caption="Impact Restore Timeline", Top=48.05, Left=496.75, Width=144.0, Height=295.5)

Which is the closet I have gotten but it seems to be a regular slicer and doesn't let me change it.

Tried this also:
pt.PivotFields("Impact Restore Time").PivotFilters.Add2(51, None, '10/10/2017')
But although successful, it is not shown on the screen.

Can anyone show me the steps to add a timeline slicer to a workbook?  I have seen a number of articles on it but they are missing key steps and seem to assume it already exists.


问:
Expand All and Collapse All for questions and Answers in Vue
I am developing question and answers where the Q&A are in v-for. All have a show answer and hide answer where we can expand and collapse every single answer and also have the collapse all /Expand all buttons.

The functionality for expand all /collapse all and also show answer /hide answer are working fine but the issue is when I click on expand all and then try to hide one answer, all the answers are getting closed.

Please let me know how do I fix it.

         {{techQuest.question}}

            By Member

                    Did you find this answer helpful?

                    Thanks for your feedback!

// js part:

    showAnswer: function(value) {
    this.showThanks = false;
    this.showQuestThanks = false;
    this.questionList.questions.forEach(show => {
      show['expanded'] = false;
    });
    this.show = true;
    this.expand = false;
    this.showIndex = value;
    this.questionList.questions[value].expanded = true;
   },
   hideAnswer: function(value) {
    if(!this.expand){
      console.log("Inside the this.expand loop" + this.expand);
    this.questionList.questions.forEach(hide => {
      hide['expanded'] = false;
    });}
    this.show = false;
    this.expand = false;
    this.showIndex = null;
    this.questionList.questions[value].expanded = false;
   },
  collapseAll: function() {
     this.questionList.questions.forEach(collapse => {
      collapse['expanded'] = false;
    });
    this.show = false;
    this.expand = false;
    this.showIndex = null;
  },
  expandAll: function() {
      this.questionList.questions.forEach(expand => {
      expand['expanded'] = true;
    });
    this.expand = true;
    this.show = true;
    },

```


问:
Octave - generate config.h header file
I am trying to make working a fixed-point arithmetics toolbox in Octave 6.4.0. I have installed Octave using
apt-get. While installing the toolkit using pkg install octave-fixed, several errors related to missing header files appear. I found that some of the header files (e.g. <octave/config.h>) have been deprecated in the new version of octave.

Having some header files deprecated, I found a build script octave/build-aux/mk-octave-config-h.sh on the Octave github repository, provided to generate the necessary header file.
However, not having Octave built from sources, I cannot find the associated configuration files.
Please do you have any ideas whether I should rebuild Octave from sources or is it possible to do it from standard Octave environment downloaded using the apt-get method.
Thank you.
Ivan

Title: Octave - generate config.h header file


问:
Coding from dbeaver to python sql scripting
I have a database called edgar_transposed. I can work with this data in dbeaver Just realized I could work with this in python. I was hoping to get some help. Can someone help turn this script I used in dbeaver into a sql script I could use in python? I still very new, so hoping this conversion, I could study.

dbeaver code

```<code>CREATE VIEW reference_table AS
SELECT b.short_name AS 'Table_Name',
       a.company_name AS  'Company_Name' ,
       a.filing_number AS  'Filing_Number',
       a.filing_date AS 'Filing_Date',
       a.cik  AS  'Company_CIK' ,
       a.filing_type AS  'Filing_Type',
       a.table_name AS 'Full_Table_Name',
       b.report_url AS 'Link_to_Table'
FROM (
    SELECT a.filing_number, a.filing_date, a.company_name, a.cik, a.filing_type, b.table_name
    FROM filing_list AS a
    INNER JOIN (SELECT name AS table_name
                FROM sqlite_master
                WHERE type='table') AS b
    ON b.table_name LIKE '%' || a.filing_number || '%') AS a
LEFT OUTER JOIN individual_report_links AS b
ON (a.table_name LIKE '%' || REPLACE(b.short_name, ' ' , '_') || '_'||  b.filing_number|| '%')
AND a.filing_number = b.filing_number
GROUP BY a.table_name
ORDER BY a.filing_date
</code>```

Body:
I have a database called edgar_transposed. I can work with this data in dbeaver Just realized I could work with this in python. I was hoping to get some help. Can someone help turn this script I used in dbeaver into a sql script I could use in python? I still very new, so hoping this conversion, I could study.

dbeaver code

CREATE VIEW reference_table AS
SELECT b.short_name AS 'Table_Name',
       a.company_name AS  'Company_Name' ,
       a.filing_number AS  'Filing_Number',
       a.filing_date AS 'Filing_Date',
       a.cik  AS  'Company_CIK' ,
       a.filing_type AS  'Filing_Type',
       a.table_name AS 'Full_Table_Name',
       b.report_url AS 'Link_to_Table'
FROM (
    SELECT a.filing_number, a.filing_date, a.company_name, a.cik, a.filing_type, b.table_name
    FROM filing_list AS a
    INNER JOIN (SELECT name AS table_name
                FROM sqlite_master
                WHERE type='table') AS b
    ON b.table_name LIKE '%' || a.filing_number || '%') AS a
LEFT OUTER JOIN individual_report_links AS b
ON (a.table_name LIKE '%' || REPLACE(b.short_name, ' ' , '_') || '_'||  b.filing_number|| '%')
AND a.filing_number = b.filing_number
GROUP BY a.table_name
ORDER BY a.filing_date


问:
After pandas .agg the histogram produced is taking a count of each record instead of taking the value within the column
Based on the data below I want to create a histogram. How can I do this? The code below is reading the data as a count of 1 for each record instead of taking the value from patient_unique_count

```<code>df5=df.groupby(["PANDEMIC","PATIENT_AGE_GRP"]).agg(
    {"PATIENT_ID": pd.Series.nunique}).rename(columns={'PATIENT_ID':'PATIENT_UNIQUE_COUNT'})
sns.histplot(x='PATIENT_AGE_GRP', data=df5, kde=True, hue='PANDEMIC')
plt.show()
</code>```
```<code>

                          PATIENT_UNIQUE_COUNT
PANDEMIC PATIENT_AGE_GRP
AFTER    15-19                              14
         20-24                              21
         25-29                              58
         30-34                              90
         35-39                             156
         40-44                             194
         45-49                             266
         50-54                             369
         55-59                             535
         60-64                             660
         65-69                             829
         70-74                             823
         75-79                             713
         80-84                             657
         85-89                             576
         90+                               595
         <1                                  1
         NA                                  5
BEFORE   15-19                              13
         20-24                              14
         25-29                              41
         30-34                              56
         35-39                             144
         40-44                             179
         45-49                             279
         50-54                             466
         55-59                             758
         60-64                             873
         65-69                             929
         70-74                             890
         75-79                             860
         80-84                             789
         85-89                             726
         90+                               757
         NA                                 11
</code>```

The code is reading the data as a count of 1 for each record instead of taking the value from patient_unique_count. I would also like the histograms to be side by side for before and after pandemic flag.

Body:
Based on the data below I want to create a histogram. How can I do this? The code below is reading the data as a count of 1 for each record instead of taking the value from patient_unique_count

df5=df.groupby(["PANDEMIC","PATIENT_AGE_GRP"]).agg(
    {"PATIENT_ID": pd.Series.nunique}).rename(columns={'PATIENT_ID':'PATIENT_UNIQUE_COUNT'})
sns.histplot(x='PATIENT_AGE_GRP', data=df5, kde=True, hue='PANDEMIC')
plt.show()

                          PATIENT_UNIQUE_COUNT
PANDEMIC PATIENT_AGE_GRP
AFTER    15-19                              14
         20-24                              21
         25-29                              58
         30-34                              90
         35-39                             156
         40-44                             194
         45-49                             266
         50-54                             369
         55-59                             535
         60-64                             660
         65-69                             829
         70-74                             823
         75-79                             713
         80-84                             657
         85-89                             576
         90+                               595
         <1                                  1
         NA                                  5
BEFORE   15-19                              13
         20-24                              14
         25-29                              41
         30-34                              56
         35-39                             144
         40-44                             179
         45-49                             279
         50-54                             466
         55-59                             758
         60-64                             873
         65-69                             929
         70-74                             890
         75-79                             860
         80-84                             789
         85-89                             726
         90+                               757
         NA                                 11

The code is reading the data as a count of 1 for each record instead of taking the value from patient_unique_count. I would also like the histograms to be side by side for before and after pandemic flag.


问:
A better way for me to implement swapping elements in 2Darray with ArrowKeys input
I am new and looking to learn object oriented programing with c#. The problem I am facing is how would I make the current solution better or cleaner? I have a method inside my board class that functions as swapping tiles via the arrow keys.

```<code>        private void SwapTiles(int[,] arr, int n)
        {
            int x = 0;
            int y = 0;
            var isSorted = ArrSorted(arr);//method to check if array is sorted works!

            do
            {
                ConsoleKeyInfo info = Console.ReadKey();
                Console.WriteLine();

                if (info.Key == ConsoleKey.RightArrow)
                {
                    if (y >= (n - 1))
                    {
                        continue;
                    }
                }
                int temp = arr[x, y];
                arr[x, y] = arr[x, (y + 1)];
                arr[x, (y + 1)] = temp;
            } while (isSorted == true);

        }
</code>```

As I was implementing my solution to the problem I realized that I would need to implement the same code multiple times but with slight variation for each arrow key. I dont know how I would achieve the same results cleaner. Any help on this matter would be appreciated and hints to links or other solutions is also appreciated as I am trying to learn.

Body:
I am new and looking to learn object oriented programing with c#. The problem I am facing is how would I make the current solution better or cleaner? I have a method inside my board class that functions as swapping tiles via the arrow keys.

        private void SwapTiles(int[,] arr, int n)
        {
            int x = 0;
            int y = 0;
            var isSorted = ArrSorted(arr);//method to check if array is sorted works!

            do
            {
                ConsoleKeyInfo info = Console.ReadKey();
                Console.WriteLine();

                if (info.Key == ConsoleKey.RightArrow)
                {
                    if (y >= (n - 1))
                    {
                        continue;
                    }
                }
                int temp = arr[x, y];
                arr[x, y] = arr[x, (y + 1)];
                arr[x, (y + 1)] = temp;
            } while (isSorted == true);

        }

As I was implementing my solution to the problem I realized that I would need to implement the same code multiple times but with slight variation for each arrow key. I dont know how I would achieve the same results cleaner. Any help on this matter would be appreciated and hints to links or other solutions is also appreciated as I am trying to learn.


问:
Getting Net::ReadTimeout with #<socket:(closed)>, immediately when attempting to send action mail rails 6
Rails 6.1, using action mailer.
Getting this error message, Completed 500 Internal Server Error in (X)ms

Net::ReadTimeout (Net::ReadTimeout with #socket:(closed)):

It doesn't matter which kind of email I send or how long it takes.
The only change between my production and development is that I updated my gems, which I only allowed for minor updates (2.5.1 ~> 2.5.2)

No clue where to look.

Any help would be appreciated.


问:
monorepo fronend projects with kubernetes solution
Deal with several frontend projects before, that normally I release the static files to AWS S3 bucket with AWS CDN cloudfront (or Azure Storage with Azure CDN) or others, such as heroku, vercel, etc.

But this time, the developer want to deploy both frontend and backend in a kubernetes cluster (I don't understand the reason, why this design, but let's not discuss at this point)

Make one container for the fronend is easy, share the Dockerfile for your reference

```<code>#stage1
FROM node:16 as build-step

WORKDIR /usr/src/app

RUN npm cache clear --force

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .
RUN npm run build

#stage2
FROM nginx
COPY --from=build-step /usr/src/app/dist /usr/share/nginx/html

EXPOSE 80

STOPSIGNAL SIGTERM

CMD ["nginx", "-g", "daemon off;"]
</code>```

But the frontend project is monorepo, same structure as this repo (https://github.com/richardtbell/microfrontend-hello-world/tree/master/packages) , there are three packages of fronends

container

helloReact

helloVue

the application has different configuration for dev and prod.

```<code>$ cd apps/container/config
$ webpack.dev.js webpack.prod.js

...
<         publicPath: 'http://localhost:8080/',
---
>         filename: '[name].[contenthash].js',
>         publicPath: '/container/latest/'
...
21,22c18,19
<                 helloReact: 'helloReact@http://localhost:8081/remoteEntry.js',
<                 helloVue: 'helloVue@http://localhost:8082/remoteEntry.js'
---
>                 helloReact: `helloReact@${domain}/helloReact/latest/remoteEntry.js`,
>                 helloVue: `helloVue@${domain}/helloVue/latest/remoteEntry.js`
27c24

$ cd ../../helloReact/config
$ diff webpack.dev.js webpack.prod.js

<         publicPath: 'http://localhost:8081/',
---
>         filename: '[name].[contenthash].js',
>         publicPath: '/helloReact/latest/'

</code>```

so for dev, it works locally, it use localhost with port, but this way doesn't work when we deploy to s3 bucket, so in prod configuration, set the domain name directly or use related path only.

When I want to deploy to a kubernetes cluster, what should I change? looks both configuration (dev and prod) are not suitable.

each frontend would be a set of replicate pods (via deployment/replicaset). How the frontend publicPath I should set?

Or in another word, how can I deploy this project (https://github.com/richardtbell/microfrontend-hello-world/tree/master/packages) to Kubernetes cluster?

Body:
Deal with several frontend projects before, that normally I release the static files to AWS S3 bucket with AWS CDN cloudfront (or Azure Storage with Azure CDN) or others, such as heroku, vercel, etc.

But this time, the developer want to deploy both frontend and backend in a kubernetes cluster (I don't understand the reason, why this design, but let's not discuss at this point)

Make one container for the fronend is easy, share the Dockerfile for your reference

#stage1
FROM node:16 as build-step

WORKDIR /usr/src/app

RUN npm cache clear --force

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .
RUN npm run build

#stage2
FROM nginx
COPY --from=build-step /usr/src/app/dist /usr/share/nginx/html

EXPOSE 80

STOPSIGNAL SIGTERM

CMD ["nginx", "-g", "daemon off;"]

But the frontend project is monorepo, same structure as this repo (https://github.com/richardtbell/microfrontend-hello-world/tree/master/packages) , there are three packages of fronends

container

helloReact

helloVue

the application has different configuration for dev and prod.

$ cd apps/container/config
$ webpack.dev.js webpack.prod.js

...
<         publicPath: 'http://localhost:8080/',
---
>         filename: '[name].[contenthash].js',
>         publicPath: '/container/latest/'
...
21,22c18,19
<                 helloReact: 'helloReact@http://localhost:8081/remoteEntry.js',
<                 helloVue: 'helloVue@http://localhost:8082/remoteEntry.js'
---
>                 helloReact: `helloReact@${domain}/helloReact/latest/remoteEntry.js`,
>                 helloVue: `helloVue@${domain}/helloVue/latest/remoteEntry.js`
27c24

$ cd ../../helloReact/config
$ diff webpack.dev.js webpack.prod.js

<         publicPath: 'http://localhost:8081/',
---
>         filename: '[name].[contenthash].js',
>         publicPath: '/helloReact/latest/'

so for dev, it works locally, it use localhost with port, but this way doesn't work when we deploy to s3 bucket, so in prod configuration, set the domain name directly or use related path only.

When I want to deploy to a kubernetes cluster, what should I change? looks both configuration (dev and prod) are not suitable.

each frontend would be a set of replicate pods (via deployment/replicaset). How the frontend publicPath I should set?

Or in another word, how can I deploy this project (https://github.com/richardtbell/microfrontend-hello-world/tree/master/packages) to Kubernetes cluster?


问:
Get Jetpack Compose FlowRow to produce a masonry layout
Android has a view-based layout for achieving a masonry style layout where elements that could fit in a row would also evenly consume the remain row space:

I'm trying to replicate this with the Accompanist FlowRow, but as I browse the source, I don't think it was written to perform the extra measure and resizing necessary to adjust it's placeable elements. Seems the best I can get from it is:

Anyone have an example of getting FlowRow modified to layout in this way? I just started browsing source to perform custom layouts, so a pointer or two would help.

I think the algorithm would be something like:

Get the parent container width

Get the width of each item where its width is set to wrap its content

Take n items where the total width of n <= parent width

Add the remaining row width (width/n) to each item's width

Set the x, y positions of those items

Repeat starting with n+1 item


问:
Joomla 3.10 Error 500 Fatal error: Class 'JHtml' not found cms.php
I have installed and configured Joomla site on one of my domains (in sub folder), and it works great there, so now, I wanted to move it to original domain where it has to be, so in WHM I created new account for new domain, and moved my Joomla files and DB to new account, in config file, I've changed user and DB data, also changed path for log and temp and when I run Joomla on new domain, I get this error:

Fatal error: Class 'JHtml' not found in /home/newsite/public_html/libraries/cms.php on line 12

The line 12 in that file is:
if (!defined('JPATH_PLATFORM'))
but since it works on old domain, that should not be a problem?

Everything stayed on same server and folders and files in root directory have same permissions

I've added this code to index.php, before that I just got blank page

ini_set('display_errors','On');  error_reporting(E_ALL);


问:
In Keycloak, is it possible to specify required claims for an OIDC Identity Provider?
I want to federate a Keycloak realm with an upstream OIDC provider, but I only want users that have a particular group in the groups claim from the upstream provider to be able to authenticate with the Keycloak realm.

I am able to configure an OIDC identity provider in the Keycloak realm so that users can authenticate using the upstream OIDC provider, but after spending a while playing with various settings and mappers I cannot find a way to get the upstream group restriction that I require. I do not want all the users from the upstream provider to be able to authenticate with my Keycloak realm.

Any ideas would be welcome!


问:
How to add data with same name to database as array? (PDO)
In a system with bus services, I want to save the intermediate stops and their times in the database. Since there are multiple intermediate stops and arrival times, I want to save and display them as an array in the database.

Honestly, I tried for a few days, but I couldn't find any results. I've never needed anything like this before.

Here is everything you need:

First of all my problem is that it is added to the database like this:

database

and this is my code,

```<code><select class="form-control mt-3" name="ara_durak[]">
    <option value="12">Ankara</option>
    <option value="14">Balıkesir</option>
    <option value="13">İzmir</option>
</select>

<input type="time" class="form-control mt-3" name="ara_durak_saat[]">
<input type="time" class="form-control mt-3" name="ara_durak_saat[]">
<input type="time" class="form-control mt-3" name="ara_durak_saat[]">
</code>```
```<code>  if(isset($_POST['seferEkle'])){
    $sorgu = $db->prepare("INSERT INTO seferler SET
        sefer_no=:sefer_no,
        kalkis=:kalkis,
        varis=:varis,
        ara_durak=:ara_durak,
        ara_durak_saat=:ara_durak_saat,
        kalkis_tarih=:kalkis_tarih,
        varis_tarih=:varis_tarih,
        kaptan_id=:kaptan_id,
        arac_id=:arac_id
    ");
    $sonuc = $sorgu->execute(array(
        'sefer_no' => $_POST['sefer_no'],
        'kalkis' => $_POST['kalkis'],
        'ara_durak' => $_POST['ara_durak'],
        'ara_durak_saat' => $_POST['ara_durak_saat'],
        'varis' => $_POST['varis'],
        'kalkis_tarih' => $_POST['kalkis_tarih'],
        'varis_tarih' => $_POST['varis_tarih'],
        'kaptan_id' => $_POST['kaptan_id'],
        'arac_id' => $_POST['arac_id']
    ));
  }
</code>```

an image of my form,

form

This is how I want to show the information to the user when the addition is complete:

what i need

I tried adding the data like this:

```<code>$sorgu = $db->prepare("INSERT INTO seferler SET
    sefer_no=:sefer_no,
    kalkis=:kalkis,
    varis=:varis,
    ara_durak[]=:ara_durak,
    ara_durak_saat[]=:ara_durak_saat,
    kalkis_tarih=:kalkis_tarih,
    varis_tarih=:varis_tarih,
    kaptan_id=:kaptan_id,
    arac_id=:arac_id
");
$sonuc = $sorgu->execute(array(
    'sefer_no' => $_POST['sefer_no'],
    'kalkis' => $_POST['kalkis'],
    'ara_durak' => $_POST['ara_durak'],
    'ara_durak_saat' => $_POST['ara_durak_saat'],
    'varis' => $_POST['varis'],
    'kalkis_tarih' => $_POST['kalkis_tarih'],
    'varis_tarih' => $_POST['varis_tarih'],
    'kaptan_id' => $_POST['kaptan_id'],
    'arac_id' => $_POST['arac_id']
));
</code>```

and this:

```<code>for($i=0;$i<count($_POST['ara_durak']);$i++)

{

$araDurak = $_POST['ara_durak'][$i];
$araDurakSaat =$_POST['ara_durak_saat'][$i];

}
$sorgu = $db->prepare("INSERT INTO seferler SET
    sefer_no=:sefer_no,
    kalkis=:kalkis,
    varis=:varis,
    ara_durak=:ara_durak,
    ara_durak_saat=:ara_durak_saat,
    kalkis_tarih=:kalkis_tarih,
    varis_tarih=:varis_tarih,
    kaptan_id=:kaptan_id,
    arac_id=:arac_id
");
$sonuc = $sorgu->execute(array(
    'sefer_no' => $_POST['sefer_no'],
    'kalkis' => $_POST['kalkis'],
    'ara_durak' => $araDurak,
    'ara_durak_saat' => $araDurakSaat,
    'varis' => $_POST['varis'],
    'kalkis_tarih' => $_POST['kalkis_tarih'],
    'varis_tarih' => $_POST['varis_tarih'],
    'kaptan_id' => $_POST['kaptan_id'],
    'arac_id' => $_POST['arac_id']
));
</code>```

but this just gives me the last value in the array here

Please excuse my english. I ask for your help and i love you all <3

Body:
In a system with bus services, I want to save the intermediate stops and their times in the database. Since there are multiple intermediate stops and arrival times, I want to save and display them as an array in the database.

Honestly, I tried for a few days, but I couldn't find any results. I've never needed anything like this before.

Here is everything you need:

First of all my problem is that it is added to the database like this:

database

and this is my code,

<select class="form-control mt-3" name="ara_durak[]">
    <option value="12">Ankara</option>
    <option value="14">Balıkesir</option>
    <option value="13">İzmir</option>
</select>

<input type="time" class="form-control mt-3" name="ara_durak_saat[]">
<input type="time" class="form-control mt-3" name="ara_durak_saat[]">
<input type="time" class="form-control mt-3" name="ara_durak_saat[]">

  if(isset($_POST['seferEkle'])){
    $sorgu = $db->prepare("INSERT INTO seferler SET
        sefer_no=:sefer_no,
        kalkis=:kalkis,
        varis=:varis,
        ara_durak=:ara_durak,
        ara_durak_saat=:ara_durak_saat,
        kalkis_tarih=:kalkis_tarih,
        varis_tarih=:varis_tarih,
        kaptan_id=:kaptan_id,
        arac_id=:arac_id
    ");
    $sonuc = $sorgu->execute(array(
        'sefer_no' => $_POST['sefer_no'],
        'kalkis' => $_POST['kalkis'],
        'ara_durak' => $_POST['ara_durak'],
        'ara_durak_saat' => $_POST['ara_durak_saat'],
        'varis' => $_POST['varis'],
        'kalkis_tarih' => $_POST['kalkis_tarih'],
        'varis_tarih' => $_POST['varis_tarih'],
        'kaptan_id' => $_POST['kaptan_id'],
        'arac_id' => $_POST['arac_id']
    ));
  }

an image of my form,

form

This is how I want to show the information to the user when the addition is complete:

what i need

I tried adding the data like this:

$sorgu = $db->prepare("INSERT INTO seferler SET
    sefer_no=:sefer_no,
    kalkis=:kalkis,
    varis=:varis,
    ara_durak[]=:ara_durak,
    ara_durak_saat[]=:ara_durak_saat,
    kalkis_tarih=:kalkis_tarih,
    varis_tarih=:varis_tarih,
    kaptan_id=:kaptan_id,
    arac_id=:arac_id
");
$sonuc = $sorgu->execute(array(
    'sefer_no' => $_POST['sefer_no'],
    'kalkis' => $_POST['kalkis'],
    'ara_durak' => $_POST['ara_durak'],
    'ara_durak_saat' => $_POST['ara_durak_saat'],
    'varis' => $_POST['varis'],
    'kalkis_tarih' => $_POST['kalkis_tarih'],
    'varis_tarih' => $_POST['varis_tarih'],
    'kaptan_id' => $_POST['kaptan_id'],
    'arac_id' => $_POST['arac_id']
));

and this:

for($i=0;$i<count($_POST['ara_durak']);$i++)

{

$araDurak = $_POST['ara_durak'][$i];
$araDurakSaat =$_POST['ara_durak_saat'][$i];

}
$sorgu = $db->prepare("INSERT INTO seferler SET
    sefer_no=:sefer_no,
    kalkis=:kalkis,
    varis=:varis,
    ara_durak=:ara_durak,
    ara_durak_saat=:ara_durak_saat,
    kalkis_tarih=:kalkis_tarih,
    varis_tarih=:varis_tarih,
    kaptan_id=:kaptan_id,
    arac_id=:arac_id
");
$sonuc = $sorgu->execute(array(
    'sefer_no' => $_POST['sefer_no'],
    'kalkis' => $_POST['kalkis'],
    'ara_durak' => $araDurak,
    'ara_durak_saat' => $araDurakSaat,
    'varis' => $_POST['varis'],
    'kalkis_tarih' => $_POST['kalkis_tarih'],
    'varis_tarih' => $_POST['varis_tarih'],
    'kaptan_id' => $_POST['kaptan_id'],
    'arac_id' => $_POST['arac_id']
));

but this just gives me the last value in the array here

Please excuse my english. I ask for your help and i love you all <3


问:
Getting sometimes double POST request to IIS 10 webserver
Since we migrated to an Amazon EC instance we're getting sometimes double POST requests to our SaaS application. I have no idea where this is coming from and why this is happening. I've been searching and looking at different options, but can't find the root cause. We migrated from IIS7 to IIS10 on a Windows Server 2022 Datacenter.

Here is an example of an SEQ logging session at 1 client:

SEQ Log

You can see the endpoint was requested multiple times (= OK), but there is also a double POST request at 18:19:41 and 18:18:27. This is logged from within the ASP.NET MVC controller. If I look at the IIS 10 logs, I see the same thing. So the request seems to be initiated from the browser and not doubled in the pipeline.

The MVC controller looks something like this (simplified):

```<code>if (ViewData.ModelState.IsValid){
    try
    {
       NHibernateSession.Current.Transaction.Begin();

       foreach (var item in deliveryDTosToSave){
          var delivery = new Delivery
                        {
                            //copying over the DTO to the delivery
                        };

          _deliveryRepository.SaveNew(delivery, userCode, item.Index);
       }
       NHibernateSession.Current.Transaction.Commit();

       return RedirectToAction("Add", "Delivery", new { tab, pharmacyId });
   }
   catch (RuleException ex)
   {
      NHibernateSession.Current.Transaction.Rollback();

   }
}
</code>```

On the client-side, the javascript to submit is something like this:

```<code>$('#formDeliveries').submit(function () {
   if (!canSubmit) {return false;}
   $("#loading").show();
   canSubmit = false;
});
</code>```

Things I looked for:

user double-clicking on the submit button: we've blocked this through JS after initial submit. I interviewed several users, and they are not double-clicking.

bug in browser: last user I logged in used Edge 107, which is recent. I can't find anything on the matter

HTTPS redirects: the website is HTTPS-only and users have to be authenticated to use it.

HTTP/3 fall-back scenario's: could be possible as we've enabled HTTP/3 when migrating to Amazon. However users are seeing this behaviour only sometimes and not always from the same browser.

We've tried to simulate the behaviour, but cannot find it. We've logged into the users computer and tried to simulated it while looking at the network requests through the developers utils, but cannot simulate it. I was hoping to see it happening live, so we can rule out any javascript items. If the network log in developer tools shows only 1 POST, it probably has to do something with the IIS pipeline.

Any advice would be greatly appreciated.

Body:
Since we migrated to an Amazon EC instance we're getting sometimes double POST requests to our SaaS application. I have no idea where this is coming from and why this is happening. I've been searching and looking at different options, but can't find the root cause. We migrated from IIS7 to IIS10 on a Windows Server 2022 Datacenter.

Here is an example of an SEQ logging session at 1 client:

SEQ Log

You can see the endpoint was requested multiple times (= OK), but there is also a double POST request at 18:19:41 and 18:18:27. This is logged from within the ASP.NET MVC controller. If I look at the IIS 10 logs, I see the same thing. So the request seems to be initiated from the browser and not doubled in the pipeline.

The MVC controller looks something like this (simplified):

if (ViewData.ModelState.IsValid){
    try
    {
       NHibernateSession.Current.Transaction.Begin();

       foreach (var item in deliveryDTosToSave){
          var delivery = new Delivery
                        {
                            //copying over the DTO to the delivery
                        };

          _deliveryRepository.SaveNew(delivery, userCode, item.Index);
       }
       NHibernateSession.Current.Transaction.Commit();

       return RedirectToAction("Add", "Delivery", new { tab, pharmacyId });
   }
   catch (RuleException ex)
   {
      NHibernateSession.Current.Transaction.Rollback();

   }
}

On the client-side, the javascript to submit is something like this:

$('#formDeliveries').submit(function () {
   if (!canSubmit) {return false;}
   $("#loading").show();
   canSubmit = false;
});

Things I looked for:

user double-clicking on the submit button: we've blocked this through JS after initial submit. I interviewed several users, and they are not double-clicking.

bug in browser: last user I logged in used Edge 107, which is recent. I can't find anything on the matter

HTTPS redirects: the website is HTTPS-only and users have to be authenticated to use it.

HTTP/3 fall-back scenario's: could be possible as we've enabled HTTP/3 when migrating to Amazon. However users are seeing this behaviour only sometimes and not always from the same browser.

We've tried to simulate the behaviour, but cannot find it. We've logged into the users computer and tried to simulated it while looking at the network requests through the developers utils, but cannot simulate it. I was hoping to see it happening live, so we can rule out any javascript items. If the network log in developer tools shows only 1 POST, it probably has to do something with the IIS pipeline.

Any advice would be greatly appreciated.


问:
Apply ForEach (Structured Streaming Programming) to move data from one delta table to another
Let's say that I have a delta table saved which was processed using the ForEachBatch to apply transformations and finally saved a final delta table (let's call these table Table1).

However for some requeriments the data of this table need to be merged or appended to another delta table (Table2) which is being updated by another stream.

My question here is how can I use the ForEach option instead of the ForEachBatch in the new streaming to save that data in the Table2? Considering that for requeriments we need to do append the data of the Table1 to the Table2 record by record 'cause using the option ForEachBatch when the process fail it generates duplicate data and ends breaking up the streaming?

Or is there another way to aproach the problem not using it?

It is important to consider that each table is an streaming table.

We have tried to implement these idea using two stream writting using the ForEachBatch however we have got error and duplicates in different scenarios. First due the fact that we need to use a surrogate key (an indentity) it makes the two streamings to fail.

We avoided it doing one staging table without the identity and later applying it, but the problem is that in some moments if the stream fail using the foreachbatch generates duplicated data and breaks the whole process.

That's why we tought that we could use the foreach to append the data to the table2 but we have no idea how it works and how implement it because it must be record to record and we havent' find an example or anything about how to implement it.

So any help would be appreciate.

If code it's needed, I could try to provide it.


问:
LC3 programming to prompt a user for a password, verifies if it is valid
write a program where the user must enter a password that
satisfies the following criteria:
o at most 12 characters and at least 8 characters
o may contain only capital A through Z, “*” or “ ” (space) characters

The process must continue until the user enters a valid password. To pull this off,
you’ll need to utilize TRAPS, Branches, Loads/Stores, and pretty much everything
LC3 has to offer.
The program works as follows:
o Ask to enter a password of up to 12 characters.
o If password has any characters that are not allowed, warn the user that at least
one character is not allowed, and ask for another password
o Once the user enters a password that only contains allowed characters, print
“Password created” and halt the program.

```<code>.ORIG x3000  ; start of the program

   ; setup the trap vector table
   ; TRAP x23 is used to check password
   ; TRAP x25 is used to print "Password Created"
   ; TRAP x22 is used to print "Please enter a valid password"
   ; TRAP x21 is used to read characters from keyboard

   ; set up trap vector table
   ; TRAP x23 is used to check password
   ; TRAP x25 is used to print "Password Created"
   ; TRAP x22 is used to print "Please enter a valid password"
   ; TRAP x21 is used to read characters from keyboard

TRAP x23   ; address of check password subroutine
TRAP x25   ; address of print "Password Created" subroutine
TRAP x22   ; address of print "Please enter a valid password" subroutine
TRAP x21   ; address of read characters from keyboard subroutine

.END    ; end of program

; check password subroutine

CheckPassword
   ; check if the password is valid
   ; if valid, jump to PrintSuccess
   ; if invalid, jump to PrintError

   ; get the length of the password
   ; compare it to 8 and 12
   ; if length is less than 8 or greater than 12
   ; jump to PrintError

   ; loop through the characters of the password
   ; compare each character to A..Z, *, and space
   ; if any character is not in that range
   ; jump to PrintError

   ; if all characters are valid, jump to PrintSuccess

PrintSuccess   ; print "Password Created"
   ; halt the program

PrintError   ; print "Please enter a valid password"
   ; jump back to the start of the program

.END
</code>```

Body:
write a program where the user must enter a password that
satisfies the following criteria:
o at most 12 characters and at least 8 characters
o may contain only capital A through Z, “*” or “ ” (space) characters

The process must continue until the user enters a valid password. To pull this off,
you’ll need to utilize TRAPS, Branches, Loads/Stores, and pretty much everything
LC3 has to offer.
The program works as follows:
o Ask to enter a password of up to 12 characters.
o If password has any characters that are not allowed, warn the user that at least
one character is not allowed, and ask for another password
o Once the user enters a password that only contains allowed characters, print
“Password created” and halt the program.

.ORIG x3000  ; start of the program

   ; setup the trap vector table
   ; TRAP x23 is used to check password
   ; TRAP x25 is used to print "Password Created"
   ; TRAP x22 is used to print "Please enter a valid password"
   ; TRAP x21 is used to read characters from keyboard

   ; set up trap vector table
   ; TRAP x23 is used to check password
   ; TRAP x25 is used to print "Password Created"
   ; TRAP x22 is used to print "Please enter a valid password"
   ; TRAP x21 is used to read characters from keyboard

TRAP x23   ; address of check password subroutine
TRAP x25   ; address of print "Password Created" subroutine
TRAP x22   ; address of print "Please enter a valid password" subroutine
TRAP x21   ; address of read characters from keyboard subroutine

.END    ; end of program

; check password subroutine

CheckPassword
   ; check if the password is valid
   ; if valid, jump to PrintSuccess
   ; if invalid, jump to PrintError

   ; get the length of the password
   ; compare it to 8 and 12
   ; if length is less than 8 or greater than 12
   ; jump to PrintError

   ; loop through the characters of the password
   ; compare each character to A..Z, *, and space
   ; if any character is not in that range
   ; jump to PrintError

   ; if all characters are valid, jump to PrintSuccess

PrintSuccess   ; print "Password Created"
   ; halt the program

PrintError   ; print "Please enter a valid password"
   ; jump back to the start of the program

.END


问:
Docker image in Azure App service CICD with M1 chip
I'm trying to deploy a dash app on Azure. When I build the image like docker build -t example-image etc, the app doesn't work, apparently because of the build on a mac with an M1 chip. When I specify the platform linux/amd64 it works fine.

But now I want to build it in a pipeline, so I have to describe the build in the Dockerfile. Everywhere I have looked it says that you can write
FROM --platform=linux/amd64 python:3.9-slim in the Dockerfile, but this process fails on Azure. The log says Output from dependency scanning: unable to understand line FROM --platform=linux/amd64 python:3.9-alpine

My whole Dockerfile looks like this:

```<code>FROM --platform=linux/amd64 python:3.9-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

COPY ./app /app
WORKDIR /app

RUN set -ex && \
    pip install -r requirements.txt

EXPOSE 80
ENV dash_debug="False"

CMD ["python", "app.py"]
</code>```

I'm not a Docker expert (clearly) so is there any other way on how to do this?

Cheers

Body:
I'm trying to deploy a dash app on Azure. When I build the image like docker build -t example-image etc, the app doesn't work, apparently because of the build on a mac with an M1 chip. When I specify the platform linux/amd64 it works fine.

But now I want to build it in a pipeline, so I have to describe the build in the Dockerfile. Everywhere I have looked it says that you can write
FROM --platform=linux/amd64 python:3.9-slim in the Dockerfile, but this process fails on Azure. The log says Output from dependency scanning: unable to understand line FROM --platform=linux/amd64 python:3.9-alpine

My whole Dockerfile looks like this:

FROM --platform=linux/amd64 python:3.9-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

COPY ./app /app
WORKDIR /app

RUN set -ex && \
    pip install -r requirements.txt

EXPOSE 80
ENV dash_debug="False"

CMD ["python", "app.py"]

I'm not a Docker expert (clearly) so is there any other way on how to do this?

Cheers


问:
Spring data native query filtering by List<String>
Given:
Interface projection model with

```<code> String getType();
</code>```

Postgres 13;
Hibernate+JPA+Spring data;
Query filter:

```<code>   " where ... "
 + " and (COALESCE(:types) is null or model.type in (:types)) "
</code>```

Pageable method in repository contains param

```<code> @Param("types") @Nullable List<String> types
</code>```

generated SQL when null types is being passed:

```<code>and (COALESCE(?) is null or folderModel.contentType in (?))
</code>```

error after it thrown:

```<code>org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying = bytea
  Tips: No operator matches the given name and argument types. You might need to add explicit type casts.
</code>```

There is no problem when I pass any nullable params in 'where' clause likewise when types isn't null and contains valid types. I tried to cast(model.type to varchar) with no any success. Any ideas?

Body:
Given:
Interface projection model with

 String getType();

Postgres 13;
Hibernate+JPA+Spring data;
Query filter:

   " where ... "
 + " and (COALESCE(:types) is null or model.type in (:types)) "

Pageable method in repository contains param

 @Param("types") @Nullable List<String> types

generated SQL when null types is being passed:

and (COALESCE(?) is null or folderModel.contentType in (?))

error after it thrown:

org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying = bytea
  Tips: No operator matches the given name and argument types. You might need to add explicit type casts.

There is no problem when I pass any nullable params in 'where' clause likewise when types isn't null and contains valid types. I tried to cast(model.type to varchar) with no any success. Any ideas?


问:
Hashcat : mask attack getting error "seperator unmatched"
I am desperately trying to recover a veracrypt password with hashcat.

I got the hash file of the encrypted device with dd command and then used the sha512sum command to get the hash so it should be :

```<code>c21cd34530e01d4f31f329a9c53643984894e1411ee6400551d7f614d4e3409ec643e3a0c3684238b9656c2793239666aa907f7739055197b094804679026810
</code>```

I remember a part of the password so I guessed a mask attack with hashcat should be helpful.
But I keep getting "separator unmatched"

I typed the following command :

```<code>hashcat --force -m 1800 -a 3 -i --increment-min 20 --increment-max 21 c21cd34530e01d4f31f329a9c53643984894e1411ee6400551d7f614d4e3409ec643e3a0c3684238b9656c2793239666aa907f7739055197b094804679026810 ?u?1?1?s?u?1?1?s?d?d?d?d?s?l?l

Hash 'c21cd34530e01d4f31f329a9c53643984894e1411ee6400551d7f614d4e3409ec643e3a0c3684238b9656c2793239666aa907f7739055197b094804679026810': Separator unmatched
No hashes loaded.
</code>```

I do not understand my mistake, the mask is after the hash however.

Body:
I am desperately trying to recover a veracrypt password with hashcat.

I got the hash file of the encrypted device with dd command and then used the sha512sum command to get the hash so it should be :

c21cd34530e01d4f31f329a9c53643984894e1411ee6400551d7f614d4e3409ec643e3a0c3684238b9656c2793239666aa907f7739055197b094804679026810

I remember a part of the password so I guessed a mask attack with hashcat should be helpful.
But I keep getting "separator unmatched"

I typed the following command :

hashcat --force -m 1800 -a 3 -i --increment-min 20 --increment-max 21 c21cd34530e01d4f31f329a9c53643984894e1411ee6400551d7f614d4e3409ec643e3a0c3684238b9656c2793239666aa907f7739055197b094804679026810 ?u?1?1?s?u?1?1?s?d?d?d?d?s?l?l

Hash 'c21cd34530e01d4f31f329a9c53643984894e1411ee6400551d7f614d4e3409ec643e3a0c3684238b9656c2793239666aa907f7739055197b094804679026810': Separator unmatched
No hashes loaded.

I do not understand my mistake, the mask is after the hash however.


问:
Can't run python file without .py extension even after adding shebang
Couldn't get my python script to execute without .py extension even after adding #!/usr/bin/python3 to the script but the shebang works because i could execute the script without python keyword but i also need the .py extension out, i need the it to work like a cli keyword like git,is there a way to accomplish this on windows without adding the path to environment variables?


问:
Unable to view image from s3 but image is visable in postman
I have a api the returns a image file. It works fine in postman and swagger, I am able to view the image.

Here is that api

```<code>[HttpGet("GetImage")]
public async Task<IActionResult> GetImagesAsync()
{
    Stream imageStream = await _fileOperation.ReadObjectData("computer.png");

    Response.Headers.Add("Content-Disposition", new ContentDisposition
    {
        FileName = "computer.png",
        Inline = true // false = prompt the user for downloading; true = browser to try to show the file inline
    }.ToString());

   return File(imageStream, "image/png");
}
</code>```

Here is my code to get image in typescript

```<code>  getFileImage() {
    return this.http.get(this.baseUrl + 'FileExplorer/GetImage');
  }

this.fileExplorer.getFileImage().subscribe(file => {
  this.any = file;
}, error => {
  console.log(error)
});
</code>```

When I call it in angular I get this error
error = SyntaxError: Unexpected token '�', "�PNG

I want to display the image in home.component.html

Body:
I have a api the returns a image file. It works fine in postman and swagger, I am able to view the image.

Here is that api

[HttpGet("GetImage")]
public async Task<IActionResult> GetImagesAsync()
{
    Stream imageStream = await _fileOperation.ReadObjectData("computer.png");

    Response.Headers.Add("Content-Disposition", new ContentDisposition
    {
        FileName = "computer.png",
        Inline = true // false = prompt the user for downloading; true = browser to try to show the file inline
    }.ToString());

   return File(imageStream, "image/png");
}

Here is my code to get image in typescript

  getFileImage() {
    return this.http.get(this.baseUrl + 'FileExplorer/GetImage');
  }

this.fileExplorer.getFileImage().subscribe(file => {
  this.any = file;
}, error => {
  console.log(error)
});

When I call it in angular I get this error
error = SyntaxError: Unexpected token '�', "�PNG

I want to display the image in home.component.html


问:
How to append a R data frame into Redshift?
I'm trying to upload a data frame into SQL, but I keep receiving errors. I've tried the following funciont

```<code>DBI::dbWriteTable(rposgre_rsql, name = "my_schema.the_table", value = base, row.names = FALSE, append=TRUE)

</code>```

that functions returns the error
RPosgreSQL error: could not Retrieve the result : ERROR:  syntax error at or near "STDIN"

so i tried:

```<code>insert\<- "INSERT INTO my_schema.the_table VALUES base"
M2_results\<- RPostgreSQL::dbSendQuery(conn= rposgre_rsql,statement= insert)
</code>```

but it returns
RPosgreSQL error: could not Retrieve the result : ERROR:  syntax error at or near "base"

I'm positive the connection works, since I can either select the table or use "dbExistsTable.R", but I don't understand why it doesn't work with INSERT INTO. The connection is for a corporate enviroment, maybe it's a permission issue? Also, I don't quite understand what's "STDIN" is.

Body:
I'm trying to upload a data frame into SQL, but I keep receiving errors. I've tried the following funciont

DBI::dbWriteTable(rposgre_rsql, name = "my_schema.the_table", value = base, row.names = FALSE, append=TRUE)

that functions returns the error
RPosgreSQL error: could not Retrieve the result : ERROR:  syntax error at or near "STDIN"

so i tried:

insert\<- "INSERT INTO my_schema.the_table VALUES base"
M2_results\<- RPostgreSQL::dbSendQuery(conn= rposgre_rsql,statement= insert)

but it returns
RPosgreSQL error: could not Retrieve the result : ERROR:  syntax error at or near "base"

I'm positive the connection works, since I can either select the table or use "dbExistsTable.R", but I don't understand why it doesn't work with INSERT INTO. The connection is for a corporate enviroment, maybe it's a permission issue? Also, I don't quite understand what's "STDIN" is.


问:
Encountered following error when using Pandas groupby object filtering: TypeError: 'function' object is not iterable
I have the following groupby object:

```<code>groupby=df.groupby('Product_1').mean().reset_index()
</code>```

And then when I attempt to filter the data:

```<code>groupby.filter(lambda x: x['s_qual'].mean() > 3)
</code>```

I recieve the following error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\A~1\AppData\Local\Temp/ipykernel_48512/2738959142.py in <module>
----> 1 groupby.filter(lambda x: x['s_qual'].mean() > 3.)

~\anaconda3\lib\site-packages\pandas\core\generic.py in filter(self, items, like, regex, axis)
   4980         if items is not None:
   4981             name = self._get_axis_name(axis)
-> 4982             return self.reindex(**{name: [r for r in items if r in labels]})
   4983         elif like:
   4984

TypeError: 'function' object is not iterable
</code>```

I am fairly new to coding, so if you can explain in simplified terms, it would be greatly appreciated.

I am unsure where I am going wrong here. Which function is it referencing that is not iterable?

Body:
I have the following groupby object:

groupby=df.groupby('Product_1').mean().reset_index()

And then when I attempt to filter the data:

groupby.filter(lambda x: x['s_qual'].mean() > 3)

I recieve the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\A~1\AppData\Local\Temp/ipykernel_48512/2738959142.py in <module>
----> 1 groupby.filter(lambda x: x['s_qual'].mean() > 3.)

~\anaconda3\lib\site-packages\pandas\core\generic.py in filter(self, items, like, regex, axis)
   4980         if items is not None:
   4981             name = self._get_axis_name(axis)
-> 4982             return self.reindex(**{name: [r for r in items if r in labels]})
   4983         elif like:
   4984

TypeError: 'function' object is not iterable

I am fairly new to coding, so if you can explain in simplified terms, it would be greatly appreciated.

I am unsure where I am going wrong here. Which function is it referencing that is not iterable?


问:
HTML picture always loads fallback on iOS browsers
I'm using a picture element to render WebP versions of images with the option to fallback to the unmodified JPEG if the browser does not support WebP. On Chrome and Safari on iOS, network requests are made for both versions of the image, webp and jpeg, even though it should be able to render webp on the recent browser versions.

It's difficult to troubleshoot without using a service like LambdaTest that lets you open dev tools on a mobile device, but that was how I found it after noticing poor mobile performance. Another possibly relevant detail is that it loads all JPEGs immediately, when they should lazy load. If there are 10 images on a page and 3 are above the fold, network requests will show all 10 jpegs loaded and only 3 webp images loaded, instead of 3 of each. I haven't been able to find any similar issues, so maybe I'm doing something very basic wrong.

This is what I currently have.

```<code><picture>
  <source srcSet="image.webp" type="image/webp" />
  <img src="original-image.jpg" alt="image" />
</picture>
</code>```

I've also tried adding the original image as a second source, since I've seen some examples done that way, but it didn't help.

This all works exactly as I expect on desktop browsers. The WebP images are the only ones that load, according to dev tools. No issues on Android browsers either.

Body:
I'm using a picture element to render WebP versions of images with the option to fallback to the unmodified JPEG if the browser does not support WebP. On Chrome and Safari on iOS, network requests are made for both versions of the image, webp and jpeg, even though it should be able to render webp on the recent browser versions.

It's difficult to troubleshoot without using a service like LambdaTest that lets you open dev tools on a mobile device, but that was how I found it after noticing poor mobile performance. Another possibly relevant detail is that it loads all JPEGs immediately, when they should lazy load. If there are 10 images on a page and 3 are above the fold, network requests will show all 10 jpegs loaded and only 3 webp images loaded, instead of 3 of each. I haven't been able to find any similar issues, so maybe I'm doing something very basic wrong.

This is what I currently have.

<picture>
  <source srcSet="image.webp" type="image/webp" />

</picture>

I've also tried adding the original image as a second source, since I've seen some examples done that way, but it didn't help.

This all works exactly as I expect on desktop browsers. The WebP images are the only ones that load, according to dev tools. No issues on Android browsers either.