问:
"java.lang.NumberFormatException: Cannot parse null string" dont know why this isnt working , any advice?
```<code>package cs3220.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cs3220.model.Games;

@WebServlet("/DisplayGame")
public class DisplayGame extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public DisplayGame() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Games getEntry(int id) {
        Games entry = new Games();
        Connection c = null;

        try {
            String url = "jdbc:mysql://cs3.calstatela.edu/cs3220stu16";
            String username = "foo";
            String password = "bar";

            c = DriverManager.getConnection(url, username, password);

            String sql = "select * from games_list where id = ?";
            PreparedStatement pstmt = c.prepareStatement(sql);
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {

                entry.setId(rs.getInt("id"));
                entry.setRating(rs.getInt("rating"));

                entry.setTitle(rs.getString("title"));
                entry.setComment(rs.getString("comment"));

            }
            pstmt.close();
        } catch (SQLException e) {

            e.printStackTrace();
        }
        return entry;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int id = Integer.parseInt(request.getParameter("id"));
        DisplayGame ds = new DisplayGame();

        request.setAttribute("entry", ds.getEntry(id));
        request.getRequestDispatcher("/WEB-INF/DisplayGame.jsp").forward(request, response);

    }

}
</code>```

I usually do a seperate class for all the sql methods and just call it in the servlet but I wanted to figure out how to do it a different way. What i am doing is using a seperate method for the entry data from database, I want to display a certian data using id so it doesn't loop all of the data when i want to display a "game".

Body:
package cs3220.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cs3220.model.Games;

@WebServlet("/DisplayGame")
public class DisplayGame extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public DisplayGame() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Games getEntry(int id) {
        Games entry = new Games();
        Connection c = null;

        try {
            String url = "jdbc:mysql://cs3.calstatela.edu/cs3220stu16";
            String username = "foo";
            String password = "bar";

            c = DriverManager.getConnection(url, username, password);

            String sql = "select * from games_list where id = ?";
            PreparedStatement pstmt = c.prepareStatement(sql);
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {

                entry.setId(rs.getInt("id"));
                entry.setRating(rs.getInt("rating"));

                entry.setTitle(rs.getString("title"));
                entry.setComment(rs.getString("comment"));

            }
            pstmt.close();
        } catch (SQLException e) {

            e.printStackTrace();
        }
        return entry;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int id = Integer.parseInt(request.getParameter("id"));
        DisplayGame ds = new DisplayGame();

        request.setAttribute("entry", ds.getEntry(id));
        request.getRequestDispatcher("/WEB-INF/DisplayGame.jsp").forward(request, response);

    }

}

I usually do a seperate class for all the sql methods and just call it in the servlet but I wanted to figure out how to do it a different way. What i am doing is using a seperate method for the entry data from database, I want to display a certian data using id so it doesn't loop all of the data when i want to display a "game".


来源: stackexchange

问:
Is there a way we can simplify the UX of adding a CalDav Account in my react-native application?
I work for a company that generates calendars for professionals and we'd like our users to synchronize their calendar on their phone for simplicity's sake. We initially had an ICS file, but we started hitting issues out of our control and we're looking to switch to a full CalDav support.

However, the steps necessary to create a CalDav account can be a bit tedious
( https://www.youtube.com/watch?v=BfPtH8fOLfw ) especially since in our mobile app, we already have an authentified user, we were wondering if there was any way we could do the setup for the user, so he/she doesn't have to switch back and forth to copy/paste the CalDav Account Credentials.

Surprisingly, we've found nothing. No NPM package, no way to simplify this. We did found a way to generate a configuration profile with the data, but we were told to steer clear this idea since some of our customers may be using a company-provided phone and it was possible to prevent any sort of installation through configuration profiles.

Anyone has an idea on how we can make it simple for our users and give them the best UX as possible ?

Thanks :)

ContentLicense: CC BY-SA 4.0


问:
CapRover app fails to find docker files path when deploying through Windows
I am not very familiar with CapRover, but my company uses it to deploy local branches to staging server. I completed a task in a ruby and rails project and tried to deploy my branch using the caprover deploy command.

The build passes, but the deployed app webpage goes to error 502. In the App Logs, it prints repeatedly that it could not find docker-entrypoint.sh: /bin/sh: 1: docker-entrypoint.sh: not found

Now, I use Windows and my colleagues use Linux. They tried to replicate the deploy on their machines and it is passing normally. That's why the suspicions falls on Windows causing it with some characters incompatibility, like slashes or quotations marks... I don't know how can I try to correct this issue without modifying the project files that they are already using and risk causing some problems where it is working...

I am not sure if I provided enough information for someone to try to help me fix this issue? I will gladly try to provide more infos if required
Thanks


问:
I want to make a function in react js so that when I click on a Link tag, I set the 'to' path to a setState
[[Link]enter image description here(https://i.stack.imgur.com/CopPx.png)
[enter image description here](https://i.stack.imgur.com/VPoTE.png)

I tried to make a function to set product with setState and in the same time to set the route to product.strMeal(name). The problem is that when i click on the Link tag my route does not update.

```<code><div className="category-container">
        {
            category.map(meal => {
                return (
                    isLoading ? <Loader /> : (
                        <Link onClick={() => getClickedProductCompleteInfo(meal.strMeal)} to={`/${product.strMeal}`}  className="meal-card" key={meal.idMeal}>
                            <h3>{meal.strMeal}</h3>
                            <img className='meal-thumbnail' src={meal.strMealThumb} style={{ width: 200, height: 200 }} alt="meal" />
                        </Link>
                    )
                )
            })
        }
    </div>

const getClickedProductCompleteInfo = async (meal: string) => {
    const productCompleteInfo = await getDataFromApi(`https://www.themealdb.com/api/json/v1/1/search.php?s=${meal}`);
    setProduct(productCompleteInfo.meals[0]);
}

<Routes>
    <Route path="/" >
      <Route index element={<Home isLoading={isLoading} categories={categories} setCurrentCategory={setCurrentCategory} />} />
      <Route path={`categories/${currentCategory}`} element={<Category product={product} setProduct={setProduct} currentCategory={currentCategory} getDataFromApi={getDataFromApi} />} />
      <Route path={`${product.strMeal}`} element={<Product product={product}/>}/>
      <Route path='about' element={<About />} />
      <Route path='contact' element={<Contact />} />
      <Route path='*' element={<Navigate to="/"></Navigate>} />
    </Route>
  </Routes>
</code>```

Body:
[[Link]enter image description here(https://i.stack.imgur.com/CopPx.png)
[enter image description here](https://i.stack.imgur.com/VPoTE.png)

I tried to make a function to set product with setState and in the same time to set the route to product.strMeal(name). The problem is that when i click on the Link tag my route does not update.

        {
            category.map(meal => {
                return (
                    isLoading ? <Loader /> : (
                        <Link onClick={() => getClickedProductCompleteInfo(meal.strMeal)} to={`/${product.strMeal}`}  className="meal-card" key={meal.idMeal}>

{meal.strMeal}

                        </Link>
                    )
                )
            })
        }

const getClickedProductCompleteInfo = async (meal: string) => {
    const productCompleteInfo = await getDataFromApi(`https://www.themealdb.com/api/json/v1/1/search.php?s=${meal}`);
    setProduct(productCompleteInfo.meals[0]);
}

<Routes>
    <Route path="/" >
      <Route index element={<Home isLoading={isLoading} categories={categories} setCurrentCategory={setCurrentCategory} />} />
      <Route path={`categories/${currentCategory}`} element={<Category product={product} setProduct={setProduct} currentCategory={currentCategory} getDataFromApi={getDataFromApi} />} />
      <Route path={`${product.strMeal}`} element={<Product product={product}/>}/>
      <Route path='about' element={<About />} />
      <Route path='contact' element={<Contact />} />
      <Route path='*' element={<Navigate to="/"></Navigate>} />
    </Route>
  </Routes>


问:
How do I create a Github Action that will convert my markdown files into a single .json file
I am trying to create a Github Action that will take multiple markdown files and convert them into a single .json file. I tried the following and it did not work.

I used this found script.

```<code>// filename: buildJson.js

const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");

const getAll = dir => {
  // Read files at _posts/{directory}
  const directory = path.join(process.cwd(), `content/${dir}`);
  const fileNames = fs.readdirSync(directory);
  // Get the content of the files as JSON
  const content = fileNames.map((fileName, index) => {
    const slug = fileName.replace(/\.md$/, "");
    const fullPath = path.join(directory, fileName);
    const fileContents = fs.readFileSync(fullPath, "utf8");
    const matterResult = matter(fileContents);
    return {
      id: index + 1, slug, ...matterResult
    };
  });
  // Return a big array of JSON
  return JSON.stringify(content);
};

const allPosts = getAll("blog");

const postFileContents = `${allPosts}`;

// Create the cache folder if it doesn't exist
try {
  fs.readdirSync("public/cache");
} catch (e) {
  fs.mkdirSync("public/cache");
}

// Create our cached posts JSON
fs.writeFile("public/cache/posts.json", postFileContents, err => {
  if (err) return console.log(err);
  console.log("Posts cached.");
});
</code>```

and this yml file in .github/workflows

```<code>name: create-json
on: [push]
jobs:
  create-json:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm install
      - run: node buildJson.js
</code>```

The script ran in Github Actions, it outputted the conole.log message I left myself, it did not create the .json file.

Body:
I am trying to create a Github Action that will take multiple markdown files and convert them into a single .json file. I tried the following and it did not work.

I used this found script.

// filename: buildJson.js

const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");

const getAll = dir => {
  // Read files at _posts/{directory}
  const directory = path.join(process.cwd(), `content/${dir}`);
  const fileNames = fs.readdirSync(directory);
  // Get the content of the files as JSON
  const content = fileNames.map((fileName, index) => {
    const slug = fileName.replace(/\.md$/, "");
    const fullPath = path.join(directory, fileName);
    const fileContents = fs.readFileSync(fullPath, "utf8");
    const matterResult = matter(fileContents);
    return {
      id: index + 1, slug, ...matterResult
    };
  });
  // Return a big array of JSON
  return JSON.stringify(content);
};

const allPosts = getAll("blog");

const postFileContents = `${allPosts}`;

// Create the cache folder if it doesn't exist
try {
  fs.readdirSync("public/cache");
} catch (e) {
  fs.mkdirSync("public/cache");
}

// Create our cached posts JSON
fs.writeFile("public/cache/posts.json", postFileContents, err => {
  if (err) return console.log(err);
  console.log("Posts cached.");
});

and this yml file in .github/workflows

name: create-json
on: [push]
jobs:
  create-json:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm install
      - run: node buildJson.js

The script ran in Github Actions, it outputted the conole.log message I left myself, it did not create the .json file.


问:
PIP error: Could not find a version that matches google-auth
I been trying to resolve dependencies for my project.
Here is the version error I am getting for google auth.
<2.0dev,<3.0dev,==1.35.0,>=1.24.0,>=2.14.1

I tried the pipenv graph and have my requirements set to 1.35 version for google-auth.
Can you please tell me which version should help here?


问:
TableCalendar only shows dots on selected day
I have a calendar like this

TableCalendar<Task>(
                onDaySelected: (date, date2) {
          onDateChanged!(date2);
        },
        selectedDayPredicate: (day) => isSameDay(dateSelected, day),
        calendarStyle: const CalendarStyle(
          markersAlignment: Alignment.bottomRight,
        ),
        eventLoader: (day) => _getEventsForDay(day),
        headerStyle: const HeaderStyle(
          formatButtonVisible: false,
        ),
        calendarFormat: CalendarFormat.month,
        currentDay: dateSelected,
        focusedDay: dateSelected,
        startingDayOfWeek: StartingDayOfWeek.monday,

        firstDay: DateTime.utc(2010, 10, 16),
        // registered on
        lastDay: DateTime.now().add(const Duration(days: 1000)),
      ),
```
<p>And the problem is, it only shows the dots for the events, when i selected that date.
<img src="https://i.stack.imgur.com/5OR0r.png" alt="enter image description here" /></p>
<p><img src="https://i.stack.imgur.com/NmboU.png" alt="enter image description here" /></p>
<p>I want the dots to be visible for all the days of the month event if they are note selected,</p>
<p>Here is how i returned the venets:</p>
```List<Task> _getEventsForDay(DateTime day) {
   return allEvents.where((element) => DateTime(day.year, day.month, day.day).isSameDate(element.nextScheduledAt)).toList();
  }
```

Body:
I have a calendar like this

TableCalendar<Task>(
                onDaySelected: (date, date2) {
          onDateChanged!(date2);
        },
        selectedDayPredicate: (day) => isSameDay(dateSelected, day),
        calendarStyle: const CalendarStyle(
          markersAlignment: Alignment.bottomRight,
        ),
        eventLoader: (day) => _getEventsForDay(day),
        headerStyle: const HeaderStyle(
          formatButtonVisible: false,
        ),
        calendarFormat: CalendarFormat.month,
        currentDay: dateSelected,
        focusedDay: dateSelected,
        startingDayOfWeek: StartingDayOfWeek.monday,

        firstDay: DateTime.utc(2010, 10, 16),
        // registered on
        lastDay: DateTime.now().add(const Duration(days: 1000)),
      ),

And the problem is, it only shows the dots for the events, when i selected that date.

I want the dots to be visible for all the days of the month event if they are note selected,

Here is how i returned the venets:

List<Task> _getEventsForDay(DateTime day) {
   return allEvents.where((element) => DateTime(day.year, day.month, day.day).isSameDate(element.nextScheduledAt)).toList();
  }


问:
Error trying to crrate new enviroment with anaconda: You probably need to delete and re-download or re-create this file
I am trying to create a new enviroment in anaconda using the following command:

```<code>conda create --name=labelme python=3
</code>```

And i am getting the next error:

InvalidArchiveError("Error with archive C:\\Users\\ttt\\.conda\\pkgs\\xz-5.2.8-h8cc25b3_0\\.cph_tmpv91fk9n9\\info-xz-5.2.8-h8cc25b3_0.tar.zst.  You probably need to delete and re-download or re-create this file.  Message from libarchive was:\n\nFailed to open 'C:\\Users\\tt\\.conda\\pkgs\\xz-5.2.8-h8cc25b3_0\\.cph_tmpv91fk9n9\\info-xz-5.2.8-h8cc25b3_0.tar.zst'")

I have tryed eliminating the file but it appears again. Does anybody know how can I resolve the problem?

```<code>conda clean --all
</code>```

Body:
I am trying to create a new enviroment in anaconda using the following command:

conda create --name=labelme python=3

And i am getting the next error:

InvalidArchiveError("Error with archive C:\\Users\\ttt\\.conda\\pkgs\\xz-5.2.8-h8cc25b3_0\\.cph_tmpv91fk9n9\\info-xz-5.2.8-h8cc25b3_0.tar.zst.  You probably need to delete and re-download or re-create this file.  Message from libarchive was:\n\nFailed to open 'C:\\Users\\tt\\.conda\\pkgs\\xz-5.2.8-h8cc25b3_0\\.cph_tmpv91fk9n9\\info-xz-5.2.8-h8cc25b3_0.tar.zst'")

I have tryed eliminating the file but it appears again. Does anybody know how can I resolve the problem?

conda clean --all


问:
How to prevent background jobs from printing next to prompt?
I am trying to implement my own shell and am experimenting with background jobs with using WNOHANG option in waitpid. But whenever I run a command in shell it just prints the output next to my prompt like this:

user@hostmachine:/.../$: [output]

Where am I going wrong?
`

```<code>    while (1) {
      int childPid, status;

      // Display prompt and read input
      char *buffer = print_prompt();
      char *input = readline(buffer);
      check_and_free(buffer)

//    add input to readline history.
      add_history(input);
      time_t t;
      time(&t);
      add_history_time(ctime(&t));

      // Check for EOF.
      if (!input)
         break;

      parseInfo *result = parse(input);
      if (result == NULL) {
         goto free;
      }
      print_info(result);

      commandType *input_command = &result->CommArray[0];

//    execute builtin command in parent process
      int commType = isBuiltInCommand(input_command->command);
      if (commType == EXIT) {
         free_info(result);
         check_and_free(input)
         exit(0);
      }
      else if (commType != NO_SUCH_BUILTIN) {
         executeBuiltInCommand(input_command, commType, history_get_history_state());
      } else {
//       create a child process to execute command
         childPid = fork();
         if (childPid == 0) {
//          calls execvp
            printf("Executing child process...\n\n");
            executeCommand(input_command, result);
         } else {
            waitpid(childPid, &status, WNOHANG);
            if (status != 0) {
               printf("Error! Child exited with error code %d\n", WEXITSTATUS(status));
            }
         }
      }
      // Free buffer that was allocated by readline
      free:
      free_info(result);
      check_and_free(input)
   }
   return 0;
}
</code>```

`

I tried to execute a job in background and for quick ones like "ls" it just prints the output next to my prompt!

Body:
I am trying to implement my own shell and am experimenting with background jobs with using WNOHANG option in waitpid. But whenever I run a command in shell it just prints the output next to my prompt like this:

user@hostmachine:/.../$: [output]

Where am I going wrong?
`

    while (1) {
      int childPid, status;

      // Display prompt and read input
      char *buffer = print_prompt();
      char *input = readline(buffer);
      check_and_free(buffer)

//    add input to readline history.
      add_history(input);
      time_t t;
      time(&t);
      add_history_time(ctime(&t));

      // Check for EOF.
      if (!input)
         break;

      parseInfo *result = parse(input);
      if (result == NULL) {
         goto free;
      }
      print_info(result);

      commandType *input_command = &result->CommArray[0];

//    execute builtin command in parent process
      int commType = isBuiltInCommand(input_command->command);
      if (commType == EXIT) {
         free_info(result);
         check_and_free(input)
         exit(0);
      }
      else if (commType != NO_SUCH_BUILTIN) {
         executeBuiltInCommand(input_command, commType, history_get_history_state());
      } else {
//       create a child process to execute command
         childPid = fork();
         if (childPid == 0) {
//          calls execvp
            printf("Executing child process...\n\n");
            executeCommand(input_command, result);
         } else {
            waitpid(childPid, &status, WNOHANG);
            if (status != 0) {
               printf("Error! Child exited with error code %d\n", WEXITSTATUS(status));
            }
         }
      }
      // Free buffer that was allocated by readline
      free:
      free_info(result);
      check_and_free(input)
   }
   return 0;
}

`

I tried to execute a job in background and for quick ones like "ls" it just prints the output next to my prompt!


问:
Irregular bar spacing in barplot using ggplot2
I want to make a barplot in using ggplot2 where all of values in the data get their own bar on the x-axis. However, I get irregular spacing between the bars.

This is my code:

```<code>library("plyr")
dataTable <- count(player_data, "dpi")

ggplot(dataTable, aes(x = dpi, y = freq, fill = dpi)) +
    geom_bar(stat = "identity", width = 20)
</code>```

And this is the output:

Instead of plotting on a range of x values, I want to plot for the specific values of 'x' like a base R barplot does, like this:

Body:
I want to make a barplot in using ggplot2 where all of values in the data get their own bar on the x-axis. However, I get irregular spacing between the bars.

This is my code:

library("plyr")
dataTable <- count(player_data, "dpi")

ggplot(dataTable, aes(x = dpi, y = freq, fill = dpi)) +
    geom_bar(stat = "identity", width = 20)

And this is the output:

Instead of plotting on a range of x values, I want to plot for the specific values of 'x' like a base R barplot does, like this:


问:
How to use autowired services when using PhpUnit?
Was testing an application and was repeatable getting the infamous new entity not configured to cascade persist error.  I was surprised since I wasn't even creating new entities, and after digging into it, it appears to be relate to using different instances of the EntityManager object (I have confirmed that they are working with the same database, however) which I guess makes sense since each test will have a transaction applied.  The only way I was able to get rid of the errors was to use the entityManager in the container instead of the autowired ones.  While it works, it is a bit of a kludge and I would like to know the right way of doing this.  Thank you

namespace App\Tests;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
class MyTest extends ApiTestCase
{
    /**
     * @dataProvider getData
     */
    public function testWhichDoesNotWork(int $id, string $class)
    {
        $service = static::getContainer()->get(MyService::class);
        $user = $service->getUser();
        $randomEntity = $service->getRandomEntity($user->getTenant(), $class);
        $randomEntity->setSomething('something');
        $service->saveEntity($randomEntity);
    }

    /**
     * @dataProvider getData
     */
    public function testWhichWorks(int $id, string $class)
    {
        $service = static::getContainer()->get(MyService::class);
        $em = static::getContainer()->get(EntityManagerInterface::class);
        $user = $service->getUser();
        $randomId = $service->getRandomEntityId($user->getTenant(), $class);
        $randomEntity = $em->getRepository($class)->find($randomId);
        $randomEntity->setSomething('something');
        $em->persist($randomEntity);
        $em->flush();
    }

    /**
     * @dataProvider getData
     */
    public function testAnotherWhichWorks(int $id, string $class)
    {
        $service = static::getContainer()->get(MyService::class);
        $service->setNewEntityManager(static::getContainer()->get(EntityManagerInterface::class));
        $user = $service->getUser();
        $randomEntity = $service->getRandomEntity($user->getTenant(), $class);
        $randomEntity->setSomething('something');
        $service->saveEntity($randomEntity);
    }

    public function getData(): array
    {
        return [
            [123, SomeClass::class]
        ];
    }
}
```
<pre class="lang-php prettyprint-override"><code>namespace App\Test\Service;
final class MyService
{
    public function __construct(private EntityManagerInterface $entityManager)
    {}

    public function setNewEntityManager(EntityManagerInterface $entityManager):self
    {
        $this->entityManager = $entityManager;
        return $this;
    }

    public function getDatabase():string
    {
        return $this->entityManager->getConnection()->getDatabase();
    }

    public function getUser(int $id):User
    {
        return $this->entityManager->getRepository(User::class)->find($id);
    }

    public function getRandomId(Tenant $tenant, string $class):int
    {
        $meta = $this->entityManager->getClassMetadata($class);
        $_sql = 'SELECT %s FROM public.%s WHERE tenant_id=? OFFSET floor(random() * (SELECT COUNT(*) FROM public.%s WHERE tenant_id=?)) LIMIT 1;';
        $sql = sprintf($_sql, $meta->getSingleIdentifierFieldName(), $meta->getTableName(), $meta->getTableName());
        return $this->entityManager->getConnection()->prepare($sql)->execute([$tenant->getId(), $tenant->getId()])->fetchOne();
    }

    public function getRandomEntity(Tenant $tenant, string $class):object
    {
        return $this->entityManager->getRepository($class)->find($this->getRandomId($tenant, $class));
    }

    public function saveEntity(object $entity):self
    {
        $this->entityManager->persist($entity);
        $this->flush();
        return $this;
    }
}
</code>```

services:
    app.test.my.service:
        alias: App\Test\Service\MyService
        public: true
```

Body:
Was testing an application and was repeatable getting the infamous new entity not configured to cascade persist error.  I was surprised since I wasn't even creating new entities, and after digging into it, it appears to be relate to using different instances of the EntityManager object (I have confirmed that they are working with the same database, however) which I guess makes sense since each test will have a transaction applied.  The only way I was able to get rid of the errors was to use the entityManager in the container instead of the autowired ones.  While it works, it is a bit of a kludge and I would like to know the right way of doing this.  Thank you

namespace App\Tests;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
class MyTest extends ApiTestCase
{
    /**
     * @dataProvider getData
     */
    public function testWhichDoesNotWork(int $id, string $class)
    {
        $service = static::getContainer()->get(MyService::class);
        $user = $service->getUser();
        $randomEntity = $service->getRandomEntity($user->getTenant(), $class);
        $randomEntity->setSomething('something');
        $service->saveEntity($randomEntity);
    }

    /**
     * @dataProvider getData
     */
    public function testWhichWorks(int $id, string $class)
    {
        $service = static::getContainer()->get(MyService::class);
        $em = static::getContainer()->get(EntityManagerInterface::class);
        $user = $service->getUser();
        $randomId = $service->getRandomEntityId($user->getTenant(), $class);
        $randomEntity = $em->getRepository($class)->find($randomId);
        $randomEntity->setSomething('something');
        $em->persist($randomEntity);
        $em->flush();
    }

    /**
     * @dataProvider getData
     */
    public function testAnotherWhichWorks(int $id, string $class)
    {
        $service = static::getContainer()->get(MyService::class);
        $service->setNewEntityManager(static::getContainer()->get(EntityManagerInterface::class));
        $user = $service->getUser();
        $randomEntity = $service->getRandomEntity($user->getTenant(), $class);
        $randomEntity->setSomething('something');
        $service->saveEntity($randomEntity);
    }

    public function getData(): array
    {
        return [
            [123, SomeClass::class]
        ];
    }
}

namespace App\Test\Service;
final class MyService
{
    public function __construct(private EntityManagerInterface $entityManager)
    {}

    public function setNewEntityManager(EntityManagerInterface $entityManager):self
    {
        $this->entityManager = $entityManager;
        return $this;
    }

    public function getDatabase():string
    {
        return $this->entityManager->getConnection()->getDatabase();
    }

    public function getUser(int $id):User
    {
        return $this->entityManager->getRepository(User::class)->find($id);
    }

    public function getRandomId(Tenant $tenant, string $class):int
    {
        $meta = $this->entityManager->getClassMetadata($class);
        $_sql = 'SELECT %s FROM public.%s WHERE tenant_id=? OFFSET floor(random() * (SELECT COUNT(*) FROM public.%s WHERE tenant_id=?)) LIMIT 1;';
        $sql = sprintf($_sql, $meta->getSingleIdentifierFieldName(), $meta->getTableName(), $meta->getTableName());
        return $this->entityManager->getConnection()->prepare($sql)->execute([$tenant->getId(), $tenant->getId()])->fetchOne();
    }

    public function getRandomEntity(Tenant $tenant, string $class):object
    {
        return $this->entityManager->getRepository($class)->find($this->getRandomId($tenant, $class));
    }

    public function saveEntity(object $entity):self
    {
        $this->entityManager->persist($entity);
        $this->flush();
        return $this;
    }
}

services:
    app.test.my.service:
        alias: App\Test\Service\MyService
        public: true


问:
Scrapy (python) only collecting 75% of target web pages - how to improve
I'm using Scrapy to collect about 150 attributes for Cloud Services listed on the UK Gov Digital Marketplace (G-Cloud). The catalogue holds details of about 40,000 services accessed through summary pages with 30 products to a page (1,355 pages). Things have been going fine for 5 or 6 years. Now the catalogue has been moved to a new URL. I have repaired all the Xpaths and tested and I am getting all the data I need when a product is hit.

But comparing my downloaded product count to the total on the catalogue, I am getting only 30,000 products - missing 25%.

"custom_settings" includes 'AUTOTHROTTLE_START_DELAY': .5,
'AUTOTHROTTLE_MAX_DELAY': 60,

Would changing these settings improve my harvest?

What else can you suggest may be impacting my low yield?

For completeness, here is the pagination function, which seems to work effectively, so I don't think the fault lies here:

    def parse(self, response):
        for link in response.xpath('//h2/a/@href').getall():
            yield scrapy.Request(response.urljoin(link), callback=self.parse_item)

        next_page = response.xpath('//li[@class="dm-pagination__item dm-pagination__item--next"]/a/@href').get()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
```

Historically, I never get the full product count as a small number are suspended for editing or deletion. But this would be less then 1%. The script takes roughly 15 hours to run from my desktop. I am running the script repeatedly to see if the outcome is consistent and if the missing products are always the same ones. Due to the long run-time it will be a week or so before I have sufficient data to draw a conclusion.

Body:
I'm using Scrapy to collect about 150 attributes for Cloud Services listed on the UK Gov Digital Marketplace (G-Cloud). The catalogue holds details of about 40,000 services accessed through summary pages with 30 products to a page (1,355 pages). Things have been going fine for 5 or 6 years. Now the catalogue has been moved to a new URL. I have repaired all the Xpaths and tested and I am getting all the data I need when a product is hit.

But comparing my downloaded product count to the total on the catalogue, I am getting only 30,000 products - missing 25%.

"custom_settings" includes 'AUTOTHROTTLE_START_DELAY': .5,
'AUTOTHROTTLE_MAX_DELAY': 60,

Would changing these settings improve my harvest?

What else can you suggest may be impacting my low yield?

For completeness, here is the pagination function, which seems to work effectively, so I don't think the fault lies here:

    def parse(self, response):
        for link in response.xpath('//h2/a/@href').getall():
            yield scrapy.Request(response.urljoin(link), callback=self.parse_item)

        next_page = response.xpath('//li[@class="dm-pagination__item dm-pagination__item--next"]/a/@href').get()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)

Historically, I never get the full product count as a small number are suspended for editing or deletion. But this would be less then 1%. The script takes roughly 15 hours to run from my desktop. I am running the script repeatedly to see if the outcome is consistent and if the missing products are always the same ones. Due to the long run-time it will be a week or so before I have sufficient data to draw a conclusion.


问:
How do I record audio using a microphone and play it in a speaker simultaneously by only storing one sec of Audio in LINUX
I am now working on a Audio algorithm which need 256 samples of audio from a micro phone and i need to process this 256 samples and result should get played  on a speaker. I have done it using two wave file which is already on the file, now i need to do it in the real time.

Need a solution for this


问:
VS Code Terminal Not Working - no fix found
I recently updated Powershell and since my integrated terminal is VS Code has not been working (not just PS but also WSL and others). Therefore I do not believe that is the culprit. I looked online for fixes and even re-installed VS Code to no avail. How can I get my terminal back up and running?

Here is my settings.json:

```<code>{
    "security.workspace.trust.untrustedFiles": "open",
    "terminal.integrated.sendKeybindingsToShell": true,
    "files.autoSave": "afterDelay",
    "editor.fontSize": 12,
    "sonarlint.ls.javaHome": "C:\\Program Files\\Java\\jdk-18.0.1",
    "redhat.telemetry.enabled": true,
    "explorer.confirmDelete": false,
    "java.configuration.runtimes": [
        {
            "name": "JavaSE-18",
            "path": "C:\\Program Files\\Java\\jdk-18.0.1",
            "default": true
        }
    ],
    "liveServer.settings.donotShowInfoMsg": true,
    "explorer.confirmDragAndDrop": false,
    "editor.bracketPairColorization.enabled": true,
    "editor.guides.bracketPairs": "active",
    "prettier.bracketSpacing": false,
    "prettier.semi": false,
    "prettier.useTabs": true,
    "prettier.withNodeModules": true,
    "color-highlight.matchRgbWithNoFunction": true,
    "color-highlight.matchWords": true,
    "terminal.integrated.defaultProfile.windows": "Ubuntu (WSL)",
    "terminal.integrated.automationProfile.windows": {},
    "[dart]": {
        "editor.formatOnSave": true,
        "editor.formatOnType": true,
        "editor.rulers": [80],
        "editor.selectionHighlight": false,
        "editor.suggest.snippetsPreventQuickSuggestions": false,
        "editor.suggestSelection": "first",
        "editor.tabCompletion": "onlySnippets",
        "editor.wordBasedSuggestions": false
    },
    "javascript.updateImportsOnFileMove.enabled": "always",
    "editor.tabSize": 2,
    "window.zoomLevel": 1,
    "terminal.integrated.defaultProfile.linux": "",
    "editor.formatOnSave": true,
    "prettier.singleQuote": true,
    "jshint.config": "",
    "jshint.options": {
        "esversion": 9
    },
    "vs-kubernetes": {
        "vs-kubernetes.namespace": "",
        "vs-kubernetes.kubectl-path": "",
        "vs-kubernetes.helm-path": "",
        "vs-kubernetes.minikube-path": "",
        "vs-kubernetes.kubectlVersioning": "user-provided",
        "vs-kubernetes.outputFormat": "yaml",
        "vs-kubernetes.kubeconfig": "",
        "vs-kubernetes.knownKubeconfigs": [],
        "vs-kubernetes.autoCleanupOnDebugTerminate": false,
        "vs-kubernetes.nodejs-autodetect-remote-root": true,
        "vs-kubernetes.nodejs-remote-root": "",
        "vs-kubernetes.nodejs-debug-port": 9229,
        "vs-kubernetes.dotnet-vsdbg-path": "~/vsdbg/vsdbg",
        "vs-kubernetes.local-tunnel-debug-provider": "",
        "checkForMinikubeUpgrade": true,
        "imageBuildTool": "Docker",
        "disable-linters": ["resource-limits"]
    },
    "terminal.integrated.env.linux": {},
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "rsp-ui.enableStartServerOnActivation": [
        {
            "id": "redhat.vscode-community-server-connector",
            "name": "Community Server Connector",
            "startOnActivation": true
        }
    ],
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "editor.accessibilitySupport": "off"
}
</code>```

Body:
I recently updated Powershell and since my integrated terminal is VS Code has not been working (not just PS but also WSL and others). Therefore I do not believe that is the culprit. I looked online for fixes and even re-installed VS Code to no avail. How can I get my terminal back up and running?

Here is my settings.json:

{
    "security.workspace.trust.untrustedFiles": "open",
    "terminal.integrated.sendKeybindingsToShell": true,
    "files.autoSave": "afterDelay",
    "editor.fontSize": 12,
    "sonarlint.ls.javaHome": "C:\\Program Files\\Java\\jdk-18.0.1",
    "redhat.telemetry.enabled": true,
    "explorer.confirmDelete": false,
    "java.configuration.runtimes": [
        {
            "name": "JavaSE-18",
            "path": "C:\\Program Files\\Java\\jdk-18.0.1",
            "default": true
        }
    ],
    "liveServer.settings.donotShowInfoMsg": true,
    "explorer.confirmDragAndDrop": false,
    "editor.bracketPairColorization.enabled": true,
    "editor.guides.bracketPairs": "active",
    "prettier.bracketSpacing": false,
    "prettier.semi": false,
    "prettier.useTabs": true,
    "prettier.withNodeModules": true,
    "color-highlight.matchRgbWithNoFunction": true,
    "color-highlight.matchWords": true,
    "terminal.integrated.defaultProfile.windows": "Ubuntu (WSL)",
    "terminal.integrated.automationProfile.windows": {},
    "[dart]": {
        "editor.formatOnSave": true,
        "editor.formatOnType": true,
        "editor.rulers": [80],
        "editor.selectionHighlight": false,
        "editor.suggest.snippetsPreventQuickSuggestions": false,
        "editor.suggestSelection": "first",
        "editor.tabCompletion": "onlySnippets",
        "editor.wordBasedSuggestions": false
    },
    "javascript.updateImportsOnFileMove.enabled": "always",
    "editor.tabSize": 2,
    "window.zoomLevel": 1,
    "terminal.integrated.defaultProfile.linux": "",
    "editor.formatOnSave": true,
    "prettier.singleQuote": true,
    "jshint.config": "",
    "jshint.options": {
        "esversion": 9
    },
    "vs-kubernetes": {
        "vs-kubernetes.namespace": "",
        "vs-kubernetes.kubectl-path": "",
        "vs-kubernetes.helm-path": "",
        "vs-kubernetes.minikube-path": "",
        "vs-kubernetes.kubectlVersioning": "user-provided",
        "vs-kubernetes.outputFormat": "yaml",
        "vs-kubernetes.kubeconfig": "",
        "vs-kubernetes.knownKubeconfigs": [],
        "vs-kubernetes.autoCleanupOnDebugTerminate": false,
        "vs-kubernetes.nodejs-autodetect-remote-root": true,
        "vs-kubernetes.nodejs-remote-root": "",
        "vs-kubernetes.nodejs-debug-port": 9229,
        "vs-kubernetes.dotnet-vsdbg-path": "~/vsdbg/vsdbg",
        "vs-kubernetes.local-tunnel-debug-provider": "",
        "checkForMinikubeUpgrade": true,
        "imageBuildTool": "Docker",
        "disable-linters": ["resource-limits"]
    },
    "terminal.integrated.env.linux": {},
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "rsp-ui.enableStartServerOnActivation": [
        {
            "id": "redhat.vscode-community-server-connector",
            "name": "Community Server Connector",
            "startOnActivation": true
        }
    ],
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "editor.accessibilitySupport": "off"
}


问:
getCookie(name) in django for paypal integration
`I am trying to integrate paypal payment in one website. I need paypal payment id and status response. I have a paypal button integrated already using paypal.Buttons function.

The problem I face is if I use csrf token, the paypal button disappears from the page. If I am not using the csrf then the function will work, but with errors "Forbidden (CSRF token missing.):". If I remove  " 'X-CSRFToken': 'csrftoken'  " from function sendData() and "var csrftoken = getCookie('csrftoken');" then the paypal button will appear again.

```<code>var csrftoken = getCookie('csrftoken');
var url = "{% url 'payments' %}"     // payments is a custom name
var orderID = "{{ order.order_number }}"
var payment_method = " PayPal"

function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = docodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

function sendData() {
                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': 'csrftoken',
                        },
                        body: JSON.stringify({
                            orderID: orderID,
                            transID: details.id,   // from paypal response
                            payment_method: payment_method,
                            status: details.status,  // from paypal response
                        }),
                    })
                }
</code>```

I have tried with multiple getCookie function. The error is with the csrftoken for sure. Expecting a support for this issue. Thanks in advance. `

Body:
`I am trying to integrate paypal payment in one website. I need paypal payment id and status response. I have a paypal button integrated already using paypal.Buttons function.

The problem I face is if I use csrf token, the paypal button disappears from the page. If I am not using the csrf then the function will work, but with errors "Forbidden (CSRF token missing.):". If I remove  " 'X-CSRFToken': 'csrftoken'  " from function sendData() and "var csrftoken = getCookie('csrftoken');" then the paypal button will appear again.

var csrftoken = getCookie('csrftoken');
var url = "{% url 'payments' %}"     // payments is a custom name
var orderID = "{{ order.order_number }}"
var payment_method = " PayPal"

function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = docodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

function sendData() {
                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': 'csrftoken',
                        },
                        body: JSON.stringify({
                            orderID: orderID,
                            transID: details.id,   // from paypal response
                            payment_method: payment_method,
                            status: details.status,  // from paypal response
                        }),
                    })
                }

I have tried with multiple getCookie function. The error is with the csrftoken for sure. Expecting a support for this issue. Thanks in advance. `


问:
Parameter #1 $object of method expects x given y - abstract entities
I have a abstract class User:

abstract class User
```
<p>and a child of User, "Administrator":</p>
<pre class="lang-php prettyprint-override"><code>class Administrator extends User
</code>```

When i create a new Administrator and want to persist with this signature:

public function persist(Administrator $object): void
```
<pre class="lang-php prettyprint-override"><code>$this->repo->persist(new Administrator())
</code>```

PHPSTAN is complaining:

Parameter #1 $object of method AdministratorRepository::persist() expects Administrator, User given

Why it thinks it's User where i am instantiating an new Administrator directly?
I think its about Covariance and Contravariance but cant figure out how to tell PHPSTAN correctly?

I checked the https://phpstan.org/blog/whats-up-with-template-covariant but did not get a solution to work properly.

Body:
I have a abstract class User:

abstract class User

and a child of User, "Administrator":

class Administrator extends User

When i create a new Administrator and want to persist with this signature:

public function persist(Administrator $object): void

$this->repo->persist(new Administrator())

PHPSTAN is complaining:

Parameter #1 $object of method AdministratorRepository::persist() expects Administrator, User given

Why it thinks it's User where i am instantiating an new Administrator directly?
I think its about Covariance and Contravariance but cant figure out how to tell PHPSTAN correctly?

I checked the https://phpstan.org/blog/whats-up-with-template-covariant but did not get a solution to work properly.


问:
svg html string to UIImage
I have a svg html sting, it looks like that:

```<code>   let svg = """
            <svg aria-hidden="true" class="pre-logo-svg" focusable="false" viewbox="0 0 24 24" role="img" width="60px" height="60px" fill="none">
             <path fill="currentColor" fill-rule="evenodd" d="M21 8.719L7.836 14.303C6.74 14.768 5.818 15 5.075 15c-.836 0-1.445-.295-1.819-.884-.485-.76-.273-1.982.559-3.272.494-.754 1.122-1.446 1.734-2.108-.144.234-1.415 2.349-.025 3.345.275.2.666.298 1.147.298.386 0 .829-.063 1.316-.19L21 8.719z" clip-rule="evenodd"></path> </svg>
            """
</code>```

I want to load it into an UIImageView. So I convert it to data and use it in an UIImage

```<code> let data = Data(svg.utf8)
 imageView.image = UIImage(data: data)
</code>```

but UIImage(data: data) is nil, so I use SVGKitlibrary to do that

```<code> let data = Data(svg.utf8)
 let svgImage = SVGKImage(data: data)
 imageView.image = svgImage?.uiImage
</code>```

But it's same, could anyone help me on it
Thanks

Title: svg html string to UIImage

Body:
I have a svg html sting, it looks like that:

   let svg = """
            <svg aria-hidden="true" class="pre-logo-svg" focusable="false" viewbox="0 0 24 24" role="img" width="60px" height="60px" fill="none">
             <path fill="currentColor" fill-rule="evenodd" d="M21 8.719L7.836 14.303C6.74 14.768 5.818 15 5.075 15c-.836 0-1.445-.295-1.819-.884-.485-.76-.273-1.982.559-3.272.494-.754 1.122-1.446 1.734-2.108-.144.234-1.415 2.349-.025 3.345.275.2.666.298 1.147.298.386 0 .829-.063 1.316-.19L21 8.719z" clip-rule="evenodd"></path> </svg>
            """

I want to load it into an UIImageView. So I convert it to data and use it in an UIImage

 let data = Data(svg.utf8)
 imageView.image = UIImage(data: data)

but UIImage(data: data) is nil, so I use SVGKitlibrary to do that

 let data = Data(svg.utf8)
 let svgImage = SVGKImage(data: data)
 imageView.image = svgImage?.uiImage

But it's same, could anyone help me on it
Thanks


问:
How can I associate text box with radio button group
I am trying to prepare a simple form. My form has 3 radio buttons and 1 text/numeric input box.
This is supposed work like this, user can choose to click on radio 1,2 or 3 that is alright, but if the user chooses to click radio 4, it reveals a text box where user can input text. So saying this simple, the user input from radio 1 or 2 or 3 or text box only is collected. But i am not able to do this....phew....and i can collect user input upon form submission but don't have any idea how to restrict user only to choose 1 option out of these 4.</p>
```<code><div class="panel-group" id="accordion">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Present</a>
        </h4>
      </div>
      <div id="collapse1" class="panel-collapse collapse in">
        <div class="panel-body"><input class="form-control input-lg text-left" name="1" id="1" type="text"></div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Absent</a>
        </h4>
      </div>
      <div id="collapse2" class="panel-collapse collapse">
        <div class="panel-body"><input type="radio" id="Absent" name="jan1" value="Absent"></div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Holiday</a>
        </h4>
      </div>
      <div id="collapse3" class="panel-collapse collapse">
        <div class="panel-body"><input type="radio" id="Holiday" name="jan1" value="Holiday"></div>
      </div>
    </div>
  </div>
</code>```

Body:
I am trying to prepare a simple form. My form has 3 radio buttons and 1 text/numeric input box.
This is supposed work like this, user can choose to click on radio 1,2 or 3 that is alright, but if the user chooses to click radio 4, it reveals a text box where user can input text. So saying this simple, the user input from radio 1 or 2 or 3 or text box only is collected. But i am not able to do this....phew....and i can collect user input upon form submission but don't have any idea how to restrict user only to choose 1 option out of these 4.

          Present

<input class="form-control input-lg text-left" name="1" id="1" type="text">

          Absent

<input type="radio" id="Absent" name="jan1" value="Absent">

          Holiday

<input type="radio" id="Holiday" name="jan1" value="Holiday">


问:
Hash table word count
At the following code is the wordCount

```<code>public List<Link<String, Integer>> countWords(String filename) throws IOException {
        List<String> lines = readFile(filename);

        for(String line : lines) {
            line = removePunctuation(line);

            List<String> words = splitLineIntoWords(line);
            for(String word : words) {
                // lowercase the word to count all capitalization as same word
                word = word.toLowerCase().trim();
                if(word.isBlank()) {
                    continue;
                }

                // TODO implement

                // Does this word exist in the hash table?

                // If not, create a new entry with the word as the key
                // and the data is the integer 1 (to represent one instance of the word)

                // If the value does exist, update the node's data to add 1 to the count
                // because another instance of the word has been found
                Link<String, Integer> wordLink = wordMap.find(word);
                if (wordLink != null) {
                    // If the word exists, update the value to add 1 to the count
                    wordMap.insert(word, wordMap.hashFunc(word) + 1);
                } else {
                    // If the word doesn't exist, add the word as a new key with a value of 1
                    wordMap.insert(word, 1);
                }
            }
        }
</code>```

base on the test file below the “a_Christmas_carol.txt “file should contain 4428 unique word

@Test
void testCountWords() throws IOException {
List<Link<String, Integer>> words = wordCount.countWords("a_christmas_carol.txt");

```<code>    Assertions.assertEquals(4428, words.size(), "a_christmas_carol.txt file should contain 4428 unique words");

    Link<String, Integer> tiny = wordCount.wordMap.find("tiny");
    Assertions.assertNotNull(tiny, "The word 'tiny' should exist");
    Assertions.assertEquals(26, tiny.getData(), "The word 'tiny' should occur 26 times");

    Link<String, Integer> humbug = wordCount.wordMap.find("humbug");
    Assertions.assertNotNull(humbug, "The word 'humbug' should exist");
    Assertions.assertEquals(33, humbug.getData(), "The word 'humbug' should occur 33 times");
}
</code>```

When I run the test file it failed the results shows :
Expected:4428
Actual: 32304

The actual results is wordCount number is too big it goes to 32304, even though when add uniqueword method the wordCount still too big not close to the expected number

Title: Hash table word count

Body:
At the following code is the wordCount

public List<Link<String, Integer>> countWords(String filename) throws IOException {
        List<String> lines = readFile(filename);

        for(String line : lines) {
            line = removePunctuation(line);

            List<String> words = splitLineIntoWords(line);
            for(String word : words) {
                // lowercase the word to count all capitalization as same word
                word = word.toLowerCase().trim();
                if(word.isBlank()) {
                    continue;
                }

                // TODO implement

                // Does this word exist in the hash table?

                // If not, create a new entry with the word as the key
                // and the data is the integer 1 (to represent one instance of the word)

                // If the value does exist, update the node's data to add 1 to the count
                // because another instance of the word has been found
                Link<String, Integer> wordLink = wordMap.find(word);
                if (wordLink != null) {
                    // If the word exists, update the value to add 1 to the count
                    wordMap.insert(word, wordMap.hashFunc(word) + 1);
                } else {
                    // If the word doesn't exist, add the word as a new key with a value of 1
                    wordMap.insert(word, 1);
                }
            }
        }

base on the test file below the “a_Christmas_carol.txt “file should contain 4428 unique word

@Test
void testCountWords() throws IOException {
List<Link<String, Integer>> words = wordCount.countWords("a_christmas_carol.txt");

    Assertions.assertEquals(4428, words.size(), "a_christmas_carol.txt file should contain 4428 unique words");

    Link<String, Integer> tiny = wordCount.wordMap.find("tiny");
    Assertions.assertNotNull(tiny, "The word 'tiny' should exist");
    Assertions.assertEquals(26, tiny.getData(), "The word 'tiny' should occur 26 times");

    Link<String, Integer> humbug = wordCount.wordMap.find("humbug");
    Assertions.assertNotNull(humbug, "The word 'humbug' should exist");
    Assertions.assertEquals(33, humbug.getData(), "The word 'humbug' should occur 33 times");
}

When I run the test file it failed the results shows :
Expected:4428
Actual: 32304

The actual results is wordCount number is too big it goes to 32304, even though when add uniqueword method the wordCount still too big not close to the expected number


问:
How to use Material UI in react version 16.5.2
I am trying to use Material UI select in react version 16.5.2 However I am unable to use useState since that hook can only be used by react 16.8.0 and above.

Is there any way to use Material UI select in 16.5.2 without using useState?

```<code>import React, { useEffect, useState } from "react";
import { withTaskContext } from "@twilio/flex-ui";
import { selectCurrentEntity } from "../helpers/channelIntegrationFramework";
import "./styles.css";
import TextField from "@material-ui/core/TextField";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";

class VoiceCallComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      functionsBaseUrl: this.props.functionsBaseUrl,
      settingsBaseUrl: this.props.settingsBaseUrl,
    };

    this.init();
  }

  init = () => {
    console.log(
      `Connector: -- VoiceCallComponent -- functionsBaseUrl: ${this.state.functionsBaseUrl} -- settingsBaseUrl: ${this.state.settingsBaseUrl}`
    );
  };

  render() {
    console.log("Connector: ====== render ========");
    const [disposition, setDisposition] = useState("");
    console.log("disposition :- ", { disposition });
    const { task } = this.props;
    return (
      <div class="Twilio-TaskInfoPanel-default css-18ljn0d">
        <span class="Twilio" />
        <h1>Notes:</h1>
        <ul>
          <TextField
            style={{
              textAlign: "left",
              margin: "0px",
              width: "250px",
              height: "55px",
            }}
            hintText="Message Field"
            floatingLabelText="Note"
            multiline
            rows={2}
            maxRows={5}
            value={this.state.callnotes}
            onChange={this.handleChange}
          />
          <p style={{ marginTop: "5px" }}></p>
          <label style={{ fontWeight: "700" }}>Disposition*: </label>

          <FormControl fullWidth>
            <InputLabel id="disposition-label">Disposition*:</InputLabel>
            <select
              labelId="disposition-label"
              id="disposition-select-label"
              value={disposition}
              onChange={handleSelectChange}
              fullWidth
            >
              <MenuItem value={"11"}>Contacted</MenuItem>
              <MenuItem value={"22"}>Bad Number</MenuItem>
              <MenuItem value={"33"}>Hung up on Call</MenuItem>
            </select>
          </FormControl>
</div>
);
}
}

export default withTaskContext(VoiceCallComponent);
</code>```

The above code is throwing error since I am not using react version 16.8.0.

Body:
I am trying to use Material UI select in react version 16.5.2 However I am unable to use useState since that hook can only be used by react 16.8.0 and above.

Is there any way to use Material UI select in 16.5.2 without using useState?

import React, { useEffect, useState } from "react";
import { withTaskContext } from "@twilio/flex-ui";
import { selectCurrentEntity } from "../helpers/channelIntegrationFramework";
import "./styles.css";
import TextField from "@material-ui/core/TextField";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";

class VoiceCallComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      functionsBaseUrl: this.props.functionsBaseUrl,
      settingsBaseUrl: this.props.settingsBaseUrl,
    };

    this.init();
  }

  init = () => {
    console.log(
      `Connector: -- VoiceCallComponent -- functionsBaseUrl: ${this.state.functionsBaseUrl} -- settingsBaseUrl: ${this.state.settingsBaseUrl}`
    );
  };

  render() {
    console.log("Connector: ====== render ========");
    const [disposition, setDisposition] = useState("");
    console.log("disposition :- ", { disposition });
    const { task } = this.props;
    return (

Notes:

          <TextField
            style={{
              textAlign: "left",
              margin: "0px",
              width: "250px",
              height: "55px",
            }}
            hintText="Message Field"
            floatingLabelText="Note"
            multiline
            rows={2}
            maxRows={5}
            value={this.state.callnotes}
            onChange={this.handleChange}
          />

          Disposition*:

          <FormControl fullWidth>
            <InputLabel id="disposition-label">Disposition*:</InputLabel>
            <select
              labelId="disposition-label"
              id="disposition-select-label"
              value={disposition}
              onChange={handleSelectChange}
              fullWidth
            >
              <MenuItem value={"11"}>Contacted</MenuItem>
              <MenuItem value={"22"}>Bad Number</MenuItem>
              <MenuItem value={"33"}>Hung up on Call</MenuItem>
            </select>
          </FormControl>

);
}
}

export default withTaskContext(VoiceCallComponent);

The above code is throwing error since I am not using react version 16.8.0.


问:
What the CADisplayLink's timestamp actually is?
I've been playing with functionality of CADisplayLink to programmatically monitor rendering performance in an iOS app. Also spent quite some time in Instruments, of course, but curious of what it looks like in the field and for specific screens in the app.

The documentation says that a CADisplayLink timer object

allows your app to synchronize its drawing to the refresh rate of the display.

which makes me expect that the provided selector is called somewhat close to vsync events emitted by the underlying hardware. Also, the timestamp property is defined as follows:

The time interval that represents when the last frame displayed.

So I just use the two successive callbacks to figure out the on-screen duration of the frame and decide if there was a hitch or not, like so:

```<code>@objc private func handleDisplayUpdate(_ displayLink: CADisplayLink) {
    defer { cachedTimestamp = displayLink.timestamp }
    guard let cachedTimestamp = cachedTimestamp else { return }
    let frameTime = displayLink.timestamp - cachedTimestamp
    if frameTime > aThreshold {
      // do some lightweight logging
    }
}
</code>```

By using CACurrentMediaTime() call I can see that the handler is called pretty close to what the latest timestamp holds, so it is 1ms-ish behind the recent frame update. However the frameTime intervals are not always a multiple of 16.67ms (assuming the device renders @60fps): while scrolling I can observe the numbers being e.g. 25ms or 43ms.

Given that frames are swapped onto the display at vsync points in time only, does the above mean that the timestamp property actually represents something else in the whole render loop?

Body:
I've been playing with functionality of CADisplayLink to programmatically monitor rendering performance in an iOS app. Also spent quite some time in Instruments, of course, but curious of what it looks like in the field and for specific screens in the app.

The documentation says that a CADisplayLink timer object

allows your app to synchronize its drawing to the refresh rate of the display.

which makes me expect that the provided selector is called somewhat close to vsync events emitted by the underlying hardware. Also, the timestamp property is defined as follows:

The time interval that represents when the last frame displayed.

So I just use the two successive callbacks to figure out the on-screen duration of the frame and decide if there was a hitch or not, like so:

@objc private func handleDisplayUpdate(_ displayLink: CADisplayLink) {
    defer { cachedTimestamp = displayLink.timestamp }
    guard let cachedTimestamp = cachedTimestamp else { return }
    let frameTime = displayLink.timestamp - cachedTimestamp
    if frameTime > aThreshold {
      // do some lightweight logging
    }
}

By using CACurrentMediaTime() call I can see that the handler is called pretty close to what the latest timestamp holds, so it is 1ms-ish behind the recent frame update. However the frameTime intervals are not always a multiple of 16.67ms (assuming the device renders @60fps): while scrolling I can observe the numbers being e.g. 25ms or 43ms.

Given that frames are swapped onto the display at vsync points in time only, does the above mean that the timestamp property actually represents something else in the whole render loop?


问:
MariaDB/InnoDB performance: composite primary key vs. unused surrogate integer primary key to a table?
Years ago with MySQL/InnoDB, I've researched and found that adding a surrogate integer primary key to a table which doesn't have it always makes sense for performance reason. Even if that key is never used in JOINs or child tables. That's because of the clustered index used in InnoDB meaning the table records are sorted by the primary key and as such, any key that's not a simple AUTOINC may mean different pages have to be continuously accessed and updated when making INSERTs rather than just the last page.

As we're now with MariaDB/InnoDB and I can't seem to find updated data on this topic, I'm asking this question in hopes for additional specific references and performance/integrity considerations.

It is quite clear that primary keys should always exist and integer (the smaller the better) is the preferred thing to have but in case such doesn't naturally make sense for the table, should some fakeid primary key be created, even when there are no JOINs done which will use it directly nor are there any child tables?

I'm guessing the answer is a yes if the natural primary key is a string but what if it's a composite primary key? For example my_table(category_id, item_id, detailA, detailB) where the natural primary key would be category_id+item_id (both integers)? Would it make sense to add an integer fakeid to that table so that we'll have a single integer primary key?

This question isn't about the theoretical SQL concept but about current implementation of MariaDB (now at v10.6.x).


问:
stable baseline, how can we sample reproducible env value with each episode
Iam trying to use DDPG (stable baseline3) to solve a problem.

I would like to know, how can we change the env sampled values with every episode "and it should be reproducible", using stable baseline.

for example, assume we have an env where we harvest energy, we assume that the harvested energy is normally distributed for example, and then in every episode, I will sample DIFFERENT Values of my harvested energy.I would just like to emphasize again, that I would like that the different values of my harvested energy should be reproducible, so I can compare the RL method to other methods. PS: using stable baseline


问:
The right way to copy object or array of objects without passing reference?
The right way to copy object or array of objects without passing reference? I having an issue with this sample of code.

```<code>let raw = { rows: [{a: 1, b: 2}, {a: 2, b: 1}] };
let rows = new Array();

for(let x in raw.rows) {
    if(App.isObjectHas(x, raw.rows)) {
        rows[App.getLength(rows)] = raw.rows[x];
    }
}
for(let x=0; x<App.getLength(rows); x++) {
    (function(row) {
        // i modify the rows[x] but raw.rows[x] follow
        row.a = 5; console.log(raw.rows[x]);
    }.bind(this))(rows[x]);
}
</code>```

I want to modify raw.rows but keep its originality for later use (repeating process) so i thougt with the first loop i copying its value not its reference, since both declared differently. Using new Object instead of new Array doesn't effect same as using anonymous function on both loops.

Body:
The right way to copy object or array of objects without passing reference? I having an issue with this sample of code.

let raw = { rows: [{a: 1, b: 2}, {a: 2, b: 1}] };
let rows = new Array();

for(let x in raw.rows) {
    if(App.isObjectHas(x, raw.rows)) {
        rows[App.getLength(rows)] = raw.rows[x];
    }
}
for(let x=0; x<App.getLength(rows); x++) {
    (function(row) {
        // i modify the rows[x] but raw.rows[x] follow
        row.a = 5; console.log(raw.rows[x]);
    }.bind(this))(rows[x]);
}

I want to modify raw.rows but keep its originality for later use (repeating process) so i thougt with the first loop i copying its value not its reference, since both declared differently. Using new Object instead of new Array doesn't effect same as using anonymous function on both loops.


问:
unable to display acf values in woocommerce order page
I create a custom field "Upload Invoice" in ACF, having PDF files to upload in woocommerce order page. It working fine when admin upload pdf in order page, but at customer dashboard I am unable to call that PDF uploaded by admin.

kindly suggest

https://xxxxxxxxxx/my-account/view-order/196121629/
having code

```<code><?php
/**
 * View Order
 *
 * Shows the details of a particular order on the account page.
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/myaccount/view-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.0.0
 */

defined( 'ABSPATH' ) || exit;

$notes = $order->get_customer_order_notes();
?>
<p>
<?php
printf(
    /* translators: 1: order number 2: order date 3: order status */
    esc_html__( 'Order #%1$s was placed on %2$s and is currently %3$s.', 'woocommerce' ),
    '<mark class="order-number">' . $order->get_order_number() . '</mark>', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '<mark class="order-date">' . wc_format_datetime( $order->get_date_created() ) . '</mark>', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '<mark class="order-status">' . wc_get_order_status_name( $order->get_status() ) . '</mark>' // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
);
?>
</p>

<?php if ( $notes ) : ?>
    <h2><?php esc_html_e( 'Order updates', 'woocommerce' ); ?></h2>
    <ol class="woocommerce-OrderUpdates commentlist notes">
        <?php foreach ( $notes as $note ) : ?>
        <li class="woocommerce-OrderUpdate comment note">
            <div class="woocommerce-OrderUpdate-inner comment_container">
                <div class="woocommerce-OrderUpdate-text comment-text">
                    <p class="woocommerce-OrderUpdate-meta meta"><?php echo date_i18n( esc_html__( 'l jS \o\f F Y, h:ia', 'woocommerce' ), strtotime( $note->comment_date ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
                    <div class="woocommerce-OrderUpdate-description description">
                        <?php echo wpautop( wptexturize( $note->comment_content ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                    </div>

                    <div class="clear"></div>
                </div>
                <div class="clear"></div>
            </div>
        </li>
        <?php endforeach; ?>
    </ol>
<?php endif; ?>

<?php do_action( 'woocommerce_view_order', $order_id );
</code>```
```<code><?php
/**
 * View Order
 *
 * Shows the details of a particular order on the account page.
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/myaccount/view-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.0.0
 */

defined( 'ABSPATH' ) || exit;

$notes = $order->get_customer_order_notes();
?>
<p>
<?php
printf(
    /* translators: 1: order number 2: order date 3: order status */
    esc_html__( 'Order #%1$s was placed on %2$s and is currently %3$s.', 'woocommerce' ),
    '<mark class="order-number">' . $order->get_order_number() . '</mark>', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '<mark class="order-date">' . wc_format_datetime( $order->get_date_created() ) . '</mark>', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '<mark class="order-status">' . wc_get_order_status_name( $order->get_status() ) . '</mark>' // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
);
?>
</p>

<?php if ( $notes ) : ?>
    <h2><?php esc_html_e( 'Order updates', 'woocommerce' ); ?></h2>
    <ol class="woocommerce-OrderUpdates commentlist notes">
        <?php foreach ( $notes as $note ) : ?>
        <li class="woocommerce-OrderUpdate comment note">
            <div class="woocommerce-OrderUpdate-inner comment_container">
                <div class="woocommerce-OrderUpdate-text comment-text">
                    <p class="woocommerce-OrderUpdate-meta meta"><?php echo date_i18n( esc_html__( 'l jS \o\f F Y, h:ia', 'woocommerce' ), strtotime( $note->comment_date ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
                    <div class="woocommerce-OrderUpdate-description description">
                        <?php echo wpautop( wptexturize( $note->comment_content ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                    </div>

                    <div class="clear"></div>
                </div>
                <div class="clear"></div>
            </div>
        </li>
        <?php endforeach; ?>
    </ol>
<?php endif; ?>

<?php do_action( 'woocommerce_view_order', $order_id );
</code>```

Body:
I create a custom field "Upload Invoice" in ACF, having PDF files to upload in woocommerce order page. It working fine when admin upload pdf in order page, but at customer dashboard I am unable to call that PDF uploaded by admin.

kindly suggest

https://xxxxxxxxxx/my-account/view-order/196121629/
having code

<?php
/**
 * View Order
 *
 * Shows the details of a particular order on the account page.
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/myaccount/view-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.0.0
 */

defined( 'ABSPATH' ) || exit;

$notes = $order->get_customer_order_notes();
?>

<?php
printf(
    /* translators: 1: order number 2: order date 3: order status */
    esc_html__( 'Order #%1$s was placed on %2$s and is currently %3$s.', 'woocommerce' ),
    '' . $order->get_order_number() . '', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '' . wc_format_datetime( $order->get_date_created() ) . '', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '' . wc_get_order_status_name( $order->get_status() ) . '' // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
);
?>

<?php if ( $notes ) : ?>

<?php esc_html_e( 'Order updates', 'woocommerce' ); ?>

        <?php foreach ( $notes as $note ) : ?>

<?php echo date_i18n( esc_html__( 'l jS \o\f F Y, h:ia', 'woocommerce' ), strtotime( $note->comment_date ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

                        <?php echo wpautop( wptexturize( $note->comment_content ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

        <?php endforeach; ?>

<?php endif; ?>

<?php do_action( 'woocommerce_view_order', $order_id );

<?php
/**
 * View Order
 *
 * Shows the details of a particular order on the account page.
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/myaccount/view-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.0.0
 */

defined( 'ABSPATH' ) || exit;

$notes = $order->get_customer_order_notes();
?>

<?php
printf(
    /* translators: 1: order number 2: order date 3: order status */
    esc_html__( 'Order #%1$s was placed on %2$s and is currently %3$s.', 'woocommerce' ),
    '' . $order->get_order_number() . '', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '' . wc_format_datetime( $order->get_date_created() ) . '', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    '' . wc_get_order_status_name( $order->get_status() ) . '' // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
);
?>

<?php if ( $notes ) : ?>

<?php esc_html_e( 'Order updates', 'woocommerce' ); ?>

        <?php foreach ( $notes as $note ) : ?>

<?php echo date_i18n( esc_html__( 'l jS \o\f F Y, h:ia', 'woocommerce' ), strtotime( $note->comment_date ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

                        <?php echo wpautop( wptexturize( $note->comment_content ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

        <?php endforeach; ?>

<?php endif; ?>

<?php do_action( 'woocommerce_view_order', $order_id );


问:
Why am I getting the error: InternalError: Blas xGEMV launch failed
I have a ColabPro+ subscription and after training a simple model for 40 min, I did a forward pass and got the above error notification.
enter image description here

I had to change the runtime type to a "normal" subscription and then it worked....Nonetheless this is extremely inefficient. I'd like to use the GPUs I payed for..


问:
Async-Await doesn't automatically update component
I have this simple webpage that can add or remove things to/from a list. There's an http request function(sendRequest) inside a custom hook that I use to dispatch various requests to the server, the requests themselves work but the list doesn't update automatically with the requests, I have to do it manually by refreshing the page. If I replace the async-await code with fetch it does update, so I'm sure the issue is with this function or something closely related. http.jsx is the custom hook where I define the requests and ingredients.jsx is where I actually render and manage the requests.

To be more precise, the <IngredientList /> component in the ingredients.jsx is the one I need to automatically update the render with my async-await code in http.jsx.

http.jsx:

```<code>import { useReducer, useCallback } from 'react';

const HTTP_ACTION = {
  SEND: `send`,
  RESPONSE: `response`,
  ERROR: `error`,
  CLEAR: `clear`
};
const { SEND, RESPONSE, ERROR, CLEAR } = HTTP_ACTION;

const initialState = {
  loading: false,
  error: null,
  data: null,
  extra: null,
  identifier: null
};

const httpReducer = (currentHttpState, action) => {
  switch (action.type) {
    case SEND: {
      return {
        loading: true,
        error: null,
        data: null,
        extra: null,
        identifier: action.identifier
      };
    }
    case RESPONSE: {
      return {
        ...currentHttpState,
        loading: false,
        data: action.responseData,
        extra: action.extra
      };
    }
    case ERROR: {
      return { loading: false, error: action.errorMessage };
    }
    case CLEAR: {
      return initialState;
    }
    default: {
      throw new Error(`HTTP Error: Should not be reached!`);
    }
  }
};

const useHttp = () => {
  const [httpState, dispatchHttp] = useReducer(httpReducer, initialState);

  const clear = () => useCallback(dispatchHttp({ type: CLEAR }), []);

  const sendRequest = useCallback(
    async (url, method, body, reqIdentifier, reqExtra) => {
      try {
        dispatchHttp({ type: SEND, identifier: reqIdentifier });

        const response = await fetch(url, {
          method,
          body,
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const responseData = await response.json();

        dispatchHttp({
          type: RESPONSE,
          responseData,
          extra: reqExtra
        });
      } catch (error) {
        dispatchHttp({
          type: ERROR,
          errorMessage: `Something went wrong! ${error.message}`
        });
      }
    },
    []
  );

  return {
    isLoading: httpState.loading,
    data: httpState.data,
    error: httpState.error,
    sendRequest,
    reqExtra: httpState.extra,
    reqIdentifier: httpState.identifier,
    clear
  };
};

export default useHttp;

</code>```

Related code in Ingredients.jsx:

```<code>import { useReducer, useCallback, useEffect, useMemo } from 'react';

import IngredientForm from './IngredientForm';
import IngredientList from './IngredientList';
import ErrorModal from '../UI/ErrorModal';
import Search from './Search';
import useHttp from '../../hooks/http';

const INGREDIENT_ACTION = {
  SET: `set`,
  ADD: `add`,
  DELETE: `delete`
};
const { SET, ADD, DELETE } = INGREDIENT_ACTION;

const ingredientReducer = (currentIngredients, action) => {
  switch (action.type) {
    case SET: {
      return action.ingredients;
    }
    case ADD: {
      return [...currentIngredients, action.ingredient];
    }
    case DELETE: {
      return currentIngredients.filter(({ id }) => id !== action.id);
    }
    default:
      throw new Error(`Should not get there!`);
  }
};

const Ingredients = () => {
  const [userIngredients, dispatch] = useReducer(ingredientReducer, []);
  const {
    isLoading,
    error,
    data,
    sendRequest,
    reqExtra,
    reqIdentifier,
    clear
  } = useHttp();

  useEffect(() => {
    if (!isLoading && !error && reqIdentifier === `REMOVE_INGREDIENT`) {
      dispatch({ type: DELETE, id: reqExtra });
    } else if (!isLoading && !error && reqIdentifier === `ADD_INGREDIENT`) {
      dispatch({
        type: ADD,
        ingredient: { id: data.name, ...reqExtra }
      });
    }
  }, [data, reqExtra, reqIdentifier, isLoading, error]);

  const addIngredientHandler = useCallback(
    ingredient => {
      sendRequest(
        `https://db-training-2efa8-default-rtdb.firebaseio.com/ingredients.json`,
        `POST`,
        JSON.stringify(ingredient),
        ingredient,
        `ADD_INGREDIENT`
      );
    },
    [sendRequest]
  );

  const handleRemoveItem = useCallback(
    listIngredientId => {
      sendRequest(
        `https://db-training-2efa8-default-rtdb.firebaseio.com/ingredients/${listIngredientId}.json`,
        `DELETE`,
        null,
        listIngredientId,
        `REMOVE_INGREDIENT`
      );
    },
    [sendRequest]
  );

  const filteredIngredientsHandler = useCallback(filteredIngredients => {
    dispatch({ type: SET, ingredients: filteredIngredients });
  }, []);

  const ingredientList = useMemo(() => {
    return (
      <IngredientList
        ingredients={userIngredients}
        onRemoveItem={handleRemoveItem}
      />
    );
  }, [userIngredients, handleRemoveItem]);

  return (
    <div className="App">
      {error && <ErrorModal onClose={clear}>{error}</ErrorModal>}

      <IngredientForm
        onAddIngredient={addIngredientHandler}
        loading={isLoading}
      />

      <section>
        <Search onLoadIngredients={filteredIngredientsHandler} />
        {ingredientList}
      </section>
    </div>
  );
};

export default Ingredients;
</code>```

Feel free to look at the full project at Stackblitz, though the only relevant pages are "http.jsx" and "ingredients.jsx".

I've tried a lot of things but nothing worked so far. I'm really lost at what I have to do.

Body:
I have this simple webpage that can add or remove things to/from a list. There's an http request function(sendRequest) inside a custom hook that I use to dispatch various requests to the server, the requests themselves work but the list doesn't update automatically with the requests, I have to do it manually by refreshing the page. If I replace the async-await code with fetch it does update, so I'm sure the issue is with this function or something closely related. http.jsx is the custom hook where I define the requests and ingredients.jsx is where I actually render and manage the requests.

To be more precise, the <IngredientList /> component in the ingredients.jsx is the one I need to automatically update the render with my async-await code in http.jsx.

http.jsx:

import { useReducer, useCallback } from 'react';

const HTTP_ACTION = {
  SEND: `send`,
  RESPONSE: `response`,
  ERROR: `error`,
  CLEAR: `clear`
};
const { SEND, RESPONSE, ERROR, CLEAR } = HTTP_ACTION;

const initialState = {
  loading: false,
  error: null,
  data: null,
  extra: null,
  identifier: null
};

const httpReducer = (currentHttpState, action) => {
  switch (action.type) {
    case SEND: {
      return {
        loading: true,
        error: null,
        data: null,
        extra: null,
        identifier: action.identifier
      };
    }
    case RESPONSE: {
      return {
        ...currentHttpState,
        loading: false,
        data: action.responseData,
        extra: action.extra
      };
    }
    case ERROR: {
      return { loading: false, error: action.errorMessage };
    }
    case CLEAR: {
      return initialState;
    }
    default: {
      throw new Error(`HTTP Error: Should not be reached!`);
    }
  }
};

const useHttp = () => {
  const [httpState, dispatchHttp] = useReducer(httpReducer, initialState);

  const clear = () => useCallback(dispatchHttp({ type: CLEAR }), []);

  const sendRequest = useCallback(
    async (url, method, body, reqIdentifier, reqExtra) => {
      try {
        dispatchHttp({ type: SEND, identifier: reqIdentifier });

        const response = await fetch(url, {
          method,
          body,
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const responseData = await response.json();

        dispatchHttp({
          type: RESPONSE,
          responseData,
          extra: reqExtra
        });
      } catch (error) {
        dispatchHttp({
          type: ERROR,
          errorMessage: `Something went wrong! ${error.message}`
        });
      }
    },
    []
  );

  return {
    isLoading: httpState.loading,
    data: httpState.data,
    error: httpState.error,
    sendRequest,
    reqExtra: httpState.extra,
    reqIdentifier: httpState.identifier,
    clear
  };
};

export default useHttp;

Related code in Ingredients.jsx:

import { useReducer, useCallback, useEffect, useMemo } from 'react';

import IngredientForm from './IngredientForm';
import IngredientList from './IngredientList';
import ErrorModal from '../UI/ErrorModal';
import Search from './Search';
import useHttp from '../../hooks/http';

const INGREDIENT_ACTION = {
  SET: `set`,
  ADD: `add`,
  DELETE: `delete`
};
const { SET, ADD, DELETE } = INGREDIENT_ACTION;

const ingredientReducer = (currentIngredients, action) => {
  switch (action.type) {
    case SET: {
      return action.ingredients;
    }
    case ADD: {
      return [...currentIngredients, action.ingredient];
    }
    case DELETE: {
      return currentIngredients.filter(({ id }) => id !== action.id);
    }
    default:
      throw new Error(`Should not get there!`);
  }
};

const Ingredients = () => {
  const [userIngredients, dispatch] = useReducer(ingredientReducer, []);
  const {
    isLoading,
    error,
    data,
    sendRequest,
    reqExtra,
    reqIdentifier,
    clear
  } = useHttp();

  useEffect(() => {
    if (!isLoading && !error && reqIdentifier === `REMOVE_INGREDIENT`) {
      dispatch({ type: DELETE, id: reqExtra });
    } else if (!isLoading && !error && reqIdentifier === `ADD_INGREDIENT`) {
      dispatch({
        type: ADD,
        ingredient: { id: data.name, ...reqExtra }
      });
    }
  }, [data, reqExtra, reqIdentifier, isLoading, error]);

  const addIngredientHandler = useCallback(
    ingredient => {
      sendRequest(
        `https://db-training-2efa8-default-rtdb.firebaseio.com/ingredients.json`,
        `POST`,
        JSON.stringify(ingredient),
        ingredient,
        `ADD_INGREDIENT`
      );
    },
    [sendRequest]
  );

  const handleRemoveItem = useCallback(
    listIngredientId => {
      sendRequest(
        `https://db-training-2efa8-default-rtdb.firebaseio.com/ingredients/${listIngredientId}.json`,
        `DELETE`,
        null,
        listIngredientId,
        `REMOVE_INGREDIENT`
      );
    },
    [sendRequest]
  );

  const filteredIngredientsHandler = useCallback(filteredIngredients => {
    dispatch({ type: SET, ingredients: filteredIngredients });
  }, []);

  const ingredientList = useMemo(() => {
    return (
      <IngredientList
        ingredients={userIngredients}
        onRemoveItem={handleRemoveItem}
      />
    );
  }, [userIngredients, handleRemoveItem]);

  return (

      {error && <ErrorModal onClose={clear}>{error}</ErrorModal>}

      <IngredientForm
        onAddIngredient={addIngredientHandler}
        loading={isLoading}
      />

        <Search onLoadIngredients={filteredIngredientsHandler} />
        {ingredientList}

  );
};

export default Ingredients;

Feel free to look at the full project at Stackblitz, though the only relevant pages are "http.jsx" and "ingredients.jsx".

I've tried a lot of things but nothing worked so far. I'm really lost at what I have to do.


问:
Is there a way to insolate and iframe selenium grid to show in my FE application
we are in the process of building RPA tool
One specific requirement is
end user should able to interact/See the live bot (test script) execution
Looks like selenium grid has a way to interact with test script with is execution in docker container
Question :
How to insolate a specific execution may be by using session id, later i will use it to iframe in our FE applicationenter image description hereenter image description here

..............................


问:
Determine working days based on project duration, start date, and arrays of how many days a task should take
I am trying to figure out how to calculate how long a project when what I have is duration of working days. I want to assign each task a date but all I have is how long a task should take based off of the duration time. I also have the startDate, the start date can be changed. The point here is the projectDuration only refers to working days and does not includes weekends. The other thing is that dates that are assigned to the Tasks need to avoid weekends but the length of time of each task in terms of working days needs to stay intact.

I don't know if this makes sense but I am a little stumped in terms of how tot tackle this any help would be appreciated.
Here is a sample of data:

```<code>let projectDuration = 39
let projectSteps = [
    {"TaskA": "Sample1" , Days: 2},
    {"TaskA": "Sample1" , Days: 6},
    {"TaskA": "Sample1" , Days: 10}
    {"TaskA": "Sample1" , Days: 12}
    {"TaskA": "Sample1" , Days: 16}
   ]
let startDate = "10/12/2023"
</code>```

So a simple way to determine date for the task would be adding Days values to the startDate the problem is that when that date falls on the weekend then everything else would need to be recalculated in order for the totality of of each task takes the amount of days it has assigned.

Body:
I am trying to figure out how to calculate how long a project when what I have is duration of working days. I want to assign each task a date but all I have is how long a task should take based off of the duration time. I also have the startDate, the start date can be changed. The point here is the projectDuration only refers to working days and does not includes weekends. The other thing is that dates that are assigned to the Tasks need to avoid weekends but the length of time of each task in terms of working days needs to stay intact.

I don't know if this makes sense but I am a little stumped in terms of how tot tackle this any help would be appreciated.
Here is a sample of data:

let projectDuration = 39
let projectSteps = [
    {"TaskA": "Sample1" , Days: 2},
    {"TaskA": "Sample1" , Days: 6},
    {"TaskA": "Sample1" , Days: 10}
    {"TaskA": "Sample1" , Days: 12}
    {"TaskA": "Sample1" , Days: 16}
   ]
let startDate = "10/12/2023"

So a simple way to determine date for the task would be adding Days values to the startDate the problem is that when that date falls on the weekend then everything else would need to be recalculated in order for the totality of of each task takes the amount of days it has assigned.


问:
Can a single cloudfront distribution be used to create two s3 origins one with OAI and the other with OAC enabled in aws
Am trying to create a single cloud front distribution with 2 s3 origins, one with OAI and the other with OAC. Need an answer if this approach would work

Am expecting this approach to work, as per the customers requirement one origin has to have a OAI and the other OAC


问:
React Native + Firebase JS SDK - Whats the name of the cookie (local storage) used for persisting Auth state?
I am creating the Cookies Policy of my App (GDPR stuff) and I need to set the name of the cookies (AsyncStorage) I use in my React Native app.

I have read here, that

When running on React Native, Firebase Authentication uses AsyncStorage to store the user data.

But, what's the name of that "cookie"? I have tried to log all my AsyncStorage data in my App, but there is no more information than the one I have collected manually.


问:
How to implement darkmode in stencil.js using tailwind and test it on storybook?
I have tried using these two methods.
1. Using storybook tailwind dark mode add-on.
https://corechasm.com/addons/@jhaynie/storybook-tailwind-dark-mode
2. Using storybook config.
https://workingconcept.com/blog/storybook-components-dark-mode

Note: Dark mode works when I turn it on from the system setting of the windows. (personalization app mode in default to dark)

get to know how to configure dark mode in stencil.js and storybook with tailwindcss.


问:
Place inner html content in multiple DIVs
Trying to place the value of checkbox in inner HTML and in multiple DIVS. Seems like the code I have isn't working.</p>
```<code>const ids = ['acc-title-placeholder-3', 'acc-title-placeholder-4', 'acc-title-placeholder-5'];
    const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
    var a = cb.checked ? cb.value : ' ';
    document.querySelectorAll(elements).innerHTML = a;
</code>```

Body:
Trying to place the value of checkbox in inner HTML and in multiple DIVS. Seems like the code I have isn't working.

const ids = ['acc-title-placeholder-3', 'acc-title-placeholder-4', 'acc-title-placeholder-5'];
    const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
    var a = cb.checked ? cb.value : ' ';
    document.querySelectorAll(elements).innerHTML = a;


问:
How to automatically click javascript link when landed to an html page
I want to add a Tax Calendar link to my webpage.
This is the link:
https://www.tax.gov/calendar/

But IRS is asking visitors to click another link to show the calendar. And it looks like a deadend page.

So I want to make a link that automatically choose Grid setting
1. Continue with calendar-month grid enabled. which is:
javascript:continueWith('grid')

Is it possible to make a simple html link that will click this choice?

Thanks!

```<code> <a href="http://www.tax.gov/calendar/" onclick="document.getElementById('grid').click() "
             target="_blank" >Tax Calendar</a>
</code>```

and I tried:

```<code><script type="text/javascript"> document.querySelector('a[href="javascript:continueWith('grid')"]').click();</script>
          <a href="http://www.tax.gov/calendar/"
             target="_blank" >Tax Calendar</a>
</code>```

Body:
I want to add a Tax Calendar link to my webpage.
This is the link:
https://www.tax.gov/calendar/

But IRS is asking visitors to click another link to show the calendar. And it looks like a deadend page.

So I want to make a link that automatically choose Grid setting
1. Continue with calendar-month grid enabled. which is:
javascript:continueWith('grid')

Is it possible to make a simple html link that will click this choice?

Thanks!

 Tax Calendar

and I tried:

          Tax Calendar