问:
Flurl/HttpClient messes up memory on simultaneous requests using IoC
We are using Flurl to upload many files at once in our Web API app (.net 6). Usually, from 20 to 30 simultaneous uploads are executed.

I am trying to manage Flurl instances explicitly and use IoC. The code below works fine for a small number of parallel uploads, but if simultaneous request counts reach around 30, the CPU and Memory consumption for our app go mad, the memory jumping from 1GB to a total of 5GB RAM, CPU usage goes from 20 to 100% and back and app hangs in that state!

If I use new Url and leave Flurl to manage instances, everything works fine. Any idea what may cause such behavior?

```<code>public class BuildFileServer : IBuildFileServer
{

    private readonly IFlurlClient _client;

    public BuildFileServer(IFlurlClient client)
    {
        _client = client;
    }

 public async Task<StoreFile> StoreAsync(FileInfo file)
    {
        var fileUploadResultDto = await
            _client.Request("upload")
                .WithHeader("accept", "application/json")
                .WithHeader("content-type", MimeMapping.MimeUtility.GetMimeMapping(fileName))
                .WithHeader("content-disposition", new ContentDispositionHeaderValue("form-data")
                {
                    Name = "file",
                    FileName = fileName,
                    FileNameStar = fileName
                })
                .PostAsync(new FileContent(file.FullName))
                .ReceiveJson<FileUploadResultDto>();

        return ///....
    }
}

public static class FileServerDiRegistry
{
    public static void AddFileServer(this IServiceCollection services)
    {
        services.AddSingleton<IFlurlClient>(serviceProvider =>
        {
            var client = new FlurlClient(new Url
            {
                Scheme = "http",
                Host = AppConstants.CfsHost,
                Port = AppConstants.CfsPort
            });

            client.Configure(settings =>
            {
                settings.OnErrorAsync = async (httpCall) =>
                {

                };

                settings.AfterCallAsync = async (httpCall) =>
                {

                };
            });

            return client;
        });
    }
}

    builder.Services.AddFileServer();
</code>```

This is code that works stable.

```<code>public class BuildFileServer : IBuildFileServer
{
   public async Task<StoreFile> StoreAsync(FileInfo file)
    {

      var url = new Url
        {
            Scheme = ServerSchema,
            Host = ServerHost,
            Path = "upload",
            Port = ServerPort
        };

        var fileUploadResultDto = await
            url
                .WithHeader("accept", "application/json")
                .WithHeader("content-type", MimeMapping.MimeUtility.GetMimeMapping(fileName))
                .WithHeader("content-disposition", new ContentDispositionHeaderValue("form-data")
                {
                    Name = "file",
                    FileName = fileName,
                    FileNameStar = fileName
                })
                .PostAsync(new FileContent(file.FullName))
                .ReceiveJson<FileUploadResultDto>();

        return ///....
    }
}
</code>```

Body:
We are using Flurl to upload many files at once in our Web API app (.net 6). Usually, from 20 to 30 simultaneous uploads are executed.

I am trying to manage Flurl instances explicitly and use IoC. The code below works fine for a small number of parallel uploads, but if simultaneous request counts reach around 30, the CPU and Memory consumption for our app go mad, the memory jumping from 1GB to a total of 5GB RAM, CPU usage goes from 20 to 100% and back and app hangs in that state!

If I use new Url and leave Flurl to manage instances, everything works fine. Any idea what may cause such behavior?

public class BuildFileServer : IBuildFileServer
{

    private readonly IFlurlClient _client;

    public BuildFileServer(IFlurlClient client)
    {
        _client = client;
    }

 public async Task<StoreFile> StoreAsync(FileInfo file)
    {
        var fileUploadResultDto = await
            _client.Request("upload")
                .WithHeader("accept", "application/json")
                .WithHeader("content-type", MimeMapping.MimeUtility.GetMimeMapping(fileName))
                .WithHeader("content-disposition", new ContentDispositionHeaderValue("form-data")
                {
                    Name = "file",
                    FileName = fileName,
                    FileNameStar = fileName
                })
                .PostAsync(new FileContent(file.FullName))
                .ReceiveJson<FileUploadResultDto>();

        return ///....
    }
}

public static class FileServerDiRegistry
{
    public static void AddFileServer(this IServiceCollection services)
    {
        services.AddSingleton<IFlurlClient>(serviceProvider =>
        {
            var client = new FlurlClient(new Url
            {
                Scheme = "http",
                Host = AppConstants.CfsHost,
                Port = AppConstants.CfsPort
            });

            client.Configure(settings =>
            {
                settings.OnErrorAsync = async (httpCall) =>
                {

                };

                settings.AfterCallAsync = async (httpCall) =>
                {

                };
            });

            return client;
        });
    }
}

    builder.Services.AddFileServer();

This is code that works stable.

public class BuildFileServer : IBuildFileServer
{
   public async Task<StoreFile> StoreAsync(FileInfo file)
    {

      var url = new Url
        {
            Scheme = ServerSchema,
            Host = ServerHost,
            Path = "upload",
            Port = ServerPort
        };

        var fileUploadResultDto = await
            url
                .WithHeader("accept", "application/json")
                .WithHeader("content-type", MimeMapping.MimeUtility.GetMimeMapping(fileName))
                .WithHeader("content-disposition", new ContentDispositionHeaderValue("form-data")
                {
                    Name = "file",
                    FileName = fileName,
                    FileNameStar = fileName
                })
                .PostAsync(new FileContent(file.FullName))
                .ReceiveJson<FileUploadResultDto>();

        return ///....
    }
}


来源: stackexchange

问:
Tailwind peer out of radio div
Unable to find in official documentation it is possible to use peer out of div where located radio buttons?
I try this but this not work .

Code Example :

```<code><div>
    <label for="head-company" class="block text-xs font-medium mb-0.5">Payment
        terms</label>
    <!-- tabs -->
    <div class="grid grid-cols-2 rounded-xl bg-basic-white p-0.5" x-data="app">
        <div>
            <input type="radio" name="option" id="cred"
                class="peer hidden flex items-center py-2.5 px-4 relative rounded-lg active:bg-turquoise-600 active:text-basic-white hover:bg-turquoise-600 hover:text-basic-white focus:bg-turquoise-600 focus:text-basic-white"
                checked />
            <label for="cred"
                class="block cursor-pointer select-none rounded-xl p-2 text-center peer-checked:bg-turquoise-600  peer-checked:text-basic-white">
                CIA
            </label>
        </div>
        <div>
            <input type="radio" name="option" id="2" class="peer/cred hidden" />
            <label for="2"
                class="block cursor-pointer select-none rounded-xl p-2 text-center peer-checked/cred:bg-turquoise-600 peer-checked/cred:text-basic-white">
                Credit terms
            </label>
        </div>
    </div>
</div>
<div class="new-trade__input-group peer-checked/cred:bg-turquoise-600  peer-checked/cred:hidden">
    <div class="input-text-group">
        <label for="head-company" class="input-text-group__label">Credit
            Terms</label>
        <div class="input-text-group__wrap">
            <input class="max-w-[96px]" type="text" id="fname" name="fname"
                placeholder="Max">
        </div>
    </div>
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Tailwind peer out of radio div

Body:
Unable to find in official documentation it is possible to use peer out of div where located radio buttons?
I try this but this not work .

Code Example :

    Payment
        terms

            <input type="radio" name="option" id="cred"
                class="peer hidden flex items-center py-2.5 px-4 relative rounded-lg active:bg-turquoise-600 active:text-basic-white hover:bg-turquoise-600 hover:text-basic-white focus:bg-turquoise-600 focus:text-basic-white"
                checked />

                CIA

            <input type="radio" name="option" id="2" class="peer/cred hidden" />

                Credit terms

        Credit
            Terms

            <input class="max-w-[96px]" type="text" id="fname" name="fname"
                placeholder="Max">


问:
Creating new ultragrid from old ultragrid by applying filter on cell of old grid in C# win form
I have to create new ultagrid from a given ultragrid which have filter value of old ultragrid for example:- I have a ultragrid(XYZ) which hava A,B,C column & i have to create a new grid from this grid by applying the condition that if C cloumn do not have any value in cell then dont add that entire row to the new grid.

I tried nested loop but it does not work.


问:
What are the best practices for using cronjob along with docker and laravel?
I ran into a problem that I have to manually write a cronjob in a production environment inside Ubuntu, I would like to have a completely standalone docker project. There is a solution with creating an ubuntu container, but it looks weird, ubuntu inside ubuntu. So far, I've had to set up a cronjob outside of a container on Ubuntu itself.

Dockerfile

```<code>FROM php:8.1-fpm

RUN apt-get update && apt-get install -y \
      apt-utils \
      libpq-dev \
      libpng-dev \
      libzip-dev \
      zip unzip \
      git && \
      docker-php-ext-install pdo_mysql && \
      docker-php-ext-install bcmath && \
      docker-php-ext-install gd && \
      docker-php-ext-install zip && \
      apt-get clean && \
      rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

COPY ./_docker/app/php.ini /usr/local/etc/php/conf.d/php.ini

# Install composer
ENV COMPOSER_ALLOW_SUPERUSER=1
RUN curl -sS https://getcomposer.org/installer | php -- \
    --filename=composer \
    --install-dir=/usr/local/bin

WORKDIR /var/www
</code>```

docker-compose.yml

```<code> version: '3'

services:
  nginx:
    image: nginx:latest
    volumes:
      - ./:/var/www/
      - ./_docker/nginx/conf.d/:/etc/nginx/conf.d/
    ports:
      - 8876:80
    container_name: flowers_nginx
    depends_on:
        -   flowers

  flowers:
    build:
        context: .
        dockerfile: _docker/app/Dockerfile
    volumes:
      - ./:/var/www/
    depends_on:
        -   database
    container_name: flowers_php

  database:
    image: mysql:8.0
    restart: always
    volumes:
      - ./temp/db:/var/lib/mysql
    environment:
        MYSQL_DATABASE: ****
        MYSQL_ROOT_PASSWORD: *****
        MYSQL_USER: ****
        MYSQL_PASSWORD: *****
    ports:
      - 8101:3306
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    container_name: flowers_mysql
</code>```

Due to lack of experience, I need a hint with the best solution, maybe use kubernetes-cronjob or redis, but I have not yet learned these technologies, I will be grateful if you help me choose the right solution and development path.

I tried to do the following inside Ubuntu itself which has docker installed and it works, but because of this I can't make a completely standalone docker project without connecting to the ubuntu job which has docker installed

crontab -e

* * * * * cd /var/www/public/flowers_shop && php artisan schedule:run >> /dev/null 2>&1

Body:
I ran into a problem that I have to manually write a cronjob in a production environment inside Ubuntu, I would like to have a completely standalone docker project. There is a solution with creating an ubuntu container, but it looks weird, ubuntu inside ubuntu. So far, I've had to set up a cronjob outside of a container on Ubuntu itself.

Dockerfile

FROM php:8.1-fpm

RUN apt-get update && apt-get install -y \
      apt-utils \
      libpq-dev \
      libpng-dev \
      libzip-dev \
      zip unzip \
      git && \
      docker-php-ext-install pdo_mysql && \
      docker-php-ext-install bcmath && \
      docker-php-ext-install gd && \
      docker-php-ext-install zip && \
      apt-get clean && \
      rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

COPY ./_docker/app/php.ini /usr/local/etc/php/conf.d/php.ini

# Install composer
ENV COMPOSER_ALLOW_SUPERUSER=1
RUN curl -sS https://getcomposer.org/installer | php -- \
    --filename=composer \
    --install-dir=/usr/local/bin

WORKDIR /var/www

docker-compose.yml

 version: '3'

services:
  nginx:
    image: nginx:latest
    volumes:
      - ./:/var/www/
      - ./_docker/nginx/conf.d/:/etc/nginx/conf.d/
    ports:
      - 8876:80
    container_name: flowers_nginx
    depends_on:
        -   flowers

  flowers:
    build:
        context: .
        dockerfile: _docker/app/Dockerfile
    volumes:
      - ./:/var/www/
    depends_on:
        -   database
    container_name: flowers_php

  database:
    image: mysql:8.0
    restart: always
    volumes:
      - ./temp/db:/var/lib/mysql
    environment:
        MYSQL_DATABASE: ****
        MYSQL_ROOT_PASSWORD: *****
        MYSQL_USER: ****
        MYSQL_PASSWORD: *****
    ports:
      - 8101:3306
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    container_name: flowers_mysql

Due to lack of experience, I need a hint with the best solution, maybe use kubernetes-cronjob or redis, but I have not yet learned these technologies, I will be grateful if you help me choose the right solution and development path.

I tried to do the following inside Ubuntu itself which has docker installed and it works, but because of this I can't make a completely standalone docker project without connecting to the ubuntu job which has docker installed

crontab -e

* * * * * cd /var/www/public/flowers_shop && php artisan schedule:run >> /dev/null 2>&1


问:
Cannot Render images in React while using Server Side Rendering after creating Build ,Cannot GET /[object%20Object]
I used create-react-app to create a React project. I was experimenting with server-side rendering on express servers.
I found a code snippet that showed me how to do it.

```<code>ReactDOM.hydrate(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById("root")
);
</code>```

This is my server side code.
index.js

```<code>require("ignore-styles");

require("@babel/register")({
    ignore: [/(node_modules)/],
    presets: ["@babel/preset-env", "@babel/preset-react"],
});

require("./server");

</code>```

server.js

```<code>import path from "path";
import fs from "fs";

import express from "express";
import React from "react";
import ReactDOMServer from "react-dom/server";

import App from "../src/App";

const PORT = 8080;
const app = express();

const router = express.Router();

const serverRenderer = (req, res, next) => {
    fs.readFile(path.resolve("./build/index.html"), "utf8", (err, data) => {
        if (err) {
            console.error(err);
            return res.status(500).send("An error occurred");
        }
        return res.send(
            data.replace(
                '<div id="root"></div>',
                `<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`
            )
        );
    });
};
router.use("^/$", serverRenderer);

router.use(
    express.static(path.resolve(__dirname, "..", "build"), { maxAge: "30d" })
);

// tell the app to use the above rules
app.use(router);

// app.use(express.static('./build'))
app.listen(PORT, () => {
    console.log(`SSR running on port ${PORT}`);
});
</code>```

It works fine when I try to get text or other data; however, when I try to render images from the server side, they do not appear.
I tried every other solution I could think of, but nothing seemed to work.

images are not rendering
and also not showing in View Page Source
enter image description here

we also tried

I tried all the solutions from stackoverflow as well as other sources, but its not working.

I was expecting images to be rendered properly on page.

Body:
I used create-react-app to create a React project. I was experimenting with server-side rendering on express servers.
I found a code snippet that showed me how to do it.

ReactDOM.hydrate(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById("root")
);

This is my server side code.
index.js

require("ignore-styles");

require("@babel/register")({
    ignore: [/(node_modules)/],
    presets: ["@babel/preset-env", "@babel/preset-react"],
});

require("./server");

server.js

import path from "path";
import fs from "fs";

import express from "express";
import React from "react";
import ReactDOMServer from "react-dom/server";

import App from "../src/App";

const PORT = 8080;
const app = express();

const router = express.Router();

const serverRenderer = (req, res, next) => {
    fs.readFile(path.resolve("./build/index.html"), "utf8", (err, data) => {
        if (err) {
            console.error(err);
            return res.status(500).send("An error occurred");
        }
        return res.send(
            data.replace(
                '

',
                `<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`
            )
        );
    });
};
router.use("^/$", serverRenderer);

router.use(
    express.static(path.resolve(__dirname, "..", "build"), { maxAge: "30d" })
);

// tell the app to use the above rules
app.use(router);

// app.use(express.static('./build'))
app.listen(PORT, () => {
    console.log(`SSR running on port ${PORT}`);
});

It works fine when I try to get text or other data; however, when I try to render images from the server side, they do not appear.
I tried every other solution I could think of, but nothing seemed to work.

images are not rendering
and also not showing in View Page Source
enter image description here

we also tried

I tried all the solutions from stackoverflow as well as other sources, but its not working.

I was expecting images to be rendered properly on page.


问:
Using Protégé as Ontology Manager
I want to use Protégé as an ontology manager. The most basic feature would be to see all the ontology files I have in my repo together in a single opened instance of Protégé i.e. a unified view of all the schema I have in a specific folder. It will be like an Ontology library. Can I do this in Protégé?

I know I can merge all the files first and then see the output file in Protégé but I am looking for a better solution.
Thanks.

Title: Using Protégé as Ontology Manager


问:
Keras model.fit hangs
Attempting to fit a Keras model on an audio_dataset_from_directory results in the kernel apparently not responding. The following code reproduces my problem (tested in VScode and Jupyter Notebook):

```<code>import tensorflow.keras as keras
import pandas as pd
import os

# Create architecture of model
inputs = keras.layers.Input((None, 1))
rnn = keras.layers.SimpleRNN(200)(inputs)
output = keras.layers.Dense(1)(rnn)
# Compile model
model = keras.Model(inputs, output)
model.compile(loss="mean_squared_error")

# Load data
data = pd.read_csv(".\\files\\metadata.csv", index_col="title")
data = keras.utils.audio_dataset_from_directory(
    ".\\files\\songs",
    labels=data["UserLikes"].to_list(),
    label_mode="int",
    ragged=True,
    shuffle=True,
)

# Fit model
model.fit(data, epochs=1, verbose=2)
</code>```

In this code, data["UserLikes"] (and thus y in the Keras dataset) consists of integers in the range [0, inf). An audiofile is processed by Keras as  Tensors of floats of shape (timesteps, channels=1). The total size of the audiofiles is merely 320 MB. The goal of the code is to predict the amount of likes a song gets.

The result of this code is nothing: Everytime I run it, the code gets stuck on model.fit. Sometimes the application (i.e., VScode or Jupyter Notebook) even crashes.

Any advice would be greatly appreciated.

Title: Keras model.fit hangs

Body:
Attempting to fit a Keras model on an audio_dataset_from_directory results in the kernel apparently not responding. The following code reproduces my problem (tested in VScode and Jupyter Notebook):

import tensorflow.keras as keras
import pandas as pd
import os

# Create architecture of model
inputs = keras.layers.Input((None, 1))
rnn = keras.layers.SimpleRNN(200)(inputs)
output = keras.layers.Dense(1)(rnn)
# Compile model
model = keras.Model(inputs, output)
model.compile(loss="mean_squared_error")

# Load data
data = pd.read_csv(".\\files\\metadata.csv", index_col="title")
data = keras.utils.audio_dataset_from_directory(
    ".\\files\\songs",
    labels=data["UserLikes"].to_list(),
    label_mode="int",
    ragged=True,
    shuffle=True,
)

# Fit model
model.fit(data, epochs=1, verbose=2)

In this code, data["UserLikes"] (and thus y in the Keras dataset) consists of integers in the range [0, inf). An audiofile is processed by Keras as  Tensors of floats of shape (timesteps, channels=1). The total size of the audiofiles is merely 320 MB. The goal of the code is to predict the amount of likes a song gets.

The result of this code is nothing: Everytime I run it, the code gets stuck on model.fit. Sometimes the application (i.e., VScode or Jupyter Notebook) even crashes.

Any advice would be greatly appreciated.


问:
Does Redis cache supports Native sql Api
I am using apache ignite for my application now I wanted to migrate to redis-cache but I used ignite query api to fetch data. Is there any possible way I can use the same queries just by changing dependencies from ignite to redis-cache?

Is there any alternative tool where i can use in AWS cloud platform which supports Native SQL API?


问:
Send Message to discord from changes in Formulated Cell in Google Sheet
I have formulated all cells in my Google Sheet, but since they are not counted as edits (since it is formualated update and not manual edit), I am not receiving notifications when there are updates in the value of the cell. Is there a way to set up notifications for updates in a Google Sheet, regardless of whether the cells are edited or not?

In Addition, Can I send the notification of these update in Discord/Whatsapp/Telegram?

Thanks.

I tried set up with zapier, iftt, etc. But it doesnt work since it is not edited.

To put context of the code below:
I want to run in tab "Sheet1" and whenever value changes in Column L, update me in discord (would be great if someone can help edit the code to just run the cell value as message in Discord)

```<code>function onChange(e) {
  // Get the active sheet in the Google Sheet
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");

  // Set the range to the entire sheet
  var range = sheet.getDataRange();

  // Set the value of e to the active sheet
  e = {range: range};

  // Send a notification to Discord when the range L:L is changed
  if (e.range.getA1Notation() == "L:L") {
    // Replace YOUR_DISCORD_WEBHOOK_URL with your own Discord webhook URL
    sendDiscordNotification("xxx", "New booking testing.");
  }
}

// Sends a message to a Discord webhook
function sendDiscordNotification(webhookUrl, message) {
  var payload = {
    "content": message
  };
  var options = {
    "method": "post",
    "payload": JSON.stringify(payload)
  };
  UrlFetchApp.fetch(webhookUrl, options);
}
</code>```

Body:
I have formulated all cells in my Google Sheet, but since they are not counted as edits (since it is formualated update and not manual edit), I am not receiving notifications when there are updates in the value of the cell. Is there a way to set up notifications for updates in a Google Sheet, regardless of whether the cells are edited or not?

In Addition, Can I send the notification of these update in Discord/Whatsapp/Telegram?

Thanks.

I tried set up with zapier, iftt, etc. But it doesnt work since it is not edited.

To put context of the code below:
I want to run in tab "Sheet1" and whenever value changes in Column L, update me in discord (would be great if someone can help edit the code to just run the cell value as message in Discord)

function onChange(e) {
  // Get the active sheet in the Google Sheet
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");

  // Set the range to the entire sheet
  var range = sheet.getDataRange();

  // Set the value of e to the active sheet
  e = {range: range};

  // Send a notification to Discord when the range L:L is changed
  if (e.range.getA1Notation() == "L:L") {
    // Replace YOUR_DISCORD_WEBHOOK_URL with your own Discord webhook URL
    sendDiscordNotification("xxx", "New booking testing.");
  }
}

// Sends a message to a Discord webhook
function sendDiscordNotification(webhookUrl, message) {
  var payload = {
    "content": message
  };
  var options = {
    "method": "post",
    "payload": JSON.stringify(payload)
  };
  UrlFetchApp.fetch(webhookUrl, options);
}


问:
Laravel Stripe - Your request was in live mode, but used a known test card
This is a strange issue no idea from Laravel or from Stripe?

Used same card to checkout order -- Success payment

Defined Laravel Schedule job to re-order -- (Run command from CLI php artisan runReorder) -- Success payment

The scheduled job which runs at 00:00 once a day defined in Kernel.php

```<code> $schedule->command('runReorder')->dailyAt('00:00');
</code>```

Failed payment and got the following error:

Your card was declined. Your request was in live mode,
but used a known test card

in Advance cache and configs are cleared
Merchant account is on LIVE mode

Body:
This is a strange issue no idea from Laravel or from Stripe?

Used same card to checkout order -- Success payment

Defined Laravel Schedule job to re-order -- (Run command from CLI php artisan runReorder) -- Success payment

The scheduled job which runs at 00:00 once a day defined in Kernel.php

 $schedule->command('runReorder')->dailyAt('00:00');

Failed payment and got the following error:

Your card was declined. Your request was in live mode,
but used a known test card

in Advance cache and configs are cleared
Merchant account is on LIVE mode


问:
working on visual inventory with html only working partly
I´m currently working with Twine(sugarcube) to finish my adventure game. The inventory is another page you can always go to, where the gathered items are each presented with an image or textelement. I´ve put the image elements in a div class, but some are working, while others don´t even if the code structure is the same. I´ve changed it around multiple times but it didn´t matter, some elements just don´t show up...
here is the inventory html:

```<code><<if $plot is true>><div class="plotbackground"></div>
<</if>>

          <mark>this is your storage: </mark>
          <<return>>
<<if $fruits >0>><mark>fruits= $fruits</mark> [[eat one]]
<</if>>

<<if $flexibility is true>>
<div class="flexibilityinventory"
    <img src="data/inventory/flexibility.png" width="300px" height="300px">
</div>
<</if>>
<<if $fluidity is true>>
<div class="fluidityinventory"
    <img src="data/inventory/fluidity.png" width="300px" height="300px">
</div>
<</if>>
<<if $stability is true>>
<div class="stabilityinventory"
    <img src="data/inventory/stability.png" width="300px" height="300px">
</div>
<</if>>

<<if $raumazug is true>>
<div class="raumanzuginventory">
    <img src="data/inventory/raumanzug.png" width="442" height="1000">
</div>
<</if>>

<<if $investment is true>> your investment is growing
<</if>>

<<if $poster is true>>
<div class="fishy">
    <img src="data/inventory/fishklein.png" width="300px" height="300px">
</div>
<</if>>

<<if $hut is true>>
<div class="hutinv">
    <img src="data/inventory/hutinv.png" width="1500px" height="844px">
</div>
<</if>>

<<if $cinemaseat is true>> you have purchased seat $row $seat.
<</if>>
<<if $cinemaseat2 is true>> you have purchased seat $row2 $seat2.
<</if>>
<<if $cinemaseat3 is true>> you have purchased seat $row3 $seat3.
<</if>>

<<if $hammer is true>>
<div class="hammer">
    <img src="data/inventory/hammerklein.png" width="150px" height="150px">
</div>
<</if>>

<<if $lighter is true>> you have one lighter. [[make a fire]]
<</if>>

<<if $bench is true>>
<div class="bench">
    <img src="data/inventory/bench.png" width="500px" height="327px">
</div>
[[take a break|rest]]
<</if>>

<<if $window is true>>
<div class="window">
    <img src="data/inventory/fensterklein.png" width="200px" height="200px">
</div>
<</if>>

<<if $bike is true>>
<div class="bike">
    <img src="data/inventory/bikeschrott.png" width="200px" height="200px">
</div>
<</if>>

<<if $roller is true>>
<div class="rollerinv">
    <img src="data/inventory/eroller.png" width="600px" height="800px">
</div>
<</if>>

<<if $treeinv is true>>
<div class="treeinv">
    <img src="data/inventory/treeinv.png" width="2638px" height="1311px">
</div>
<</if>>

<<if $fireextinguisher is true>>
<div class="extinv">
    <img src="data/inventory/extinguishersmall.png" width="200px" height="200px">
</div>
<</if>>
</code>```

when starting the story, you go through a reset, and set the variables to true during the game.
reset html:

```<code> <<set $hammer to false>>
<<set $treeinv to false>>
<<set $window to false>>
<<set $bench to false>>
<<set $roller to false>>
<<set $bike to false>>
<<set $lighter to false>>
<<set $investment to false>>
<<set $friend to true>>
<<set $burned to false>>
<<set $cinemaseat to false>>
<<set $cinemaseat2 to false>>
<<set $cinemaseat3 to false>>
<<set $door to 0>>
<<set $fruits to 0>>
<<set $poster to false>>
<<set $hut to false>>
<<set $treeinv to false>>
<<set $fireextinguisher to false>>
<<set $plot to false>>
<<set $axe to false>>
<<set $fluditiy to false>>
<<set $stability to false>>
<<set $flexibility to false>>
<<set $raumanzug to false>>

<<goto "start">>
</code>```

this is the CSS Stylesheet:

```<code>.inventory {background-image:url("data/inventory/background.jpg");   background-repeat: no-repeat;height: 1360px; width: 2293px; overflow: visible;z-index:-5;position:absolute;}
.plotbackground {background-image:url("data/inventory/plotbackground.png");   background-repeat: no-repeat;height: 1660px; width: 2496px; z-index:-5;position:absolute;}
.hammer {width:150px;height:150px;position:absolute;top:0px;left:0px;z-index:-4}
.treeinv {position:absolute; z-index: -2; bottom:0px; left: -500px;; top:auto;width:2638px; height:1311px;}
.window {width:200px;height:200px;position:absolute;top:0px;left:160px;z-index:-4}
.bench {width:500px;height:327px; position:absolute;bottom:10px; left:700px; z-index:-2}
.rollerinv {position:absolute;bottom:10px; left:50px; z-index:-2}
.bike {width:200px;height:200px;position:absolute;top:0px;left:370px;z-index:-4}
.fishy {width:300px;height:300px;position:absolute;top:0px;left:600px;z-index:-4}
.hutinv {position:absolute; z-index: -3; bottom:0px;left: 400px;top:auto;}
.extinv {position:absolute; z-index: -2; top:200px;left: -600px;}
.raumanzuginventory {position:absolute; z-index: -1; top:0px;right:0px;}
.stabilityinventory{("data/inventory/stability.png"), width:300px;height:300px;position:absolute; z-index: -1; top:0px;right: 200px;}
.fluidityinventory{position:absolute; z-index: -1; top:350px;right: 200px;}
.flexibilityinventory {position:absolute;  z-index: -1; width:300px;height:300px; top:700px;right: 200px;}
</code>```

Body:
I´m currently working with Twine(sugarcube) to finish my adventure game. The inventory is another page you can always go to, where the gathered items are each presented with an image or textelement. I´ve put the image elements in a div class, but some are working, while others don´t even if the code structure is the same. I´ve changed it around multiple times but it didn´t matter, some elements just don´t show up...
here is the inventory html:

<<if $plot is true>>

<</if>>

          this is your storage:
          <<return>>
<<if $fruits >0>>fruits= $fruits [[eat one]]
<</if>>

<<if $flexibility is true>>
<div class="flexibilityinventory"

<</if>>
<<if $fluidity is true>>
<div class="fluidityinventory"

<</if>>
<<if $stability is true>>
<div class="stabilityinventory"

<</if>>

<<if $raumazug is true>>

<</if>>

<<if $investment is true>> your investment is growing
<</if>>

<<if $poster is true>>

<</if>>

<<if $hut is true>>

<</if>>

<<if $cinemaseat is true>> you have purchased seat $row $seat.
<</if>>
<<if $cinemaseat2 is true>> you have purchased seat $row2 $seat2.
<</if>>
<<if $cinemaseat3 is true>> you have purchased seat $row3 $seat3.
<</if>>

<<if $hammer is true>>

<</if>>

<<if $lighter is true>> you have one lighter. [[make a fire]]
<</if>>

<<if $bench is true>>

[[take a break|rest]]
<</if>>

<<if $window is true>>

<</if>>

<<if $bike is true>>

<</if>>

<<if $roller is true>>

<</if>>

<<if $treeinv is true>>

<</if>>

<<if $fireextinguisher is true>>

<</if>>

when starting the story, you go through a reset, and set the variables to true during the game.
reset html:

 <<set $hammer to false>>
<<set $treeinv to false>>
<<set $window to false>>
<<set $bench to false>>
<<set $roller to false>>
<<set $bike to false>>
<<set $lighter to false>>
<<set $investment to false>>
<<set $friend to true>>
<<set $burned to false>>
<<set $cinemaseat to false>>
<<set $cinemaseat2 to false>>
<<set $cinemaseat3 to false>>
<<set $door to 0>>
<<set $fruits to 0>>
<<set $poster to false>>
<<set $hut to false>>
<<set $treeinv to false>>
<<set $fireextinguisher to false>>
<<set $plot to false>>
<<set $axe to false>>
<<set $fluditiy to false>>
<<set $stability to false>>
<<set $flexibility to false>>
<<set $raumanzug to false>>

<<goto "start">>

this is the CSS Stylesheet:

.inventory {background-image:url("data/inventory/background.jpg");   background-repeat: no-repeat;height: 1360px; width: 2293px; overflow: visible;z-index:-5;position:absolute;}
.plotbackground {background-image:url("data/inventory/plotbackground.png");   background-repeat: no-repeat;height: 1660px; width: 2496px; z-index:-5;position:absolute;}
.hammer {width:150px;height:150px;position:absolute;top:0px;left:0px;z-index:-4}
.treeinv {position:absolute; z-index: -2; bottom:0px; left: -500px;; top:auto;width:2638px; height:1311px;}
.window {width:200px;height:200px;position:absolute;top:0px;left:160px;z-index:-4}
.bench {width:500px;height:327px; position:absolute;bottom:10px; left:700px; z-index:-2}
.rollerinv {position:absolute;bottom:10px; left:50px; z-index:-2}
.bike {width:200px;height:200px;position:absolute;top:0px;left:370px;z-index:-4}
.fishy {width:300px;height:300px;position:absolute;top:0px;left:600px;z-index:-4}
.hutinv {position:absolute; z-index: -3; bottom:0px;left: 400px;top:auto;}
.extinv {position:absolute; z-index: -2; top:200px;left: -600px;}
.raumanzuginventory {position:absolute; z-index: -1; top:0px;right:0px;}
.stabilityinventory{("data/inventory/stability.png"), width:300px;height:300px;position:absolute; z-index: -1; top:0px;right: 200px;}
.fluidityinventory{position:absolute; z-index: -1; top:350px;right: 200px;}
.flexibilityinventory {position:absolute;  z-index: -1; width:300px;height:300px; top:700px;right: 200px;}


问:
How to install/symlink packages in monorepos from root node_modules in yarn workspace
I have to use the cached node_modules at root level and use it to add symlinks to all the mono-repo packages as the current command, yarn install ignores the available root level node_modules and re-install them from server instead. Any way I can save time here?

Repo Structure

```<code> - node_modules # available already in repo
 - packages/
   - package1
     - node_modules # this to installed/symlink from root node_modules
     - package.json
   - package2
     - node_modules # this to installed/symlink from root node_modules
     - package.json
</code>```

Body:
I have to use the cached node_modules at root level and use it to add symlinks to all the mono-repo packages as the current command, yarn install ignores the available root level node_modules and re-install them from server instead. Any way I can save time here?

Repo Structure

 - node_modules # available already in repo
 - packages/
   - package1
     - node_modules # this to installed/symlink from root node_modules
     - package.json
   - package2
     - node_modules # this to installed/symlink from root node_modules
     - package.json


问:
reply to sender mail php script
I have been looking for a mailform script and came up with his. Works fine, but just this matter: when I reply to the received email, I am replying to myself, whilst I would like to reply automatically to the mailadres of the sender.

```<code><?php
$to = "MY@MAILADRES.COM";
$subject = "mail via website";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$onderwerp = $_POST['onderwerp'];
$comments = $_POST['message'];
$message = "
name: $firstname $lastname
email: $email

subject: $onderwerp

message: $comments
";
  $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
     $headers = "From: MY@MAILADRES.COM\r\n".
     "MIME-Version: 1.0\r\n" .
        "Content-Type: multipart/mixed;\r\n" .
        " boundary=\"{$mime_boundary}\"";
     $message = "This is a multi-part message in MIME format.\n\n" .
        "--{$mime_boundary}\n" .
        "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
        "Content-Transfer-Encoding: 7bit\n\n" .
     $message . "\n\n";
     foreach($_FILES as $userfile)
     {
        $tmp_name = $userfile['tmp_name'];
        $type = $userfile['type'];
        $name = $userfile['name'];
        $size = $userfile['size'];
        if (file_exists($tmp_name))
        {
           if(is_uploaded_file($tmp_name))
           {
              $file = fopen($tmp_name,'rb');
              $data = fread($file,filesize($tmp_name));
              fclose($file);
              $data = chunk_split(base64_encode($data));
           }
           $message .= "--{$mime_boundary}\n" .
              "Content-Type: {$type};\n" .
              " name=\"{$name}\"\n" .
              "Content-Disposition: attachment;\n" .
              " filename=\"{$fileatt_name}\"\n" .
              "Content-Transfer-Encoding: base64\n\n" .
           $data . "\n\n";
        }
     }
     $message.="--{$mime_boundary}--\n";
if (mail($to, $subject, $message, $headers))
   echo "Thanks for getting in touch.<br>Your message wil get my full attention.<br>I     will get back to you soon.";
else
   echo "Error in mail.<br>Please try again.";
?>
</code>```

What should I change in this code, please?
I added these (seperately):

$headers .= "From: Contact Form (Domain.com) <no-reply@domain.com>\r\n";

$headers .= "Reply-To: ".$_REQUEST['email']."<". $_REQUEST['email'].">\r\n"

But none seem to work. I got this code to work with and all good, except for the reply-to.

Title: reply to sender mail php script

Body:
I have been looking for a mailform script and came up with his. Works fine, but just this matter: when I reply to the received email, I am replying to myself, whilst I would like to reply automatically to the mailadres of the sender.

<?php
$to = "MY@MAILADRES.COM";
$subject = "mail via website";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$onderwerp = $_POST['onderwerp'];
$comments = $_POST['message'];
$message = "
name: $firstname $lastname
email: $email

subject: $onderwerp

message: $comments
";
  $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
     $headers = "From: MY@MAILADRES.COM\r\n".
     "MIME-Version: 1.0\r\n" .
        "Content-Type: multipart/mixed;\r\n" .
        " boundary=\"{$mime_boundary}\"";
     $message = "This is a multi-part message in MIME format.\n\n" .
        "--{$mime_boundary}\n" .
        "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
        "Content-Transfer-Encoding: 7bit\n\n" .
     $message . "\n\n";
     foreach($_FILES as $userfile)
     {
        $tmp_name = $userfile['tmp_name'];
        $type = $userfile['type'];
        $name = $userfile['name'];
        $size = $userfile['size'];
        if (file_exists($tmp_name))
        {
           if(is_uploaded_file($tmp_name))
           {
              $file = fopen($tmp_name,'rb');
              $data = fread($file,filesize($tmp_name));
              fclose($file);
              $data = chunk_split(base64_encode($data));
           }
           $message .= "--{$mime_boundary}\n" .
              "Content-Type: {$type};\n" .
              " name=\"{$name}\"\n" .
              "Content-Disposition: attachment;\n" .
              " filename=\"{$fileatt_name}\"\n" .
              "Content-Transfer-Encoding: base64\n\n" .
           $data . "\n\n";
        }
     }
     $message.="--{$mime_boundary}--\n";
if (mail($to, $subject, $message, $headers))
   echo "Thanks for getting in touch.
Your message wil get my full attention.
I     will get back to you soon.";
else
   echo "Error in mail.
Please try again.";
?>

What should I change in this code, please?
I added these (seperately):

$headers .= "From: Contact Form (Domain.com) <no-reply@domain.com>\r\n";

$headers .= "Reply-To: ".$_REQUEST['email']."<". $_REQUEST['email'].">\r\n"

But none seem to work. I got this code to work with and all good, except for the reply-to.


问:
Integrate AWS API Gateway and AWS S3 Using AWS CDK for binary files
I am trying to setup content-type integration to my api gateway integration with S3.

s3_bucket_name=Fn.import_value("s3-bucket-name")

```<code>    # Creating the Policy Document for Api gateway to access s3
    s3_access_document=aws_iam.PolicyDocument(
        statements=[
            aws_iam.PolicyStatement(
                actions=[
                    "s3:GetObject",
                ],
                effect=aws_iam.Effect.ALLOW,
                resources=[f"arn:aws:s3:::{s3_bucket_name}/script.ps1"],
            )
        ]
    )

    # Create the Role for API Gateway to Access S3
    api_s3_role=aws_iam.Role(
        self,
        id=f"{stack_id}-s3-access-role",
        assumed_by=aws_iam.ServicePrincipal("apigateway.amazonaws.com"),
        role_name=f"remote-debugging-s3-access-role",
        inline_policies={
            "s3-access": s3_access_document,
        },
    )

    #Integrating s3 with API Gateway
    s3_integration=aws_apigateway.AwsIntegration(
        service="s3",
        integration_http_method="GET",
        path=f"{s3_bucket_name}"+"{proxy}",
        options=aws_apigateway.IntegrationOptions(
            credentials_role=api_s3_role,
            integration_responses=[
                aws_apigateway.IntegrationResponse(
                    status_code="200",
                    response_parameters= {
                        "method.response.header.Content-Type": "integration.response.header.Content-Type",
                    },
                )
            ],
            request_parameters= {
              "integration.request.path.proxy": "method.request.path.proxy",
            },
        ),
    )
    script_resource=api_gateway.root.add_resource("script")
    script_resource.add_method(
        "GET",
        s3_integration,
        method_responses =[
            aws_apigateway.MethodResponse(
                status_code = "200",
                response_parameters={
                    "method.response.header.Content-Type": True,
                },
            )
        ],
        request_parameters= {
          "method.request.path.proxy": True,
          "method.request.header.Content-Type": True,
        },
        authorizer=authorizer,
        authorization_type=aws_apigateway.AuthorizationType.COGNITO,
    )
</code>```

There are two things to fix here:
1.
Something is not right with path=f"{s3_bucket_name}"+"{proxy}", I am getting Access denied error which i use it.

If i use path=f"{s3_bucket_name}/script.ps1", it gives me a response.

2 The content-type is not being propagate to method response and integration response.

I am trying to find any documents that would help me.

followed this link

I feel i am missing out some import details could you please help me with this as i am new CDK

Body:
I am trying to setup content-type integration to my api gateway integration with S3.

s3_bucket_name=Fn.import_value("s3-bucket-name")

    # Creating the Policy Document for Api gateway to access s3
    s3_access_document=aws_iam.PolicyDocument(
        statements=[
            aws_iam.PolicyStatement(
                actions=[
                    "s3:GetObject",
                ],
                effect=aws_iam.Effect.ALLOW,
                resources=[f"arn:aws:s3:::{s3_bucket_name}/script.ps1"],
            )
        ]
    )

    # Create the Role for API Gateway to Access S3
    api_s3_role=aws_iam.Role(
        self,
        id=f"{stack_id}-s3-access-role",
        assumed_by=aws_iam.ServicePrincipal("apigateway.amazonaws.com"),
        role_name=f"remote-debugging-s3-access-role",
        inline_policies={
            "s3-access": s3_access_document,
        },
    )

    #Integrating s3 with API Gateway
    s3_integration=aws_apigateway.AwsIntegration(
        service="s3",
        integration_http_method="GET",
        path=f"{s3_bucket_name}"+"{proxy}",
        options=aws_apigateway.IntegrationOptions(
            credentials_role=api_s3_role,
            integration_responses=[
                aws_apigateway.IntegrationResponse(
                    status_code="200",
                    response_parameters= {
                        "method.response.header.Content-Type": "integration.response.header.Content-Type",
                    },
                )
            ],
            request_parameters= {
              "integration.request.path.proxy": "method.request.path.proxy",
            },
        ),
    )
    script_resource=api_gateway.root.add_resource("script")
    script_resource.add_method(
        "GET",
        s3_integration,
        method_responses =[
            aws_apigateway.MethodResponse(
                status_code = "200",
                response_parameters={
                    "method.response.header.Content-Type": True,
                },
            )
        ],
        request_parameters= {
          "method.request.path.proxy": True,
          "method.request.header.Content-Type": True,
        },
        authorizer=authorizer,
        authorization_type=aws_apigateway.AuthorizationType.COGNITO,
    )

There are two things to fix here:
1.
Something is not right with path=f"{s3_bucket_name}"+"{proxy}", I am getting Access denied error which i use it.

If i use path=f"{s3_bucket_name}/script.ps1", it gives me a response.

2 The content-type is not being propagate to method response and integration response.

I am trying to find any documents that would help me.

followed this link

I feel i am missing out some import details could you please help me with this as i am new CDK


问:
docker buildx takes longer time to build multi arch images - ARM64 and AMD64 than single arch
using docker buildx build --platform linux/arm64,linux/amd64 takes 5 times longer than
docker build .

I'm running the command using jenkins pipeline on a amd64 slave.
Is there any way to build the image faster?


问:
React Native app reloads clicking on push notification
I am using react-native-notifications. I am getting push notifications perfectly but the issue is when the app is in the foreground and received push notifications. I clicked on the notification, the app reloads instead of resuming and the app is in the foreground all this time. It happens for every single push notification.

The event handler on click of push notification is being called and app reloads. I am just doing console in the handler.

```<code>Notifications.events().registerNotificationOpened()
</code>```

Tried singleTop, singleTask, or singleInstance in manifest file. no luck

Body:
I am using react-native-notifications. I am getting push notifications perfectly but the issue is when the app is in the foreground and received push notifications. I clicked on the notification, the app reloads instead of resuming and the app is in the foreground all this time. It happens for every single push notification.

The event handler on click of push notification is being called and app reloads. I am just doing console in the handler.

Notifications.events().registerNotificationOpened()

Tried singleTop, singleTask, or singleInstance in manifest file. no luck


问:
Doctrine: get more context on scheme reverse engineering type mapping
I'm trying to develop a MySQL enum type that uses PHP 8 enums, in order to replace a good old:

```<code>#[ORM\Column(type: Types::STRING, length: 16, enumType: Language::class)]
</code>```

By:

```<code>#[ORM\Column(type: 'enum', enumType: Language::class)]
</code>```

And moreover, prevent that someone inserts a wrong value that would break objects hydratation.

For this, I created a custom doctrine type:

```<code><?php

namespace App\Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

class EnumType extends Type
{
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $enumType = $fieldDeclaration['enumType'] ?? null;

        // Because Doctrine uses ::from() method coming from \BackedEnum contract when hydrating objects
        if (!\is_subclass_of($enumType, \BackedEnum::class)) {
            throw new \LogicException('Doctrine "enum" type requires a native PHP 8 backed enum class in the "enumType" column mapping property.');
        }

        // TODO escape values containing quotes

        return \sprintf(
            'ENUM(%s)',
            \implode(',', \array_map(fn($e) => \sprintf("'%s'", $e->value), $enumType::cases()))
        );
    }

    public function getName(): string
    {
        return 'enum';
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform): bool
    {
        return true;
    }
}
</code>```

When running a first doctrine migration, I properly get the expected enumeration:

```<code>public function up(Schema $schema): void
{
    // this up() migration is auto-generated, please modify it to your needs
    $this->addSql('ALTER TABLE user_preference CHANGE language language ENUM(\'fr\',\'en\') NOT NULL COMMENT \'(DC2Type:enum)\'');
}
</code>```

But once the MySQL scheme contains that enum(), Doctrine cannot perform any diffs anymore.

The first error is quite obvious, Doctrine is not aware of the enum type:

Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.

So I added its support in my custom type:

```<code>public function getMappedDatabaseTypes(AbstractPlatform $platform)
{
    return ['enum'];
}
</code>```

But when getSQLDeclaration is called from my class, it does not contain enough context:

```<code>^ array:12 [
  "name" => "language"
  "type" => App\Doctrine\DBAL\Types\EnumType^ {#569}
  "default" => null
  "notnull" => true
  "length" => 0
  "precision" => 10
  "scale" => 0
  "fixed" => false
  "unsigned" => false
  "autoincrement" => false
  "comment" => "(DC2Type:enum)"
  "version" => false
]
</code>```

As you can see, the mysql enum() values (what's inside the braces) are not provided, so I"m not able to reconstruct the same SQL declaration.

Is there a way to get more context? Or add a custom comment containing the values?

Body:
I'm trying to develop a MySQL enum type that uses PHP 8 enums, in order to replace a good old:

#[ORM\Column(type: Types::STRING, length: 16, enumType: Language::class)]

By:

#[ORM\Column(type: 'enum', enumType: Language::class)]

And moreover, prevent that someone inserts a wrong value that would break objects hydratation.

For this, I created a custom doctrine type:

<?php

namespace App\Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

class EnumType extends Type
{
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $enumType = $fieldDeclaration['enumType'] ?? null;

        // Because Doctrine uses ::from() method coming from \BackedEnum contract when hydrating objects
        if (!\is_subclass_of($enumType, \BackedEnum::class)) {
            throw new \LogicException('Doctrine "enum" type requires a native PHP 8 backed enum class in the "enumType" column mapping property.');
        }

        // TODO escape values containing quotes

        return \sprintf(
            'ENUM(%s)',
            \implode(',', \array_map(fn($e) => \sprintf("'%s'", $e->value), $enumType::cases()))
        );
    }

    public function getName(): string
    {
        return 'enum';
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform): bool
    {
        return true;
    }
}

When running a first doctrine migration, I properly get the expected enumeration:

public function up(Schema $schema): void
{
    // this up() migration is auto-generated, please modify it to your needs
    $this->addSql('ALTER TABLE user_preference CHANGE language language ENUM(\'fr\',\'en\') NOT NULL COMMENT \'(DC2Type:enum)\'');
}

But once the MySQL scheme contains that enum(), Doctrine cannot perform any diffs anymore.

The first error is quite obvious, Doctrine is not aware of the enum type:

Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.

So I added its support in my custom type:

public function getMappedDatabaseTypes(AbstractPlatform $platform)
{
    return ['enum'];
}

But when getSQLDeclaration is called from my class, it does not contain enough context:

^ array:12 [
  "name" => "language"
  "type" => App\Doctrine\DBAL\Types\EnumType^ {#569}
  "default" => null
  "notnull" => true
  "length" => 0
  "precision" => 10
  "scale" => 0
  "fixed" => false
  "unsigned" => false
  "autoincrement" => false
  "comment" => "(DC2Type:enum)"
  "version" => false
]

As you can see, the mysql enum() values (what's inside the braces) are not provided, so I"m not able to reconstruct the same SQL declaration.

Is there a way to get more context? Or add a custom comment containing the values?


问:
Chart.js space issue
I am creating charts using chartjs library. Everything works fine but there is no space between title and bar. I am using below code, rest is fine but there is no gap.

below is my code

I am creating charts using chartjs library. Everything works fine but there is no space between title and bar. I am using below code, rest is fine but there is no gap.

```<code>document.addEventListener("DOMContentLoaded", function() {
    var patternSize = 20;
    new Chart(document.getElementById("chart-3"), {
        type: "bar",
        data: {

            labels: ["3.2.2","3.3.3b","3.5.3"],
            datasets: [{
                label: "3.2.2",
                backgroundColor: [
                    pattern.draw('line', "#F1C40F ", undefined, patternSize)
                  ],
                data: [0,50,0],

            }
        ]
        },
        options: {
            indexAxis: 'y',
            maintainAspectRatio: false,
            scales: {
                yAxes: [{
                    gridLines: {
                        display: true
                    },
                    stacked: false,
                    ticks: {
                        stepSize: 10,
                        callback: function(value, index, ticks) {
                        return  value + '%';
                        }
                    },
                    scaleLabel: {
                        display: false,
                        labelString: 'Progress'
                    }
                }],
                xAxes: [{
                    stacked: false,

                    scaleLabel: {
                        display: false,
                        labelString: 'Tasks',
                    }
                }]
            },
        }
    });
});
</code>```

Title: Chart.js space issue

Body:
I am creating charts using chartjs library. Everything works fine but there is no space between title and bar. I am using below code, rest is fine but there is no gap.

below is my code

I am creating charts using chartjs library. Everything works fine but there is no space between title and bar. I am using below code, rest is fine but there is no gap.

document.addEventListener("DOMContentLoaded", function() {
    var patternSize = 20;
    new Chart(document.getElementById("chart-3"), {
        type: "bar",
        data: {

            labels: ["3.2.2","3.3.3b","3.5.3"],
            datasets: [{
                label: "3.2.2",
                backgroundColor: [
                    pattern.draw('line', "#F1C40F ", undefined, patternSize)
                  ],
                data: [0,50,0],

            }
        ]
        },
        options: {
            indexAxis: 'y',
            maintainAspectRatio: false,
            scales: {
                yAxes: [{
                    gridLines: {
                        display: true
                    },
                    stacked: false,
                    ticks: {
                        stepSize: 10,
                        callback: function(value, index, ticks) {
                        return  value + '%';
                        }
                    },
                    scaleLabel: {
                        display: false,
                        labelString: 'Progress'
                    }
                }],
                xAxes: [{
                    stacked: false,

                    scaleLabel: {
                        display: false,
                        labelString: 'Tasks',
                    }
                }]
            },
        }
    });
});


问:
Submitting dynamically created form to database in reactJS
I am trying to insert the values through this dynamic form but I am only able to insert just one entry (even though I enter multiple forms) and the values that are getting inserted are 0 (in the database as well).
I am passing the index still I am not getting the desired output. The list looks like this:
List of the entered details

The previous entry was entered manually.
This is the CODE through which I submit values.

```<code>import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
import { useNavigate, useParams } from 'react-router-dom'
import RoomInfoService from '../services/RoomInfoService';

const RoomInfo = () => {
    const [shared_no] = useState();
    const [no_of_rooms] = useState();
    const [rent_per_month] = useState();
    const [vacancy] = useState();
    const [total_capacity] = useState();
    const [pg_fid, setpgfid] = useState();H

    let handleChange = (i, e) => {
        let newFormValues = [...formValues]; /** makes a copy of the current form values and assign it to newFormValues **/
        newFormValues[i][e.target.name] = e.target.value;
        setFormValues(newFormValues);
    }

    const navigate = useNavigate();

    let addFormFields = () => {
        setFormValues([...formValues, { shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}])
    };

    let removeFormFields = (i) => {
        let newFormValues = [...formValues];
        newFormValues.splice(i, 1);
        setFormValues(newFormValues)
    }

    const [formValues, setFormValues] = useState([{ shared_no: "", no_of_rooms: "", rent_per_month: "", total_capacity: "", vacancy: "" }])

    /*const [settotal_no_of_rooms] = useState('1');
    const [setrooms_entered] = useState('1');

    const getTotalCapacity = () => {

        return formValues.reduce((total,element) => {
            return total + Number(element.shared_no) * Number(element.no_of_rooms);
        }, 0);
    };*/

    const resetForm = () => setFormValues([{shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}]);

    const Total_no_of_rooms_entered = () => {
        return formValues.reduce((total, element) => {
            return total + Number(element.no_of_rooms);
        }, 0);
    };

    const saveRoomInfo = (e) =>{
        e.preventDefault();
        const roominfo = [...formValues];
        RoomInfoService.createRoomInfo(roominfo).then((response) => {
            console.log(response.data);
            navigate('/listroominfo');
        }).catch(error =>{
            console.log(error);
        })
    }

    return (
        <>
            <div className='heading'>
                <h1 style={{ marginBottom: '50px' }}>Enter Your PG Room Details</h1>
            </div>
            <form>

                <div className="form-inline" style={{ marginBottom: '50px' }}>
                    {/*<label>Total of Rooms:    </label>
                    <input type="number" name="total_no_of_rooms" style={{ width: '90px' }} onClick={(e) => settotal_no_of_rooms(e.target.value)} defaultValue={1} />    */}
                    <label>Rooms Entered:</label>
                    <div><input type="number" name="rooms_entered" value={Total_no_of_rooms_entered()} readOnly></input></div>
                </div>
            </form>
            <div>
                <form>
                    {formValues.map((element, index) => (
                        <div className="form-inline" key={index} style={{ borderBottom: '1px solid black' }}>
                            <label>Sharing Number</label>
                            <select id="shared_no" name="shared_no" title="no of shared rooms" value={element.shared_no || ""} onChange={e => handleChange(index, e)} >
                                <option value="">---Select---</option>
                                <option value="1">Single Sharing</option>
                                <option value="2">Two Bed Sharing</option>
                                <option value="3">Three Bed Sharing</option>
                                <option value="4">Four Bed Sharing</option>
                                <option value="5">Five Bed Sharing</option>
                            </select>

                            <label>   No of Rooms:</label>
                            <input type="number" style={{ width: '60px' }} name="no_of_rooms" value={element.no_of_rooms || ""} onChange={e => handleChange(index, e)}></input>

                            <label>   Rent per month:</label>
                            <input type="number" style={{ width: '100px' }} name="rent_per_month" value={element.rent_per_month || ""} onChange={e => handleChange(index, e)}></input>

                            <label>   Total Capacity:</label>
                            <input type="number" style={{ width: '80px' }} name="total_capacity" value={element.total_capacity} onChange={e => handleChange(index, e)}></input>

                            <label>   Vacancy:</label>
                            <input type="number" style={{ width: '50px' }} name="vacancy" value={element.vacancy || ""} onChange={e => handleChange(index, e)}></input>
                            {
                                index ?
                                    <button type="button"  className="button-remove" onClick={() => removeFormFields(index)}><ImBin size={20}/></button>
                                    : null
                            }
                        </div>
                    ))}
                    <div className="button-section">
                        <button className="button" type="button" onClick={() => addFormFields()}>Add</button>
                        <button className="button" type="button" onClick={resetForm}>Reset</button>
                        <button className="button" type="submit" onClick={(e) => saveRoomInfo(e)}>Submit</button>
                    </div>
                </form>
            </div>
        </>
    )
}

export default RoomInfo
</code>```

Reference of Dynamic Form

The issue is while I am fetching the data from the form. But I can't figure it out. Thank you.

Body:
I am trying to insert the values through this dynamic form but I am only able to insert just one entry (even though I enter multiple forms) and the values that are getting inserted are 0 (in the database as well).
I am passing the index still I am not getting the desired output. The list looks like this:
List of the entered details

The previous entry was entered manually.
This is the CODE through which I submit values.

import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
import { useNavigate, useParams } from 'react-router-dom'
import RoomInfoService from '../services/RoomInfoService';

const RoomInfo = () => {
    const [shared_no] = useState();
    const [no_of_rooms] = useState();
    const [rent_per_month] = useState();
    const [vacancy] = useState();
    const [total_capacity] = useState();
    const [pg_fid, setpgfid] = useState();H

    let handleChange = (i, e) => {
        let newFormValues = [...formValues]; /** makes a copy of the current form values and assign it to newFormValues **/
        newFormValues[i][e.target.name] = e.target.value;
        setFormValues(newFormValues);
    }

    const navigate = useNavigate();

    let addFormFields = () => {
        setFormValues([...formValues, { shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}])
    };

    let removeFormFields = (i) => {
        let newFormValues = [...formValues];
        newFormValues.splice(i, 1);
        setFormValues(newFormValues)
    }

    const [formValues, setFormValues] = useState([{ shared_no: "", no_of_rooms: "", rent_per_month: "", total_capacity: "", vacancy: "" }])

    /*const [settotal_no_of_rooms] = useState('1');
    const [setrooms_entered] = useState('1');

    const getTotalCapacity = () => {

        return formValues.reduce((total,element) => {
            return total + Number(element.shared_no) * Number(element.no_of_rooms);
        }, 0);
    };*/

    const resetForm = () => setFormValues([{shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}]);

    const Total_no_of_rooms_entered = () => {
        return formValues.reduce((total, element) => {
            return total + Number(element.no_of_rooms);
        }, 0);
    };

    const saveRoomInfo = (e) =>{
        e.preventDefault();
        const roominfo = [...formValues];
        RoomInfoService.createRoomInfo(roominfo).then((response) => {
            console.log(response.data);
            navigate('/listroominfo');
        }).catch(error =>{
            console.log(error);
        })
    }

    return (
        <>

Enter Your PG Room Details

            <form>

                    {/*Total of Rooms:
                    <input type="number" name="total_no_of_rooms" style={{ width: '90px' }} onClick={(e) => settotal_no_of_rooms(e.target.value)} defaultValue={1} />    */}
                    Rooms Entered:

<input type="number" name="rooms_entered" value={Total_no_of_rooms_entered()} readOnly></input>

            </form>

                <form>
                    {formValues.map((element, index) => (

                            Sharing Number
                            <select id="shared_no" name="shared_no" title="no of shared rooms" value={element.shared_no || ""} onChange={e => handleChange(index, e)} >
                                <option value="">---Select---</option>
                                <option value="1">Single Sharing</option>
                                <option value="2">Two Bed Sharing</option>
                                <option value="3">Three Bed Sharing</option>
                                <option value="4">Four Bed Sharing</option>
                                <option value="5">Five Bed Sharing</option>
                            </select>

                               No of Rooms:
                            <input type="number" style={{ width: '60px' }} name="no_of_rooms" value={element.no_of_rooms || ""} onChange={e => handleChange(index, e)}></input>

                               Rent per month:
                            <input type="number" style={{ width: '100px' }} name="rent_per_month" value={element.rent_per_month || ""} onChange={e => handleChange(index, e)}></input>

                               Total Capacity:
                            <input type="number" style={{ width: '80px' }} name="total_capacity" value={element.total_capacity} onChange={e => handleChange(index, e)}></input>

                               Vacancy:
                            <input type="number" style={{ width: '50px' }} name="vacancy" value={element.vacancy || ""} onChange={e => handleChange(index, e)}></input>
                            {
                                index ?
                                    <button type="button"  className="button-remove" onClick={() => removeFormFields(index)}><ImBin size={20}/></button>
                                    : null
                            }

                    ))}

                        <button className="button" type="button" onClick={() => addFormFields()}>Add</button>
                        <button className="button" type="button" onClick={resetForm}>Reset</button>
                        <button className="button" type="submit" onClick={(e) => saveRoomInfo(e)}>Submit</button>

                </form>

        </>
    )
}

export default RoomInfo

Reference of Dynamic Form

The issue is while I am fetching the data from the form. But I can't figure it out. Thank you.


问:
Can a GitLab runner be given access rights to an AWS account?
To DevOps,
I am running a GitLab pipeline and I want to push a created image to an AWS ECR in an account. How would I give access rights to the GitLab Runner to access the AWS ECR?
Thanks,
Marc</p>


问:
How to open instagram DM list page usgin url scheme for ios
How to open instagram DM list page usgin url scheme for ios.

This is a example.

```<code>instagram://hogehoge
</code>```
```<code>instagram://camera //open camera in IG app.
</code>```

I'm finding.
Please tell me how to solve.
Thank you.

Body:
How to open instagram DM list page usgin url scheme for ios.

This is a example.

instagram://hogehoge

instagram://camera //open camera in IG app.

I'm finding.
Please tell me how to solve.
Thank you.


问:
Regex for text (and numbers and special characters) between multiple commas
My data looks like this

914,Alil,138,12 or

914,5 Alil -500mg !@#$%^&*(),138,12

I want to make the

Alil -> 'Alil'
or the

5 Alil -500mg !@#$%^&*() -> '5 Alil -500mg !@#$%^&*()'

In short, turn the 2nd column to the same text between the single quotes ''

I have tried the (?<=,)(.+)(?=,) : Look positive behind , gets any characters and looks positive in front of , but it didn't work.


问:
Shinyapp mapping by species and color
I should create in my shiny app this conditions:
In the UI setup add a selectInput field: the first argument is
the name (how to access the selection in the server setup, we will
call this "species"), the second argument is the label (appears on
the app), and the third argument should list the choices: here we
want to choose between the three different species (can you
obtain the three choices from the data directly?).

I receive this error in my code:
I receive this error:
Error in match.arg(position) : 'arg' must be NULL or a character vector

CODE:

```<code>library(shiny)
library(palmerpenguins)
library(ggplot2)

# Define UI for application that draws a plot
ui <- fluidPage(

    # Application title
titlePanel("Penguins"),

# Sidebar with a slider input for number of bins
sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "VarX",
      label = "Select X-axis Variable",
      choices =  list("flipper_length_mm","species","island",
                      "bill_length_mm","bill_depth_mm","body_mass_g",
                      "sex","year")),
      selectInput(inputId = "VarY",
                  label = "Select Y-axis Variable",
                  choices = list("flipper_length_mm","species","island",
                  "bill_length_mm","bill_depth_mm","body_mass_g",
                  "sex","year")),
      selectInput(
        inputId = "varColor",
        label = "Color",
        choices = c("species"),
        selected = "species")),
 selectInput(
      inputId = "species",
                label = "select species",
                choices = list("adelie","gentoo","chinstrap")),

    # Show a plot
    mainPanel(
       plotOutput("scatter")
    )
)
)

#Define server logic required to draw a scatter
server <- function(input, output) {
  pengu <- reactive({ggplot(penguins,
                            aes(y = bill_depth_mm, x = bill_length_mm))+
      geom_point(aes(color = .data[[input$species]]))})

    output$scatter <- renderPlot({
      pengu()

    })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Title: Shinyapp mapping by species and color

Body:
I should create in my shiny app this conditions:
In the UI setup add a selectInput field: the first argument is
the name (how to access the selection in the server setup, we will
call this "species"), the second argument is the label (appears on
the app), and the third argument should list the choices: here we
want to choose between the three different species (can you
obtain the three choices from the data directly?).

I receive this error in my code:
I receive this error:
Error in match.arg(position) : 'arg' must be NULL or a character vector

CODE:

library(shiny)
library(palmerpenguins)
library(ggplot2)

# Define UI for application that draws a plot
ui <- fluidPage(

    # Application title
titlePanel("Penguins"),

# Sidebar with a slider input for number of bins
sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "VarX",
      label = "Select X-axis Variable",
      choices =  list("flipper_length_mm","species","island",
                      "bill_length_mm","bill_depth_mm","body_mass_g",
                      "sex","year")),
      selectInput(inputId = "VarY",
                  label = "Select Y-axis Variable",
                  choices = list("flipper_length_mm","species","island",
                  "bill_length_mm","bill_depth_mm","body_mass_g",
                  "sex","year")),
      selectInput(
        inputId = "varColor",
        label = "Color",
        choices = c("species"),
        selected = "species")),
 selectInput(
      inputId = "species",
                label = "select species",
                choices = list("adelie","gentoo","chinstrap")),

    # Show a plot
    mainPanel(
       plotOutput("scatter")
    )
)
)

#Define server logic required to draw a scatter
server <- function(input, output) {
  pengu <- reactive({ggplot(penguins,
                            aes(y = bill_depth_mm, x = bill_length_mm))+
      geom_point(aes(color = .data[[input$species]]))})

    output$scatter <- renderPlot({
      pengu()

    })
}

# Run the application
shinyApp(ui = ui, server = server)


问:
How to set environment variable MAKEFLAGS in CMakeLists.txt?
I am trying to compile some code which is managed with Cmake with make, and I have noticed that when I use cmake 3.25.1, I do not get "Entering directory ..." messages from make; but when I use cmake 3.14.3, I get these messages.

I would like to suppress these messages regardless of the cmake version used. So, I found cmake: How to suppress "Entering directory" messages? where it says

You can use

```<code>MAKEFLAGS += --no-print-directory
</code>```

... which, I gather, is an environment variable that make would read.

So, as per Setting a NEW environment variable with CMake?, I wrote at the start of my CMakeLists.txt file:

```<code>set(ENV{MAKEFLAGS} "--no-print-directory")
</code>```

... then re-ran cmake, then ran make, and ... no effect, I still get:

```<code>$ make
make[1]: Entering directory '/c/src/build'
make[2]: Entering directory '/c/src/build'
...
</code>```

So, how can I set this MAKEFLAGSenvironment variable in my CMakeLists.txt file, so make can see it, and perform without these printouts? Note that I would prefer NOT setting this variable permanently in my shell environment (MINGW64 bash), so I would like to handle this in CMakeLists.txt alone.

Body:
I am trying to compile some code which is managed with Cmake with make, and I have noticed that when I use cmake 3.25.1, I do not get "Entering directory ..." messages from make; but when I use cmake 3.14.3, I get these messages.

I would like to suppress these messages regardless of the cmake version used. So, I found cmake: How to suppress "Entering directory" messages? where it says

You can use

MAKEFLAGS += --no-print-directory

... which, I gather, is an environment variable that make would read.

So, as per Setting a NEW environment variable with CMake?, I wrote at the start of my CMakeLists.txt file:

set(ENV{MAKEFLAGS} "--no-print-directory")

... then re-ran cmake, then ran make, and ... no effect, I still get:

$ make
make[1]: Entering directory '/c/src/build'
make[2]: Entering directory '/c/src/build'
...

So, how can I set this MAKEFLAGSenvironment variable in my CMakeLists.txt file, so make can see it, and perform without these printouts? Note that I would prefer NOT setting this variable permanently in my shell environment (MINGW64 bash), so I would like to handle this in CMakeLists.txt alone.


问:
DuckDB `explain analyze` total time and operator time discrepancy
When I use explain analyze to profile a join query:

```<code>D create or replace table r1 as select range, (random()*100)::UINT8 as r from range(0,500000);
D create or replace table r2 as select range, (random()*100)::UINT8 as r from range(0,500000);
D explain analyze select avg(r1.range + r2.range) from r1 join r2 on r1.r = r2.r;
</code>```

I see that Total Time (~9s) is less than the HASH_JOIN operator time (~21s), how should I interpret that?

```<code>┌─────────────────────────────────────┐
│┌───────────────────────────────────┐│
││         Total Time: 9.10s         ││
│└───────────────────────────────────┘│
└─────────────────────────────────────┘
┌───────────────────────────┐
│      EXPLAIN_ANALYZE      │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             0             │
│          (0.00s)          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│    UNGROUPED_AGGREGATE    │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│          avg(#0)          │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             1             │
│          (6.83s)          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         PROJECTION        │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│     (range) + (range)     │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│         2499963940        │
│          (4.69s)          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         HASH_JOIN         │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│           INNER           │
│           r = r           │
│   EC = 2551020408.163265  ├──────────────┐
│  COST = 2551020408.163265 │              │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │              │
│         2499963940        │              │
│          (21.19s)         │              │
└─────────────┬─────────────┘              │
┌─────────────┴─────────────┐┌─────────────┴─────────────┐
│          SEQ_SCAN         ││          SEQ_SCAN         │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   ││   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             r1            ││             r2            │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   ││   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             r             ││             r             │
│           range           ││           range           │
│         EC=500000         ││         EC=500000         │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   ││   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│           500000          ││           500000          │
│          (0.00s)          ││          (0.00s)          │
└───────────────────────────┘└───────────────────────────┘
</code>```

Body:
When I use explain analyze to profile a join query:

D create or replace table r1 as select range, (random()*100)::UINT8 as r from range(0,500000);
D create or replace table r2 as select range, (random()*100)::UINT8 as r from range(0,500000);
D explain analyze select avg(r1.range + r2.range) from r1 join r2 on r1.r = r2.r;

I see that Total Time (~9s) is less than the HASH_JOIN operator time (~21s), how should I interpret that?

┌─────────────────────────────────────┐
│┌───────────────────────────────────┐│
││         Total Time: 9.10s         ││
│└───────────────────────────────────┘│
└─────────────────────────────────────┘
┌───────────────────────────┐
│      EXPLAIN_ANALYZE      │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             0             │
│          (0.00s)          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│    UNGROUPED_AGGREGATE    │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│          avg(#0)          │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             1             │
│          (6.83s)          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         PROJECTION        │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│     (range) + (range)     │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│         2499963940        │
│          (4.69s)          │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         HASH_JOIN         │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│           INNER           │
│           r = r           │
│   EC = 2551020408.163265  ├──────────────┐
│  COST = 2551020408.163265 │              │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │              │
│         2499963940        │              │
│          (21.19s)         │              │
└─────────────┬─────────────┘              │
┌─────────────┴─────────────┐┌─────────────┴─────────────┐
│          SEQ_SCAN         ││          SEQ_SCAN         │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   ││   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             r1            ││             r2            │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   ││   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│             r             ││             r             │
│           range           ││           range           │
│         EC=500000         ││         EC=500000         │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   ││   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
│           500000          ││           500000          │
│          (0.00s)          ││          (0.00s)          │
└───────────────────────────┘└───────────────────────────┘


问:
How can I update my experience array in profile using prisma
```<code>model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  avatar    String
  userId    String
  password  String
  createdAt String
  profile   Profile?
}

model Profile {
  id             Int          @id @default(autoincrement())
  company        String?
  website        String?
  location       String?
  email          String?
  skills         String[]
  status         String
  bio            String?
  githubusername String?
  user           User?        @relation(fields: [userId], references: [id])
  userId         Int          @unique
  createdAt      String
  experience     Experience[]
  education      Education[]
  socials        Social?
}

model Experience {
  id           Int      @id @default(autoincrement())
  title        String?
  company      String?
  location     String?
  from         String?
  to           String?
  current      Boolean?
  createdAt    String?
  profile      Profile? @relation(fields: [experienceId], references: [id], onDelete: Cascade)
  experienceId Int?     @unique
}
const profile = await prisma.profile.update({where: { id: profileData.id },data: {experience: {
deleteMany: {id: { in: profileData.experience.map((exp) => exp.id) }},
createMany: {data: [{ title,company,current,from,to,createdAt: new Date().toDateString(),location],
},},},

    include: {experience: true,},}

);
</code>```

I was hoping to get something like this:

```<code>experience:[{title:"",location:"", ....},{title:"",location:"",...}]. kindly help me as am new in prisma.
</code>```

Body:
model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  avatar    String
  userId    String
  password  String
  createdAt String
  profile   Profile?
}

model Profile {
  id             Int          @id @default(autoincrement())
  company        String?
  website        String?
  location       String?
  email          String?
  skills         String[]
  status         String
  bio            String?
  githubusername String?
  user           User?        @relation(fields: [userId], references: [id])
  userId         Int          @unique
  createdAt      String
  experience     Experience[]
  education      Education[]
  socials        Social?
}

model Experience {
  id           Int      @id @default(autoincrement())
  title        String?
  company      String?
  location     String?
  from         String?
  to           String?
  current      Boolean?
  createdAt    String?
  profile      Profile? @relation(fields: [experienceId], references: [id], onDelete: Cascade)
  experienceId Int?     @unique
}
const profile = await prisma.profile.update({where: { id: profileData.id },data: {experience: {
deleteMany: {id: { in: profileData.experience.map((exp) => exp.id) }},
createMany: {data: [{ title,company,current,from,to,createdAt: new Date().toDateString(),location],
},},},

    include: {experience: true,},}

);

I was hoping to get something like this:

experience:[{title:"",location:"", ....},{title:"",location:"",...}]. kindly help me as am new in prisma.


问:
How to use twitter API v2 in wordpress php? // I can't get the oauth 1 auth headers right on the request and get error "Not Authenticated"
TLDR: Trying to post a tweet everytime someone posts on wordpress but can't authenticate correctly with oauth 1 to use the /2/tweets endpoint.

So I was annoyed when Jetpack social on my site decided to start charging for tweet scheduling. Usually I would be fine with this but it just seemed dumb that they were charging for something that I could build in a few days. So I'm planning on making an open source plugin that let's anyone use their wordpress as a tweet scheduler.

I'm currently struggling to properly authenticate with oauth to use the api v2. There's a lot of content out there for v1 but far less for v2 and particuarly v2 with wordpress.

Here's the resources I've used:

-https://www.youtube.com/watch?v=jOlJ5VJ_kSw for the oauth code

-https://developer.wordpress.org/reference/functions/wp_remote_post/ for the wp_remote_post() api call

-Numerous stack articles ie Wordpress twitter api 1.1 search class
which provides a good solution for 1.1 but I have made the possibly
false assumption based on what I've seen that 1.1 is now deprecated

-https://developer.twitter.com/en/docs/authentication/oauth-1-0a/creating-a-signature
shows you how to make a signature for a 1.1 endpoint to post a tweet.

I believe the problem is with the parameters I pass in for oauth, I used all that params from the above twitter docs article but that was 1.1 so possibly an issue.

Here's my code:

```<code>function focus_tweet_getSignature($endpoint, $method, $params, $focus_tweet_api_key_secret, $focus_tweet_access_token_secret)
{
    uksort($params, 'strcmp');

    foreach ($params as $key => $value) {
        $params[$key] = rawurlencode($key) . '=' . rawurlencode($value);
    }

    $signatureBase = array(
        rawurlencode($method),
        rawurlencode($endpoint),
        rawurlencode(implode('&', $params)),
    );
    $signatureBaseString = implode('&', $signatureBase);

    $signatureKey = array(
        rawurlencode($focus_tweet_api_key_secret),
        rawurlencode($focus_tweet_access_token_secret),
    );

    $signatureKeyString = implode('&', $signatureKey);

    return base64_encode(hash_hmac('sha1', $signatureBaseString, $signatureKeyString, true));
}

// 'oauth_consumer_key',
// 'oauth_nonce',
// 'oauth_signature',
// 'oauth_signature_method',
// 'oauth_timestamp',
// 'oauth_token',
// 'oauth_version',
// 'status'

function focus_tweet_getAuthorizationString($oauth)
{
    $authorizationString = 'Authorization OAuth:';
    $count = 0;

    foreach ($oauth as $key => $value) {
        $authorizationString .= !$count ? ' ' : ', ';
        $authorizationString .= rawurlencode($key) . '="' . rawurlencode($value) . '"';
        $count++;
    }

    return $authorizationString;
}

function focus_tweet_makeApiCall( $apiParams, $focus_tweet_status ){
    $response = wp_remote_post($apiParams['endpoint'], array(
        'method' => $apiParams['method'],
        'headers' => array(
            array(
                'Accept: application/json',
                $apiParams['authorization'],
                'Expect:'
            ),
        ),
        'body' => "{
            'text': $focus_tweet_status
        }",
    )
    );
    //If response is not 200, trigger fatal error
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) {
        //Combine response details and build auth header function
        $focus_tweet_res_body = wp_remote_retrieve_body($response);
        wp_die($apiParams['authorization'] . '&' . $focus_tweet_res_body);
    } else {
        wp_die("Tweeted!");
    }
}

function focus_tweet_tweet($focus_tweet_status)
{
    $focus_tweet_api_key = '';
    $focus_tweet_api_key_secret = '';
    $focus_tweet_access_token = '';
    $focus_tweet_access_token_secret = '';
    $oauth = array(
        'oauth_consumer_key' => $focus_tweet_api_key,
        'oauth_nonce' => md5(microtime() . mt_rand()),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_token' => $focus_tweet_access_token,
        'oauth_timestamp' => time(),
        'oauth_version' => '1.0',
        'status' => $focus_tweet_status,
    );
    $oauth['oauth_signature'] = focus_tweet_getSignature('https://api.twitter.com/2/tweets', 'POST', $oauth, $focus_tweet_api_key_secret, $focus_tweet_access_token_secret);
    $apiParams = array(
        'method' => 'POST',
        'endpoint' => 'https://api.twitter.com/2/tweets',
        'authorization' => focus_tweet_getAuthorizationString($oauth),
        'url_params' => array(),
    );
    focus_tweet_makeApiCall($apiParams, $focus_tweet_status);
}
</code>```

Triggered when I save a post for now while I'm testing.

Warning: Array to string conversion in C:\Users\Will\Local Sites\plugintestbench\app\public\wp-includes\class-requests.php on line 800
Authorization OAuth: oauth_consumer_key="", oauth_nonce="", oauth_signature_method="HMAC-SHA1", oauth_token="", oauth_timestamp="1672918493", oauth_version="1.0", status="Hello%20World%21", oauth_signature=""&{ "title": "Unauthorized", "type": "about:blank", "status": 401, "detail": "Unauthorized" }

The warning I believe is fine for now although will fix later.

I have used the credentials to post a tweet from postman so that's not the issue.

I initially believed that it was not possible to use curl in wordpress so may try switching to that although I really believe that the issue is with the oauth params.

(Including twitter/flickr api calls on every page load (WordPress))

Will keep this post updated while I work on this and will ofcourse post the finished github code once it's completed.

Body:
TLDR: Trying to post a tweet everytime someone posts on wordpress but can't authenticate correctly with oauth 1 to use the /2/tweets endpoint.

So I was annoyed when Jetpack social on my site decided to start charging for tweet scheduling. Usually I would be fine with this but it just seemed dumb that they were charging for something that I could build in a few days. So I'm planning on making an open source plugin that let's anyone use their wordpress as a tweet scheduler.

I'm currently struggling to properly authenticate with oauth to use the api v2. There's a lot of content out there for v1 but far less for v2 and particuarly v2 with wordpress.

Here's the resources I've used:

-https://www.youtube.com/watch?v=jOlJ5VJ_kSw for the oauth code

-https://developer.wordpress.org/reference/functions/wp_remote_post/ for the wp_remote_post() api call

-Numerous stack articles ie Wordpress twitter api 1.1 search class
which provides a good solution for 1.1 but I have made the possibly
false assumption based on what I've seen that 1.1 is now deprecated

-https://developer.twitter.com/en/docs/authentication/oauth-1-0a/creating-a-signature
shows you how to make a signature for a 1.1 endpoint to post a tweet.

I believe the problem is with the parameters I pass in for oauth, I used all that params from the above twitter docs article but that was 1.1 so possibly an issue.

Here's my code:

function focus_tweet_getSignature($endpoint, $method, $params, $focus_tweet_api_key_secret, $focus_tweet_access_token_secret)
{
    uksort($params, 'strcmp');

    foreach ($params as $key => $value) {
        $params[$key] = rawurlencode($key) . '=' . rawurlencode($value);
    }

    $signatureBase = array(
        rawurlencode($method),
        rawurlencode($endpoint),
        rawurlencode(implode('&', $params)),
    );
    $signatureBaseString = implode('&', $signatureBase);

    $signatureKey = array(
        rawurlencode($focus_tweet_api_key_secret),
        rawurlencode($focus_tweet_access_token_secret),
    );

    $signatureKeyString = implode('&', $signatureKey);

    return base64_encode(hash_hmac('sha1', $signatureBaseString, $signatureKeyString, true));
}

// 'oauth_consumer_key',
// 'oauth_nonce',
// 'oauth_signature',
// 'oauth_signature_method',
// 'oauth_timestamp',
// 'oauth_token',
// 'oauth_version',
// 'status'

function focus_tweet_getAuthorizationString($oauth)
{
    $authorizationString = 'Authorization OAuth:';
    $count = 0;

    foreach ($oauth as $key => $value) {
        $authorizationString .= !$count ? ' ' : ', ';
        $authorizationString .= rawurlencode($key) . '="' . rawurlencode($value) . '"';
        $count++;
    }

    return $authorizationString;
}

function focus_tweet_makeApiCall( $apiParams, $focus_tweet_status ){
    $response = wp_remote_post($apiParams['endpoint'], array(
        'method' => $apiParams['method'],
        'headers' => array(
            array(
                'Accept: application/json',
                $apiParams['authorization'],
                'Expect:'
            ),
        ),
        'body' => "{
            'text': $focus_tweet_status
        }",
    )
    );
    //If response is not 200, trigger fatal error
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) {
        //Combine response details and build auth header function
        $focus_tweet_res_body = wp_remote_retrieve_body($response);
        wp_die($apiParams['authorization'] . '&' . $focus_tweet_res_body);
    } else {
        wp_die("Tweeted!");
    }
}

function focus_tweet_tweet($focus_tweet_status)
{
    $focus_tweet_api_key = '';
    $focus_tweet_api_key_secret = '';
    $focus_tweet_access_token = '';
    $focus_tweet_access_token_secret = '';
    $oauth = array(
        'oauth_consumer_key' => $focus_tweet_api_key,
        'oauth_nonce' => md5(microtime() . mt_rand()),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_token' => $focus_tweet_access_token,
        'oauth_timestamp' => time(),
        'oauth_version' => '1.0',
        'status' => $focus_tweet_status,
    );
    $oauth['oauth_signature'] = focus_tweet_getSignature('https://api.twitter.com/2/tweets', 'POST', $oauth, $focus_tweet_api_key_secret, $focus_tweet_access_token_secret);
    $apiParams = array(
        'method' => 'POST',
        'endpoint' => 'https://api.twitter.com/2/tweets',
        'authorization' => focus_tweet_getAuthorizationString($oauth),
        'url_params' => array(),
    );
    focus_tweet_makeApiCall($apiParams, $focus_tweet_status);
}

Triggered when I save a post for now while I'm testing.

Warning: Array to string conversion in C:\Users\Will\Local Sites\plugintestbench\app\public\wp-includes\class-requests.php on line 800
Authorization OAuth: oauth_consumer_key="", oauth_nonce="", oauth_signature_method="HMAC-SHA1", oauth_token="", oauth_timestamp="1672918493", oauth_version="1.0", status="Hello%20World%21", oauth_signature=""&{ "title": "Unauthorized", "type": "about:blank", "status": 401, "detail": "Unauthorized" }

The warning I believe is fine for now although will fix later.

I have used the credentials to post a tweet from postman so that's not the issue.

I initially believed that it was not possible to use curl in wordpress so may try switching to that although I really believe that the issue is with the oauth params.

(Including twitter/flickr api calls on every page load (WordPress))

Will keep this post updated while I work on this and will ofcourse post the finished github code once it's completed.