问:
How to identify repeated ints on python
I've been learning python in a couple weeks and doing some challenges.
My question is:
I'm gonna ask for 2 ints inputs from user and put on a list ''list = []''
if the user write the same value(int) I have to print a message like ''Denied, already on list''
that's my code so far:

```<code>list = []
yourn = ' ' #yesorno
while yorn != 'n': #condition to break the loop
    list.append(int(input('Insert a number: ')))

  *** #thats where I'm stucked
    ***for rep in list
    if rep not in lista:
        continue
    else:
        print('duplicate')****
** (I know that's no the right way, thats just me trying it out)
    yorn = str(input('Continue? [Y/N]: ')).strip().lower()[0]
print('END!')
print(f'The numbers are: {sorted(list)} ', end=' → ')
</code>```

trying my best here!
thanks!!

I tried 'for' loop to identify a repeat number and if to get the condition

Title: How to identify repeated ints on python

Body:
I've been learning python in a couple weeks and doing some challenges.
My question is:
I'm gonna ask for 2 ints inputs from user and put on a list ''list = []''
if the user write the same value(int) I have to print a message like ''Denied, already on list''
that's my code so far:

list = []
yourn = ' ' #yesorno
while yorn != 'n': #condition to break the loop
    list.append(int(input('Insert a number: ')))

  *** #thats where I'm stucked
    ***for rep in list
    if rep not in lista:
        continue
    else:
        print('duplicate')****
** (I know that's no the right way, thats just me trying it out)
    yorn = str(input('Continue? [Y/N]: ')).strip().lower()[0]
print('END!')
print(f'The numbers are: {sorted(list)} ', end=' → ')

trying my best here!
thanks!!

I tried 'for' loop to identify a repeat number and if to get the condition


来源: stackexchange

问:
Upgrade Lambda Python 2.7 to 3.9 - Library Dependencies
We have a AWS Lambda Python 2.7 function with multiple libraries (lxml, lib & cx_Oracle-7.0.0.dist-info). We want to upgrade the Python 2.7 code to 3.9 and we are pretty clear on how to do that but we are not sure how to handle the library dependencies to get those upgraded or if they even need to be upgraded. Any help would be appreciated as we are a bit new to this.</p>

ContentLicense: CC BY-SA 4.0


问:
Failed to resolve import "./schemas" from "sanity.config.ts". Does the file exist
I tried removing the dot and / but still nothing is happening.

[screenshot1

i think the file is in the wrong location. but i dont know where should it be.


问:
Windowbuilder not showing the full frame
enter image description here

enter image description here

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;

public class AAA {

    private JFrame frame;

    /
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AAA window = new AAA();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /
     * Create the application.
     */
    public AAA() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}
</code>```

When I open WB via Eclipse. as soon as the project opens, my screen is like this.

Body:
enter image description here

enter image description here

import java.awt.EventQueue;

import javax.swing.JFrame;

public class AAA {

    private JFrame frame;

    /
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AAA window = new AAA();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /
     * Create the application.
     */
    public AAA() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

When I open WB via Eclipse. as soon as the project opens, my screen is like this.


问:
Data Loader for WSI converted into patches in tensorflow/keras
I want to create a dataloader for wsi images in keras. i have already converted images in patches. so each image is represented by a directory which contain image patches

How can i write a custom dataloader for it.


问:
How can I make my library compatible with libraries that use Proxies
I've written a library that relies on equality checks. Example:

export class Item {
  constructor(opts) {
    if (typeof opts.name !== 'string') throw new TypeError('Name should be a string');
    if (!opts.name) throw new Error('Please give item a name');
    this.name = opts.name;
    this.active = typeof opts.active === 'boolean' ? opts.active : false;
  }

  activate() {
    this.active = true;
  }

  deactivate() {
    this.active = false;
  }
}

export class Stage {
  constructor(opts) {
    this.items = [];
  }

  add(item) {
    this.items.push(item);
  }

  activate(itemToActivate) {
    // Strict equality check here
    const found = this.items.find(i => i === itemToActivate);
    if (!found) throw new Error('Item "${itemToActivate.name}" not found');
    found.activate();
  }
}
```
<p>Using this library could look like this:</p>
<pre class="lang-js prettyprint-override"><code>import { Item, Stage } from 'lib.js';

const stage = new Stage();
const item1 = new Item({ name: 'one' });
const item2 = new Item({ name: 'two' });
stage.add(item1);
stage.add(item2);
stage.activate(item2);
</code>```

This all works fine, but I'm running into issues when using this library in a framework that works with proxied objects like Vue 3, since I'm using a strict equality test in the activate method of the Stage class.

For example, in Vue 3:

```<code><script>
import { Item, Stage } from 'lib.js';

export default {
  data() {
    return {
      stage: null,
    };
  },
  created() {
    this.stage = new Stage();
    const item1 = new Item({ name: 'one' });
    const item2 = new Item({ name: 'two' });
    stage.add(item1);
    stage.add(item2);
    stage.activate(item2); // This will throw an error `Item "two" not found`
  }
}
</script>

<template>
  <div v-if="stage">
    <div>Items:</div>
    <div v-for="(item, idx) in stage.items">{{ item.name }}</div>
  </div>
<template>
</code>```

From what I understand, Vue 3 and other frameworks' use of Proxy introduce a caveat to be aware of: the proxied object is not equal to the original object in terms of identity comparison (===), which is why activate throws an Error.

My question is: how do I update my library so it supports Proxy-based frameworks without using any framework helpers like toRaw which would make my library dependent on that framework?

Body:
I've written a library that relies on equality checks. Example:

export class Item {
  constructor(opts) {
    if (typeof opts.name !== 'string') throw new TypeError('Name should be a string');
    if (!opts.name) throw new Error('Please give item a name');
    this.name = opts.name;
    this.active = typeof opts.active === 'boolean' ? opts.active : false;
  }

  activate() {
    this.active = true;
  }

  deactivate() {
    this.active = false;
  }
}

export class Stage {
  constructor(opts) {
    this.items = [];
  }

  add(item) {
    this.items.push(item);
  }

  activate(itemToActivate) {
    // Strict equality check here
    const found = this.items.find(i => i === itemToActivate);
    if (!found) throw new Error('Item "${itemToActivate.name}" not found');
    found.activate();
  }
}

Using this library could look like this:

import { Item, Stage } from 'lib.js';

const stage = new Stage();
const item1 = new Item({ name: 'one' });
const item2 = new Item({ name: 'two' });
stage.add(item1);
stage.add(item2);
stage.activate(item2);

This all works fine, but I'm running into issues when using this library in a framework that works with proxied objects like Vue 3, since I'm using a strict equality test in the activate method of the Stage class.

For example, in Vue 3:

<template>

Items:

{{ item.name }}

<template>

From what I understand, Vue 3 and other frameworks' use of Proxy introduce a caveat to be aware of: the proxied object is not equal to the original object in terms of identity comparison (===), which is why activate throws an Error.

My question is: how do I update my library so it supports Proxy-based frameworks without using any framework helpers like toRaw which would make my library dependent on that framework?


问:
Send Boolean integer from Child to parent using Pipe
I am writing a program copying each of the files into two separate processes. For each copy, we will have the parent process which will act as reader and the child process which will act as writer.
The two processes will need to communicate through single pipes.

I m blocked in a step where The writer sends the reader a boolean integer (int of 0 or 1) depending on whether the copy of the block should be performed.

It looks good but I am getting error writer sends wether it needs block to reader (int boolean (1 or 0))
I tried with strace -f but I can't find the error.

Here is the code in the child process.

```<code>else
        {
            // CHILD
     // Read elements
     // compare checksums
     // we return 1 or 0 depending on the comparison
     // we read the block to copy
     // we copy the block ds dest.
     // Close and free memory
     // child written
            close(pipefds1[1]);
            close(pipefds2[0]);

            int notDone = 1; //true
            //Read the size of the file
            size_t lenInput = 0;
            xread(pipefds1[0], &lenInput, sizeof(lenInput));
            if(arg->repert)
            {
                fd2 = open(otail, O_RDWR | O_CREAT, 0644);
            }
                while (notDone)
                {
                    //Read the number of bytes read by the reader
                    size_t lenReadLect = 0;
                    xread(pipefds1[0], &lenReadLect, sizeof(lenReadLect));

                    //Buffer for reading the end
                    char *buff2 = malloc(lenReadLect * sizeof(char));
                    char *buff1 = malloc(lenReadLect * sizeof(char));

                    if(0 == lenReadLect)
                    {
                        notDone = 0;
                    }
                    //Lecture du checksum du bout lu par le lecteur
                    uint32_t checksum1 = 0;
                    xread(pipefds1[0], &checksum1, sizeof(checksum1));
                    xread(fd2, buff2, lenReadLect);
                    uint32_t checksum2 = fletcher32((uint16_t *)buff2,strlen(buff2));

                    //Write bool if equal checksums on pipe2
                    int same = (checksum1 == checksum2);
                    printf("%i\n",same);

                    xwrite(pipefds2[1], &same, sizeof(same)); // HERE I SEND THE BOOLEAN TO THE PARENT
                    if(!same && notDone)
                    {
                        xread(pipefds1[0], buff1, lenReadLect);
                        xwrite(fd2, buff1, strlen(buff1));
                    }

                    free(buff1);
                    free(buff2);
                }
                close(fd2);

            close(pipefds1[0]);
            close(pipefds2[1]);
            free(arg);
            exit(0);
        }
</code>```

I'm not sure if I expressed myself well, you can ask me for more specifications

Body:
I am writing a program copying each of the files into two separate processes. For each copy, we will have the parent process which will act as reader and the child process which will act as writer.
The two processes will need to communicate through single pipes.

I m blocked in a step where The writer sends the reader a boolean integer (int of 0 or 1) depending on whether the copy of the block should be performed.

It looks good but I am getting error writer sends wether it needs block to reader (int boolean (1 or 0))
I tried with strace -f but I can't find the error.

Here is the code in the child process.

else
        {
            // CHILD
     // Read elements
     // compare checksums
     // we return 1 or 0 depending on the comparison
     // we read the block to copy
     // we copy the block ds dest.
     // Close and free memory
     // child written
            close(pipefds1[1]);
            close(pipefds2[0]);

            int notDone = 1; //true
            //Read the size of the file
            size_t lenInput = 0;
            xread(pipefds1[0], &lenInput, sizeof(lenInput));
            if(arg->repert)
            {
                fd2 = open(otail, O_RDWR | O_CREAT, 0644);
            }
                while (notDone)
                {
                    //Read the number of bytes read by the reader
                    size_t lenReadLect = 0;
                    xread(pipefds1[0], &lenReadLect, sizeof(lenReadLect));

                    //Buffer for reading the end
                    char *buff2 = malloc(lenReadLect * sizeof(char));
                    char *buff1 = malloc(lenReadLect * sizeof(char));

                    if(0 == lenReadLect)
                    {
                        notDone = 0;
                    }
                    //Lecture du checksum du bout lu par le lecteur
                    uint32_t checksum1 = 0;
                    xread(pipefds1[0], &checksum1, sizeof(checksum1));
                    xread(fd2, buff2, lenReadLect);
                    uint32_t checksum2 = fletcher32((uint16_t *)buff2,strlen(buff2));

                    //Write bool if equal checksums on pipe2
                    int same = (checksum1 == checksum2);
                    printf("%i\n",same);

                    xwrite(pipefds2[1], &same, sizeof(same)); // HERE I SEND THE BOOLEAN TO THE PARENT
                    if(!same && notDone)
                    {
                        xread(pipefds1[0], buff1, lenReadLect);
                        xwrite(fd2, buff1, strlen(buff1));
                    }

                    free(buff1);
                    free(buff2);
                }
                close(fd2);

            close(pipefds1[0]);
            close(pipefds2[1]);
            free(arg);
            exit(0);
        }

I'm not sure if I expressed myself well, you can ask me for more specifications


问:
MarkLogic xdmp.save never returning value or throwing error
Version: MarkLogic 10.0-9

For context I am using the JavaScript version of the xdmp library.

I am using the built in xdmp library to add objects in S3. For saving and object we use xdmp.save, and for deleting we use xdmp.filesystemFileDelete. I am going to assume xdmp.filesystemFileDelete is deprecated. I no longer see this function in the documentation, but it's not very important since I am going to handle the object deletion on the AWS side going forward. This issue exists in both functions regardless.

As you can see from the logs below, the xdmp.save function is receiving a 403 Forbidden error. This makes sense. I accidentally tried to use the wrong S3 bucket. The problem is that the xdmp.save function never returned a value or threw any errors. The function kept running until MarkLogic killed the process after the timeout limit was reached. This had a knock on effect as the whole process queue was backed up waiting for this to finish.

It took about 37 seconds to give up on uploading the object in S3. The function ran for about 30 more seconds and never hit my trace (via xdmp.trace) log at the end of the script. It's like the xdmp.save function is stuck in an infinite loop.

```<code>2022-12-20 11:22:54.266 Debug: Retrying S3Rep::PUT 4314 1 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:54.367 Debug: Retrying S3Rep::PUT 4314 2 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:54.533 Debug: Retrying S3Rep::PUT 4314 3 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:54.827 Debug: Retrying S3Rep::PUT 4314 4 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:55.379 Debug: Retrying S3Rep::PUT 4314 5 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:56.426 Debug: Retrying S3Rep::PUT 4314 6 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:58.452 Debug: Retrying S3Rep::PUT 4314 7 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:01.505 Debug: Retrying S3Rep::PUT 4314 8 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:05.552 Debug: Retrying S3Rep::PUT 4314 9 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:10.600 Debug: Retrying S3Rep::PUT 4314 10 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:16.648 Debug: Retrying S3Rep::PUT 4314 11 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:23.700 Debug: Retrying S3Rep::PUT 4314 12 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:31.729 Debug: Retrying S3Rep::PUT 4314 13 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
</code>```

Here is the code (this is very much a work in progress):

```<code>'use strict';
declareUpdate();

const config = require('/config/config.sjs');

xdmp.trace('export trace', 'Firing Trigger for export');
if (config.exportEnabled && uri) {
    const inputType = fn.substringBefore(fn.substringAfter(uri, '/data/'), '/');
    const document = cts.doc(uri);
    const mutableDocument = document.toObject();
    const key = `${config.s3ExportPath}/${inputType}-${mutableDocument.content.uuid}.json`;

    if(inputType === 'tasker' && mutableDocument && mutableDocument.workflowStatus === 'Draft') {
        xdmp.trace('export trace', 'Drafts are not exported.');
    } else {
      const permissions = xdmp.documentGetPermissions(uri);
      const exportedDocument = Object.assign(
          {},
          mutableDocument,
          {
              properties: {
                uri,
                type: inputType,
                permissions: permissions.map(permission => [xdmp.roleName(permission.roleId), permission.capability]),
                collections: xdmp.documentGetCollections(uri),
                exportDate: fn.currentDateTime()
            }
        });
      xdmp.trace('export trace', `Adding document with properties in S3: ${key}`);
      xdmp.save(key, exportedDocument, { outputEncoding: 'utf-8', mediaType: 'application/json' });
    }
} else {
  xdmp.trace('export trace', 'Either export is disabled, or uri is missing.');
  xdmp.trace('export trace', `config.exportEnabled: ${config.exportEnabled}`);
  xdmp.trace('export trace', `uri: ${uri}`);
}

xdmp.trace('export trace', 'Fired Trigger for export');
</code>```

I tried wrapping it in a try/catch block, but the function never returns anything or throws and error.

Is there a better way to save objects to S3 using MarkLogic?

Body:
Version: MarkLogic 10.0-9

For context I am using the JavaScript version of the xdmp library.

I am using the built in xdmp library to add objects in S3. For saving and object we use xdmp.save, and for deleting we use xdmp.filesystemFileDelete. I am going to assume xdmp.filesystemFileDelete is deprecated. I no longer see this function in the documentation, but it's not very important since I am going to handle the object deletion on the AWS side going forward. This issue exists in both functions regardless.

As you can see from the logs below, the xdmp.save function is receiving a 403 Forbidden error. This makes sense. I accidentally tried to use the wrong S3 bucket. The problem is that the xdmp.save function never returned a value or threw any errors. The function kept running until MarkLogic killed the process after the timeout limit was reached. This had a knock on effect as the whole process queue was backed up waiting for this to finish.

It took about 37 seconds to give up on uploading the object in S3. The function ran for about 30 more seconds and never hit my trace (via xdmp.trace) log at the end of the script. It's like the xdmp.save function is stuck in an infinite loop.

2022-12-20 11:22:54.266 Debug: Retrying S3Rep::PUT 4314 1 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:54.367 Debug: Retrying S3Rep::PUT 4314 2 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:54.533 Debug: Retrying S3Rep::PUT 4314 3 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:54.827 Debug: Retrying S3Rep::PUT 4314 4 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:55.379 Debug: Retrying S3Rep::PUT 4314 5 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:56.426 Debug: Retrying S3Rep::PUT 4314 6 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:22:58.452 Debug: Retrying S3Rep::PUT 4314 7 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:01.505 Debug: Retrying S3Rep::PUT 4314 8 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:05.552 Debug: Retrying S3Rep::PUT 4314 9 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:10.600 Debug: Retrying S3Rep::PUT 4314 10 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:16.648 Debug: Retrying S3Rep::PUT 4314 11 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:23.700 Debug: Retrying S3Rep::PUT 4314 12 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]
2022-12-20 11:23:31.729 Debug: Retrying S3Rep::PUT 4314 13 because SVC-S3ERR: S3 error: PUT 4314 https://[REDACTED].s3.amazonaws.com/[REDACTED].json 403 Forbidden Code=AccessDenied Message="Access Denied" RequestId=[REDACTED] HostId=[REDACTED]

Here is the code (this is very much a work in progress):

'use strict';
declareUpdate();

const config = require('/config/config.sjs');

xdmp.trace('export trace', 'Firing Trigger for export');
if (config.exportEnabled && uri) {
    const inputType = fn.substringBefore(fn.substringAfter(uri, '/data/'), '/');
    const document = cts.doc(uri);
    const mutableDocument = document.toObject();
    const key = `${config.s3ExportPath}/${inputType}-${mutableDocument.content.uuid}.json`;

    if(inputType === 'tasker' && mutableDocument && mutableDocument.workflowStatus === 'Draft') {
        xdmp.trace('export trace', 'Drafts are not exported.');
    } else {
      const permissions = xdmp.documentGetPermissions(uri);
      const exportedDocument = Object.assign(
          {},
          mutableDocument,
          {
              properties: {
                uri,
                type: inputType,
                permissions: permissions.map(permission => [xdmp.roleName(permission.roleId), permission.capability]),
                collections: xdmp.documentGetCollections(uri),
                exportDate: fn.currentDateTime()
            }
        });
      xdmp.trace('export trace', `Adding document with properties in S3: ${key}`);
      xdmp.save(key, exportedDocument, { outputEncoding: 'utf-8', mediaType: 'application/json' });
    }
} else {
  xdmp.trace('export trace', 'Either export is disabled, or uri is missing.');
  xdmp.trace('export trace', `config.exportEnabled: ${config.exportEnabled}`);
  xdmp.trace('export trace', `uri: ${uri}`);
}

xdmp.trace('export trace', 'Fired Trigger for export');

I tried wrapping it in a try/catch block, but the function never returns anything or throws and error.

Is there a better way to save objects to S3 using MarkLogic?


问:
npm run command not working after git clone
Every time I created new git clone, the following npm run command is not working. Anyone faced any issue with it?

I need to go through npm install command.


问:
How do I Setup this mocked object in Xunit?
So I have this class that accesses data in a database. Let's call it dbAccessor. I have an interface for it called IDbAccessor. I am writing xunit tests for a file that utilizes this IDbAccessor. Can someone explain how to set up this mocked object so that it returns an object?

Currently, my test file looks like this

```<code>[Fact]
public async Task TestDB_Accessor()
{
    var dbAccessorMock = CreateMock<IDbAccessor>();

    // This fails before it even reaches the verification. Because inside
    // of dbAccessor, there is a line of code that utilizes the return
    // data from the database, but in this case, it is null, I believe
    // because this dbAccessorMock has not been set up to return an obj.
    await dbAccessorMock.PostItem(CreateMock<Dog>().Object);

    // Verification
    dbAccessorMock.Verify(x => x.PostItem(It.IsAny<Dog>()));
}
</code>```

But the above test code does not work because I believe the dbAccessorMock variable has not been set up to return an object. It just returns null, thus the code/test will fail. Does anyone know the proper way to set up this mock object to ensure that it returns something?

Body:
So I have this class that accesses data in a database. Let's call it dbAccessor. I have an interface for it called IDbAccessor. I am writing xunit tests for a file that utilizes this IDbAccessor. Can someone explain how to set up this mocked object so that it returns an object?

Currently, my test file looks like this

[Fact]
public async Task TestDB_Accessor()
{
    var dbAccessorMock = CreateMock<IDbAccessor>();

    // This fails before it even reaches the verification. Because inside
    // of dbAccessor, there is a line of code that utilizes the return
    // data from the database, but in this case, it is null, I believe
    // because this dbAccessorMock has not been set up to return an obj.
    await dbAccessorMock.PostItem(CreateMock<Dog>().Object);

    // Verification
    dbAccessorMock.Verify(x => x.PostItem(It.IsAny<Dog>()));
}

But the above test code does not work because I believe the dbAccessorMock variable has not been set up to return an object. It just returns null, thus the code/test will fail. Does anyone know the proper way to set up this mock object to ensure that it returns something?


问:
Jinja2 is adding unwanted trailing zeros to html table values from pandas dataframe
Pandas Dataframe:

Price
Value

EAT
148.84
116.18

Jinja2 Table:

Price
Value

EAT
148.84
116.180000

What should I be doing to remove the Jinja generated zeros? All columns following Price are containing extra zeros.

Matplotlib table renders fine.

Tried:

html = template.render(my_table = styler.to_html(float_format='%.2f'))
```
```{{ "$%.2f"|format(my_table|float) }}
{{my_table}}
```

Body:
Pandas Dataframe:

Price
Value

EAT
148.84
116.18

Jinja2 Table:

Price
Value

EAT
148.84
116.180000

What should I be doing to remove the Jinja generated zeros? All columns following Price are containing extra zeros.

Matplotlib table renders fine.

Tried:

html = template.render(my_table = styler.to_html(float_format='%.2f'))

{{ "$%.2f"|format(my_table|float) }}
{{my_table}}


问:
Discord.py Remind Bot
I have the bot where it can respond to messages sent like "good morning" "hello" etc. I want to implement an event where a user can set a reminder, so the bot can ping them. Ive looked at so many other examples and have been messing with it for weeks.

heres my code:

```<code>import asyncio

class RemindCommand(commands.Cog):

  def __init__(self, client):
    self.client = client

  @commands.command()
  async def remind(self, ctx, time, *, task):

    def convert(time):
      pos = ['s', 'm', 'h', 'd']

      time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}

      unit = time[-1]

      if unit not in pos:
        #        print("Failed Unit!")
        return -1
      try:
        val = int(time[:-1])

  #     print("Pass Unit!")
      except:
        return -2

        return val * time_dict[unit]

    converted_time = convert(time)

    if converted_time == -1:
      await ctx.send("you didnt imput the time correctly.")
      return

    if converted_time == -2:
      await ctx.send("The number must be an integer")
      return

    await ctx.send(f"Okay, i will remind you to **{task}** at **{time}**.")

    await asyncio.sleep(converted_time)
    await ctx.send(
      f"{ctx.author.mention} your reminder for **{task}** has finished!")

def setup(client):
  client.add_cog(RemindCommand(client))

bot.run('token')

</code>```

Title: Discord.py Remind Bot

Body:
I have the bot where it can respond to messages sent like "good morning" "hello" etc. I want to implement an event where a user can set a reminder, so the bot can ping them. Ive looked at so many other examples and have been messing with it for weeks.

heres my code:

import asyncio

class RemindCommand(commands.Cog):

  def __init__(self, client):
    self.client = client

  @commands.command()
  async def remind(self, ctx, time, *, task):

    def convert(time):
      pos = ['s', 'm', 'h', 'd']

      time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}

      unit = time[-1]

      if unit not in pos:
        #        print("Failed Unit!")
        return -1
      try:
        val = int(time[:-1])

  #     print("Pass Unit!")
      except:
        return -2

        return val * time_dict[unit]

    converted_time = convert(time)

    if converted_time == -1:
      await ctx.send("you didnt imput the time correctly.")
      return

    if converted_time == -2:
      await ctx.send("The number must be an integer")
      return

    await ctx.send(f"Okay, i will remind you to **{task}** at **{time}**.")

    await asyncio.sleep(converted_time)
    await ctx.send(
      f"{ctx.author.mention} your reminder for **{task}** has finished!")

def setup(client):
  client.add_cog(RemindCommand(client))

bot.run('token')


问:
Test a Rest API in python jupyter notebook and mac terminal
I have a REST API with an endpoint that accepts a few parameters: lat, long, and val and uses basic authentication with host, user and pwd.

Endpoint nearby is a python function that accepts lat, long, and val and returns a json response with a calculated value.

How do I test the API in python jupyter notebook? How do I pass parameters?

```<code>
import requests

r = requests.get(
                 'https://dev/callbacks/api/nearby',
                 auth=('usernm', 'mybasicpass')
                )

</code>```

How do I test the API on mac terminal? construct curl command?

```<code>   curl https://dev/callbacks/api/nearby \
   -u "usernm:mybasicpass" \
</code>```

Body:
I have a REST API with an endpoint that accepts a few parameters: lat, long, and val and uses basic authentication with host, user and pwd.

Endpoint nearby is a python function that accepts lat, long, and val and returns a json response with a calculated value.

How do I test the API in python jupyter notebook? How do I pass parameters?

import requests

r = requests.get(
                 'https://dev/callbacks/api/nearby',
                 auth=('usernm', 'mybasicpass')
                )

How do I test the API on mac terminal? construct curl command?

   curl https://dev/callbacks/api/nearby \
   -u "usernm:mybasicpass" \


问:
Firebase Realtime Database, .indexOn with nested child with dynamic ID not working
This is what my database looks like..

```<code>{
"users":{
     "user_id4243":{
        "friends":{
             "friend1_ID5321":1,
             "friend2_ID5321":1,
             "friend3_ID5321":1}
        "sData":"some_data"
     }
   }
}
</code>```

In the other words, I store user's friend's Id's, and try to filter users, using a friend ID.

Everything works perfectly, except it downloads the whole "friends" data, and does the filtering on the client side. I get logs saying(Android/iOS),

```<code>Consider adding '".indexOn": "friends/115883230405231926879"' at users to your security and Firebase Database rules...
</code>```

But how should I do that with no static user ids?
I've tried the following method, but it doesn't work as indexOn required only static path..

```<code>"users": {
      "$user_id": {
          "friends": {
                ".indexOn": "$user_id"
            }
        }
    }
</code>```

I've even tried adding another "ID" variable inside the friend id, but still no success..

```<code>"users": {
      "$user_id": {
          "friends": {
              "$user_id": {
                ".indexOn": ["ID"]
              }
            }
        }
    }
</code>```

Any idea how can I use .indexOn in this situation? Or how can I make a structure, where I'll be able to filter users, that will have certain ID inside..?

Body:
This is what my database looks like..

{
"users":{
     "user_id4243":{
        "friends":{
             "friend1_ID5321":1,
             "friend2_ID5321":1,
             "friend3_ID5321":1}
        "sData":"some_data"
     }
   }
}

In the other words, I store user's friend's Id's, and try to filter users, using a friend ID.

Everything works perfectly, except it downloads the whole "friends" data, and does the filtering on the client side. I get logs saying(Android/iOS),

Consider adding '".indexOn": "friends/115883230405231926879"' at users to your security and Firebase Database rules...

But how should I do that with no static user ids?
I've tried the following method, but it doesn't work as indexOn required only static path..

"users": {
      "$user_id": {
          "friends": {
                ".indexOn": "$user_id"
            }
        }
    }

I've even tried adding another "ID" variable inside the friend id, but still no success..

"users": {
      "$user_id": {
          "friends": {
              "$user_id": {
                ".indexOn": ["ID"]
              }
            }
        }
    }

Any idea how can I use .indexOn in this situation? Or how can I make a structure, where I'll be able to filter users, that will have certain ID inside..?


问:
Programmatically appending to NavigationStack path behaves differently than using NavigationLink
I have a basic log-in flow on a project I'm working on and wanted to try out the new programmatic navigation in SwiftUI from iOS 16. I noticed that appending to the path array after pressing a Button for example made transitions behave differently than using a NavigationLink. This gif illustrates the differences clearer. My theory is the view makes space for the toolbar that appears in the next view and gets redrawn right before it goes offscreen. I'd like some help understanding the differences between these two ways of navigating.

Here is what I have set up regarding the NavigationStack and the state of the path array within an ObservedObject.

enum Path {
    case welcome
    case login
}

class AppState: ObservableObject {
    @Published var path: [Path] = []
}
```
<pre class="lang-swift prettyprint-override"><code>@main
struct MainApp: App {
    @ObservedObject var appState = AppState()

    var body: some Scene {
        WindowGroup {
            NavigationStack(path: self.$appState.path) {
                // Root View
                SplashView()
                    .navigationDestination(for: Path.self) { path in
                        switch path {
                        case .welcome:
                            WelcomeView()
                        case .login:
                            LoginView()
                        }
                    }
            }
            .environmentObject(self.appState)
        }
    }
}
</code>```

These are the NavigationLink/Button being called from my WelcomeView:

NavigationLink(value: Path.login) {
    RoundedRectangle(cornerRadius: 10)
        .foregroundColor(.black)
        .frame(maxWidth: .infinity)
        .frame(height: 55)
        .overlay {
            Text("NavigationLink Login")
                .font(.custom("Poppins-SemiBold", size: 14))
                .foregroundColor(.white)
        }
}
```
<pre class="lang-swift prettyprint-override"><code>Button {
    self.appState.path.append(.login)
} label: {
    RoundedRectangle(cornerRadius: 10)
        .foregroundColor(.black)
        .frame(maxWidth: .infinity)
        .frame(height: 55)
        .overlay {
            Text("Button Login")
                .font(.custom("Poppins-SemiBold", size: 14))
                .foregroundColor(.white)
        }
}
</code>```

Thanks!

Body:
I have a basic log-in flow on a project I'm working on and wanted to try out the new programmatic navigation in SwiftUI from iOS 16. I noticed that appending to the path array after pressing a Button for example made transitions behave differently than using a NavigationLink. This gif illustrates the differences clearer. My theory is the view makes space for the toolbar that appears in the next view and gets redrawn right before it goes offscreen. I'd like some help understanding the differences between these two ways of navigating.

Here is what I have set up regarding the NavigationStack and the state of the path array within an ObservedObject.

enum Path {
    case welcome
    case login
}

class AppState: ObservableObject {
    @Published var path: [Path] = []
}

@main
struct MainApp: App {
    @ObservedObject var appState = AppState()

    var body: some Scene {
        WindowGroup {
            NavigationStack(path: self.$appState.path) {
                // Root View
                SplashView()
                    .navigationDestination(for: Path.self) { path in
                        switch path {
                        case .welcome:
                            WelcomeView()
                        case .login:
                            LoginView()
                        }
                    }
            }
            .environmentObject(self.appState)
        }
    }
}

These are the NavigationLink/Button being called from my WelcomeView:

NavigationLink(value: Path.login) {
    RoundedRectangle(cornerRadius: 10)
        .foregroundColor(.black)
        .frame(maxWidth: .infinity)
        .frame(height: 55)
        .overlay {
            Text("NavigationLink Login")
                .font(.custom("Poppins-SemiBold", size: 14))
                .foregroundColor(.white)
        }
}

Button {
    self.appState.path.append(.login)
} label: {
    RoundedRectangle(cornerRadius: 10)
        .foregroundColor(.black)
        .frame(maxWidth: .infinity)
        .frame(height: 55)
        .overlay {
            Text("Button Login")
                .font(.custom("Poppins-SemiBold", size: 14))
                .foregroundColor(.white)
        }
}

Thanks!


问:
Convert multiple genres of movie to different rows in excel
I have a dataset which has multiple genres for movie, I want to make multiple rows with same movie name but each time with different genre in excel

example:

dataset I have:

movie
genre1
genre2

abc
horror
action

efg
comedy
drama

dataset I want:

movie
genre1

abc
horror

abc
action

efg
comedy

efg
drama


问:
How to find a complementary parallelogram
On https://stackoverflow.com/a/8862483/4918319, an algorithm is put forward with which to determine whether a ray in 3-space goes through a given rectangle, if we specify the ray by two vectors (one specifying the origin of the ray and the other its direction) and the rectangle by three vectors (one specifying the location of one corner and the other two giving the relative positions of the two corners adjacent to that one).

The author then asserts that this algorithm is not limited to squares & rectangles, but also works for any parallelogram. However, while that initially appears to be true, and works to a limited extent, the fact is that, because projection is used, which involves moving a point onto a line by a course perpendicular to the line, it does not work, as it is, for just any parallelogram.

However, it appears that every parallelogram, once you have selected a corner, has one complementary parallelogram. Each parallelogram covers the area which that algorithm would attribute to its complement, and vice versa. For example, if you draw a rhombus and select an obtuse corner of it, and then shade the area of the paper that projects to each of the two sides which that corner joins, the shaded areas will overlap to form another rhombus, with one acute corner at the point which you selected. Then, if you draw the acute rhombus and then shade the areas of the paper which project to the sides adjacent to the originally selected corner, the shaded area will form the same shape, size, and orientation as your original rhombus.

The question remains, how to derive the complement of a parallelogram once you know the three vectors which define the first?


问:
Duplicate column names are automatically renamed - Setting mangle_dupe_cols=False still gives ValueError - But why is it working with workarounds?
Identical column names will be renamed automatically when using panda's method read_excel() (MRE: method 2). The same is true if the header of the dataframe is reassigned from a list element which is given to read_excel()'s parameter names (MRE: method 4).

I understand the method's mangle_dupe_cols parameter being set to false is supposed to suppress this behaviour (https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html).* But it is resulting in a ValueError: Setting mangle_dupe_cols=False is not supported yet (MRE: method 3).

Trying out several solutions I was wondering about the following 3 questions.

Why is it that the behaviour I am looking for is found in MRE method 1 and method 5 but not in the above described cases?

Method 1 is constructing its own dataframe without reading it from an external table; but why are the rules being applied to the column names of that dataframe differ from panda's read_excel()?

Method 5 shows that the header can be reassigned by a list element to df.columns and duplicate column names will not be renamed.

Why is this possible but not by reassigning a list element to  read_excel()'s parameter names (MRE: method 4)?

This is a minimal, reproducible example containing the 5 cases described:

```<code>import pandas as pd
import numpy as np
import openpyxl

# Pandas Version
print(pd.__version__)

# Method 1: Write df with duplicate column names
df = pd.DataFrame(np.arange(12).reshape(3, 4), columns=['A', 'B', 'C', 'A'])
print("Method 1: \n", df, "\n\n")

# Method 2: Read df from xlsx
df = pd.read_excel("mwe_dupeCols.xlsx")
print("Method 2: \n", df, "\n\n")

# Method 3: Read df from xlsx, mangle_dupe_cols=False
# https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html
# ValueError: Setting mangle_dupe_cols=False is not supported yet
#df = pd.read_excel("mwe_dupeCols.xlsx", index_col=[0], mangle_dupe_cols=False)
#print("Method 3: ValueError \n", df, "\n\n")

# Method 4: Read df from xlsx, reassign header out of list to names parameter in read_excel()
header = pd.read_excel("mwe_dupeCols.xlsx", header=None)
header_list = header.iloc[0].values.flatten().tolist() # Take first row and cast it to list
#print(header_list)
#print(type(header_list))
# Read xlsx, skipping header column
df = pd.read_excel("mwe_dupeCols.xlsx", skiprows=1, header=None, names=header_list)
print("Method 4: \n", df, "\n\n")

# Method 5: Read df from xlsx, reassign header out of list to df.columns
header = pd.read_excel("mwe_dupeCols.xlsx", header=None) #.set_index(0)
#print(header.iloc[0].values)
header.drop([1], axis=0, inplace=True)
header_list = header.iloc[0].values.flatten().tolist() # Take first row and cast it to list
#print(header_list)
#print(type(header_list))
# Read xlsx, skipping header column
df = pd.read_excel("mwe_dupeCols.xlsx", skiprows=1, header=None)
#print(df)
df.columns = header_list
print("Method 5: \n", df, "\n\n")
</code>```

The table mwe_dupeCols.xlsx has the following structure:

A
B
C
A

0
1
2
3

4
5
6
7

8
9
10
11

Thanks for your time!

*The parameter is deprecated since version 1.5.0, I am currently using 1.4.3. Python 3.9 is used within a virtualenv executed in PyCharm.

Body:
Identical column names will be renamed automatically when using panda's method read_excel() (MRE: method 2). The same is true if the header of the dataframe is reassigned from a list element which is given to read_excel()'s parameter names (MRE: method 4).

I understand the method's mangle_dupe_cols parameter being set to false is supposed to suppress this behaviour (https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html).* But it is resulting in a ValueError: Setting mangle_dupe_cols=False is not supported yet (MRE: method 3).

Trying out several solutions I was wondering about the following 3 questions.

Why is it that the behaviour I am looking for is found in MRE method 1 and method 5 but not in the above described cases?

Method 1 is constructing its own dataframe without reading it from an external table; but why are the rules being applied to the column names of that dataframe differ from panda's read_excel()?

Method 5 shows that the header can be reassigned by a list element to df.columns and duplicate column names will not be renamed.

Why is this possible but not by reassigning a list element to  read_excel()'s parameter names (MRE: method 4)?

This is a minimal, reproducible example containing the 5 cases described:

import pandas as pd
import numpy as np
import openpyxl

# Pandas Version
print(pd.__version__)

# Method 1: Write df with duplicate column names
df = pd.DataFrame(np.arange(12).reshape(3, 4), columns=['A', 'B', 'C', 'A'])
print("Method 1: \n", df, "\n\n")

# Method 2: Read df from xlsx
df = pd.read_excel("mwe_dupeCols.xlsx")
print("Method 2: \n", df, "\n\n")

# Method 3: Read df from xlsx, mangle_dupe_cols=False
# https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html
# ValueError: Setting mangle_dupe_cols=False is not supported yet
#df = pd.read_excel("mwe_dupeCols.xlsx", index_col=[0], mangle_dupe_cols=False)
#print("Method 3: ValueError \n", df, "\n\n")

# Method 4: Read df from xlsx, reassign header out of list to names parameter in read_excel()
header = pd.read_excel("mwe_dupeCols.xlsx", header=None)
header_list = header.iloc[0].values.flatten().tolist() # Take first row and cast it to list
#print(header_list)
#print(type(header_list))
# Read xlsx, skipping header column
df = pd.read_excel("mwe_dupeCols.xlsx", skiprows=1, header=None, names=header_list)
print("Method 4: \n", df, "\n\n")

# Method 5: Read df from xlsx, reassign header out of list to df.columns
header = pd.read_excel("mwe_dupeCols.xlsx", header=None) #.set_index(0)
#print(header.iloc[0].values)
header.drop([1], axis=0, inplace=True)
header_list = header.iloc[0].values.flatten().tolist() # Take first row and cast it to list
#print(header_list)
#print(type(header_list))
# Read xlsx, skipping header column
df = pd.read_excel("mwe_dupeCols.xlsx", skiprows=1, header=None)
#print(df)
df.columns = header_list
print("Method 5: \n", df, "\n\n")

The table mwe_dupeCols.xlsx has the following structure:

A
B
C
A

0
1
2
3

4
5
6
7

8
9
10
11

Thanks for your time!

*The parameter is deprecated since version 1.5.0, I am currently using 1.4.3. Python 3.9 is used within a virtualenv executed in PyCharm.


问:
Is there a reliable way to get __name__ in Manim when using multiprocessing
I am working on a video that has a simulation of ideal gas (points) or realistic gas (circles) going on in the background for parts of it. In order to make processing go faster with a useful number of "molecules" for the realistic gas, I've been using the multiprocessing python package. This requires checks for "__name__ = '__main__'" in regular python to avoid bad multiprocessing conditions. In manim 0.16 versions, I was able to use "__name__ = 'py'", but this broke in the upgrade to 0.17 versions. I eventually fixed it by doing a quick check for whatever __name__ is now by having the main process print("__name__ is now ", __name__), which now outputs "path.to.working.dir.main".

Is there an easy way to find out what to use from within the program without having to check and fix with every update?

In manim 0.16 versions, checking for

__name__ = "py"

was good enough. This changed in manim 0.17 versions and it took me a while to figure out why my animation was crashing. I finally resolved it by inserting a

print("__name__ is now ", __name__)

near the top of the code to find out what to use now. However, this seems like an ineffective approach in the long run (will I have to go through this in version 0.18?) and I'd like to find a better way, more reliable, more automated way.


问:
Windows PowerShell: Unable to read data from the transport connection
I am running Windows PowerShell as administrator and I am trying to create a file with information I get from Sharepoint Online. I run the below and get a message with a link I follow (devicelogin), enter the code given and then after I add my credentials, I am signed in.

```<code>Import-Module PnP.PowerShell
Update-Module SharePointPnPPowerShell*
Connect-PnPOnline -Url "https://<mydomain>-admin.sharepoint.com" -PnPManagementShell
$siteUrl = "https://<mydomain>.sharepoint.com/sites/ASI-DropPoint"
$cred = Get-Credential
#Connect-PnPOnline -Url $siteUrl -Credential $cred
#or the below to get more detailed info about connection process
Connect-PnPOnline -Url $siteUrl -Credential $cred -Verbose

$filePath = "C:\Users\ASI_app_eng\Desktop\To do"
$DocLibraryName="Documents"

# testing if the path can be accessed because sometimes I get an error that the access is denied.
if (Test-Path $filePath) {
    Write-Output "It has access"
} else {
    Write-Output "Cannot access the specified file path"
}

# Get the list items from the document library in batches of 1000 items
$listItems = Get-PnPListItem -List $DocLibraryName -PageSize 1000

# Create a new file and write the names of the files and last accessed date to it with tab (default) separator
$listItems | Select-Object Name,LastAccessedDate | Out-File -FilePath "$filePath\filenames.txt"

</code>```

The error I get after some minutes is the below.
Get-PnPListItem : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

The library contains almost 7000 documents/items.

I found some information online about the problem here, here  and on these 2 stackoverflow posts: 1, 2.

I am completely new to PowerShell and Sharepoint management; I practically came up with this script after days of asking chatgpt and solving bug after bug. Are the above solutions suitable for my issue? I am afraid I might do something I'm not supposed to and cause problems to my work laptop and/or sharepoint.

I tried the below, in case it was a connection issue, but this doesn't seem to be the problem. My connection is fast and stable.

```<code>Connect-PnPOnline -Url $siteUrl -Credential $cred -RetryCount 3 -RetryWait 10

</code>```

Body:
I am running Windows PowerShell as administrator and I am trying to create a file with information I get from Sharepoint Online. I run the below and get a message with a link I follow (devicelogin), enter the code given and then after I add my credentials, I am signed in.

Import-Module PnP.PowerShell
Update-Module SharePointPnPPowerShell*
Connect-PnPOnline -Url "https://<mydomain>-admin.sharepoint.com" -PnPManagementShell
$siteUrl = "https://<mydomain>.sharepoint.com/sites/ASI-DropPoint"
$cred = Get-Credential
#Connect-PnPOnline -Url $siteUrl -Credential $cred
#or the below to get more detailed info about connection process
Connect-PnPOnline -Url $siteUrl -Credential $cred -Verbose

$filePath = "C:\Users\ASI_app_eng\Desktop\To do"
$DocLibraryName="Documents"

# testing if the path can be accessed because sometimes I get an error that the access is denied.
if (Test-Path $filePath) {
    Write-Output "It has access"
} else {
    Write-Output "Cannot access the specified file path"
}

# Get the list items from the document library in batches of 1000 items
$listItems = Get-PnPListItem -List $DocLibraryName -PageSize 1000

# Create a new file and write the names of the files and last accessed date to it with tab (default) separator
$listItems | Select-Object Name,LastAccessedDate | Out-File -FilePath "$filePath\filenames.txt"

The error I get after some minutes is the below.
Get-PnPListItem : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

The library contains almost 7000 documents/items.

I found some information online about the problem here, here  and on these 2 stackoverflow posts: 1, 2.

I am completely new to PowerShell and Sharepoint management; I practically came up with this script after days of asking chatgpt and solving bug after bug. Are the above solutions suitable for my issue? I am afraid I might do something I'm not supposed to and cause problems to my work laptop and/or sharepoint.

I tried the below, in case it was a connection issue, but this doesn't seem to be the problem. My connection is fast and stable.

Connect-PnPOnline -Url $siteUrl -Credential $cred -RetryCount 3 -RetryWait 10


问:
Is it SOLID if a class and another class which is used through composition both have same interfaces?
I have the following code where I have an EnvalidValidator class that implements an IEnvironmentVariableValidator interface

```<code>import { cleanEnv, port, str } from "envalid";

import IEnvironmentVariableValidator from "../Interfaces/EnvironmentVariableValidator";

class EnvalidValidator implements IEnvironmentVariableValidator {
  validate(env: NodeJS.ProcessEnv) {
    cleanEnv(env, {
      API_PORT: port(),

      DATABASE_TYPE: str(),
      DATABASE_HOST: str(),
      DATABASE_USERNAME: str(),
      DATABASE_PORT: port(),
      DATABASE_PASSWORD: str(),
      DATABASE_NAME: str(),

      NODE_ENV: str(),
    });
  }
}

export default EnvalidValidator;
</code>```

and another class called EnvironmentVariableValidator that has an instance of IEnvironmentVariableValidator injected into it through its constructor.

```<code>import IEnvironmentVariableValidator from "../Interfaces/EnvironmentVariableValidator";

class EnvironmentVariableValidator implements IEnvironmentVariableValidator {
  validator: IEnvironmentVariableValidator;

  constructor(validator: IEnvironmentVariableValidator) {
    this.validator = validator;
  }

  validate(env: NodeJS.ProcessEnv) {
    this.validator.validate(env);
  }
}

export default EnvironmentVariableValidator;
</code>```

My question is, is it following clean code, SOLID and is the correct way to make EnvalidValidator encapsulation?

Body:
I have the following code where I have an EnvalidValidator class that implements an IEnvironmentVariableValidator interface

import { cleanEnv, port, str } from "envalid";

import IEnvironmentVariableValidator from "../Interfaces/EnvironmentVariableValidator";

class EnvalidValidator implements IEnvironmentVariableValidator {
  validate(env: NodeJS.ProcessEnv) {
    cleanEnv(env, {
      API_PORT: port(),

      DATABASE_TYPE: str(),
      DATABASE_HOST: str(),
      DATABASE_USERNAME: str(),
      DATABASE_PORT: port(),
      DATABASE_PASSWORD: str(),
      DATABASE_NAME: str(),

      NODE_ENV: str(),
    });
  }
}

export default EnvalidValidator;

and another class called EnvironmentVariableValidator that has an instance of IEnvironmentVariableValidator injected into it through its constructor.

import IEnvironmentVariableValidator from "../Interfaces/EnvironmentVariableValidator";

class EnvironmentVariableValidator implements IEnvironmentVariableValidator {
  validator: IEnvironmentVariableValidator;

  constructor(validator: IEnvironmentVariableValidator) {
    this.validator = validator;
  }

  validate(env: NodeJS.ProcessEnv) {
    this.validator.validate(env);
  }
}

export default EnvironmentVariableValidator;

My question is, is it following clean code, SOLID and is the correct way to make EnvalidValidator encapsulation?


问:
Why am I getting the warning message that NaNs are produced and the error message that function cannot be evaluated at initial parameters?
Here is my code.  I'm trying to model an ROC curve using a custom function.  My goal is to estimate the 8 parameters that minimize the sse_total.  However, I keep running into two messages.

The first message is a warning message that tells me NaNs are produced.  The second message is an error message that says the function cannot be evaluated at the initial parameters.

X are non-cumulative false alarm rates, and Y are non-cumulative hit rates.  Non-cumulative are for model estimation only.

Any help would be greatly appreciated.

`

```<code>X<-c(0.01666667,
     0.00000000,
     0.06666667,
     0.11666667,
     0.36666667,
     0.43333333)
Y<-c(0.03333333,
     0.05000000,
     0.06666667,
     0.05000000,
     0.10000000,
     0.70000000)

df_dpsd<-data.frame(x=X,y=Y)

DPSD_1<-function(par){
R<-par[1]
Rn<-par[2]
dprime<-par[3]
c6<-par[4]
c5<-par[5]
c4<-par[6]
c3<-par[7]
c2<-par[8]
# c1<-par[9]

pred_FAR6<-((1-Rn)*qnorm(c6,0,1))
pred_FAR5<-((1-Rn)*(qnorm(c5,0,1)-qnorm(c6,0,1)))
pred_FAR4<-((1-Rn)*(qnorm(c4,0,1)-qnorm(c5,0,1)))
pred_FAR3<-((1-Rn)*(qnorm(c3,0,1)-qnorm(c4,0,1)))
pred_FAR2<-((1-Rn)*(qnorm(c2,0,1)-qnorm(c3,0,1)))
pred_FAR1<-(Rn+(1-Rn)*(1-qnorm(c2,0,1)))

pred_HR6<-(R+(1-R)*qnorm(c6,-dprime,1))
pred_HR5<-((1-R)*(qnorm(c5,-dprime,1)-qnorm(c6,-dprime,1)))
pred_HR4<-((1-R)*(qnorm(c4,-dprime,1)-qnorm(c5,-dprime,1)))
pred_HR3<-((1-R)*(qnorm(c3,-dprime,1)-qnorm(c4,-dprime,1)))
pred_HR2<-((1-R)*(qnorm(c2,-dprime,1)-qnorm(c3,-dprime,1)))
pred_HR1<-((1-R)*(1-qnorm(c2,-dprime,1)))

# SSE
sseH6<-(Y[1]-pred_HR6)^2
sseH5<-(Y[2]-pred_HR5)^2
sseH4<-(Y[3]-pred_HR4)^2
sseH3<-(Y[4]-pred_HR3)^2
sseH2<-(Y[5]-pred_HR2)^2
sseH1<-(Y[6]-pred_HR1)^2

sseF6<-(X[1]-pred_FAR6)^2
sseF5<-(X[2]-pred_FAR5)^2
sseF4<-(X[3]-pred_FAR4)^2
sseF3<-(X[4]-pred_FAR3)^2
sseF2<-(X[5]-pred_FAR2)^2
sseF1<-(X[6]-pred_FAR1)^2

sse_total<-(
  # sseH1+
              sseH2+sseH3+sseH4+sseH5+sseH6+
              # sseF1+
                sseF2+sseF3+sseF4+sseF5+sseF6)
return(sse_total)
}

(result <-optim(par=c(R=.25,Rn=.25,dprime=1,c6=-1.5,c5=-1,c4=-.5,c3=1,c2=1.5),
                fn=DPSD_1))
</code>```

`

I've tried varying the initial parameters and have played around with various ways to configure the function so that it will optimize, but to no avail.

I've also looked through multiple top solutions to similar problems, but I have not had any luck in solving my problem.

Body:
Here is my code.  I'm trying to model an ROC curve using a custom function.  My goal is to estimate the 8 parameters that minimize the sse_total.  However, I keep running into two messages.

The first message is a warning message that tells me NaNs are produced.  The second message is an error message that says the function cannot be evaluated at the initial parameters.

X are non-cumulative false alarm rates, and Y are non-cumulative hit rates.  Non-cumulative are for model estimation only.

Any help would be greatly appreciated.

`

X<-c(0.01666667,
     0.00000000,
     0.06666667,
     0.11666667,
     0.36666667,
     0.43333333)
Y<-c(0.03333333,
     0.05000000,
     0.06666667,
     0.05000000,
     0.10000000,
     0.70000000)

df_dpsd<-data.frame(x=X,y=Y)

DPSD_1<-function(par){
R<-par[1]
Rn<-par[2]
dprime<-par[3]
c6<-par[4]
c5<-par[5]
c4<-par[6]
c3<-par[7]
c2<-par[8]
# c1<-par[9]

pred_FAR6<-((1-Rn)*qnorm(c6,0,1))
pred_FAR5<-((1-Rn)*(qnorm(c5,0,1)-qnorm(c6,0,1)))
pred_FAR4<-((1-Rn)*(qnorm(c4,0,1)-qnorm(c5,0,1)))
pred_FAR3<-((1-Rn)*(qnorm(c3,0,1)-qnorm(c4,0,1)))
pred_FAR2<-((1-Rn)*(qnorm(c2,0,1)-qnorm(c3,0,1)))
pred_FAR1<-(Rn+(1-Rn)*(1-qnorm(c2,0,1)))

pred_HR6<-(R+(1-R)*qnorm(c6,-dprime,1))
pred_HR5<-((1-R)*(qnorm(c5,-dprime,1)-qnorm(c6,-dprime,1)))
pred_HR4<-((1-R)*(qnorm(c4,-dprime,1)-qnorm(c5,-dprime,1)))
pred_HR3<-((1-R)*(qnorm(c3,-dprime,1)-qnorm(c4,-dprime,1)))
pred_HR2<-((1-R)*(qnorm(c2,-dprime,1)-qnorm(c3,-dprime,1)))
pred_HR1<-((1-R)*(1-qnorm(c2,-dprime,1)))

# SSE
sseH6<-(Y[1]-pred_HR6)^2
sseH5<-(Y[2]-pred_HR5)^2
sseH4<-(Y[3]-pred_HR4)^2
sseH3<-(Y[4]-pred_HR3)^2
sseH2<-(Y[5]-pred_HR2)^2
sseH1<-(Y[6]-pred_HR1)^2

sseF6<-(X[1]-pred_FAR6)^2
sseF5<-(X[2]-pred_FAR5)^2
sseF4<-(X[3]-pred_FAR4)^2
sseF3<-(X[4]-pred_FAR3)^2
sseF2<-(X[5]-pred_FAR2)^2
sseF1<-(X[6]-pred_FAR1)^2

sse_total<-(
  # sseH1+
              sseH2+sseH3+sseH4+sseH5+sseH6+
              # sseF1+
                sseF2+sseF3+sseF4+sseF5+sseF6)
return(sse_total)
}

(result <-optim(par=c(R=.25,Rn=.25,dprime=1,c6=-1.5,c5=-1,c4=-.5,c3=1,c2=1.5),
                fn=DPSD_1))

`

I've tried varying the initial parameters and have played around with various ways to configure the function so that it will optimize, but to no avail.

I've also looked through multiple top solutions to similar problems, but I have not had any luck in solving my problem.


问:
How to modify behaviour of a VR controller's pointer
My university colleagues and I are trying to develop a Virtual Reality project for university where we use an Oculus headset and create a scene with a mouse where you can select and click and drag different objects in the scene. You are supposed to be stationary and move one of the controllers as if it was a mouse. However, we want to modify the behaviour of the controller to better fit the 3D environment. When an object is not selected, we want to interpolate the depth of the cursor according to the interpolation of the nearest objects. There is a paper that we were shown in class that we are supposed to drag inspiration from, and it achieved this kind of behaviour of the cursor with a normal mouse but I can't seem to find any information on how they did it. Our final goal would be to compare both ways of managing the scene and assess which one is better. We are using Unity with VRTK as suggested by our professor, but we and can't really seem to be able to access the mouse's file on how it moves or its behaviour, and we are kind of lost on where to go. Could someone help with this?

Here is the paper where they talk about it:
https://dl.acm.org/doi/pdf/10.1145/3491102.3501884

We so far have tried creating a simple scene and adding objects with different behaviours as well as a controller instance, but we seem to only be able to modify the events of the mouse and not its specific behaviour.

Kind regards and thanks


问:
How to run postmapping in a RestController in Springboot
I am very new to Springboot and do not fully understand how postmapping works. Currently, I have to implement Stripe payment system. From what I gathered, Stripe provides a custom payment flow but it is using Spark framework. I was able to create a Springboot Postmapping in place of the Spark Post. I have tried different methods I see online with no success. What would be the best method to do the following.

My PostMapping Code

```<code>@PostMapping("/create-payment-intent")
public String StripeTest(HttpServletRequest request, HttpServletResponse response) throws StripeException {
    System.out.println("Stripe Controller Begins");
    Gson gson = new Gson();
    response.setContentType("application/json");
    Stripe.apiKey = "sk_test_key";

    try {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        String dataBody = buffer.toString();

        CreatePayment postBody = gson.fromJson(dataBody,
                CreatePayment.class);

        PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder()
                .setCurrency("USD")
                .setAmount(new Long(calculateOrderAmount(postBody.getItems())))
                .build();
        // Create a PaymentIntent with the order amount and currency
        PaymentIntent intent = PaymentIntent.create(createParams);
        // Send publishable key and PaymentIntent  details to client
        return gson.toJson(new Server.CreatePaymentResponse(intent.getClientSecret()));
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
        return "";
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }

}
</code>```

I need to get the post to run then fetch the data using my javascript:

```<code>// Fetches a payment intent and captures the client secret
async function initialize() {
    const response = await fetch("/create-payment-intent", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items }),
    });
    const { clientSecret } = await response.json();

    const appearance = {
        theme: 'stripe',
    };
    elements = stripe.elements({ appearance, clientSecret });

    const paymentElementOptions = {
        layout: "tabs",
    };

    const paymentElement = elements.create("payment", paymentElementOptions);
    paymentElement.mount("#payment-element");
}
</code>```

Which will then be injected into the payment-id in the html below:

```<code><form id="payment-form"         action='/create-payment-intent' method='POST'>
  <div id="payment-element">
    <!--Stripe.js injects the Payment Element-->
  </div>
  <button id="submit">
    <div class="spinner hidden" id="spinner"></div>
    <span id="button-text">Pay now</span>
  </button>
  <div id="payment-message" class="hidden"></div>
</form>
</code>```

I have tried $.Ajax from an example I read with no luck.

Body:
I am very new to Springboot and do not fully understand how postmapping works. Currently, I have to implement Stripe payment system. From what I gathered, Stripe provides a custom payment flow but it is using Spark framework. I was able to create a Springboot Postmapping in place of the Spark Post. I have tried different methods I see online with no success. What would be the best method to do the following.

My PostMapping Code

@PostMapping("/create-payment-intent")
public String StripeTest(HttpServletRequest request, HttpServletResponse response) throws StripeException {
    System.out.println("Stripe Controller Begins");
    Gson gson = new Gson();
    response.setContentType("application/json");
    Stripe.apiKey = "sk_test_key";

    try {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        String dataBody = buffer.toString();

        CreatePayment postBody = gson.fromJson(dataBody,
                CreatePayment.class);

        PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder()
                .setCurrency("USD")
                .setAmount(new Long(calculateOrderAmount(postBody.getItems())))
                .build();
        // Create a PaymentIntent with the order amount and currency
        PaymentIntent intent = PaymentIntent.create(createParams);
        // Send publishable key and PaymentIntent  details to client
        return gson.toJson(new Server.CreatePaymentResponse(intent.getClientSecret()));
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
        return "";
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }

}

I need to get the post to run then fetch the data using my javascript:

// Fetches a payment intent and captures the client secret
async function initialize() {
    const response = await fetch("/create-payment-intent", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items }),
    });
    const { clientSecret } = await response.json();

    const appearance = {
        theme: 'stripe',
    };
    elements = stripe.elements({ appearance, clientSecret });

    const paymentElementOptions = {
        layout: "tabs",
    };

    const paymentElement = elements.create("payment", paymentElementOptions);
    paymentElement.mount("#payment-element");
}

Which will then be injected into the payment-id in the html below:

<form id="payment-form"         action='/create-payment-intent' method='POST'>

  <button id="submit">

    Pay now
  </button>

</form>

I have tried $.Ajax from an example I read with no luck.


问:
REACT-NATIVE-SCREENS CompileSdkVersion not found Error
I'm getting a CompileSdkVersion error when I install react-native-screens to my project. I have followed the changes needed to make react-native screens work from the documentation and  controlled if there is version mistake but it seems like there isn't any! Could you help me out. Thank you in advance

The versions I am working on are:

``

```<code>    dependencies": {
        "@react-navigation/native": "^6.1.1",
        "react": "18.1.0",
        "react-native": "0.70.6",
        "react-native-safe-area-context": "^4.4.1",
        "react-native-screens": "^3.18.2"
</code>```

`

This is my android/build.gradle config
`

```<code>    ext {
            buildToolsVersion = "31.0.0"
            minSdkVersion = 21
            compileSdkVersion = 31
            targetSdkVersion = 31
}
</code>```

`

This is my android/app/build.gradle config
`

`

```<code> defaultConfig {
        applicationId "com.navigationtrial"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        compileSdkVersion rootProject.ext.compileSdkVersion
        versionCode 1
        versionName "1.0"
</code>```

`

This is the default config in node_modules\react-native-screens\android\build.gradle

```<code>    apply plugin: 'kotlin-android'
</code>```

android {
compileSdkVersion safeExtGet('compileSdkVersion', 28)

```<code>
    defaultConfig {
            minSdkVersion safeExtGet('minSdkVersion', 21)
            targetSdkVersion safeExtGet('targetSdkVersion', 22)
            versionCode 1
            versionName "1.0"
</code>```

`

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

Body:
I'm getting a CompileSdkVersion error when I install react-native-screens to my project. I have followed the changes needed to make react-native screens work from the documentation and  controlled if there is version mistake but it seems like there isn't any! Could you help me out. Thank you in advance

The versions I am working on are:

``

    dependencies": {
        "@react-navigation/native": "^6.1.1",
        "react": "18.1.0",
        "react-native": "0.70.6",
        "react-native-safe-area-context": "^4.4.1",
        "react-native-screens": "^3.18.2"

`

This is my android/build.gradle config
`

    ext {
            buildToolsVersion = "31.0.0"
            minSdkVersion = 21
            compileSdkVersion = 31
            targetSdkVersion = 31
}

`

This is my android/app/build.gradle config
`

`

 defaultConfig {
        applicationId "com.navigationtrial"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        compileSdkVersion rootProject.ext.compileSdkVersion
        versionCode 1
        versionName "1.0"

`

This is the default config in node_modules\react-native-screens\android\build.gradle

    apply plugin: 'kotlin-android'

android {
compileSdkVersion safeExtGet('compileSdkVersion', 28)

    defaultConfig {
            minSdkVersion safeExtGet('minSdkVersion', 21)
            targetSdkVersion safeExtGet('targetSdkVersion', 22)
            versionCode 1
            versionName "1.0"

`


问:
Compiling assembly code with gcc for STM32
GCC was not able to compile the following assembly code for the STM32 microcontroller. The programm should flash the onboard LED of the STM32 "Blue Pill".

```<code>        .section .text
        .syntax unified
        .thumb

start:
        ldr r0, =0x48000401  ; Load address of GPIOC_ODR register into R0
loop:
        ldr r1, [r0]         ; Load value of GPIOC_ODR register into R1
        eor r1, r1, #0x2000 ; Toggle bit 13 of R1 (GPIOC_ODR_ODR13)
        str r1, [r0]         ; Store value back to GPIOC_ODR register
        mov r1, #5000000    ; Load delay value into R1
delay:
        sub r1, r1, #1       ; Decrement R1
        cmp r1, #0           ; Compare R1 to 0
        bne delay            ; If not zero, loop again
        b loop               ; Loop back to the beginning
</code>```
```<code>arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb main.s
</code>```
```<code>GCC issues these problems:
main.s: Assembler messages:
main.s:6: Error: bad instruction `load address of GPIOC_ODR register into R0'
main.s:8: Error: bad instruction `load value of GPIOC_ODR register into R1'
main.s:9: Error: bad instruction `toggle bit 13 of R1(GPIOC_ODR_ODR13)'
main.s:10: Error: bad instruction `store value back to GPIOC_ODR register'
main.s:11: Error: bad instruction `load delay value into R1'
main.s:13: Error: bad instruction `decrement R1'
main.s:14: Error: bad instruction `compare R1 to 0'
main.s:15: Error: bad instruction `if not zero,loop again'
main.s:16: Error: bad instruction `loop back to the beginning'
main.s:11: Error: invalid constant (4c4b40) after fixup
</code>```

I do not understand, why GCC is not realizing, that these parts of the code are commented out.

Body:
GCC was not able to compile the following assembly code for the STM32 microcontroller. The programm should flash the onboard LED of the STM32 "Blue Pill".

        .section .text
        .syntax unified
        .thumb

start:
        ldr r0, =0x48000401  ; Load address of GPIOC_ODR register into R0
loop:
        ldr r1, [r0]         ; Load value of GPIOC_ODR register into R1
        eor r1, r1, #0x2000 ; Toggle bit 13 of R1 (GPIOC_ODR_ODR13)
        str r1, [r0]         ; Store value back to GPIOC_ODR register
        mov r1, #5000000    ; Load delay value into R1
delay:
        sub r1, r1, #1       ; Decrement R1
        cmp r1, #0           ; Compare R1 to 0
        bne delay            ; If not zero, loop again
        b loop               ; Loop back to the beginning

arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb main.s

GCC issues these problems:
main.s: Assembler messages:
main.s:6: Error: bad instruction `load address of GPIOC_ODR register into R0'
main.s:8: Error: bad instruction `load value of GPIOC_ODR register into R1'
main.s:9: Error: bad instruction `toggle bit 13 of R1(GPIOC_ODR_ODR13)'
main.s:10: Error: bad instruction `store value back to GPIOC_ODR register'
main.s:11: Error: bad instruction `load delay value into R1'
main.s:13: Error: bad instruction `decrement R1'
main.s:14: Error: bad instruction `compare R1 to 0'
main.s:15: Error: bad instruction `if not zero,loop again'
main.s:16: Error: bad instruction `loop back to the beginning'
main.s:11: Error: invalid constant (4c4b40) after fixup

I do not understand, why GCC is not realizing, that these parts of the code are commented out.


问:
SQL Percent Rank use 4-week average number to find percentage rank within full FlowFunds values. Partition by FlowGroup
I want to find the percentage rank of where a 4-week average sits across an entire time series of data.

[table attached here]

In this example, I want to find how the 4-week avg of FlowGroup a (507.5858) ranks in comparison to the other 4 values of FlowGroup a (804.6113, 1781.3388, 627.1612, -1182.7681).

The return value for FlowGroup a should be = 0.311

Currently I am ranking each individual Flow$ against the total like this:

```<code>PERCENT_RANK ()
OVER (PARTITION BY FlowGroup ORDER BY Flow$) as PctRank
</code>```

I do not know how I can percent rank the 4-week average against the total Flow$, partitioned by FlowGroup.

Cheers!

Body:
I want to find the percentage rank of where a 4-week average sits across an entire time series of data.

[table attached here]

In this example, I want to find how the 4-week avg of FlowGroup a (507.5858) ranks in comparison to the other 4 values of FlowGroup a (804.6113, 1781.3388, 627.1612, -1182.7681).

The return value for FlowGroup a should be = 0.311

Currently I am ranking each individual Flow$ against the total like this:

PERCENT_RANK ()
OVER (PARTITION BY FlowGroup ORDER BY Flow$) as PctRank

I do not know how I can percent rank the 4-week average against the total Flow$, partitioned by FlowGroup.

Cheers!


问:
React Native app takes time for first launch
after using react-native-bootsplash library, my app takes time to launch for the first time, and also after submitting the releasing version on the play store, I'm getting Pre-Launch report as: Your app took 22,761ms to launch for the first time.
I also noticed the same on the iOS too, here is my configuration:
My MainActivity.java file:

```<code>package com.qadaapp;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import android.os.Bundle;
import com.zoontek.rnbootsplash.RNBootSplash;

public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "Qadaapp";
  }

  /**
   * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
   * you can specify the renderer you wish to use - the new renderer (Fabric) or the old renderer
   * (Paper).
   */
  @Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new MainActivityDelegate(this, getMainComponentName());
  }

  public static class MainActivityDelegate extends ReactActivityDelegate {
    public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
      super(activity, mainComponentName);
    }

    @Override
    protected ReactRootView createRootView() {
      ReactRootView reactRootView = new ReactRootView(getContext());
      // If you opted-in for the New Architecture, we enable the Fabric Renderer.
      reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
      return reactRootView;
    }

    @Override
    protected boolean isConcurrentRootEnabled() {
      // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18).
      // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html
      return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    RNBootSplash.init(this);
    super.onCreate(null);
  }
}
</code>```

My AndroidMainfest.file:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.qadaapp">

  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

  <uses-permission android:name="com.android.vending.BILLING"/>
  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@style/BootTheme">
    <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="qadaapp"/>
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name"/>
    <activity android:name="com.facebook.CustomTabActivity" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="@string/fb_login_protocol_scheme"/>
      </intent-filter>
    </activity>
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
      <meta-data
          android:name="preloaded_fonts"
          android:resource="@array/preloaded_fonts" />
  </application>
</manifest>
</code>```

My styles.xml file:

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
    </style>
    <!-- BootTheme should inherit from Theme.SplashScreen -->
    <style name="BootTheme" parent="Theme.SplashScreen">
        <item name="windowSplashScreenBackground">@color/bootsplash_background</item>
        <item name="windowSplashScreenAnimatedIcon">@mipmap/bootsplash_logo</item>
        <item name="postSplashScreenTheme">@style/AppTheme</item>
    </style>

</resources>
</code>```

Also I added this in my build.gradle file:
implementation "androidx.core:core-splashscreen:1.0.0"

My App.js:

```<code>    const unsubscribe = auth().onUserChanged(async usr => {
      if (!usr) {
        await _getSlideShows();
        setUser(null);
        return RNBootSplash.hide({fade: true});
      }
      if (usr?.uid) {
        let dbResult = await DB.collection('users').doc(usr?.uid).get();
        setUser(usr);
        if (dbResult?.exists) {
          let dbUser = dbResult.data();
          setUser(dbUser);
        }
        return RNBootSplash.hide({fade: true});
      }
    });
    return () => unsubscribe();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
</code>```

When I was not using react-native-bootsplash, the app was working fast, however when I implemeneted the react-native-boot-splash library, my app's cold start time increased on both the platforms.

Body:
after using react-native-bootsplash library, my app takes time to launch for the first time, and also after submitting the releasing version on the play store, I'm getting Pre-Launch report as: Your app took 22,761ms to launch for the first time.
I also noticed the same on the iOS too, here is my configuration:
My MainActivity.java file:

package com.qadaapp;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import android.os.Bundle;
import com.zoontek.rnbootsplash.RNBootSplash;

public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "Qadaapp";
  }

  /**
   * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
   * you can specify the renderer you wish to use - the new renderer (Fabric) or the old renderer
   * (Paper).
   */
  @Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new MainActivityDelegate(this, getMainComponentName());
  }

  public static class MainActivityDelegate extends ReactActivityDelegate {
    public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
      super(activity, mainComponentName);
    }

    @Override
    protected ReactRootView createRootView() {
      ReactRootView reactRootView = new ReactRootView(getContext());
      // If you opted-in for the New Architecture, we enable the Fabric Renderer.
      reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
      return reactRootView;
    }

    @Override
    protected boolean isConcurrentRootEnabled() {
      // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18).
      // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html
      return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    RNBootSplash.init(this);
    super.onCreate(null);
  }
}

My AndroidMainfest.file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.qadaapp">

  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

  <uses-permission android:name="com.android.vending.BILLING"/>
  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@style/BootTheme">
    <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="qadaapp"/>
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name"/>
    <activity android:name="com.facebook.CustomTabActivity" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="@string/fb_login_protocol_scheme"/>
      </intent-filter>
    </activity>
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
      <meta-data
          android:name="preloaded_fonts"
          android:resource="@array/preloaded_fonts" />
  </application>
</manifest>

My styles.xml file:

<resources>

</resources>

Also I added this in my build.gradle file:
implementation "androidx.core:core-splashscreen:1.0.0"

My App.js:

    const unsubscribe = auth().onUserChanged(async usr => {
      if (!usr) {
        await _getSlideShows();
        setUser(null);
        return RNBootSplash.hide({fade: true});
      }
      if (usr?.uid) {
        let dbResult = await DB.collection('users').doc(usr?.uid).get();
        setUser(usr);
        if (dbResult?.exists) {
          let dbUser = dbResult.data();
          setUser(dbUser);
        }
        return RNBootSplash.hide({fade: true});
      }
    });
    return () => unsubscribe();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

When I was not using react-native-bootsplash, the app was working fast, however when I implemeneted the react-native-boot-splash library, my app's cold start time increased on both the platforms.


问:
Make clustered dendrogram more readable in R
I would like to make a dendrogram to group countries that had similiar course of HICP index in the EU through 2000-2022. I can only use eurostat, dplyr and ggplot2 libraries except the basic R-ones.
I used hierarchical grouping of distances that are calculated with the "minkowski" method where p=1.5. Then I would like to make a dendrogram of it with 4 clusters. The graph should look like this:

How the dendrogram should look like:

But I have trouble with displaying only the countries's names like in the example. My graph is very cluttered that is basically unreadable.

I used the data from eurostat library:

install.packages("eurostat")
install.packages("dplyr")
install.packages("ggplot2")
library(eurostat)
library(dplyr)
library(ggplot2)

#Downloading the HICP dataset for EU
hicp <- get_eurostat("prc_hicp_manr", time_format = "date")
```
<p>Filtering the time in the dataset from 2000-02-01 to 2022-09-01, then filter only CP00 basket of goods, then filtered the dataset to show the data for current 27 member states only additionally, replacing the iso codes with english names.</p>
<pre class="lang-r prettyprint-override"><code>member_states <- c("AT", "BE", "BG", "HR", "CY", "CZ",
                        "DK", "EE", "FI", "FR", "DE", "GR",
                        "HU", "IE", "IT", "LV", "LT", "LU",
                        "MT", "NL", "PL", "PT", "RO", "SK",
                        "SI", "ES", "SE", "EL")

hicp_filtered <- hicp %>% filter(time >= as.Date("2000-02-1")
                               & time <= as.Date("2022-09-01")) %>%
                          filter(coicop == "CP00") %>%
                          filter(geo %in% member_states) %>%
                          mutate(geo = case_when(
                            geo == "AT" ~ "Austria",
                            geo == "BE" ~ "Belgium",
                            geo == "BG" ~ "Bulgaria",
                            geo == "HR" ~ "Croatia",
                            geo == "CY" ~ "Cyprus",
                            geo == "CZ" ~ "Czech Republic",
                            geo == "DK" ~ "Denmark",
                            geo == "EE" ~ "Estonia",
                            geo == "FI" ~ "Finland",
                            geo == "FR" ~ "France",
                            geo == "DE" ~ "Germany",
                            geo == "GR" ~ "Greece",
                            geo == "HU" ~ "Hungary",
                            geo == "IE" ~ "Ireland",
                            geo == "IT" ~ "Italy",
                            geo == "LV" ~ "Latvia",
                            geo == "LT" ~ "Lithuania",
                            geo == "LU" ~ "Luxembourg",
                            geo == "MT" ~ "Malta",
                            geo == "NL" ~ "Netherlands",
                            geo == "PL" ~ "Poland",
                            geo == "PT" ~ "Portugal",
                            geo == "RO" ~ "Romania",
                            geo == "SK" ~ "Slovakia",
                            geo == "SI" ~ "Slovenia",
                            geo == "ES" ~ "Spain",
                            geo == "SE" ~ "Sweden",
                            geo == "EL" ~ "Greece",
                            TRUE ~ geo
                          ))
</code>```

Creating the dataset that shows only countries, time and HICP value

hicp_uncluttered <- hicp_filtered[, c(3,4,5)]
```
<p>the dataset now looks like this:
<img src="https://i.stack.imgur.com/0Xp9S.png" alt="the dataset now looks like this:" /></p>
<p>Now, when the context is given I tried to code the dendrogram plot:</p>
<pre class="lang-r prettyprint-override"><code>values <- hicp_uncluttered[,3]

dist_matrix <- dist(values, method = "minkowski", p = 1.5)

hc <- hclust(dist_matrix)

dend <- as.dendrogram(hc)

plot(dend)

</code>```

But I get resulting plot:

How do I have to rewrite the code so there only countries are visible rather than values that I suppose generate such messy plot?

Body:
I would like to make a dendrogram to group countries that had similiar course of HICP index in the EU through 2000-2022. I can only use eurostat, dplyr and ggplot2 libraries except the basic R-ones.
I used hierarchical grouping of distances that are calculated with the "minkowski" method where p=1.5. Then I would like to make a dendrogram of it with 4 clusters. The graph should look like this:

How the dendrogram should look like:

But I have trouble with displaying only the countries's names like in the example. My graph is very cluttered that is basically unreadable.

I used the data from eurostat library:

install.packages("eurostat")
install.packages("dplyr")
install.packages("ggplot2")
library(eurostat)
library(dplyr)
library(ggplot2)

#Downloading the HICP dataset for EU
hicp <- get_eurostat("prc_hicp_manr", time_format = "date")

Filtering the time in the dataset from 2000-02-01 to 2022-09-01, then filter only CP00 basket of goods, then filtered the dataset to show the data for current 27 member states only additionally, replacing the iso codes with english names.

member_states <- c("AT", "BE", "BG", "HR", "CY", "CZ",
                        "DK", "EE", "FI", "FR", "DE", "GR",
                        "HU", "IE", "IT", "LV", "LT", "LU",
                        "MT", "NL", "PL", "PT", "RO", "SK",
                        "SI", "ES", "SE", "EL")

hicp_filtered <- hicp %>% filter(time >= as.Date("2000-02-1")
                               & time <= as.Date("2022-09-01")) %>%
                          filter(coicop == "CP00") %>%
                          filter(geo %in% member_states) %>%
                          mutate(geo = case_when(
                            geo == "AT" ~ "Austria",
                            geo == "BE" ~ "Belgium",
                            geo == "BG" ~ "Bulgaria",
                            geo == "HR" ~ "Croatia",
                            geo == "CY" ~ "Cyprus",
                            geo == "CZ" ~ "Czech Republic",
                            geo == "DK" ~ "Denmark",
                            geo == "EE" ~ "Estonia",
                            geo == "FI" ~ "Finland",
                            geo == "FR" ~ "France",
                            geo == "DE" ~ "Germany",
                            geo == "GR" ~ "Greece",
                            geo == "HU" ~ "Hungary",
                            geo == "IE" ~ "Ireland",
                            geo == "IT" ~ "Italy",
                            geo == "LV" ~ "Latvia",
                            geo == "LT" ~ "Lithuania",
                            geo == "LU" ~ "Luxembourg",
                            geo == "MT" ~ "Malta",
                            geo == "NL" ~ "Netherlands",
                            geo == "PL" ~ "Poland",
                            geo == "PT" ~ "Portugal",
                            geo == "RO" ~ "Romania",
                            geo == "SK" ~ "Slovakia",
                            geo == "SI" ~ "Slovenia",
                            geo == "ES" ~ "Spain",
                            geo == "SE" ~ "Sweden",
                            geo == "EL" ~ "Greece",
                            TRUE ~ geo
                          ))

Creating the dataset that shows only countries, time and HICP value

hicp_uncluttered <- hicp_filtered[, c(3,4,5)]

the dataset now looks like this:

Now, when the context is given I tried to code the dendrogram plot:

values <- hicp_uncluttered[,3]

dist_matrix <- dist(values, method = "minkowski", p = 1.5)

hc <- hclust(dist_matrix)

dend <- as.dendrogram(hc)

plot(dend)

But I get resulting plot:

How do I have to rewrite the code so there only countries are visible rather than values that I suppose generate such messy plot?