问:
Vue-router errors, javascript undefined properties
I have a function to get the logged in user details and check for the 'permissions' in the 'teams array'.

However, after running the code, I got two errors, and after the UI is loaded, the currentUser displays null until any component in the UI is selected. See the image, currentUser is null when UI is loaded but as soon as I click on a component, it prints the currentUser. I do not understand how to get through these errors.

This is a part of the vue-store code from which I am getting the currentUser array:

```<code>state(){
 return currentUser: null
}
mutations: {
   setCurrentUser(state, payload) {
      // console.log("set current user", payload);
      state.currentUser = payload;
    }
  },
actions: {
    loadCurrentUser(context, data) {
      // console.log("loadcurrentuser");
      return new Promise((resolve, reject) => {
        axiosService({ requiresAuth: true })
          .get(`/administration/users/${data.id}`)
          .then(response => {
            context.commit("setCurrentUser", response.data);
            resolve(response.data);
          })
          .catch(error => reject(error));
      });
    },
}
getters: {
    isCurrentUser(state){
      return state.currentUser;
    }
  }

</code>```

here is the code from the router.js

```<code>{
  path: "/administration",
    name: "Administration",
    component: PageAdministration,
    meta: {
      requiresAuth: true,
      neededPermissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
   },

function authorizeUser(to, from,next) {
  let isAllowed = true;
  const currentUser = store.getters["auth/isCurrentUser"];
  console.log(currentUser);

  for(let i = 0;i<currentUser.teams.length;i++){
    const team = currentUser.teams[i]
    const validPermissions = team.permissions.filter((item) => { return to.meta.neededPermissions.includes(item.permissionType); }); //returns array of objects
    const mappedValidPermissions = validPermissions.map((item) => { return item.permissionType;  });// returns array with permissionType
    if (!to.meta.neededPermissions.every(i=>mappedValidPermissions.includes(i))) {
      isAllowed = false;
      next({ path: "/:notFound(.*)" });

      break;
    }
  }

  if(isAllowed) next();
}

router.beforeEach((to, from, next) => {

  if (to.meta.requiresAuth && !store.getters["auth/isLoggedIn"]) {
    next({
      name: "Authentication",
      params: {
        desiredRoute: to.fullPath,
      },
    });
  } else {
    authorizeUser(to,next)
  }
});
</code>```

These are the two errors

Body:
I have a function to get the logged in user details and check for the 'permissions' in the 'teams array'.

However, after running the code, I got two errors, and after the UI is loaded, the currentUser displays null until any component in the UI is selected. See the image, currentUser is null when UI is loaded but as soon as I click on a component, it prints the currentUser. I do not understand how to get through these errors.

This is a part of the vue-store code from which I am getting the currentUser array:

state(){
 return currentUser: null
}
mutations: {
   setCurrentUser(state, payload) {
      // console.log("set current user", payload);
      state.currentUser = payload;
    }
  },
actions: {
    loadCurrentUser(context, data) {
      // console.log("loadcurrentuser");
      return new Promise((resolve, reject) => {
        axiosService({ requiresAuth: true })
          .get(`/administration/users/${data.id}`)
          .then(response => {
            context.commit("setCurrentUser", response.data);
            resolve(response.data);
          })
          .catch(error => reject(error));
      });
    },
}
getters: {
    isCurrentUser(state){
      return state.currentUser;
    }
  }

here is the code from the router.js

{
  path: "/administration",
    name: "Administration",
    component: PageAdministration,
    meta: {
      requiresAuth: true,
      neededPermissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
   },

function authorizeUser(to, from,next) {
  let isAllowed = true;
  const currentUser = store.getters["auth/isCurrentUser"];
  console.log(currentUser);

  for(let i = 0;i<currentUser.teams.length;i++){
    const team = currentUser.teams[i]
    const validPermissions = team.permissions.filter((item) => { return to.meta.neededPermissions.includes(item.permissionType); }); //returns array of objects
    const mappedValidPermissions = validPermissions.map((item) => { return item.permissionType;  });// returns array with permissionType
    if (!to.meta.neededPermissions.every(i=>mappedValidPermissions.includes(i))) {
      isAllowed = false;
      next({ path: "/:notFound(.*)" });

      break;
    }
  }

  if(isAllowed) next();
}

router.beforeEach((to, from, next) => {

  if (to.meta.requiresAuth && !store.getters["auth/isLoggedIn"]) {
    next({
      name: "Authentication",
      params: {
        desiredRoute: to.fullPath,
      },
    });
  } else {
    authorizeUser(to,next)
  }
});

These are the two errors


来源: stackexchange

问:
Vite include .ts file in tsconfig.json and tsconfig.node.json
I have a Vite + Vue project with a pretty standard tsconfig.json file

```<code>{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "jsx": "preserve",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["ESNext", "DOM"],
    "skipLibCheck": true,
    "noEmit": true,
    "types": [
      "vite/client"
    ],
    "paths": {
      "@/*": ["./src"],
      "@comp/*": ["./src/components"],
      "@styl/*": ["./src/styles"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "stories/**/*.ts", "tests/**/*.ts"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
</code>```

and tsconfig.node.json file

```<code>{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}
</code>```

Inside of src, I have a utils directory: src/utils/example.ts

I'm building the project as a library with Vite, so I have an index.ts file that includes export { ... } from './utils/example'.

However, I also use some of that utility typescript in vite.config.ts: import { ... } from './src/utils/example' and then use it in defineConfig.

However, I get this error when I import in vite.config.ts:
File '.../src/utils/example.ts' is not listed within the file list of project '.../tsconfig.node.json'. Projects must list all files or use an 'include' pattern. ts(6307)

I've had a similar issue in the past, and solved it by adding "src/utils/example.ts" to "include": [...] in tsconfig.node.json.

While adding this makes that error go away, I then get this error in index.ts when importing: Output file '.../src/utils/examples.d.ts' has not been built from source file '.../src/utils/example.ts'. ts(6305).

Note that the project seems to build and run just fine despite this, and I'm wondering if it's an IDE issue? I'm using VS Code with Volar.

ContentLicense: CC BY-SA 4.0

Body:
I have a Vite + Vue project with a pretty standard tsconfig.json file

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "jsx": "preserve",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["ESNext", "DOM"],
    "skipLibCheck": true,
    "noEmit": true,
    "types": [
      "vite/client"
    ],
    "paths": {
      "@/*": ["./src"],
      "@comp/*": ["./src/components"],
      "@styl/*": ["./src/styles"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "stories/**/*.ts", "tests/**/*.ts"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

and tsconfig.node.json file

{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}

Inside of src, I have a utils directory: src/utils/example.ts

I'm building the project as a library with Vite, so I have an index.ts file that includes export { ... } from './utils/example'.

However, I also use some of that utility typescript in vite.config.ts: import { ... } from './src/utils/example' and then use it in defineConfig.

However, I get this error when I import in vite.config.ts:
File '.../src/utils/example.ts' is not listed within the file list of project '.../tsconfig.node.json'. Projects must list all files or use an 'include' pattern. ts(6307)

I've had a similar issue in the past, and solved it by adding "src/utils/example.ts" to "include": [...] in tsconfig.node.json.

While adding this makes that error go away, I then get this error in index.ts when importing: Output file '.../src/utils/examples.d.ts' has not been built from source file '.../src/utils/example.ts'. ts(6305).

Note that the project seems to build and run just fine despite this, and I'm wondering if it's an IDE issue? I'm using VS Code with Volar.


问:
S-function does not exist error in Simulink MATLAB
I am trying to run a model in SImulink Matlab that uses both Matlab based S-function block (a .mexw32 file) and a C code based S-function block (a .c file). When I run the model, I get the error below:

```<code>Error in S-function 'Transformer/Practical characteristics to  biochemical composition  Waste1': S-Function 'GeneralADM1Transformer' does not exist
Component:Simulink | Category:Model error

Error in S-function 'Transformer/Practical characteristics to biochemical composition Waste2 ': S-Function 'GeneralADM1Transformer' does not exist
Component:Simulink | Category:Model error
</code>```

I don't know why it keeps saying "It does not exist". The file is there, and it does exist. Someone should please help me out here.

The error message

The files arranged in a folder

I downloaded and installed MATLAB support for MinGW-w64 C/C++ Compiler to compile the C code so that it can be called from MATLAB using MEX. I'm still getting the same error despite doing this. I don't know what else to do.

Body:
I am trying to run a model in SImulink Matlab that uses both Matlab based S-function block (a .mexw32 file) and a C code based S-function block (a .c file). When I run the model, I get the error below:

Error in S-function 'Transformer/Practical characteristics to  biochemical composition  Waste1': S-Function 'GeneralADM1Transformer' does not exist
Component:Simulink | Category:Model error

Error in S-function 'Transformer/Practical characteristics to biochemical composition Waste2 ': S-Function 'GeneralADM1Transformer' does not exist
Component:Simulink | Category:Model error

I don't know why it keeps saying "It does not exist". The file is there, and it does exist. Someone should please help me out here.

The error message

The files arranged in a folder

I downloaded and installed MATLAB support for MinGW-w64 C/C++ Compiler to compile the C code so that it can be called from MATLAB using MEX. I'm still getting the same error despite doing this. I don't know what else to do.


问:
apache2.service Process: 76072 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)
I want to add self-signed SSL to "/etc/apache2/sites-available/default-ssl.conf".

code want to put in the file.

```<code>SSLCertificateFile /etc/encryption/mydomain.com.crt
SSLCertificateKeyFile /etc/encryption/mydomain.com.key
SSLCertificateChainFile /etc/encryption/intermediate.crt
</code>```

Default code:

```<code>SSLCertificateFile  /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
</code>```

If I replace "SSLCertificateFile" & "SSLCertificateKeyFile", I am getting an error while restarting apache.

When reverting back to default for this two above-mentioned apache worked perfectly.

Command & Output:

```<code>root@myserver:~# apachectl configtest
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Syntax OK

root@myserver:~# sudo systemctl restart apache2
Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

root@myserver:~# systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2023-01-10 17:01:31 UTC; 33s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 76407 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

</code>```

I am following: https://www.ssltrust.com.au/help/setup-guides/apache-ubuntu-ssl-install-guide

Thanks in advance.

Body:
I want to add self-signed SSL to "/etc/apache2/sites-available/default-ssl.conf".

code want to put in the file.

SSLCertificateFile /etc/encryption/mydomain.com.crt
SSLCertificateKeyFile /etc/encryption/mydomain.com.key
SSLCertificateChainFile /etc/encryption/intermediate.crt

Default code:

SSLCertificateFile  /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

If I replace "SSLCertificateFile" & "SSLCertificateKeyFile", I am getting an error while restarting apache.

When reverting back to default for this two above-mentioned apache worked perfectly.

Command & Output:

root@myserver:~# apachectl configtest
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Syntax OK

root@myserver:~# sudo systemctl restart apache2
Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

root@myserver:~# systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2023-01-10 17:01:31 UTC; 33s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 76407 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

I am following: https://www.ssltrust.com.au/help/setup-guides/apache-ubuntu-ssl-install-guide

Thanks in advance.


问:
What is the most efficient way to organize and query large amounts of sensor data in GridDB?
I am currently working on a project that involves storing and querying large amounts of sensor data. I have chosen to use GridDB as the database for my project due to its support for high-throughput data ingestion and real-time querying capabilities. However, I am facing some challenges when it comes to organizing and managing the data within the GridDB cluster.

I have different types of sensor data, each with its own unique set of attributes and properties. For example, I have temperature sensor data that includes the temperature value and a timestamp, while I have humidity sensor data that includes the humidity value and a timestamp. I have been using a separate container for each type of sensor data, but this approach is becoming increasingly difficult to manage as the amount of data grows.

I am wondering if there are better ways to organize and manage my sensor data within the GridDB cluster. For example, is it possible to store multiple types of sensor data in a single container and still be able to perform efficient queries on the data? Can I use GridDB's built-in indexing and sharding capabilities to improve the performance of my queries? Are there any best practices or guidelines for structuring and querying large amounts of sensor data in GridDB?

Overall, I am looking for suggestions or advice on how to optimize my use of GridDB for my sensor data project, as it's becoming increasingly difficult to handle the data that I am collecting and querying with my current approach.


问:
How to track inactivity on mouse on page load?
Right now, I have a function set up to do something if a mouse is inactive for 10 seconds for mobile only. However my console.log doesn't appear unless there is some activity before it is triggered by the inactivity. here is my code:

```<code>    if (width <= 480) {
       const inactiveUserMessage = () => {
             console.log("mouse has been inactive for 10 seconds");
       };
       document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000));
    }

</code>```

***In another file, lives the debounce function:

```<code>export function debounce(func, timeout) {
    let timer;
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}
</code>```

There needs to be some kind of activity before the inactiveUserMessage triggers. However how do i do it where the debounce function runs right away without needing some kind of movement before?? Please help!!!

Please let me know if this makes sense or if you need some more information.

I tried to create a mousemove event listener with a debounce function but it doesn't work unless there is some kind of movement on the page before hand.

Body:
Right now, I have a function set up to do something if a mouse is inactive for 10 seconds for mobile only. However my console.log doesn't appear unless there is some activity before it is triggered by the inactivity. here is my code:

    if (width <= 480) {
       const inactiveUserMessage = () => {
             console.log("mouse has been inactive for 10 seconds");
       };
       document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000));
    }

***In another file, lives the debounce function:

export function debounce(func, timeout) {
    let timer;
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}

There needs to be some kind of activity before the inactiveUserMessage triggers. However how do i do it where the debounce function runs right away without needing some kind of movement before?? Please help!!!

Please let me know if this makes sense or if you need some more information.

I tried to create a mousemove event listener with a debounce function but it doesn't work unless there is some kind of movement on the page before hand.


问:
Blazor Server - ProtectedLocalStorage Handling When Changing Docker Container?
I am hosting a Blazor Server application using a Docker container. My project has a page that loads the following code from local storage, utilizing OnAfterRednerAsync:

```<code>@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage ProtectedLocalStore

@code {
    public List<long>? upvoted = new List<long>();
    public List<long>? downvoted = new List<long>();
    private bool isConnected;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            isConnected = true;
            await LoadStateAsync();
            StateHasChanged();
        }
    }

    private async Task LoadStateAsync()
    {
        var resultUpvoted = await ProtectedLocalStore.GetAsync<List<long>>("upvoted");
        upvoted = resultUpvoted.Success ? resultUpvoted.Value : new List<long>();
        var resultDownvoted = await ProtectedLocalStore.GetAsync<List<long>>("downvoted");
        upvoted = resultDownvoted.Success ? resultDownvoted.Value : new List<long>();
    }
}
</code>```

Whenever I update my project, I update and run the new Docker container on my host machine. Any clients that have a value stored in ProtectedLocalStorage are not able to reload or view the page utilizing ProtectedLocalStorage again until they enter their browser tools and manually clear the local storage data.

UPDATE: The issue lies in the await ProtectedLocalStore.GetAsync<List<long>>("upvoted"); trying to cast encrypted values to <List>. When a new Docker container is created, it can no longer decrypt the existing local storage. Is it possible to have new containers be able to decrypt the existing local storage? Perhaps I could mount something that handles this process to my container so that it stays the same for each new container?

Body:
I am hosting a Blazor Server application using a Docker container. My project has a page that loads the following code from local storage, utilizing OnAfterRednerAsync:

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage ProtectedLocalStore

@code {
    public List<long>? upvoted = new List<long>();
    public List<long>? downvoted = new List<long>();
    private bool isConnected;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            isConnected = true;
            await LoadStateAsync();
            StateHasChanged();
        }
    }

    private async Task LoadStateAsync()
    {
        var resultUpvoted = await ProtectedLocalStore.GetAsync<List<long>>("upvoted");
        upvoted = resultUpvoted.Success ? resultUpvoted.Value : new List<long>();
        var resultDownvoted = await ProtectedLocalStore.GetAsync<List<long>>("downvoted");
        upvoted = resultDownvoted.Success ? resultDownvoted.Value : new List<long>();
    }
}

Whenever I update my project, I update and run the new Docker container on my host machine. Any clients that have a value stored in ProtectedLocalStorage are not able to reload or view the page utilizing ProtectedLocalStorage again until they enter their browser tools and manually clear the local storage data.

UPDATE: The issue lies in the await ProtectedLocalStore.GetAsync<List<long>>("upvoted"); trying to cast encrypted values to <List>. When a new Docker container is created, it can no longer decrypt the existing local storage. Is it possible to have new containers be able to decrypt the existing local storage? Perhaps I could mount something that handles this process to my container so that it stays the same for each new container?


问:
Do we have any query that use meta data and provide long running queries on Presto like MSSQL?
Do we have any queries that use meta data and provide long running queries on Presto like MSSQL?

In MSSQL, we can query dm views and find the long running sessions, session id, query , etc.
Can we do the same in Presto?


问:
Building a quiz app in react. When clicking to the answers, background color is changing for all four answers
```<code>import React, { useCallback, useMemo } from "react";

function QuizPage({ item }) { const [color, setColor] = React.useState(false); console.log(item.id);

function handleClick() { setColor((prev) => !prev);   }

const styles = { backgroundColor: color ? "teal" : "", color: color ? "white" : "",   };

return (
    <div className="quiz--page">
      <h1>{item.question}</h1>
      <div className="answer-btn">
        <button onClick={handleClick} style={styles}>
          {item.correct_answer}
        </button>
        {item.incorrect_answers.map((ia, index) => (
          <button key={index} onClick={handleClick} style={styles}>
            {ia}
          </button>
        ))}
      </div>
      <hr className="solid"></hr>
    </div>   ); }

export default QuizPage;

import React from "react"; import { useState, useEffect } from "react"; import QuizPage from "./components/QuizPage"; import { nanoid } from "nanoid";

function App() { const [state, setState] = useState(false); function startQuiz() { setState((prev) => !prev);   }

https://opentdb.com/api.php?amount=5

const [allQuizzes, setAllQuizzes] = useState([]);

useEffect(function () { console.log("Effect ran"); fetch("https://opentdb.com/api.php?amount=5")
      .then((res) => res.json())
      .then((data) => { let quizzes = data.results; quizzes = quizzes.map((curQuiz) => { const id = nanoid();

return { ...curQuiz, id: id };
        }); setAllQuizzes(quizzes);
      }); []); console.log(allQuizzes); const apiResults = allQuizzes.map((item) => { return <QuizPage item={item} key={item.id} />;   }); return (
    <main>
      {state ? (
        <>
          <section>{apiResults}</section>
          <button className="check">Check answers</button>
        </>
      ) : (
        <div className="starting--page">
          <h1>Quizzical</h1>
          <p>Solve problems</p>
          <button onClick={startQuiz} className="start--btn"> Start Quiz
          </button>
        </div>
      )}
    </main>   ); }

export default App;
</code>```

Body:
import React, { useCallback, useMemo } from "react";

function QuizPage({ item }) { const [color, setColor] = React.useState(false); console.log(item.id);

function handleClick() { setColor((prev) => !prev);   }

const styles = { backgroundColor: color ? "teal" : "", color: color ? "white" : "",   };

return (

{item.question}

        <button onClick={handleClick} style={styles}>
          {item.correct_answer}
        </button>
        {item.incorrect_answers.map((ia, index) => (
          <button key={index} onClick={handleClick} style={styles}>
            {ia}
          </button>
        ))}

   ); }

export default QuizPage;

import React from "react"; import { useState, useEffect } from "react"; import QuizPage from "./components/QuizPage"; import { nanoid } from "nanoid";

function App() { const [state, setState] = useState(false); function startQuiz() { setState((prev) => !prev);   }

https://opentdb.com/api.php?amount=5

const [allQuizzes, setAllQuizzes] = useState([]);

useEffect(function () { console.log("Effect ran"); fetch("https://opentdb.com/api.php?amount=5")
      .then((res) => res.json())
      .then((data) => { let quizzes = data.results; quizzes = quizzes.map((curQuiz) => { const id = nanoid();

return { ...curQuiz, id: id };
        }); setAllQuizzes(quizzes);
      }); []); console.log(allQuizzes); const apiResults = allQuizzes.map((item) => { return <QuizPage item={item} key={item.id} />;   }); return (

      {state ? (
        <>

{apiResults}

          <button className="check">Check answers</button>
        </>
      ) : (

Quizzical

Solve problems

          <button onClick={startQuiz} className="start--btn"> Start Quiz
          </button>

      )}
       ); }

export default App;


问:
batch script copy only new files to destination
I need some help with a batch script wherein the requirement is to copy only the new or modified files to the destiantion, at the destination once the files are read they are deleted but the souce contains the same file which need not be copied again. Only the new files or modified files must be copied.

To achieve this I created a set of 2 more folders wherein the source folder is synced to the destination in doing so a text file is created which mentions only the new files copied. Next the file is duplicated and the path is changed. further both the text files are read and put into an array.

the issue I am facing is copying from the source to the destination. Can someone help or  provide a better logic of doing this.

```<code>@echo off
robocopy C:\Users\ffernandes\rifath\  C:\Users\ffernandes\raes\  /e /z /copy:DAT /mt /z /xc /xn /xo /np > C:\Users\ffernandes\Logfile.txt

setlocal enabledelayedexpansion  disabledelayedexpansion
@%SystemRoot%\System32\findstr /C:"New File" "C:\Users\ffernandes\Logfile.txt" > "C:\Users\ffernandes\report.txt"

SETLOCAL
(
FOR /f "tokens=3*" %%a IN (C:\Users\ffernandes\report.txt) DO ECHO(%%b)>"C:\Users\ffernandes\c.txt"

REM pushd "%userprofile%\Desktop"

copy C:\Users\ffernandes\c.txt  C:\Users\ffernandes\d.txt
set "search=C:\Users\ffernandes\rifath"
set "replace=C:\Users\ffernandes\francis"
set "textFile=C:\Users\ffernandes\d.txt"

for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"%textFile%" echo(!line:%search%=%replace%!
    endlocal
)

setlocal enabledelayedexpansion
for /F "delims=" %%a in (C:\Users\ffernandes\c.txt) do (
    set /A count+=1
    set "array[!count!]=%%a"
)
for /L %%i in (1,1,%count%) do echo !array[%%i]!

setlocal enabledelayedexpansion
for /F "delims=" %%b in (C:\Users\ffernandes\d.txt) do (
    set /B count+=1
    set "array1[!count!]=%%b"
)
for /L %%j in (1,1,%count%) do echo !array1[%%j]!
for /L %%j in (1,1,%count%) do (
    copy !array[%%j]!   !array1[%%j]!
)
</code>```

Body:
I need some help with a batch script wherein the requirement is to copy only the new or modified files to the destiantion, at the destination once the files are read they are deleted but the souce contains the same file which need not be copied again. Only the new files or modified files must be copied.

To achieve this I created a set of 2 more folders wherein the source folder is synced to the destination in doing so a text file is created which mentions only the new files copied. Next the file is duplicated and the path is changed. further both the text files are read and put into an array.

the issue I am facing is copying from the source to the destination. Can someone help or  provide a better logic of doing this.

@echo off
robocopy C:\Users\ffernandes\rifath\  C:\Users\ffernandes\raes\  /e /z /copy:DAT /mt /z /xc /xn /xo /np > C:\Users\ffernandes\Logfile.txt

setlocal enabledelayedexpansion  disabledelayedexpansion
@%SystemRoot%\System32\findstr /C:"New File" "C:\Users\ffernandes\Logfile.txt" > "C:\Users\ffernandes\report.txt"

SETLOCAL
(
FOR /f "tokens=3*" %%a IN (C:\Users\ffernandes\report.txt) DO ECHO(%%b)>"C:\Users\ffernandes\c.txt"

REM pushd "%userprofile%\Desktop"

copy C:\Users\ffernandes\c.txt  C:\Users\ffernandes\d.txt
set "search=C:\Users\ffernandes\rifath"
set "replace=C:\Users\ffernandes\francis"
set "textFile=C:\Users\ffernandes\d.txt"

for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"%textFile%" echo(!line:%search%=%replace%!
    endlocal
)

setlocal enabledelayedexpansion
for /F "delims=" %%a in (C:\Users\ffernandes\c.txt) do (
    set /A count+=1
    set "array[!count!]=%%a"
)
for /L %%i in (1,1,%count%) do echo !array[%%i]!

setlocal enabledelayedexpansion
for /F "delims=" %%b in (C:\Users\ffernandes\d.txt) do (
    set /B count+=1
    set "array1[!count!]=%%b"
)
for /L %%j in (1,1,%count%) do echo !array1[%%j]!
for /L %%j in (1,1,%count%) do (
    copy !array[%%j]!   !array1[%%j]!
)


问:
Woocommerce: function to update product does not update the Variations
I am using this function to update a single product. It works but the translations of this products are not updated. I use WPML for translation.
I guess this function should include a line of code to fire the update in the translations.</p>
```<code>add_action('init', 'updateProducts');
function updateProducts()
{
    $post = get_post(269850);
    $new_title = "New title";

  $post_update = array(
    'ID'         => $post->ID,
    'post_title' => $new_title
  );

  wp_update_post( $post_update );
}
</code>```

Body:
I am using this function to update a single product. It works but the translations of this products are not updated. I use WPML for translation.
I guess this function should include a line of code to fire the update in the translations.

add_action('init', 'updateProducts');
function updateProducts()
{
    $post = get_post(269850);
    $new_title = "New title";

  $post_update = array(
    'ID'         => $post->ID,
    'post_title' => $new_title
  );

  wp_update_post( $post_update );
}


问:
Make new rows dependent on previous row values in Presto
I have new users being added to my table each day and I want to check for new users.  However, the table's data removes old rows after reaching a certain number of rows.  To keep my new rows accurate, I want to calculate the new users BASED on the PREVIOUS ROWS values.  So as long as I have one previous row available, my new row will always be accurate. If there is no previous row, the row should have a default value.

Date
users_Today
New_users
All_users_To_Date

Dec 6
Allie, Jon
Allie, Jon
Allie, Jon

Dec 7
Allie, Jon, Zach
Zach
Allie, Jon, Zach

Currently I have:

```<code>WITH user_log_response AS (
    SELECT
        CAST(JSON_PARSE(user_log) AS MAP<VARCHAR, VARCHAR>) AS user_map,
        date
    FROM user_log_response_table
),
names_and_dates AS (
    SELECT DISTINCT
        user_name AS user_name,
        date
    FROM user_log_response
    CROSS JOIN UNNEST(user_map) AS u(user_name, user_age)
),
user_names AS (
    SELECT
        date,
        ARRAY_JOIN(
            ARRAY_AGG(
                user_name
                ORDER BY
                    user_name
            ),
            ','
        ) users_today,
    FROM names_and_dates
    GROUP BY
        date
    ORDER BY
        date DESC
)
SELECT
    date,
    users_today
FROM user_names
</code>```

Which results in this

Date
users_Today

Dec 6
Allie, Jon

Dec 7
Allie, Jon, Zach

If I store "all users to date" how can I calculate "new users" to equal previous row's "all users to date" minus "users today"

Also how can I calculate "all users to date" to equal previous row's "all users to date" plus current row's "new users"

Body:
I have new users being added to my table each day and I want to check for new users.  However, the table's data removes old rows after reaching a certain number of rows.  To keep my new rows accurate, I want to calculate the new users BASED on the PREVIOUS ROWS values.  So as long as I have one previous row available, my new row will always be accurate. If there is no previous row, the row should have a default value.

Date
users_Today
New_users
All_users_To_Date

Dec 6
Allie, Jon
Allie, Jon
Allie, Jon

Dec 7
Allie, Jon, Zach
Zach
Allie, Jon, Zach

Currently I have:

WITH user_log_response AS (
    SELECT
        CAST(JSON_PARSE(user_log) AS MAP<VARCHAR, VARCHAR>) AS user_map,
        date
    FROM user_log_response_table
),
names_and_dates AS (
    SELECT DISTINCT
        user_name AS user_name,
        date
    FROM user_log_response
    CROSS JOIN UNNEST(user_map) AS u(user_name, user_age)
),
user_names AS (
    SELECT
        date,
        ARRAY_JOIN(
            ARRAY_AGG(
                user_name
                ORDER BY
                    user_name
            ),
            ','
        ) users_today,
    FROM names_and_dates
    GROUP BY
        date
    ORDER BY
        date DESC
)
SELECT
    date,
    users_today
FROM user_names

Which results in this

Date
users_Today

Dec 6
Allie, Jon

Dec 7
Allie, Jon, Zach

If I store "all users to date" how can I calculate "new users" to equal previous row's "all users to date" minus "users today"

Also how can I calculate "all users to date" to equal previous row's "all users to date" plus current row's "new users"


问:
Wordpress Category Filtering Stuck
Everytime I click a category it shows only "Filtering..." and not loading all the post.
Filtering Issue

HTML

 Show all <?php  $categories = get_categories(array( 'hide_empty' => true, 'exclude' => array(1, 143) )); foreach ($categories as $category) : ?> <span class="filter" data-set="<?= $category->slug ?>"><?= $category->name ?> <?php endforeach; ?>

SCRIPT
`(($) => {
const filters = $("#filterBar .filters");
const articles = $("#all-posts .articles");

```<code>filters.children('.filter').click(function(e) {
    e.preventDefault();
    const button = $(this),
        loader = $("#loader"),
        data = {
            'action': 'filterposts',
            'category': $(this).data('set')
        };

    $.ajax({
        url : latest_reads_params.ajaxurl,
        data : data,
        type : 'POST',
        beforeSend : function ( xhr ) {
            articles.html("<span class='message'>Filtering...</span>");
            loader.remove();
            filters.find('.active').removeClass('active');
            button.addClass('active');
        },
        success : function( data ){
            if( data ) {
                data = JSON.parse(data);
                articles.hide().html(data.posts).slideDown(400);
                if (data.max_pages > 1) {
                    articles.after('<div id="loader">'+
                        '<span class="ibtn secondary large" id="loaderAction" data-category="'+data.category+'" data-maxpages="'+data.max_pages+'">Load more</span>'+
                    '</div>');
                }
            } else {
                articles.html("<span class='message'>No post found for filter</span>");
            }
        }
    });
});
</code>```

})(jQuery);`

I wanted to display all category post

Title: Wordpress Category Filtering Stuck

Body:
Everytime I click a category it shows only "Filtering..." and not loading all the post.
Filtering Issue

HTML

 Show all <?php  $categories = get_categories(array( 'hide_empty' => true, 'exclude' => array(1, 143) )); foreach ($categories as $category) : ?> <span class="filter" data-set="<?= $category->slug ?>"><?= $category->name ?> <?php endforeach; ?>

SCRIPT
`(($) => {
const filters = $("#filterBar .filters");
const articles = $("#all-posts .articles");

filters.children('.filter').click(function(e) {
    e.preventDefault();
    const button = $(this),
        loader = $("#loader"),
        data = {
            'action': 'filterposts',
            'category': $(this).data('set')
        };

    $.ajax({
        url : latest_reads_params.ajaxurl,
        data : data,
        type : 'POST',
        beforeSend : function ( xhr ) {
            articles.html("Filtering...");
            loader.remove();
            filters.find('.active').removeClass('active');
            button.addClass('active');
        },
        success : function( data ){
            if( data ) {
                data = JSON.parse(data);
                articles.hide().html(data.posts).slideDown(400);
                if (data.max_pages > 1) {
                    articles.after('
'+
                        'Load more'+
                    '
');
                }
            } else {
                articles.html("No post found for filter");
            }
        }
    });
});

})(jQuery);`

I wanted to display all category post


问:
How to get ace editor text to the judge-0-ide
Working with ace code editor and sending that code to the backend of judge-0-ide for code compilation. Facing error stating in browser console tab.

index.js:25          POST
https://judge0-ce.p.rapidapi.com/submissions?base64_encoded=true&fields=*
429 (anonymous) @ index.js:25

Line 25 here is the fetch function.
My code is as follow :

```<code>let string = editor.getValue();

  let encodedString = btoa(string);

  let stringTo = `"${encodedString}"`;
  console.log(stringTo);
  const options = {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "Content-Type": "application/json",
      "X-RapidAPI-Key": "c18004644fmsh517f476d7984463p1af20ejsn3e14b093c48f",
      "X-RapidAPI-Host": "judge0-ce.p.rapidapi.com",
    },
    body: `{"language_id":52,"source_code":${stringTo},"stdin":"SnVkZ2Uw"}`,
  };

  fetch(
    "https://judge0-ce.p.rapidapi.com/submissions?base64_encoded=true&fields=*",
    options
  )
    .then((response) => response.json())
    .then((response) => getSubmissions(response))
    .catch((err) => console.error(err));
</code>```

The judge-0-ide needs code from javascript after encoding it in base64 format. Without that it won't work at all. I am quite sure the error is being caused due to
let stringTo = "${encodedString}"; but have no solution for it yet.

Body:
Working with ace code editor and sending that code to the backend of judge-0-ide for code compilation. Facing error stating in browser console tab.

index.js:25          POST
https://judge0-ce.p.rapidapi.com/submissions?base64_encoded=true&fields=*
429 (anonymous) @ index.js:25

Line 25 here is the fetch function.
My code is as follow :

let string = editor.getValue();

  let encodedString = btoa(string);

  let stringTo = `"${encodedString}"`;
  console.log(stringTo);
  const options = {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "Content-Type": "application/json",
      "X-RapidAPI-Key": "c18004644fmsh517f476d7984463p1af20ejsn3e14b093c48f",
      "X-RapidAPI-Host": "judge0-ce.p.rapidapi.com",
    },
    body: `{"language_id":52,"source_code":${stringTo},"stdin":"SnVkZ2Uw"}`,
  };

  fetch(
    "https://judge0-ce.p.rapidapi.com/submissions?base64_encoded=true&fields=*",
    options
  )
    .then((response) => response.json())
    .then((response) => getSubmissions(response))
    .catch((err) => console.error(err));

The judge-0-ide needs code from javascript after encoding it in base64 format. Without that it won't work at all. I am quite sure the error is being caused due to
let stringTo = "${encodedString}"; but have no solution for it yet.


问:
custom Exoplayer leaving 1dp of black next to video

called from this

```<code> composable("main_screen") {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                VideoPlayerScreen()
            }
</code>```

and defined here

```<code>
@Composable
fun VideoPlayerScreen() {
    val context = LocalContext.current
    var playWhenReady by remember { mutableStateOf(true) }
    val exoPlayer = remember {
        ExoPlayer.Builder(context).build().apply {
            val s : String = "android.resource://com.gamerz.splash/" + R.raw.introstudios
            setMediaItem(MediaItem.fromUri(s))
            repeatMode = ExoPlayer.REPEAT_MODE_OFF
            playWhenReady = playWhenReady
            prepare()
            play()
        }
    }

    DisposableEffect(
        AndroidView(
            modifier = Modifier.size(200.dp),
            factory = {
                StyledPlayerView(context).apply {
                    resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
                    player = exoPlayer
                    useController = false
                    layoutParams = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT)
                }

            }
        )
    ) {
        onDispose {
            exoPlayer.release()
        }
    }
}
</code>```

With no RESIZE_MODE_ZOOM, this is what it looks like.

I feel like i should be able to change the black to transparent? Or at least properly crop out the black sides of video?

Body:
called from this

 composable("main_screen") {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                VideoPlayerScreen()
            }

and defined here

@Composable
fun VideoPlayerScreen() {
    val context = LocalContext.current
    var playWhenReady by remember { mutableStateOf(true) }
    val exoPlayer = remember {
        ExoPlayer.Builder(context).build().apply {
            val s : String = "android.resource://com.gamerz.splash/" + R.raw.introstudios
            setMediaItem(MediaItem.fromUri(s))
            repeatMode = ExoPlayer.REPEAT_MODE_OFF
            playWhenReady = playWhenReady
            prepare()
            play()
        }
    }

    DisposableEffect(
        AndroidView(
            modifier = Modifier.size(200.dp),
            factory = {
                StyledPlayerView(context).apply {
                    resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
                    player = exoPlayer
                    useController = false
                    layoutParams = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT)
                }

            }
        )
    ) {
        onDispose {
            exoPlayer.release()
        }
    }
}

With no RESIZE_MODE_ZOOM, this is what it looks like.

I feel like i should be able to change the black to transparent? Or at least properly crop out the black sides of video?


问:
i'm building an rest api using eclipse and the GET request gives me This error
```<code>public static List<Projet> projets=new ArrayList<Projet>();
@Get
@Produces(MediaType.APPLICATION_JSON)
public Response RecupererProjetListebyChef(@QueryParam(value ="matricule")String matricule)
{
    List<Projet> liste=new ArrayList<Projet>();
    for(Projet p:projets){
            if(p.getChefProjet().getMatricule().equals(matricule))
                liste.add(p);

}
  if(liste.Size()!=0){
     return Response.status(Status.OK).entity(liste).build();

}
else  return Response.status(Status.NOT_FOUND).build();
}
</code>```

when i test the api on postman the error  HTTP Status 500-Internal Server Error occurred please help me

Body:
public static List<Projet> projets=new ArrayList<Projet>();
@Get
@Produces(MediaType.APPLICATION_JSON)
public Response RecupererProjetListebyChef(@QueryParam(value ="matricule")String matricule)
{
    List<Projet> liste=new ArrayList<Projet>();
    for(Projet p:projets){
            if(p.getChefProjet().getMatricule().equals(matricule))
                liste.add(p);

}
  if(liste.Size()!=0){
     return Response.status(Status.OK).entity(liste).build();

}
else  return Response.status(Status.NOT_FOUND).build();
}

when i test the api on postman the error  HTTP Status 500-Internal Server Error occurred please help me


问:
Should Otp verification happen in a standalone api endpoint or in the actual action api
I have a mechanism to generate and verify otps in my mobile app backend and not sure what the best way to design the api structure is, should the otp generation, otp verification, and the actual action api (for example: process payment) each be standalone apis or is there a best practice approach? here's my thought process.

Option 1: All 3 actions are standalone apis:

Pros:

Separation of concerns

Cons:

More api calls

If somebody somehow get's ahold of my backend apis, they could bypass the otp verification process all together and perform the action

Option 2: Generation a standalone api and otp gets passed in the headers of the action api where the otp verification will happen

Pros:

Otp verification can't be bypassed

Less api calls

Cons:

one api is handling more than one responsibility

Which one is correct if any, is there a third option? what is the best way to use otp verification in apis?


问:
MPAndroidChart with two charts value padding
I'm using MPAndroidChart in order to draw two charts however when the two values are close they overlap like the picture

is there a way to solve this for example by setting padding on values on the red chart to be drawn on top of the green one?


问:
Null Reference Duende Identity Server on Web Assembly publish to Azure
I have a very simple Web Assembly application that is simply testing out publishing to Azure with Duende Identity Server with a SQL Server operational data store.  The "functionality" is limited to displaying data from a single table.

This is running correctly in a development environment when connected to a local SQL Server for both the operational store and the functional data base.

I have deployed the database to Asure, and the application also functions correctly when I switch the connection string from the local database to the Azure SQL.

However, when I publish my test application to Azure Application Services, I get a 500 error and the message:

This page isn’t working right now

I have looked at application Insights and see several null reference exceptions:

Microsoft.AspNetCore.ApiAuthorization.IdentityServer.IdentityServerJwtBearerOptionsConfiguration+d__5.MoveNext

and three exceptions similar on:

Duende.IdentityServer.Hosting.DynamicProviders.DynamicSchemeAuthenticationMiddleware+d__3.MoveNext


问:
Expanding serialized objects
I have records that represent the amount of money spent on specific expense types:

```<code>class ProjectExpense:
    expense_type = models.ForeignKey('ExpenseType')
    month = models.DateField()
    value = models.DecimalField(max_digits=10, decimal_places=2)
</code>```

Dollar values are input by quarter, so example entries might look like this:

```<code>[
    Expense Type: Travel
    Month: 2022-04-01  # Quarter 2
    Value: $120,000
], [
    Expense Type: Capital - Hardware
    Month: 2022-07-01  # Quarter 3
    Value: $60,000
]
</code>```

When I report these entries via my REST API, I'd like to spread the dollar amount throughout the quarter. So, using the first example above, the entries would end up looking like:

```<code>[
    Expense Type: Travel
    Month: 2022-04-01
    Value: $40,000
],
[
    Expense Type: Travel
    Month: 2022-05-01
    Value: $40,000
],
[
    Expense Type: Travel
    Month: 2022-06-01
    Value: $40,000
],
</code>```

In this example, one line item has been expanded into three, spreading the cost equally. Is this kind of thing possible using the Django Rest Framework? Serializers only ever seem to operate on one object at a time, so they feel like the wrong thing to use. Of course I could roll my own view, but I'd like to take advantage of the pagination capability that DRF offers. Is there a fairly simple solution for a case like this?

Title: Expanding serialized objects

Body:
I have records that represent the amount of money spent on specific expense types:

class ProjectExpense:
    expense_type = models.ForeignKey('ExpenseType')
    month = models.DateField()
    value = models.DecimalField(max_digits=10, decimal_places=2)

Dollar values are input by quarter, so example entries might look like this:

[
    Expense Type: Travel
    Month: 2022-04-01  # Quarter 2
    Value: $120,000
], [
    Expense Type: Capital - Hardware
    Month: 2022-07-01  # Quarter 3
    Value: $60,000
]

When I report these entries via my REST API, I'd like to spread the dollar amount throughout the quarter. So, using the first example above, the entries would end up looking like:

[
    Expense Type: Travel
    Month: 2022-04-01
    Value: $40,000
],
[
    Expense Type: Travel
    Month: 2022-05-01
    Value: $40,000
],
[
    Expense Type: Travel
    Month: 2022-06-01
    Value: $40,000
],

In this example, one line item has been expanded into three, spreading the cost equally. Is this kind of thing possible using the Django Rest Framework? Serializers only ever seem to operate on one object at a time, so they feel like the wrong thing to use. Of course I could roll my own view, but I'd like to take advantage of the pagination capability that DRF offers. Is there a fairly simple solution for a case like this?


问:
Mobile Banners API For Shopify Mobile APP
In Shopify I want to have a mobile app banners needs to be managed through theme options. I can see lot of paid apps there for mobile app in shopify but i am creating my own custom app by using shopify api's. Is there any way to get the banners/slideshow images as json response?

I tried the following way

We can render sections data using http://test.myshopify.com/?sections=banner , When i tried it is showing html directly. I need only the image url and product or collection id which can be linked.

Is there any way to achieve that?


问:
How to pass SSL cert and key in Gatling Script
I have to create one script in gatling where I need to pass ssl CERT AND KEY.Curl is in below format.I am not sure how to pass it in my simulation .Can someone please help.

curl -E abc.crt --key cde.key --location --request POST 'https://a/b' \
--header 'Content-Type: application/json'```


问:
How to place automatically the translation files (.po and .mo) in the wp-content/languages/plugins folder when someone installs the plugin
I'm trying to translate a plugin I published to the WordPress marketplace, but I'm having trouble.

I created the.pot file, compiled the.po and.mo files, and placed them in the /languages folder at wp-content/plugins/name-of-the-plugin. This is only translating the plugin description, it does not translate the plugin setting page that is created when the plugin is installed.

If I copy .po and .mo file and place them under this path: wp-content/languages/plugins/name-of-the-plugin then everything gets translated.

How can I manage to place these translation files automatically into this path (wp-content/languages/plugins/name-of-the-plugin) when someone installs the plugin?

Or please let me know if I'm missing something in this process?


问:
Is there a way to apply week-over-week growth rates from prior year to current year data in Tableau?
I have a Dataset in Tableau with fields: Date, City, Sales. The data is for all days of 2022

I created Week - over - Week growth rates for 2022. My worksheet look like this:

Iso-Year (Date)
Iso Week (Date)
City
SUM(Sales)
2022 Growth %

2022
W01
New York
2500
0

2022
W01
Boston
400
0

2022
W01
Minnesota
1300
0

2022
W02
New York
2600
4%

2022
W02
Boston
200
-50%

2022
W02
Minnesota
1340
3.07%

2022
W03
New York
2400
-7.69%

2022
W03
Boston
800
200%

2022
W03
Minnesota
1200
-10.44%

The calculated field I used to get 2022 W-o-W growth %:

(SUM([Sales]) - LOOKUP(SUM([SALES]),-1))  / SUM([Sales])

I want to use the 2022 growth rate for a specific City and Iso-Week combination to the same City and Iso-week combination for 2023. As an example,

New York grew by 4% from W01 to W02 of 2022, so I'm looking to apply the same 4% to calculate Sales in W02 of 2023 (W01 2023 Sales * 1.04) and so on. Like this, I want to apply growth rates for those week and city combination of 2022 to calculate Sales for all future weeks of 2023. I already have my W01 2023 data to start with.

Iso-Year (Date)
Iso Week (Date)
City
SUM(Sales)*Growth
New Sales

2023
W01
New York
4000
4000

2023
W02
New York
4000*(1+4%)
4160

2023
W03
New York
4160*(1-7.69%)
3840

I cannot find a way to do this with my dataset. I cannot use FIXED function because I've used a table calculation in my calculated field for growth rate.

My struggle is that I'm using a Dataset provided to me by my organization and cannot modify the table logic. After I created the calculated field, I cannot use the 2022 growth % if I have 2023 data filtered in.
I have an option to create a custom data source but I do not think that the effort is worth for this.

Does anyone have an idea to make this possible?

I can provide more information if the description is not clear enough. Thanks a lot!


问:
Is there a way to detect collisions using Circular based Extrusions in VPython?
I am currently working on a project in VPython that requires me to use Circular Based extrusions, I am currently in the process of finding a way to make the Extrusions collide with each other like Spheres or Boxes, but I haven't found any documentation that could tell me how to achieve this or if this is even possible.

Here is the code I am working with so far:

```<code>from utilities.vega_util import *

class simulateAllParticleInteractions:
    def __init__(self, mP1, mP2, mP3, mP4, xPos1, yPos1, zPos1, xPos2, yPos2, zPos2, acc1, acc2, vel1, vel2, spin1, spin2, type1, type2, trailType1, trailType2, trailPps1, trailPps2, pC1_0, pC1_1, pC1_2, pC2_0, pC2_1, pC2_2, c1, c2, name1, name2, particle1, particle2):
        self.mP1 = mP1
        self.mP2 = mP2
        self.mP3 = mP3
        self.mP4 = mP4
        self.xPos1 = xPos1
        self.yPos1 = yPos1
        self.zPos1 = zPos1
        self.xPos2 = xPos2
        self.yPos2 = yPos2
        self.zPos2 = zPos2
        self.acc1 = acc1
        self.acc2 = acc2
        self.vel1 = vel1
        self.vel2 = vel2
        self.spin1 = spin1
        self.spin2 = spin2
        self.type1 = type1
        self.type2 = type2
        self.trailType1 = trailType1
        self.trailType2 = trailType2
        self.trailPps1 = trailPps1
        self.trailPps2 = trailPps2
        self.pC1_0 = pC1_0
        self.pC1_1 = pC1_1
        self.pC1_2 = pC1_2
        self.pC2_0 = pC2_0
        self.pC2_1 = pC2_1
        self.pC2_2 = pC2_2
        self.c1 = c1
        self.c2 = c2
        self.name1 = name1
        self.name2 = name2
        self.particle1 = particle1
        self.particle2 = particle2
        self.executeParticleInteractionGraphics(self.type1, self.type2)
    def createBosonShape(self, xVec, yVec, zVec, yLength, eColor):
        bosonObj = shapes.circle(thickness=0.3)
        objPath = [vector(xVec,yVec,zVec), vector(xVec,yLength,zVec)]
        self.boson = extrusion(path=objPath, shape=bosonObj, color=eColor, scale=[1,1])
        return self.boson
    def executeEulerHamiltonian(self, particle, v1, v2, mode, extraVar):
        m1 = self.mass
        m2 = self.mass
        t = 0
        dt = 0.001
        self.m = m1
        print(int(float(self.m)))
        self.particle.p1 = int(float(self.m))*vector(int(abs(self.returnPathHamiltonian(m1, m2, v1, v2))), int(abs(self.returnPathHamiltonian(m1, m2, v1, v2))), int(abs(self.returnPathHamiltonian(m1, m2, v1, v2))))
        finalForce = vector(0,0,0)
        if mode == 1:
            return
        elif mode == 2:
            while (t<1.3):
                rate(1000)
                finalForce = vector(0,0,0)
                self.particle.p1 = self.particle.p1 + finalForce*dt
                self.particle.pos = self.particle.pos+self.particle.p1*dt/int(float(self.m))
                t = t + dt
    def convertToUseableMass(self, massToConvert):
        finalMass = str(massToConvert)
        finalHalf = finalMass[:len(finalMass)//2]
        print(finalHalf)
        return finalHalf
    def returnPathLagrangian(self, m1, m2, v1, v2):
        return self.calculateKineticEnergy(m1, v1) - self.calculatePotentialEnergy(m2, v2)
    def calculatePotentialEnergy(self, m, v):
        self.totalPotentialEnergy = float(m)*9.8*v
        return self.totalPotentialEnergy
    def calculateKineticEnergy(self, m, v):
        self.totalKineticEnergy = (float(m)*v**2)/2
        return self.totalKineticEnergy
    def executeParticleInteractionGraphics(self, type1, type2):
        #hasCollided = False
        print("hello")
        #if type1 is type2:
        #    while (not hasCollided):
        #        rate(1000)
        if type1 is not type2:
            self.newType1 = self.createBosonShape(0,0,0,0.1,eColor=vec(self.pC1_0,self.pC1_1,self.pC1_2))
            self.newType2 = self.createBosonShape(4,0,0,0.1,eColor=vec(self.pC2_0,self.pC2_1,self.pC2_2))
            print(self.newType1)
            print(self.newType2)
            self.executeEulerLagrange(self.newType1, self.newType2, 2, 5, 2, 5, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 3, 3)
        else:
            print("Please enter a proper mode for each particle involved, thank you.")

    def executeEulerLagrange(self, boson1, boson2, v1, v2, v3, v4, numArray1, numArray2, mode1, mode2, xVec1, yVec1, zVec1, xVec2, yVec2, zVec2, yLength1, yLength2):
        self.massList = [1.6e-36, 1.6e-36, 1.6e-36, 1.6e-36, 1.6e-36]
        m1 = self.convertToUseableMass(self.massList[numArray1])
        m2 = self.convertToUseableMass(self.massList[numArray1])
        m3 = self.convertToUseableMass(self.massList[numArray2])
        m4 = self.convertToUseableMass(self.massList[numArray2])
        t = 0
        dt = 0.001
        self.m1_0 = m1
        self.m2_0 = m2
        #print(int(float(self.m)))
        #print(float(self.m))
        #self.convertToUseableMass(self.m)
        self.p1 = int(float(self.m1_0))*vector(int(abs(self.returnPathLagrangian(m1, m2, v1, v2))), int(abs(self.returnPathLagrangian(m1, m2, v1, v2))), int(abs(self.returnPathLagrangian(m1, m2, v1, v2))))
        self.p2 = int(float(self.m2_0))*vector(int(abs(self.returnPathLagrangian(m3, m4, v3, v4))), -int(abs(self.returnPathLagrangian(m3, m4, v3, v4))), -int(abs(self.returnPathLagrangian(m3, m4, v3, v4))))
        finalForce1 = vector(0,0,0)
        finalForce2 = vector(0,0,0)
        k_c = 999
        hasCollided = False

        while (t<0.25):
            rate(100)
            finalForce1 = vector(0,0,0)
            finalForce2 = vector(0,0,0)
            f1 = 0.02
            f2 = 0.02
            distX=boson1.pos-boson2.pos
            if mag(distX)<(f1+f2) or hasCollided:
                finalAccelerationInitial=k_c*(mag(distX)-(f1+f2))*norm(distX)
                finalAccelerationFinal=-finalAccelerationInitial
                hasCollided=True

            self.p1 = self.p1 + finalForce1*dt
            self.p2 = self.p2 + finalForce2*dt

            boson1.m = 0.1
            boson2.m = 0.1

            print(boson2.pos)
            print(boson1.pos)

            boson1.pos = boson1.pos+self.p1*dt/boson1.m/60
            boson2.pos = boson2.pos-self.p2*dt/boson2.m/60

            t = t + dt
simulateAllParticleInteractions(1, 5, 1, 5, 0, 0, 0, 8, 0, 0, 4, 4, 4, 4, 1, 2, "muon", "anti muon", None, None, None, None, 0.5, 0.8, 0.5, 0.7, 0.4, 0.7, None, None, None, None, None, None)
</code>```

If this is possible what methods could I use to get the Extrusions to collide with each other? Thank you.

Body:
I am currently working on a project in VPython that requires me to use Circular Based extrusions, I am currently in the process of finding a way to make the Extrusions collide with each other like Spheres or Boxes, but I haven't found any documentation that could tell me how to achieve this or if this is even possible.

Here is the code I am working with so far:

from utilities.vega_util import *

class simulateAllParticleInteractions:
    def __init__(self, mP1, mP2, mP3, mP4, xPos1, yPos1, zPos1, xPos2, yPos2, zPos2, acc1, acc2, vel1, vel2, spin1, spin2, type1, type2, trailType1, trailType2, trailPps1, trailPps2, pC1_0, pC1_1, pC1_2, pC2_0, pC2_1, pC2_2, c1, c2, name1, name2, particle1, particle2):
        self.mP1 = mP1
        self.mP2 = mP2
        self.mP3 = mP3
        self.mP4 = mP4
        self.xPos1 = xPos1
        self.yPos1 = yPos1
        self.zPos1 = zPos1
        self.xPos2 = xPos2
        self.yPos2 = yPos2
        self.zPos2 = zPos2
        self.acc1 = acc1
        self.acc2 = acc2
        self.vel1 = vel1
        self.vel2 = vel2
        self.spin1 = spin1
        self.spin2 = spin2
        self.type1 = type1
        self.type2 = type2
        self.trailType1 = trailType1
        self.trailType2 = trailType2
        self.trailPps1 = trailPps1
        self.trailPps2 = trailPps2
        self.pC1_0 = pC1_0
        self.pC1_1 = pC1_1
        self.pC1_2 = pC1_2
        self.pC2_0 = pC2_0
        self.pC2_1 = pC2_1
        self.pC2_2 = pC2_2
        self.c1 = c1
        self.c2 = c2
        self.name1 = name1
        self.name2 = name2
        self.particle1 = particle1
        self.particle2 = particle2
        self.executeParticleInteractionGraphics(self.type1, self.type2)
    def createBosonShape(self, xVec, yVec, zVec, yLength, eColor):
        bosonObj = shapes.circle(thickness=0.3)
        objPath = [vector(xVec,yVec,zVec), vector(xVec,yLength,zVec)]
        self.boson = extrusion(path=objPath, shape=bosonObj, color=eColor, scale=[1,1])
        return self.boson
    def executeEulerHamiltonian(self, particle, v1, v2, mode, extraVar):
        m1 = self.mass
        m2 = self.mass
        t = 0
        dt = 0.001
        self.m = m1
        print(int(float(self.m)))
        self.particle.p1 = int(float(self.m))*vector(int(abs(self.returnPathHamiltonian(m1, m2, v1, v2))), int(abs(self.returnPathHamiltonian(m1, m2, v1, v2))), int(abs(self.returnPathHamiltonian(m1, m2, v1, v2))))
        finalForce = vector(0,0,0)
        if mode == 1:
            return
        elif mode == 2:
            while (t<1.3):
                rate(1000)
                finalForce = vector(0,0,0)
                self.particle.p1 = self.particle.p1 + finalForce*dt
                self.particle.pos = self.particle.pos+self.particle.p1*dt/int(float(self.m))
                t = t + dt
    def convertToUseableMass(self, massToConvert):
        finalMass = str(massToConvert)
        finalHalf = finalMass[:len(finalMass)//2]
        print(finalHalf)
        return finalHalf
    def returnPathLagrangian(self, m1, m2, v1, v2):
        return self.calculateKineticEnergy(m1, v1) - self.calculatePotentialEnergy(m2, v2)
    def calculatePotentialEnergy(self, m, v):
        self.totalPotentialEnergy = float(m)*9.8*v
        return self.totalPotentialEnergy
    def calculateKineticEnergy(self, m, v):
        self.totalKineticEnergy = (float(m)*v**2)/2
        return self.totalKineticEnergy
    def executeParticleInteractionGraphics(self, type1, type2):
        #hasCollided = False
        print("hello")
        #if type1 is type2:
        #    while (not hasCollided):
        #        rate(1000)
        if type1 is not type2:
            self.newType1 = self.createBosonShape(0,0,0,0.1,eColor=vec(self.pC1_0,self.pC1_1,self.pC1_2))
            self.newType2 = self.createBosonShape(4,0,0,0.1,eColor=vec(self.pC2_0,self.pC2_1,self.pC2_2))
            print(self.newType1)
            print(self.newType2)
            self.executeEulerLagrange(self.newType1, self.newType2, 2, 5, 2, 5, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 3, 3)
        else:
            print("Please enter a proper mode for each particle involved, thank you.")

    def executeEulerLagrange(self, boson1, boson2, v1, v2, v3, v4, numArray1, numArray2, mode1, mode2, xVec1, yVec1, zVec1, xVec2, yVec2, zVec2, yLength1, yLength2):
        self.massList = [1.6e-36, 1.6e-36, 1.6e-36, 1.6e-36, 1.6e-36]
        m1 = self.convertToUseableMass(self.massList[numArray1])
        m2 = self.convertToUseableMass(self.massList[numArray1])
        m3 = self.convertToUseableMass(self.massList[numArray2])
        m4 = self.convertToUseableMass(self.massList[numArray2])
        t = 0
        dt = 0.001
        self.m1_0 = m1
        self.m2_0 = m2
        #print(int(float(self.m)))
        #print(float(self.m))
        #self.convertToUseableMass(self.m)
        self.p1 = int(float(self.m1_0))*vector(int(abs(self.returnPathLagrangian(m1, m2, v1, v2))), int(abs(self.returnPathLagrangian(m1, m2, v1, v2))), int(abs(self.returnPathLagrangian(m1, m2, v1, v2))))
        self.p2 = int(float(self.m2_0))*vector(int(abs(self.returnPathLagrangian(m3, m4, v3, v4))), -int(abs(self.returnPathLagrangian(m3, m4, v3, v4))), -int(abs(self.returnPathLagrangian(m3, m4, v3, v4))))
        finalForce1 = vector(0,0,0)
        finalForce2 = vector(0,0,0)
        k_c = 999
        hasCollided = False

        while (t<0.25):
            rate(100)
            finalForce1 = vector(0,0,0)
            finalForce2 = vector(0,0,0)
            f1 = 0.02
            f2 = 0.02
            distX=boson1.pos-boson2.pos
            if mag(distX)<(f1+f2) or hasCollided:
                finalAccelerationInitial=k_c*(mag(distX)-(f1+f2))*norm(distX)
                finalAccelerationFinal=-finalAccelerationInitial
                hasCollided=True

            self.p1 = self.p1 + finalForce1*dt
            self.p2 = self.p2 + finalForce2*dt

            boson1.m = 0.1
            boson2.m = 0.1

            print(boson2.pos)
            print(boson1.pos)

            boson1.pos = boson1.pos+self.p1*dt/boson1.m/60
            boson2.pos = boson2.pos-self.p2*dt/boson2.m/60

            t = t + dt
simulateAllParticleInteractions(1, 5, 1, 5, 0, 0, 0, 8, 0, 0, 4, 4, 4, 4, 1, 2, "muon", "anti muon", None, None, None, None, 0.5, 0.8, 0.5, 0.7, 0.4, 0.7, None, None, None, None, None, None)

If this is possible what methods could I use to get the Extrusions to collide with each other? Thank you.


问:
valueFormatter function on Group row is not working?
When i add a field with this config:

```<code>var columnDefs = [{
    field: "Date", // Js Date Object
    enableRowGroup: true,
    valueFormatter: dateFormatter,
    filter: "agDateColumnFilter"
}];

function dateFormatter(p){
    return p.value.toLocalString();
}
</code>```

when the render into normal rows works fine, but the problem is when you group this field, then they don't process the key to group thru "dateFormatter" then sows date like js string "Tue Jan 10 2023 17:59......"

Temporary, i fix manually there:

```<code>agGrid.ValueService.prototype.getKeyForNode = function(e, t) {
    var r = this.getValue(e, t)
        , o = e.getColDef().keyCreator
        , n = r;
    o && (n = o({
        value: r,
        colDef: e.getColDef(),
        column: e,
        node: t,
        data: t.data,
        api: this.gridOptionsWrapper.getApi(),
        columnApi: this.gridOptionsWrapper.getColumnApi(),
        context: this.gridOptionsWrapper.getContext()
    }));

    // MY FIX
    if(typeof e.colDef.valueFormatter === 'function')
    n = e.colDef.valueFormatter({value:n});

    return "string" == typeof n || null == n || "[object Object]" === (n = String(n)) && Object(c.doOnce)((function() {...}
    ), "getKeyForNode - warn about [object,object]"),
    n
}
</code>```

any Vanilla option to run this correctly?

Body:
When i add a field with this config:

var columnDefs = [{
    field: "Date", // Js Date Object
    enableRowGroup: true,
    valueFormatter: dateFormatter,
    filter: "agDateColumnFilter"
}];

function dateFormatter(p){
    return p.value.toLocalString();
}

when the render into normal rows works fine, but the problem is when you group this field, then they don't process the key to group thru "dateFormatter" then sows date like js string "Tue Jan 10 2023 17:59......"

Temporary, i fix manually there:

agGrid.ValueService.prototype.getKeyForNode = function(e, t) {
    var r = this.getValue(e, t)
        , o = e.getColDef().keyCreator
        , n = r;
    o && (n = o({
        value: r,
        colDef: e.getColDef(),
        column: e,
        node: t,
        data: t.data,
        api: this.gridOptionsWrapper.getApi(),
        columnApi: this.gridOptionsWrapper.getColumnApi(),
        context: this.gridOptionsWrapper.getContext()
    }));

    // MY FIX
    if(typeof e.colDef.valueFormatter === 'function')
    n = e.colDef.valueFormatter({value:n});

    return "string" == typeof n || null == n || "[object Object]" === (n = String(n)) && Object(c.doOnce)((function() {...}
    ), "getKeyForNode - warn about [object,object]"),
    n
}

any Vanilla option to run this correctly?


问:
Upgrade Grafana 7.x.x to 9.x.x alerts missing
I had Grafana 7.5.7 working with a lot of alerts configured I used to save all the dashboards as a json file and this has the alerts. After I upgraded to the 9.3.1 version all the alerts disappeared.
I saw online that you can configure the old alerts

```<code>force_migration = true

[alerting]
enabled = true

[unified_alerting]
enabled = false
</code>```

But his does not work. Can someone give me some insight on what I need to do? Should I just create new rules and provision them ou is there a was to migrate these?

Thanks in advance

Body:
I had Grafana 7.5.7 working with a lot of alerts configured I used to save all the dashboards as a json file and this has the alerts. After I upgraded to the 9.3.1 version all the alerts disappeared.
I saw online that you can configure the old alerts

force_migration = true

[alerting]
enabled = true

[unified_alerting]
enabled = false

But his does not work. Can someone give me some insight on what I need to do? Should I just create new rules and provision them ou is there a was to migrate these?

Thanks in advance


问:
Get static props: Cannot read properties of undefined (reading 'headers')
On a dynamically generated page, I want to redirect if the user is not logged in. I would do it with getServerSideProps like this:

export async function getServerSideProps({ req, res }) {
  if (req.headers['x-user-id']) {
    return {
      props: {
         //...
      }
    }
  } else {
    return {
      redirect: {
        destination: '/'
      }
    }
  }
}
```
<p>However, in my dynamically generated next.js page, I need to use <code>getStaticPaths</code> and <code>getStaticProps</code> together, and you can't use <code>getStaticProps</code> and <code>getServerSideProps</code> together. Therefore, for my page <code>[username].js</code>, I tried doing this:</p>
<pre class="lang-js prettyprint-override"><code>export async function getStaticProps({ params, req, res }) {
  const results = await Get('https://example.com/api/getUsers')
  const i = results.findIndex(e => e.username === params.username)

  if (req.headers['x-user-id']) {
    return {
      props: {
        user: results[i]
      }
    }
  } else {
    return {
      redirect: {
        destination: '/'
      }
    }
  }
}
</code>```

This however gives me the error:

TypeError: Cannot read properties of undefined (reading 'headers')

How can I fix this?

Body:
On a dynamically generated page, I want to redirect if the user is not logged in. I would do it with getServerSideProps like this:

export async function getServerSideProps({ req, res }) {
  if (req.headers['x-user-id']) {
    return {
      props: {
         //...
      }
    }
  } else {
    return {
      redirect: {
        destination: '/'
      }
    }
  }
}

However, in my dynamically generated next.js page, I need to use getStaticPaths and getStaticProps together, and you can't use getStaticProps and getServerSideProps together. Therefore, for my page [username].js, I tried doing this:

export async function getStaticProps({ params, req, res }) {
  const results = await Get('https://example.com/api/getUsers')
  const i = results.findIndex(e => e.username === params.username)

  if (req.headers['x-user-id']) {
    return {
      props: {
        user: results[i]
      }
    }
  } else {
    return {
      redirect: {
        destination: '/'
      }
    }
  }
}

This however gives me the error:

TypeError: Cannot read properties of undefined (reading 'headers')

How can I fix this?


问:
no implicit conversion of HTTParty::Response into String (TypeError) ruby with httparty
This was running without problems, now I'm getting the following error when I use the same ID that I registered in the query: no implicit conversion of HTTParty::Response into String (TypeError)</p>
```<code>class Crud
  include HTTParty
  base_uri 'http://dummy.restapiexample.com/api/v1'

  def create
    nome = Faker::UniqueGenerator.clear
    nome = Faker::Name.unique.first_name
    salario = Faker::Number.number(digits: 2)
    idade   = Faker::Number.number(digits: 2)
    $body = {name: nome, salary: salario, age: idade }.to_json

    $headers = {
      'Accept' => 'application/vnd.tasksmanager.v2',
      'Content-Type' => 'application/json'
    }

    self.class.post('/create', body: $body, headers: $headers)
  end

  def retrieve(id)
    self.class.get("/employee/#{ id }")
  end

def delete(id)
self.class.delete("/delete/#{ id }")
end

  $response = @manter_user.create
  expect(@manter_user.create.code).to eq (200)
  puts $response.body
  pp @id = JSON.parse($response)["id"]
  *no implicit conversion of HTTParty::Response into String (TypeError)*
  puts @manter_user.retrieve(@id)
  expect(@manter_user.retrieve(@id).code).to eq (200)
</code>```

Body:
This was running without problems, now I'm getting the following error when I use the same ID that I registered in the query: no implicit conversion of HTTParty::Response into String (TypeError)

class Crud
  include HTTParty
  base_uri 'http://dummy.restapiexample.com/api/v1'

  def create
    nome = Faker::UniqueGenerator.clear
    nome = Faker::Name.unique.first_name
    salario = Faker::Number.number(digits: 2)
    idade   = Faker::Number.number(digits: 2)
    $body = {name: nome, salary: salario, age: idade }.to_json

    $headers = {
      'Accept' => 'application/vnd.tasksmanager.v2',
      'Content-Type' => 'application/json'
    }

    self.class.post('/create', body: $body, headers: $headers)
  end

  def retrieve(id)
    self.class.get("/employee/#{ id }")
  end

def delete(id)
self.class.delete("/delete/#{ id }")
end

  $response = @manter_user.create
  expect(@manter_user.create.code).to eq (200)
  puts $response.body
  pp @id = JSON.parse($response)["id"]
  *no implicit conversion of HTTParty::Response into String (TypeError)*
  puts @manter_user.retrieve(@id)
  expect(@manter_user.retrieve(@id).code).to eq (200)


问:
PagerDuty Terraform API Limitations
Just inquiring if anyone's aware of any permission limitations with the PagerDuty terraform API? With a base role of Observer in PagerDuty, it appears as though certain objects (which my user created) can be deleted via the GUI, but not via the terraform API even though I’m using the same user account. A PagerDuty Extension is an example of an object where I’m hitting this issue.

The same test case works as expected if I try it with a user with a base role of Manager though. Here’s a quick terraform file I threw together to verify this test case:

```<code>resource "pagerduty_schedule" "schedule" {
    name = "terraform-test-schedule"
    time_zone = "America/Denver"
    teams = ["PRDBAEK"]
    layer {
        name = "weekly"
        start = "2020-02-05T09:00:00-06:00"
        rotation_virtual_start = "2020-02-05T09:00:00-06:00"
        rotation_turn_length_seconds = 604800
        users = ["PN94M6Q"]
    }
}

resource "pagerduty_escalation_policy" "escalation_policy" {
    name = "terraform-test-ep"
    description = "terraform-test-ep"
    num_loops = 0
    teams = ["PRDBAEK"]

    rule {
        escalation_delay_in_minutes = 10
        target {
        type = "schedule_reference"
        id   = pagerduty_schedule.schedule.id
        }
    }
}

resource "pagerduty_service" "event" {
    name = "terraform-test-service"
    description = "terraform-test-service"
    alert_creation = "create_alerts_and_incidents"
    escalation_policy = pagerduty_escalation_policy.escalation_policy.id

    incident_urgency_rule {
        type = "constant"
        urgency = "severity_based"
    }

    alert_grouping_parameters {
        type = "intelligent"
        config {
            fields = []
            timeout =0
        }
    }

    auto_resolve_timeout = "null"
    acknowledgement_timeout = "null"

}

resource "pagerduty_extension" "test_extension" {
    name = "terraform-test-extension"
    extension_schema = data.pagerduty_extension_schema.generic_v2_webhook.id
    endpoint_url = https://fakeurl.com
    extension_objects = [
        pagerduty_service.event.id
    ]
    config = jsonencode({})
}
</code>```

All objects can be created successfully. I get the following error when testing a terraform destroy with an account with base role Observer though. It can't delete the Extension.

```<code>Error: DELETE API call to https://api.pagerduty.com/extensions/P53423F failed 403 Forbidden. Code: 2010, Errors: <nil>, Message: Access Denied
</code>```

But using that same account, I can delete that extension in the GUI with no issues.

Title: PagerDuty Terraform API Limitations

Body:
Just inquiring if anyone's aware of any permission limitations with the PagerDuty terraform API? With a base role of Observer in PagerDuty, it appears as though certain objects (which my user created) can be deleted via the GUI, but not via the terraform API even though I’m using the same user account. A PagerDuty Extension is an example of an object where I’m hitting this issue.

The same test case works as expected if I try it with a user with a base role of Manager though. Here’s a quick terraform file I threw together to verify this test case:

resource "pagerduty_schedule" "schedule" {
    name = "terraform-test-schedule"
    time_zone = "America/Denver"
    teams = ["PRDBAEK"]
    layer {
        name = "weekly"
        start = "2020-02-05T09:00:00-06:00"
        rotation_virtual_start = "2020-02-05T09:00:00-06:00"
        rotation_turn_length_seconds = 604800
        users = ["PN94M6Q"]
    }
}

resource "pagerduty_escalation_policy" "escalation_policy" {
    name = "terraform-test-ep"
    description = "terraform-test-ep"
    num_loops = 0
    teams = ["PRDBAEK"]

    rule {
        escalation_delay_in_minutes = 10
        target {
        type = "schedule_reference"
        id   = pagerduty_schedule.schedule.id
        }
    }
}

resource "pagerduty_service" "event" {
    name = "terraform-test-service"
    description = "terraform-test-service"
    alert_creation = "create_alerts_and_incidents"
    escalation_policy = pagerduty_escalation_policy.escalation_policy.id

    incident_urgency_rule {
        type = "constant"
        urgency = "severity_based"
    }

    alert_grouping_parameters {
        type = "intelligent"
        config {
            fields = []
            timeout =0
        }
    }

    auto_resolve_timeout = "null"
    acknowledgement_timeout = "null"

}

resource "pagerduty_extension" "test_extension" {
    name = "terraform-test-extension"
    extension_schema = data.pagerduty_extension_schema.generic_v2_webhook.id
    endpoint_url = https://fakeurl.com
    extension_objects = [
        pagerduty_service.event.id
    ]
    config = jsonencode({})
}

All objects can be created successfully. I get the following error when testing a terraform destroy with an account with base role Observer though. It can't delete the Extension.

Error: DELETE API call to https://api.pagerduty.com/extensions/P53423F failed 403 Forbidden. Code: 2010, Errors: <nil>, Message: Access Denied

But using that same account, I can delete that extension in the GUI with no issues.


问:
'Object reference not set to an instance of an object' Error when trying to move contents from view page to another
I have a button in my Index.html page which shows another view page: Reports.cshtml, there is a table inside the page, now I want to remove this button and let the table showing on my Index.html page directly, but when I paste the table to the code it shows an error:
Error

Part of my view code are showed below:

```<code><table id="hardware-data-table" class="table table-striped table-hover">
                            <thead bgcolor="silver">
                                <tr>
                                    <th hidden="hidden">
                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().InvHardwareID)
                                    </th>
                                    <th>
                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().Equipment)
                                    </th>
                                    <th>
                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().HardwareModel)
                                    </th>
                                    <th>
                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().WL_EndDateFormatted)
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var item in Model.Report_HardwareListByExpiration)
                                {
                                    if (item.WL_EndDate < DateTime.Now && item.WL_EndDate > DateTime.Now.AddYears(-99))
                                    {
                                        <tr>
                                            <td hidden="hidden">
                                                @item.InvHardwareID
                                            </td>
                                            <td>
                                                @item.Equipment
                                            </td>
                                            <td>
                                                @item.HardwareModel
                                            </td>
                                            <td style="background-color: #ff726f">@item.WL_EndDateFormatted</td>
                                        </tr>
                                    }
                                    if (item.WL_EndDate > DateTime.Now && item.WL_EndDate < DateTime.Now.AddYears(99))
                                    {
                                        <tr>
                                            <td hidden="hidden">
                                                @item.InvHardwareID
                                            </td>
                                            <td>
                                                @item.Equipment
                                            </td>
                                            <td>
                                                @item.HardwareModel
                                            </td>
                                            <td style="background-color: orange">
                                                @item.WL_EndDateFormatted
                                            </td>
                                        </tr>
                                    }
                                }
                            </tbody>
                        </table>
</code>```

My Report controller code are showed below:

```<code>public class ReportsController : Controller
{
    // GET: Report
    public ActionResult Reports()
    {
        if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
        {
            return RedirectToAction("Login", "Account");
        }
        ViewModel myViewModel = new ViewModel
        {
            User = GetSessionInfoFromSessions(),
            Params = new ParametersModel
            {
                Start_Date = new DateTime(2015, 12, 31),
                End_Date   = DateTime.Now.AddDays(60)
            }
        };
        myViewModel.Report_HardwareListByExpiration    = InvHardwareModel.Report_HardwareListByExpiration(myViewModel);

        return View(myViewModel);
    }
</code>```

And my hardware Model:

```<code>public static List<InvHardwareModel> Report_HardwareListByExpiration(ViewModel myViewModel)
    {
        try
        {
            var myAssManEnt = new AssetManagementEntities();
            var myUspList = myAssManEnt.usp_Report_InvHardware_ByExpirationDates
                (
                    agencyID  : myViewModel.User.AgencyID,
                    deptID    : myViewModel.User.DeptID,
                    roleID    : myViewModel.User.RoleID,
                    startDate : myViewModel.Params.Start_Date,
                    endDate   : myViewModel.Params.End_Date
                ).ToList();
            var myReturnList = new List<InvHardwareModel>();
            foreach(usp_Report_InvHardware_ByExpirationDates_Result myItem in myUspList)
            {
                myReturnList.Add(Models.InvHardwareModel.ToModel(myItem));
            }
            return myReturnList;
        }
        catch(Exception e)
        {
            throw ErrorHandler.MyException(e, "InvHardwareModel.Report_HardwareListByExpiration");
        }
    }
</code>```

The code works perfect when its in the other view page, but shows exception when I move it to my home page, any ideas? Thank you so much!

Body:
I have a button in my Index.html page which shows another view page: Reports.cshtml, there is a table inside the page, now I want to remove this button and let the table showing on my Index.html page directly, but when I paste the table to the code it shows an error:
Error

Part of my view code are showed below:

                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().InvHardwareID)

                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().Equipment)

                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().HardwareModel)

                                        @Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().WL_EndDateFormatted)

                                @foreach (var item in Model.Report_HardwareListByExpiration)
                                {
                                    if (item.WL_EndDate < DateTime.Now && item.WL_EndDate > DateTime.Now.AddYears(-99))
                                    {

                                                @item.InvHardwareID

                                                @item.Equipment

                                                @item.HardwareModel

                                            @item.WL_EndDateFormatted

                                    }
                                    if (item.WL_EndDate > DateTime.Now && item.WL_EndDate < DateTime.Now.AddYears(99))
                                    {

                                                @item.InvHardwareID

                                                @item.Equipment

                                                @item.HardwareModel

                                                @item.WL_EndDateFormatted

                                    }
                                }

My Report controller code are showed below:

public class ReportsController : Controller
{
    // GET: Report
    public ActionResult Reports()
    {
        if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
        {
            return RedirectToAction("Login", "Account");
        }
        ViewModel myViewModel = new ViewModel
        {
            User = GetSessionInfoFromSessions(),
            Params = new ParametersModel
            {
                Start_Date = new DateTime(2015, 12, 31),
                End_Date   = DateTime.Now.AddDays(60)
            }
        };
        myViewModel.Report_HardwareListByExpiration    = InvHardwareModel.Report_HardwareListByExpiration(myViewModel);

        return View(myViewModel);
    }

And my hardware Model:

public static List<InvHardwareModel> Report_HardwareListByExpiration(ViewModel myViewModel)
    {
        try
        {
            var myAssManEnt = new AssetManagementEntities();
            var myUspList = myAssManEnt.usp_Report_InvHardware_ByExpirationDates
                (
                    agencyID  : myViewModel.User.AgencyID,
                    deptID    : myViewModel.User.DeptID,
                    roleID    : myViewModel.User.RoleID,
                    startDate : myViewModel.Params.Start_Date,
                    endDate   : myViewModel.Params.End_Date
                ).ToList();
            var myReturnList = new List<InvHardwareModel>();
            foreach(usp_Report_InvHardware_ByExpirationDates_Result myItem in myUspList)
            {
                myReturnList.Add(Models.InvHardwareModel.ToModel(myItem));
            }
            return myReturnList;
        }
        catch(Exception e)
        {
            throw ErrorHandler.MyException(e, "InvHardwareModel.Report_HardwareListByExpiration");
        }
    }

The code works perfect when its in the other view page, but shows exception when I move it to my home page, any ideas? Thank you so much!


问:
How do I fill out a pdf document from the form data? Python
There is a form on the website. The user fills it in. This data, from the form, is entered into a pdf file in certain places. For example, there is a certificate, ready, in which the field with the full name is empty, the user enters his full name in the input on the site, and this full name gets to the certificate in the right place. How to interact with pdf format using Python, or is there any API for editing PDF or doc formats?
enter image description here
enter image description here

I've been trying to find a solution to this all day, I can't find it


问:
chocolatey doesnt install activeperl package correctly
Using Windows Server 2012 R2, on AWS.

When I install activeperl, chocolatey completes it successfully.

```<code>
C:\Users\valentin.kragelj>choco install activeperl
Chocolatey v1.2.1
Installing the following packages:
activeperl
By installing, you accept licenses for the packages.
Progress: Downloading ActivePerl 5.28... 100%

ActivePerl v5.28 [Approved]
activeperl package files install completed. Performing other installation steps.

The package ActivePerl wants to run 'ChocolateyInstall.ps1'.
Note: If you don't run this script, the installation will fail.
Note: To confirm automatically next time, use '-y' or consider:
choco feature enable -n allowGlobalConfirmation
Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint): y

Downloading ActivePerl 64 bit
  from 'https://cli-msi.s3.amazonaws.com/ActivePerl-5.28.msi'
Progress: 100% - Completed download of C:\Users\valentin.kragelj\AppData\Local\T
emp\2\chocolatey\ActivePerl\5.28\ActivePerl-5.28.msi (5.52 MB).
Download of ActivePerl-5.28.msi (5.52 MB) completed.
Hashes match.
Installing ActivePerl...
ActivePerl has been installed.
  activeperl may be able to be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The install of activeperl was successful.
  Software installed as 'msi', install location is likely default.

Chocolatey installed 1/1 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

C:\Users\valentin.kragelj>
</code>```

However when I check C:\ProgramData\chocolatey\bin there is no perl executable, and in C:\Perl64 there is only one file - perl.ico.

I'm firts time chocolatey user. What can I do about activeperl not being properly installed?

Body:
Using Windows Server 2012 R2, on AWS.

When I install activeperl, chocolatey completes it successfully.

C:\Users\valentin.kragelj>choco install activeperl
Chocolatey v1.2.1
Installing the following packages:
activeperl
By installing, you accept licenses for the packages.
Progress: Downloading ActivePerl 5.28... 100%

ActivePerl v5.28 [Approved]
activeperl package files install completed. Performing other installation steps.

The package ActivePerl wants to run 'ChocolateyInstall.ps1'.
Note: If you don't run this script, the installation will fail.
Note: To confirm automatically next time, use '-y' or consider:
choco feature enable -n allowGlobalConfirmation
Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint): y

Downloading ActivePerl 64 bit
  from 'https://cli-msi.s3.amazonaws.com/ActivePerl-5.28.msi'
Progress: 100% - Completed download of C:\Users\valentin.kragelj\AppData\Local\T
emp\2\chocolatey\ActivePerl\5.28\ActivePerl-5.28.msi (5.52 MB).
Download of ActivePerl-5.28.msi (5.52 MB) completed.
Hashes match.
Installing ActivePerl...
ActivePerl has been installed.
  activeperl may be able to be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The install of activeperl was successful.
  Software installed as 'msi', install location is likely default.

Chocolatey installed 1/1 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

C:\Users\valentin.kragelj>

However when I check C:\ProgramData\chocolatey\bin there is no perl executable, and in C:\Perl64 there is only one file - perl.ico.

I'm firts time chocolatey user. What can I do about activeperl not being properly installed?