问:
Why is numpy.random.seed() a legacy function?
I often use numpy.random.seed() for reproducibility of results. I also find it helpful when books/tutorials use it (e.g., np.random.seed(42)), so that people can reproduce things more easily.

The the documentation for random.seed() now says it is not encouraged and is a legacy function, but without any explanation. I am wondering why:

```<code>random.seed()

Reseed a legacy MT19937 BitGenerator

This is a convenience, legacy function.

The best practice is to not reseed a BitGenerator,
rather to recreate a new one. This method is here
for legacy reasons.
</code>```

More details

Note the documentation goes on to say:

```<code># This example demonstrates best practice.
from numpy.random import MT19937
from numpy.random import RandomState, SeedSequence
rs = RandomState(MT19937(SeedSequence(123456789)))
# Later, you want to restart the stream
rs = RandomState(MT19937(SeedSequence(987654321)))
</code>```

I'm not sure why this is best practice. Why is that better than using random.seed()? In particular, when you are teaching a concept and want to reproduce the same result every time and want to keep your code simple? At least on the surface, random.seed() also invokes the MT19937 BitGenerator (though from the docs it is a legacy bit generator, so they are not the same).

答: As mentioned in the comments, you can read about it in the new policy. The new policy assures more consistent results across different OS and build methods, as the old one now accessible like this is now legacy.</p>

Body:
I often use numpy.random.seed() for reproducibility of results. I also find it helpful when books/tutorials use it (e.g., np.random.seed(42)), so that people can reproduce things more easily.

The the documentation for random.seed() now says it is not encouraged and is a legacy function, but without any explanation. I am wondering why:

random.seed()

Reseed a legacy MT19937 BitGenerator

This is a convenience, legacy function.

The best practice is to not reseed a BitGenerator,
rather to recreate a new one. This method is here
for legacy reasons.

More details

Note the documentation goes on to say:

# This example demonstrates best practice.
from numpy.random import MT19937
from numpy.random import RandomState, SeedSequence
rs = RandomState(MT19937(SeedSequence(123456789)))
# Later, you want to restart the stream
rs = RandomState(MT19937(SeedSequence(987654321)))

I'm not sure why this is best practice. Why is that better than using random.seed()? In particular, when you are teaching a concept and want to reproduce the same result every time and want to keep your code simple? At least on the surface, random.seed() also invokes the MT19937 BitGenerator (though from the docs it is a legacy bit generator, so they are not the same).


来源: stackexchange

问:
nginx reverse proxy with docker-compose config to serve traffic to multiple domains
I am trying to use nginx with docker-compose to route traffic for two different apps with different domain names. I want to be able to go to publisher.dev but I can only access that app from localhost:3000 (this is a react app) and I have another app which I want to access from widget.dev but I can only access from localhost:8080 (this is a Preact app). This is my folder structure and configs:

```<code>|-docker-compose.yml
|-nginx
|--default.conf
|--Dockerfile.dev
|-publisher
|--// react app
|--Dockerfile.dev
|-widget
|--// preact app (widget)
|--Dockerfile.dev
</code>```
```<code># default.conf
upstream publisher {
  server localhost:3000;
}

upstream widget {
  server localhost:8080;
}

server {
  listen 80;
  server_name publisher.dev;
  location / {
    proxy_pass http://publisher/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }

}

server {
  listen 80;
  server_name widget.dev;
  location / {
    proxy_pass http://widget/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

</code>```

nginx Dockerfile.dev

```<code>FROM nginx:stable-alpine
COPY ./default.conf /etc/nginx/conf.d/default.conf
</code>```

publisher Dockerfile.dev (same as widget Dockerfile.dev)

```<code># Specify the base image
FROM node:16-alpine

# Specify the working directory inside the container
WORKDIR /app

# copy the package json from your local hard drive to the container
COPY ./package.json ./

# install dependencies
RUN npm install

# copy files from local hard drive into container
# by copying the package.json and running npm install before copy files,
# this insures that a change to a file does not cause a re-run of npm-install
COPY ./ ./

# command to run when the container starts up
CMD ["npm", "run", "start"]

# build this docker container with:
# docker build -f Dockerfile.dev .

# run this container with:
# docker run <container id>
</code>```

docker-compose.yml

```<code>version: '3'
services:
  nginx:
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - 3050:80
    restart: always
    depends_on:
      - publisher
      - widget

  publisher:
    stdin_open: true
    build:
      dockerfile: Dockerfile.dev
      context: ./publisher
    volumes:
      - /app/node_modules
      - ./publisher:/app
    ports:
      - 3000:3000
    environment:
      VIRTUAL_HOST: publisher.dev

  widget:
    stdin_open: true
    build:
      dockerfile: Dockerfile.dev
      context: ./widget
    volumes:
      - /app/node_modules
      - ./widget:/app
    ports:
      - 8080:8080
    environment:
      VIRTUAL_HOST: widget.dev

</code>```

hosts file

```<code>
127.0.0.1 publisher.dev
127.0.0.1 widget.dev
</code>```

答:
why is your upstream trying to connect with
publisher and widget, shouldn't they connect to localhost:3000 and localhost:8080, let upstream server name be publisher and widget but connect them to localhost.</p>
```<code>upstream publisher {
  #server publisher:3000;
  server localhost:3000;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use nginx with docker-compose to route traffic for two different apps with different domain names. I want to be able to go to publisher.dev but I can only access that app from localhost:3000 (this is a react app) and I have another app which I want to access from widget.dev but I can only access from localhost:8080 (this is a Preact app). This is my folder structure and configs:

|-docker-compose.yml
|-nginx
|--default.conf
|--Dockerfile.dev
|-publisher
|--// react app
|--Dockerfile.dev
|-widget
|--// preact app (widget)
|--Dockerfile.dev

# default.conf
upstream publisher {
  server localhost:3000;
}

upstream widget {
  server localhost:8080;
}

server {
  listen 80;
  server_name publisher.dev;
  location / {
    proxy_pass http://publisher/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }

}

server {
  listen 80;
  server_name widget.dev;
  location / {
    proxy_pass http://widget/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

nginx Dockerfile.dev

FROM nginx:stable-alpine
COPY ./default.conf /etc/nginx/conf.d/default.conf

publisher Dockerfile.dev (same as widget Dockerfile.dev)

# Specify the base image
FROM node:16-alpine

# Specify the working directory inside the container
WORKDIR /app

# copy the package json from your local hard drive to the container
COPY ./package.json ./

# install dependencies
RUN npm install

# copy files from local hard drive into container
# by copying the package.json and running npm install before copy files,
# this insures that a change to a file does not cause a re-run of npm-install
COPY ./ ./

# command to run when the container starts up
CMD ["npm", "run", "start"]

# build this docker container with:
# docker build -f Dockerfile.dev .

# run this container with:
# docker run <container id>

docker-compose.yml

version: '3'
services:
  nginx:
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - 3050:80
    restart: always
    depends_on:
      - publisher
      - widget

  publisher:
    stdin_open: true
    build:
      dockerfile: Dockerfile.dev
      context: ./publisher
    volumes:
      - /app/node_modules
      - ./publisher:/app
    ports:
      - 3000:3000
    environment:
      VIRTUAL_HOST: publisher.dev

  widget:
    stdin_open: true
    build:
      dockerfile: Dockerfile.dev
      context: ./widget
    volumes:
      - /app/node_modules
      - ./widget:/app
    ports:
      - 8080:8080
    environment:
      VIRTUAL_HOST: widget.dev

hosts file

127.0.0.1 publisher.dev
127.0.0.1 widget.dev

Body:
why is your upstream trying to connect with
publisher and widget, shouldn't they connect to localhost:3000 and localhost:8080, let upstream server name be publisher and widget but connect them to localhost.

upstream publisher {
  #server publisher:3000;
  server localhost:3000;
}


问:
Flutter ThemeData Primary color not changing from theme when trying to add a primary color
Im following the BMI Calculator app from the London App Brewery on LinkedIn Learning.
when attempting to set the primaryColor to red, my emulator still shows the Light Blue default AppBar even though i am overriding the Primary Color. here's  the code</p>
```<code>    import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.red,
      ),
      home: const InputPage(),
    );
  }
}

class InputPage extends StatefulWidget {
  const InputPage({Key? key}) : super(key: key);

  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BMI CALCULATOR'),
      ),
      body: const Center(
        child: Text('Body Text'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: const Icon(Icons.add),
      ),
    );
  }
}
</code>```

答:
This issue has been pointed at flutter github page. They say

We will eventually be moving all components away from ThemeData.primaryColor

So you can use

```<code> theme: ThemeData(
     colorScheme: ColorScheme.light().copyWith(primary: Colors.red),
 );
</code>```

Body:
Im following the BMI Calculator app from the London App Brewery on LinkedIn Learning.
when attempting to set the primaryColor to red, my emulator still shows the Light Blue default AppBar even though i am overriding the Primary Color. here's  the code

    import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.red,
      ),
      home: const InputPage(),
    );
  }
}

class InputPage extends StatefulWidget {
  const InputPage({Key? key}) : super(key: key);

  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BMI CALCULATOR'),
      ),
      body: const Center(
        child: Text('Body Text'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: const Icon(Icons.add),
      ),
    );
  }
}

Body:
This issue has been pointed at flutter github page. They say

We will eventually be moving all components away from ThemeData.primaryColor

So you can use

 theme: ThemeData(
     colorScheme: ColorScheme.light().copyWith(primary: Colors.red),
 );


问:
Get checked value from radio button group
I am populating radio buttons dynamically, and on submit button click I need to get value of the checked radio button from the group.

```<code><ul data-bind="foreach: Numbers">
        <li>
            <input name="phone-group" type="radio" data-bind="attr: {'id': $data.id}, value: $data.value" >
            <label data-bind="Text: $data.value, attr:{'for': $data.id }" ></label>
        </li>
</ul>
<button role="link">Submit</button>
</code>```

This is the model: (coffeescript)

@Numbers = ko.observableArray([{id:"1",value:"1234"}, {id:"2",value:"5678"}, {id:"3",value:"91011"}])

On submit button click, I need the selected value from the radio button list.

答:
To do this in a knockoutjs way, the only thing I can see missing is you are not  using the checked binding to get the value selected.

var ViewModel = function() {
  var self = this;
  self.Numbers = ko.observableArray([{
    id: "1",
    value: "1234"
  }, {
    id: "2",
    value: "5678"
  }, {
    id: "3",
    value: "91011"
  }]);

  self.selectedNumber = ko.observable();
  self.submit = function(){
    alert("selected Number: " + self.selectedNumber());
  }
}
ko.applyBindings(new ViewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: Numbers">
  <li>
    <input name="phone-group" type="radio" data-bind="attr: {'id': $data.id}, value: $data.value, checked: $parent.selectedNumber">
    <label data-bind="text: $data.value, attr:{'for': $data.id }"></label>
  </li>
</ul>
<button role="link" data-bind="click: submit">Submit</button></code>```

Body:
I am populating radio buttons dynamically, and on submit button click I need to get value of the checked radio button from the group.

            <input name="phone-group" type="radio" data-bind="attr: {'id': $data.id}, value: $data.value" >

<button role="link">Submit</button>

This is the model: (coffeescript)

@Numbers = ko.observableArray([{id:"1",value:"1234"}, {id:"2",value:"5678"}, {id:"3",value:"91011"}])

On submit button click, I need the selected value from the radio button list.

Body:
To do this in a knockoutjs way, the only thing I can see missing is you are not  using the checked binding to get the value selected.

var ViewModel = function() {
  var self = this;
  self.Numbers = ko.observableArray([{
    id: "1",
    value: "1234"
  }, {
    id: "2",
    value: "5678"
  }, {
    id: "3",
    value: "91011"
  }]);

  self.selectedNumber = ko.observable();
  self.submit = function(){
    alert("selected Number: " + self.selectedNumber());
  }
}
ko.applyBindings(new ViewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: Numbers">
  <li>
    <input name="phone-group" type="radio" data-bind="attr: {'id': $data.id}, value: $data.value, checked: $parent.selectedNumber">
    <label data-bind="text: $data.value, attr:{'for': $data.id }"></label>
  </li>
</ul>
<button role="link" data-bind="click: submit">Submit</button>


问:
Expanding a list of numbers into a matrix (list with n values to multiply to a n x n matrix)
I have a set of numbers, which I want to expand into a matrix.
There are 4 values in the list which I want to expand into a 4x4 matrix.
Here is some example data

```<code>freq <- c(627,449,813,111)
</code>```

I want to expand this into a matrix of so that it's like this.
Apologies I have just copied and pasted data, thus it's not an R output, but hope it helps to get the idea across.

```<code>    1   2   3   4   Total
1   197 141 255 35  627
2   141 101 183 25  449
3   255 183 330 45  813
4   35  25  45  6   111
    627 449 813 111 2000
</code>```

The cells are multiplication of the (row total)x(column total)/(table total). The value in 1,1 = (627 x 627)/2000 = 197. The value in 2,1 = (627 x 449)/2000 = 141, and so on.

Is there a function that will create this matrix? I will try to do it via a loop but was hoping there is a function or matrix calculation trick that can do this more efficiently? Apologies if I didn't articulate the above too well, any help is greatly appreciated. Thanks

答:
It doesn't really matter here, but it is good practice to avoid constructions like outer(x, x) / sum(x) in favour of ones like tcrossprod(x / sqrt(sum(x))):

round(tcrossprod(freq / sqrt(sum(freq))))
##      [,1] [,2] [,3] [,4]
## [1,]  197  141  255   35
## [2,]  141  101  183   25
## [3,]  255  183  330   45
## [4,]   35   25   45    6
```

There are a few issues with the outer approach:

outer(x, x) evaluates tcrossprod(as.vector(x), as.vector(x)) internally. The as.vector calls and everything else that happens inside of outer are completely redundant if x is already a vector. The as.vector calls are actually worse than redundant: if x has any attributes, then as.vector(x) requires a deep copy of x.

Naively doing A <- outer(x, x); A / sum(x) requires R to allocate memory for two n-by-n matrices. For large enough n, that can be quite wasteful, if not impossible. R is clever enough to avoid the second allocation if you compute outer(x, x) / sum(x) directly. However, such optimizations are low level, come with a number of gotchas, and are not even documented in ?Arithmetic, so it can be unsafe to rely on them.

outer(x, x) can result in underflow or overflow if the elements of x are very (very) small or large.

tcrossprod(x / sqrt(sum(x))) avoids all of these issues by scaling x before computing an outer product and cutting out all of the redundancies of outer.

Body:
I have a set of numbers, which I want to expand into a matrix.
There are 4 values in the list which I want to expand into a 4x4 matrix.
Here is some example data

freq <- c(627,449,813,111)

I want to expand this into a matrix of so that it's like this.
Apologies I have just copied and pasted data, thus it's not an R output, but hope it helps to get the idea across.

    1   2   3   4   Total
1   197 141 255 35  627
2   141 101 183 25  449
3   255 183 330 45  813
4   35  25  45  6   111
    627 449 813 111 2000

The cells are multiplication of the (row total)x(column total)/(table total). The value in 1,1 = (627 x 627)/2000 = 197. The value in 2,1 = (627 x 449)/2000 = 141, and so on.

Is there a function that will create this matrix? I will try to do it via a loop but was hoping there is a function or matrix calculation trick that can do this more efficiently? Apologies if I didn't articulate the above too well, any help is greatly appreciated. Thanks

Body:
It doesn't really matter here, but it is good practice to avoid constructions like outer(x, x) / sum(x) in favour of ones like tcrossprod(x / sqrt(sum(x))):

round(tcrossprod(freq / sqrt(sum(freq))))
##      [,1] [,2] [,3] [,4]
## [1,]  197  141  255   35
## [2,]  141  101  183   25
## [3,]  255  183  330   45
## [4,]   35   25   45    6

There are a few issues with the outer approach:

outer(x, x) evaluates tcrossprod(as.vector(x), as.vector(x)) internally. The as.vector calls and everything else that happens inside of outer are completely redundant if x is already a vector. The as.vector calls are actually worse than redundant: if x has any attributes, then as.vector(x) requires a deep copy of x.

Naively doing A <- outer(x, x); A / sum(x) requires R to allocate memory for two n-by-n matrices. For large enough n, that can be quite wasteful, if not impossible. R is clever enough to avoid the second allocation if you compute outer(x, x) / sum(x) directly. However, such optimizations are low level, come with a number of gotchas, and are not even documented in ?Arithmetic, so it can be unsafe to rely on them.

outer(x, x) can result in underflow or overflow if the elements of x are very (very) small or large.

tcrossprod(x / sqrt(sum(x))) avoids all of these issues by scaling x before computing an outer product and cutting out all of the redundancies of outer.


问:
Add a 1-hour expiration to the current time/date
```<code>//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration
</code>```

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

```<code>$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");
</code>```

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking

答:
```<code>$expire = date("F j, Y, H:i", strtotime('+1 hour'));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking


问:
Fail on that syntax .liquid (learning stage)
on my way to learn .liquid, i can't found issue on that syntax:

```<code>{{ 'visa.svg' | asset_img_url | image_url: width: 36, height: 36 | image_tag: alt: 'Visa', srcset: nil, class: 'filter-green', loading: 'lazy' }}
</code>```

Fail: Liquid error (sections/footer.liquid line 264): invalid url input

Where is the fail? :(

答:
It's because 'visa.svg' is not an image type object (nor 'visa.png' is).

asset_img_url returns URL and image_url expects image object. So there is a conflict "wrong input".

From docs:

image_url Returns the URL of an image. You can use image_url on the
following objects:

product, variant, line, item, collection, article, image

The Image Object

An image object returns information about an image. Image objects are usually attributes of other objects, such as product, variant, collection, and article.

Body:
on my way to learn .liquid, i can't found issue on that syntax:

{{ 'visa.svg' | asset_img_url | image_url: width: 36, height: 36 | image_tag: alt: 'Visa', srcset: nil, class: 'filter-green', loading: 'lazy' }}

Fail: Liquid error (sections/footer.liquid line 264): invalid url input

Where is the fail? :(


问:
Acumatica / problem updating a free field in a closed invoice
When I update the usrDocCom field, I get the error message:

Error: Updating  'SO Invoice' record raised at least one error. Please review the errors. Error: 'Project' cannot be empty.

I tried to remove the controls from the project field, but without result

```<code>    protected void ARTran_RowSelected(PXCache cache, PXRowSelectedEventArgs e, PXRowSelected InvokeBaseHandler)
{
  if(InvokeBaseHandler != null)
    InvokeBaseHandler(cache, e);

   var row = (ARTran) e.Row;

    if (row != null )
    {
      PXUIFieldAttribute.SetEnabled(cache, row, false);
      PXUIFieldAttribute.SetEnabled<ARTranExt.usrDocCom>(cache, row, true);
    }
}

    protected void ARInvoice_RowSelected(PXCache cache, PXRowSelectedEventArgs e, PXRowSelected InvokeBaseHandler)
{
  if(InvokeBaseHandler != null)
    InvokeBaseHandler(cache, e);
  var row = (ARInvoice)e.Row;

  **Base.Transactions.Cache.AllowUpdate = true;** // permet de mettre à jour les informations libre des lignes

}
</code>```

Thanks
Xavier

答:
Two things...

be sure the project field has at least the non-project code assigned.  Usually the value is represented by 'X'

it is recommended that you create a workflow and set the enabled property as true, in the Completed/Closed state of the invoice.

Body:
When I update the usrDocCom field, I get the error message:

Error: Updating  'SO Invoice' record raised at least one error. Please review the errors. Error: 'Project' cannot be empty.

I tried to remove the controls from the project field, but without result

    protected void ARTran_RowSelected(PXCache cache, PXRowSelectedEventArgs e, PXRowSelected InvokeBaseHandler)
{
  if(InvokeBaseHandler != null)
    InvokeBaseHandler(cache, e);

   var row = (ARTran) e.Row;

    if (row != null )
    {
      PXUIFieldAttribute.SetEnabled(cache, row, false);
      PXUIFieldAttribute.SetEnabled<ARTranExt.usrDocCom>(cache, row, true);
    }
}

    protected void ARInvoice_RowSelected(PXCache cache, PXRowSelectedEventArgs e, PXRowSelected InvokeBaseHandler)
{
  if(InvokeBaseHandler != null)
    InvokeBaseHandler(cache, e);
  var row = (ARInvoice)e.Row;

  **Base.Transactions.Cache.AllowUpdate = true;** // permet de mettre à jour les informations libre des lignes

}

Thanks
Xavier


问:
React: Card component share same state
Created RenderCard component which creates multiple cards for given data.

I am creating bulk selection of card means selecting multiple cards. So when user click on circle present at the top left then that circle become check circle

So here the issue is that all card gets selected when user click on any card. So I want only that card select which users click

```<code>const Card = () => {
  const [cardSelect, setCardSelect] = useState(false)
  const onMouseEnter =  () => {
    console.log("onMouseEnter1")
  }

  const onMouseLeave =  () => {
    console.log("onMouseLeave1")
  }

  const logMessage =  () => {
    setCardSelect(prevCheck => !prevCheck);
  }
  const RenderCard = () => {
    return album.map(item => {
      return (
        <Col className='container' onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} key={item.title} md='2'>
          <Card>
            <div>
              <Link to={`/pages/blog/detail/${item.id}`}>
                <CardImg className='img-fluid image' src={item.img} alt={item.title} top />
              </Link>
            </div>
              <div className='select-card'>
              {cardSelect ? <CheckCircle onClick={logMessage} /> : <Circle onClick={logMessage}  />}
            </div>
            <CardBody>
              <CardTitle className="image2 te" >
                  <b>{item.title}</b>
              </CardTitle>
              <CardText>{item.comment} Comments</CardText>
            </CardBody>
          </Card>
        </Col>
      )
    })
  }
  return (
    <>
      <Row>
        <RenderCard />
      </Row>
    </>
  )
}
</code>```

Anyone can point me in the right direction where I am doing mistakes.

Thanks

答:
If i understand you correctly i would suggest that
you should wrap anything that is inside the return statement and refactor it to its own component, and then pass item as prop in that component and make the clickhandler inside that component. like this:

```<code>const RenderCard = () => {
    return album.map(item => {
      return ( <Component item={item} />)
  }
</code>```

Now the component have its own state that shows either its clicked or not clicked

Title: React: Card component share same state

Body:
Created RenderCard component which creates multiple cards for given data.

I am creating bulk selection of card means selecting multiple cards. So when user click on circle present at the top left then that circle become check circle

So here the issue is that all card gets selected when user click on any card. So I want only that card select which users click

const Card = () => {
  const [cardSelect, setCardSelect] = useState(false)
  const onMouseEnter =  () => {
    console.log("onMouseEnter1")
  }

  const onMouseLeave =  () => {
    console.log("onMouseLeave1")
  }

  const logMessage =  () => {
    setCardSelect(prevCheck => !prevCheck);
  }
  const RenderCard = () => {
    return album.map(item => {
      return (
        <Col className='container' onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} key={item.title} md='2'>
          <Card>

              <Link to={`/pages/blog/detail/${item.id}`}>
                <CardImg className='img-fluid image' src={item.img} alt={item.title} top />
              </Link>

              {cardSelect ? <CheckCircle onClick={logMessage} /> : <Circle onClick={logMessage}  />}

            <CardBody>
              <CardTitle className="image2 te" >
                  {item.title}
              </CardTitle>
              <CardText>{item.comment} Comments</CardText>
            </CardBody>
          </Card>
        </Col>
      )
    })
  }
  return (
    <>
      <Row>
        <RenderCard />
      </Row>
    </>
  )
}

Anyone can point me in the right direction where I am doing mistakes.

Thanks

Body:
If i understand you correctly i would suggest that
you should wrap anything that is inside the return statement and refactor it to its own component, and then pass item as prop in that component and make the clickhandler inside that component. like this:

const RenderCard = () => {
    return album.map(item => {
      return ( <Component item={item} />)
  }

Now the component have its own state that shows either its clicked or not clicked


问:
Declarative (Annotation-based) Caching Solution for Java
Besides Spring 3.1 and ehcache-spring-annotations, do we have other alternatives that are other than EhCache and Spring?</p>

答:
Have you looked at Spring-AOP based solutions? You can create an auto-proxy object in your Spring applicationContext using the org.springframework.aop.support.RegexpMethodPointcutAdvisor and then make an object that implements AfterReturningAdvice, ThrowsAdvice and MethodBeforeAdvice.

Use that object to monitor function calls and exits and cache what information you want.

```<code><bean name="cacheHandler" class="org.yourname.CachingInterceptor" />
<bean id="cacheAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
  <property name="advice" ref="cacheHandler" />
  <property name="pattern" value="org.yourname.regex.of.stuff.you.want.cached.*" />
</bean>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
</code>```

Body:
Have you looked at Spring-AOP based solutions? You can create an auto-proxy object in your Spring applicationContext using the org.springframework.aop.support.RegexpMethodPointcutAdvisor and then make an object that implements AfterReturningAdvice, ThrowsAdvice and MethodBeforeAdvice.

Use that object to monitor function calls and exits and cache what information you want.

<bean name="cacheHandler" class="org.yourname.CachingInterceptor" />
<bean id="cacheAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
  <property name="advice" ref="cacheHandler" />
  <property name="pattern" value="org.yourname.regex.of.stuff.you.want.cached.*" />
</bean>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />


问:
Landing page URL should be redirected to "/home"
Current landing page URL after login - 'www.website.com'. But I want it to be redirected to "www.website.com/home" upon login. So it has to be redirected to home component.</p>

答:
If you have a solution to check if the user is log you can do that

```<code><Route exact path="/">
  {loggedIn ? <Redirect to="/home" /> : <LoginPage />}
</Route>
</code>```

If not, you need to redirect to '/home' after login directly after the function of log (in the .then() if you'r loginAction is promise or just after login function).
With React Router v5 : history.push('/home')
With React Router v6 : navigate('/home')
See the doc of React Router if you need more explanation.

Body:
If you have a solution to check if the user is log you can do that

<Route exact path="/">
  {loggedIn ? <Redirect to="/home" /> : <LoginPage />}
</Route>

If not, you need to redirect to '/home' after login directly after the function of log (in the .then() if you'r loginAction is promise or just after login function).
With React Router v5 : history.push('/home')
With React Router v6 : navigate('/home')
See the doc of React Router if you need more explanation.


问:
remove elementor html tags but leave the text inside the tags
I try to remove all html tags that Elementor creates but leave the text inside.

It works, but I'm very sure the RegEx can be simplified so I need only one replace. My code looks like this

I think the easiest way would be to create an array with class names and all tags that include one of these class names will then be removed. But I'm really struggeling with RegEX

```<code>if( !is_admin() ) // not admin side
    add_filter( 'the_content', 'remove_all_elementor_tags' );

function remove_all_elementor_tags( $content )
{

// remove <div class="elementor-widget-container"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-widget-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor-element"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-element\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor-container"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor-section-wrap"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-section-wrap\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <section class="elementor-section"></div>
$re = "/ ?<section[^<]*?class=[\"'][^\"']*\\belementor-section\\b[^\"']*[\"'][^<]*?>| ?<\\/section>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor\\b[^\"']*[\"'][^<]*?>| ?<\\/div/s";

$content = preg_replace($re, "", $content);

    return $content;

}
</code>```

the html content before removing looks like this

```<code><div class="page-content">
    <div data-elementor-type="wp-page" data-elementor-id="257" data-post-id="257" data-obj-id="257" class="elementor elementor-257 dce-elementor-post-257" data-elementor-settings="[]">
        <div class="elementor-section-wrap">
            <section class="elementor-section elementor-top-section elementor-element elementor-element-2e18164 elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="2e18164" data-element_type="section">
                <div class="elementor-container elementor-column-gap-default">
                    <div class="elementor-element elementor-element-1aa904f elementor-widget elementor-widget-dce-rawphp" data-id="1aa904f" data-element_type="widget" data-widget_type="dce-rawphp.default">
                        <div class="elementor-widget-container">
                            <!-- Dynamic PHP Raw -->dies ist der normale Inhalt
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
    <div class="post-tags">
    </div>
</div>
</code>```

the html content after my code looks like this

```<code><div class="page-content">
    <!-- Dynamic PHP Raw -->dies ist der normale Inhalt
    <div class="post-tags">
    </div>
</div>
</code>```

thank you

答:
This removes all the classes and properties of the tags in your HTML code that contain elementor:

```<code>function remove_all_elementor_classes($content)
{
    $content = preg_replace('/class="[^"]*elementor[^"]*"/', '', $content);
    $content = preg_replace('/[^"]*elementor[^"]*="/', '', $content);
    return $content;
}
</code>```

Body:
I try to remove all html tags that Elementor creates but leave the text inside.

It works, but I'm very sure the RegEx can be simplified so I need only one replace. My code looks like this

I think the easiest way would be to create an array with class names and all tags that include one of these class names will then be removed. But I'm really struggeling with RegEX

if( !is_admin() ) // not admin side
    add_filter( 'the_content', 'remove_all_elementor_tags' );

function remove_all_elementor_tags( $content )
{

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-widget-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-element\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-section-wrap\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<section[^<]*?class=[\"'][^\"']*\\belementor-section\\b[^\"']*[\"'][^<]*?>| ?<\\/section>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor\\b[^\"']*[\"'][^<]*?>| ?<\\/div/s";

$content = preg_replace($re, "", $content);

    return $content;

}

the html content before removing looks like this

                            dies ist der normale Inhalt

the html content after my code looks like this

    dies ist der normale Inhalt

thank you

Body:
This removes all the classes and properties of the tags in your HTML code that contain elementor:

function remove_all_elementor_classes($content)
{
    $content = preg_replace('/class="[^"]*elementor[^"]*"/', '', $content);
    $content = preg_replace('/[^"]*elementor[^"]*="/', '', $content);
    return $content;
}


问:
django auto generate and create Models.py file and other files
In django using python manage.py startapp appname it generate folder with appname etc.... or when using admin-panel startproject projectname it generate folder with projectname and all its parameters  classes

how this work ???

答:
Here is the code of the django core management commands
(Management commands is what you call like 'manage.py command'):

https://github.com/django/django/tree/main/django/core/management/commands


问:
Simple PHP Class Question regarding methods
I have a simple question regarding PHP Classes.

Multiple times I have seen other class-frameworks etc use method calls like.

```<code>$post->data->text();
</code>```

I like this functionality, rather than just doing something like this.

```<code>$post->dataReturnAsText();
</code>```

But i'm not quite sure how they created this functionality to have perhaps a 'sub-method'? Hope someone can point me in the right direction....

答:
its probably a just that the "data" is a a public property of $post  containing an object wth a text property for example :

```<code>class Textable {
    public $text;

    function __construct($intext) {
      $this->text = $intext;
    }
}

class Post {

  public $data;

  function __construct() {
      $data = new Textable("jabberwocky");
  }

}
</code>```

this will allow you to do :

```<code>$post = new Post();
echo( $post->data->text ); // print out "jabberwocky"
</code>```

of course the right OOP way is to make the property private and allow access useing a getter function but that besides the point...

Body:
I have a simple question regarding PHP Classes.

Multiple times I have seen other class-frameworks etc use method calls like.

$post->data->text();

I like this functionality, rather than just doing something like this.

$post->dataReturnAsText();

But i'm not quite sure how they created this functionality to have perhaps a 'sub-method'? Hope someone can point me in the right direction....

Body:
its probably a just that the "data" is a a public property of $post  containing an object wth a text property for example :

class Textable {
    public $text;

    function __construct($intext) {
      $this->text = $intext;
    }
}

class Post {

  public $data;

  function __construct() {
      $data = new Textable("jabberwocky");
  }

}

this will allow you to do :

$post = new Post();
echo( $post->data->text ); // print out "jabberwocky"

of course the right OOP way is to make the property private and allow access useing a getter function but that besides the point...


问:
How do I convert square brackets to curly bracket in text using by regular expression?
How do I convert square brackets to curly brackets in text using regular expression?

I'm trying to convert

[[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]]

this to

{{0,0,0,0,0},{0,0,1,0,3},{0,2,5,0,1},{4,2,4,4,2},{3,5,1,3,1}}

Can I do it in a simple way?
I found this Link but it's PHP way.

I'm trying this on an IDE like IntelliJ or online regex tester like regex101.

Thanks.

答:
In regex101 you can use the PCRE2 Replacement String Conditional trick.

Pattern :

```<code>(\[)|(\])
</code>```

Basically capture the brackets in seperate capture groups.

Substitute :

```<code>${1:+\{:$1}${2:+\}:$2}
</code>```

Or the golfcoded version

```<code>${1:+\{:${2:+\}}}
</code>```

If group 1 not empty then replace with {.

If group 2 not empty then replace with }.

Test on regex101 here

Body:
In regex101 you can use the PCRE2 Replacement String Conditional trick.

Pattern :

(\[)|(\])

Basically capture the brackets in seperate capture groups.

Substitute :

${1:+\{:$1}${2:+\}:$2}

Or the golfcoded version

${1:+\{:${2:+\}}}

If group 1 not empty then replace with {.

If group 2 not empty then replace with }.

Test on regex101 here


问:
Why does focus() without timeout sets the caret at the front of the input?
I'm experimenting with trying to implement a keyboard navigation between few input fields using VueJs.

The template is currently set up like so...

```<code><div v-for="(note, index) in notes"
         :key="index" ref="notex" class="input-wrapper" id="input-wrapper"
         :class="{ 'focused': note.isFocused }">
              <input v-model="note.value"
                     spellcheck="false" class="input" v-on:keydown.enter="createNextNote()"
                     :id="note.value ? '' : 'empty-input'"
                     @focus="note.isFocused = true" @blur="note.isFocused = false">
</div>
</code>```

The method that's being run when I click the "ArrowUp" (I have set up a global listener for that)

```<code>        moveUp() {
            const index = parseInt(Object.keys(this.notes).find(key => this.notes[key].isFocused));

            if (!this.notes[index - 1]) {
                return;
            }

            this.notes[index].isFocused = false;
            this.notes[index - 1].isFocused = true;

            let requiredInput = this.$refs['notex'][index - 1].firstChild;

            // Why does this need the timeout?
            setTimeout(() => requiredInput.focus(), 1);
        },
</code>```

Emphasis on the timeout function.

What I do not understand is the difference between using the timeout, and not using the timeout.

When I simply call requiredInput.focus() it puts the focus in the input field, but the caret is at the front of the input field.

When I use timeout and do it like in the example provided above - the caret is behind the already inputted text - just like I want it.

I tried using VueJs's nextTick method, but in that case it's the same as without the timeout - the caret is put before the input value.

Could someone help me understand the difference, please?

答:
Found the explanation not long after. The problem was with how I set up the listeners for the key stroke...

```<code>        mounted() {
           window.addEventListener('keydown', function (e) {
               if (e.code === 'ArrowUp') {
                   app.moveUp();
               }
           });
        }
</code>```

The problem was with the fact that I set it to listen for "keydown", instead of "keyup", so whenever the "keydown" was registered, it did, indeed, switch the input. But, when it was released, the input field tries to "jump" to the previous row, but since there's no previous row, it jumps to the start of the value in said input.

To add, I moved the listeners to the template itself, and introduced preventDefault() function, the limit the default behavior of the input fields.

```<code><input v-on:keydown.up="moveUp($event)" v-on:keydown.down="moveDown($event)">

moveUp(e) {
   e.preventDefault();
   // Do the rest
}
</code>```

Body:
I'm experimenting with trying to implement a keyboard navigation between few input fields using VueJs.

The template is currently set up like so...

              <input v-model="note.value"
                     spellcheck="false" class="input" v-on:keydown.enter="createNextNote()"
                     :id="note.value ? '' : 'empty-input'"
                     @focus="note.isFocused = true" @blur="note.isFocused = false">

The method that's being run when I click the "ArrowUp" (I have set up a global listener for that)

        moveUp() {
            const index = parseInt(Object.keys(this.notes).find(key => this.notes[key].isFocused));

            if (!this.notes[index - 1]) {
                return;
            }

            this.notes[index].isFocused = false;
            this.notes[index - 1].isFocused = true;

            let requiredInput = this.$refs['notex'][index - 1].firstChild;

            // Why does this need the timeout?
            setTimeout(() => requiredInput.focus(), 1);
        },

Emphasis on the timeout function.

What I do not understand is the difference between using the timeout, and not using the timeout.

When I simply call requiredInput.focus() it puts the focus in the input field, but the caret is at the front of the input field.

When I use timeout and do it like in the example provided above - the caret is behind the already inputted text - just like I want it.

I tried using VueJs's nextTick method, but in that case it's the same as without the timeout - the caret is put before the input value.

Could someone help me understand the difference, please?

Body:
Found the explanation not long after. The problem was with how I set up the listeners for the key stroke...

        mounted() {
           window.addEventListener('keydown', function (e) {
               if (e.code === 'ArrowUp') {
                   app.moveUp();
               }
           });
        }

The problem was with the fact that I set it to listen for "keydown", instead of "keyup", so whenever the "keydown" was registered, it did, indeed, switch the input. But, when it was released, the input field tries to "jump" to the previous row, but since there's no previous row, it jumps to the start of the value in said input.

To add, I moved the listeners to the template itself, and introduced preventDefault() function, the limit the default behavior of the input fields.

<input v-on:keydown.up="moveUp($event)" v-on:keydown.down="moveDown($event)">

moveUp(e) {
   e.preventDefault();
   // Do the rest
}


问:
T-SQL OPENJSON WITH clause
This question is based on information from the JSON data in SQL Server article from the online documentaion:

```<code>DECLARE @json NVARCHAR(MAX);
SET @json = N'[
  {"id": 2, "info": {"name": "John", "surname": "Smith"}, "age": 25},
  {"id": 5, "info": {"name": "Jane", "surname": "Smith"}, "dob": "2005-11-04T12:00:00"}
]';

SELECT *
FROM OPENJSON(@json)
  WITH (
    id INT 'strict $.id',
    firstName NVARCHAR(50) '$.info.name',
    lastName NVARCHAR(50) '$.info.surname',
    age INT,
    dateOfBirth DATETIME2 '$.dob'
  );
</code>```

Each line contained in the WITH clause appears to be composed of:

The Alias such as firstName

The DataType such as NVARCHAR(50)

The JSON column name such as '$.info.name'

Is there a way to parse the JSON string into columns without having to explicitly define each column?

In other words, the JSON string contains the column names, for my purposes the Alias could have the same name as the JSON string column name.

答:
Is there a way to parse the JSON string into columns without having to explicitly define each column?

In short, no. The SQL language has very strict rules that require you to know about the columns in the output at query compile time before looking at any data.

If you want it to build columns dynamically, you need dynamic SQL, which means running a query to find out about your columns, using the results to build a new SQL command on the fly using that result, and then running the new SQL.

Title: T-SQL OPENJSON WITH clause

Body:
This question is based on information from the JSON data in SQL Server article from the online documentaion:

DECLARE @json NVARCHAR(MAX);
SET @json = N'[
  {"id": 2, "info": {"name": "John", "surname": "Smith"}, "age": 25},
  {"id": 5, "info": {"name": "Jane", "surname": "Smith"}, "dob": "2005-11-04T12:00:00"}
]';

SELECT *
FROM OPENJSON(@json)
  WITH (
    id INT 'strict $.id',
    firstName NVARCHAR(50) '$.info.name',
    lastName NVARCHAR(50) '$.info.surname',
    age INT,
    dateOfBirth DATETIME2 '$.dob'
  );

Each line contained in the WITH clause appears to be composed of:

The Alias such as firstName

The DataType such as NVARCHAR(50)

The JSON column name such as '$.info.name'

Is there a way to parse the JSON string into columns without having to explicitly define each column?

In other words, the JSON string contains the column names, for my purposes the Alias could have the same name as the JSON string column name.


问:
How to get key value pairs of the objects from complex JSON using jq and map? (Active Campaign)
I have following JSON. I want to get key-value pair objects based on their role. In this example there are 3 roles(Presenter, Approver, Customer) but there can be more as it is dynamic.

JSON

{
   "Presenter Name": "Roney",
   "Presenter Email": "roney@domain.com",
   "Approver Name": "Tim",
   "Approver Email": "tim@domain.com",
   "Customer Name": "Alex",
   "Customer Email": "alex@domain.com",
   "Invoice": "001",
   "Date": "2022-02-14"
}
```
<p>Expected output using jq, map,</p>
<pre class="lang-json prettyprint-override"><code>{
    "Presenter": {
      "email_address": "roney@domain.com",
      "name": "Roney",
      "role": "Presenter"
    },
    "Approver": {
      "email_address": "tim@domain.com",
      "name": "Tim",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "alex@domain.com",
      "name": "Alex",
      "role": "Customer"
    }
}
</code>```

I have tried till following but didn't get what to do next. Please advice.

to_entries |map( { (.key): { name: .value, email_address:.value, role: .key} } ) | add

答:
```<code>{ "Name": "name",  "Email": "email_address" } as $key_map |
to_entries |
map (
   ( .key | split(" ") | select( length == 2 ) ) as [ $role, $raw_key ] |
   [ $role, "role",             $role  ],
   [ $role, $key_map[$raw_key], .value ]
) |
reduce .[] as [ $role, $key, $val ] ( {}; .[ $role ][ $key ] = $val )
</code>```

Demo on jqplay

In the above, we start by making the data uniform. Specifically, we start by producing the following:

```<code>[
   [ "Presenter", "role",          "Presenter"        ],
   [ "Presenter", "name",          "Roney"            ],
   [ "Presenter", "role",          "Presenter"        ],
   [ "Presenter", "email_address", "roney@domain.com" ],
   [ "Approver",  "role",          "Approver"         ],
   [ "Approver",  "name",          "Tim"              ],
   [ "Approver",  "role",          "Approver"         ],
   [ "Approver",  "email_address", "tim@domain.com"   ],
   [ "Customer",  "role",          "Customer"         ],
   [ "Customer",  "name",          "Alex"             ],
   [ "Customer",  "role",          "Customer"         ],
   [ "Customer",  "email_address", "alex@domain.com"  ]
]
</code>```

There's redundant information, but that doesn't matter.

Then, the final simple reduce builds the desired structure.

```<code>.key | split(" ") | select( length == 2 )
</code>```

can be replaced with the safer

```<code>.key | match("^(.*) (Name|Email)$") | .captures | map( .string )
</code>```

Body:
I have following JSON. I want to get key-value pair objects based on their role. In this example there are 3 roles(Presenter, Approver, Customer) but there can be more as it is dynamic.

JSON

{
   "Presenter Name": "Roney",
   "Presenter Email": "roney@domain.com",
   "Approver Name": "Tim",
   "Approver Email": "tim@domain.com",
   "Customer Name": "Alex",
   "Customer Email": "alex@domain.com",
   "Invoice": "001",
   "Date": "2022-02-14"
}

Expected output using jq, map,

{
    "Presenter": {
      "email_address": "roney@domain.com",
      "name": "Roney",
      "role": "Presenter"
    },
    "Approver": {
      "email_address": "tim@domain.com",
      "name": "Tim",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "alex@domain.com",
      "name": "Alex",
      "role": "Customer"
    }
}

I have tried till following but didn't get what to do next. Please advice.

to_entries |map( { (.key): { name: .value, email_address:.value, role: .key} } ) | add

Body:
{ "Name": "name",  "Email": "email_address" } as $key_map |
to_entries |
map (
   ( .key | split(" ") | select( length == 2 ) ) as [ $role, $raw_key ] |
   [ $role, "role",             $role  ],
   [ $role, $key_map[$raw_key], .value ]
) |
reduce .[] as [ $role, $key, $val ] ( {}; .[ $role ][ $key ] = $val )

Demo on jqplay

In the above, we start by making the data uniform. Specifically, we start by producing the following:

[
   [ "Presenter", "role",          "Presenter"        ],
   [ "Presenter", "name",          "Roney"            ],
   [ "Presenter", "role",          "Presenter"        ],
   [ "Presenter", "email_address", "roney@domain.com" ],
   [ "Approver",  "role",          "Approver"         ],
   [ "Approver",  "name",          "Tim"              ],
   [ "Approver",  "role",          "Approver"         ],
   [ "Approver",  "email_address", "tim@domain.com"   ],
   [ "Customer",  "role",          "Customer"         ],
   [ "Customer",  "name",          "Alex"             ],
   [ "Customer",  "role",          "Customer"         ],
   [ "Customer",  "email_address", "alex@domain.com"  ]
]

There's redundant information, but that doesn't matter.

Then, the final simple reduce builds the desired structure.

.key | split(" ") | select( length == 2 )

can be replaced with the safer

.key | match("^(.*) (Name|Email)$") | .captures | map( .string )


问:
C switch case using char[2]
I'm trying to use switch case with char[2] in C, but it only supports integers.

int main() {
        char c[2] = "h";
        switch (c) {
                case "h":
                        printf("done!");
        }
        return 1;
}
```
<p>For better understanding, what I'm trying to do is:</p>
<pre class="lang-py prettyprint-override"><code>if "h" in ")($+#&@+)#"
</code>```

Basically I want to make a condition that matches a character with a group of characters, but efficiently, the first thing that came to mind is to use switch case but it only supports int. But when I use (int)c which is recommended in other stackoverflow answers, it doesn't return the ascii value.

答:
Using the switch statement in this case does not make a sense.

Just use the standard function strchr declared in <string.h>.

```<code>#include <string.h>

//...

if ( strchr( c, 'h' ) != NULL ) puts( "done!" );
</code>```

Title: C switch case using char[2]

Body:
I'm trying to use switch case with char[2] in C, but it only supports integers.

int main() {
        char c[2] = "h";
        switch (c) {
                case "h":
                        printf("done!");
        }
        return 1;
}

For better understanding, what I'm trying to do is:

if "h" in ")($+#&@+)#"

Basically I want to make a condition that matches a character with a group of characters, but efficiently, the first thing that came to mind is to use switch case but it only supports int. But when I use (int)c which is recommended in other stackoverflow answers, it doesn't return the ascii value.

Body:
Using the switch statement in this case does not make a sense.

Just use the standard function strchr declared in <string.h>.

#include <string.h>

//...

if ( strchr( c, 'h' ) != NULL ) puts( "done!" );


问:
Can't clone repository: git@gitlab.com: Permission denied (publickey,keyboard-interactive)
I have tried anything I can think of and find online by this point to get it to work but nothing I have tried works.

I am using Windows 10. I already have a repository on GitLab and an SSH-key assigned. And I just want to clone/push/pull the normal stuff.

When I do ssh -Tv git@gitlab.com I get;
Welcome to GitLab, @user!.

But when I try to clone the repo  using
git clone git@gitlab.com:user/my-repo.git
I get;

```<code>git@gitlab.com: Permission denied (publickey,keyboard-interactive).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

This is my config in .ssh, saw some people solving their problem by doing this.

```<code>Host gitlab.com
     User git
     Hostname gitlab.com
     IdentityFile ~/.ssh/id_ed25519
     Preferredauthentications publickey
     TCPKeepAlive yes
     IdentitiesOnly yes
</code>```

I have also tried using the GitLab Personal token with GitLab workflow on vsc and I can see the repo when I use the menu under Git Clone > Clone from GitLab > user/my-repo.
I can also Open remote repo using the GitLab workflow on vsc, and I can see my code.
When  trying to clone the repo using
git clone https://gitlab.com/user/my-repo.git
I get;

```<code>remote: HTTP Basic: Access denied
remote: You must use a personal access token with 'read_repository' or 'write_repository' scope for Git over HTTP.
remote: You can generate one at https://gitlab.com/-/profile/personal_access_tokens
fatal: Authentication failed for 'https://gitlab.com/user/my-repo.git/'
</code>```

I have remade the ssh keys multiple times both rsa and ed25519, I have removed and added a new personal token nothing works.

Does anyone have had the same problems? How did you solve it?
I've seen

I have replaced my username and repo name with user and my-repo.

答: ssh still is broken but I found a way to get to my repos using the Personal Token, when it asks you to input username and password input the token instead of the password.</p>

Body:
I have tried anything I can think of and find online by this point to get it to work but nothing I have tried works.

I am using Windows 10. I already have a repository on GitLab and an SSH-key assigned. And I just want to clone/push/pull the normal stuff.

When I do ssh -Tv git@gitlab.com I get;
Welcome to GitLab, @user!.

But when I try to clone the repo  using
git clone git@gitlab.com:user/my-repo.git
I get;

git@gitlab.com: Permission denied (publickey,keyboard-interactive).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

This is my config in .ssh, saw some people solving their problem by doing this.

Host gitlab.com
     User git
     Hostname gitlab.com
     IdentityFile ~/.ssh/id_ed25519
     Preferredauthentications publickey
     TCPKeepAlive yes
     IdentitiesOnly yes

I have also tried using the GitLab Personal token with GitLab workflow on vsc and I can see the repo when I use the menu under Git Clone > Clone from GitLab > user/my-repo.
I can also Open remote repo using the GitLab workflow on vsc, and I can see my code.
When  trying to clone the repo using
git clone https://gitlab.com/user/my-repo.git
I get;

remote: HTTP Basic: Access denied
remote: You must use a personal access token with 'read_repository' or 'write_repository' scope for Git over HTTP.
remote: You can generate one at https://gitlab.com/-/profile/personal_access_tokens
fatal: Authentication failed for 'https://gitlab.com/user/my-repo.git/'

I have remade the ssh keys multiple times both rsa and ed25519, I have removed and added a new personal token nothing works.

Does anyone have had the same problems? How did you solve it?
I've seen

I have replaced my username and repo name with user and my-repo.


问:
Slow HTTP POST request in php
I'm trying to POSTing some data (a JSON string) from a php script to a java server (all written by myself) and getting the response back.
I tried the following code:

```<code>$url="http://localhost:8000/hashmap";
$opts = array('http' => array('method' => 'POST', 'content' => $JSONDATA,'header'=>"Content-Type: application/x-www-form-urlencoded"));
$st = stream_context_create($opts);
echo file_get_contents($url, false,$st);
</code>```

Now, this code actually works (I get back as result the right answer), but file_get_contents hangs everytime 20 seconds while being executed (I printed the time before and after the instruction). The operations performed by the server are executed in a small amount of time, and I'm sure it's not normal to wait all this time to get the response.
Am I missing something?

答:
Try adding Connection: close and Content-Length: strlen($JSONDATA) headers to the $opts.

Also, if you want to avoid using extensions, have a look at this class I wrote some time ago to perform HTTP requests using PHP core only. It works on PHP4 (which is why I wrote it) and PHP5, and the only extension it ever requires is OpenSSL, and you only need that if you want to do an HTTPS request. Documented(ish) in comments at the top.

Supports all sorts of stuff - GET, POST, PUT and more, including file uploads, cookies, automatic redirect handling. I have used it quite a lot on a platform I work with regularly that is stuck with PHP/4.3.10 and it works beautifully... Even if I do say so myself...

Title: Slow HTTP POST request in php

Body:
I'm trying to POSTing some data (a JSON string) from a php script to a java server (all written by myself) and getting the response back.
I tried the following code:

$url="http://localhost:8000/hashmap";
$opts = array('http' => array('method' => 'POST', 'content' => $JSONDATA,'header'=>"Content-Type: application/x-www-form-urlencoded"));
$st = stream_context_create($opts);
echo file_get_contents($url, false,$st);

Now, this code actually works (I get back as result the right answer), but file_get_contents hangs everytime 20 seconds while being executed (I printed the time before and after the instruction). The operations performed by the server are executed in a small amount of time, and I'm sure it's not normal to wait all this time to get the response.
Am I missing something?


问:
Text does not update in Unity C#
I'm designing a game for my project and somehow the score(text) does not update after an action. It stuck at 0.

```<code>using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class uiManager : MonoBehaviour {

public Text scoreText;
bool gameOver;
int score;

// Use this for initialization
void Start () {
    gameOver = false;
    score = 0;
    InvokeRepeating ("scoreUpdate", 1.0f, 0.5f);
}

// Update is called once per frame
void Update ()
{
    scoreText.text = "Point: " + score;
}

void scoreUpdate()
{
    if (gameOver == false)
    {
        score += 1;
    }
}

public void gameOVER()
{
    gameOver = true;
}

public void Play()
{
    Application.LoadLevel ("MuachiJump");
}

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "branch")
    {
        score += 1;
        Destroy(col.gameObject);
    }
}
</code>```

I just want to make sure is there any mistake in this code? All of them seem to be correct.

答: In my case the size of the textbox was the issue, just enlarge it and your score will be visible.</p>

Title: Text does not update in Unity C#

Body:
I'm designing a game for my project and somehow the score(text) does not update after an action. It stuck at 0.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class uiManager : MonoBehaviour {

public Text scoreText;
bool gameOver;
int score;

// Use this for initialization
void Start () {
    gameOver = false;
    score = 0;
    InvokeRepeating ("scoreUpdate", 1.0f, 0.5f);
}

// Update is called once per frame
void Update ()
{
    scoreText.text = "Point: " + score;
}

void scoreUpdate()
{
    if (gameOver == false)
    {
        score += 1;
    }
}

public void gameOVER()
{
    gameOver = true;
}

public void Play()
{
    Application.LoadLevel ("MuachiJump");
}

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "branch")
    {
        score += 1;
        Destroy(col.gameObject);
    }
}

I just want to make sure is there any mistake in this code? All of them seem to be correct.


问:
I want a quick solution about adding a new row to datagraidview
I have a DataGridView and I'm adding a new row. But, when I add the new row it deletes the current row and replaces it.

This is the code

Try
    con = New SqlConnection(cs)
    con.Open()
    cmd = New SqlCommand("SELECT ItemID, RTRIM(DishName),'1',Rate from Dish where ItemID like '" & TextBox1.Text & "' order by DishName", con)
    rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

    DataGridView1.Rows.Clear()

    While (rdr.Read() = True)
        DataGridView1.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3))
        Dim num1 As Double
        num1 = Val(DataGridView1.Rows(0).Cells("Qty").Value) * Val(DataGridView1.Rows(0).Cells("Rate").Value)
        num1 = Math.Round(num1, 2)
        DataGridView1.Rows(0).Cells("Amount").Value = num1
    End While

    TotalCalc()
    Compute()
    con.Close()
Catch ex As Exception
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
```

答:
I am having a little problem following your question

Suggestion Don't tell us you want a quick solution

If you are changing the value in the DB use Update

Here is some code to add values to a DataGridView with SQLite

The SELECT statement is a little odd due to another issue in my Project

Just use your SELECT also Welcome to Stackoverflow

```<code>    Private Sub ViewSearches()

    Dim intID As Integer
    Dim strCodeDesc As String
    Dim strUIProject As String
    Dim strCodeType As String
    Dim rowCount As Integer
    Dim maxRowCount As Integer

    Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
        conn.Open()

        Using cmd As New SQLiteCommand("", conn)

            If gvTxType = "View" Then
                cmd.CommandText = "SELECT * FROM CodeTable WHERE cvCodeType = @site"
                cmd.Parameters.Add("@site", DbType.String).Value = gvSCT
            ElseIf gvTxType = "All" Then
                cmd.CommandText = "SELECT * FROM CodeTable"
            End If

            Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader

                While rdr.Read()
                    intID = CInt((rdr("CID")))
                    strCodeDesc = rdr("cvCodeDesc").ToString
                    strUIProject = rdr("cvUIProject").ToString
                    strCodeType = rdr("cvCodeType").ToString

                    dgvSelCode.Rows.Add(intID, strCodeDesc, strUIProject, strCodeType)
                    rowCount += 1

                End While

                dgvSelCode.Sort(dgvSelCode.Columns(3), ListSortDirection.Ascending)

            End Using
            If rowCount <= 12 Then
                maxRowCount = 12 - rowCount
                For iA = 1 To maxRowCount
                    dgvSelCode.Rows.Add(" ")
                Next
            End If

        End Using

    End Using

End Sub
</code>```

Body:
I am having a little problem following your question

Suggestion Don't tell us you want a quick solution

If you are changing the value in the DB use Update

Here is some code to add values to a DataGridView with SQLite

The SELECT statement is a little odd due to another issue in my Project

Just use your SELECT also Welcome to Stackoverflow

    Private Sub ViewSearches()

    Dim intID As Integer
    Dim strCodeDesc As String
    Dim strUIProject As String
    Dim strCodeType As String
    Dim rowCount As Integer
    Dim maxRowCount As Integer

    Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
        conn.Open()

        Using cmd As New SQLiteCommand("", conn)

            If gvTxType = "View" Then
                cmd.CommandText = "SELECT * FROM CodeTable WHERE cvCodeType = @site"
                cmd.Parameters.Add("@site", DbType.String).Value = gvSCT
            ElseIf gvTxType = "All" Then
                cmd.CommandText = "SELECT * FROM CodeTable"
            End If

            Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader

                While rdr.Read()
                    intID = CInt((rdr("CID")))
                    strCodeDesc = rdr("cvCodeDesc").ToString
                    strUIProject = rdr("cvUIProject").ToString
                    strCodeType = rdr("cvCodeType").ToString

                    dgvSelCode.Rows.Add(intID, strCodeDesc, strUIProject, strCodeType)
                    rowCount += 1

                End While

                dgvSelCode.Sort(dgvSelCode.Columns(3), ListSortDirection.Ascending)

            End Using
            If rowCount <= 12 Then
                maxRowCount = 12 - rowCount
                For iA = 1 To maxRowCount
                    dgvSelCode.Rows.Add(" ")
                Next
            End If

        End Using

    End Using

End Sub


问:
Create random numbers that is not in database as PASSWORD_HASH
I am trying to create random 5-digit number that is not in database as PASSWORD_HASH.

This is an example I have tried to make:

```<code>function check($num, $pwdcheck) {
    if(password_verify($num, $pwdcheck)) {
        return "exist";
    } else {
        return $num;
    }
}

function createLoginPassword() {
    /* Passwords from database */$pwds = array('$2y$10$gPenW2YPLzoZOKb/PZ8SC.UFh6C0cLALoO11x/8hjP3GeefMJ6sOu' /*<- Number 1*/, '$2y$10$iOOmAx4kJLNP5H91tfoaz.SarIA1byrUgEE8rtt9llqth5l4v5ACC' /*<- Number 2*/);
    foreach ($pwds as $result) {
        do {
            $output_password = rand(0,4);
        } while (check($output_password, $result) == "exist");
        $out = $output_password;
    }
    return $out;
}
echo createLoginPassword();
</code>```

But it doesn't seem to work, it doesn't generate unique number that is not in array

答:
Try this</p>
```<code>function createLoginPassword() {
    // Passwords from database
    $pwds = [
        '$2y$10$gPenW2YPLzoZOKb/PZ8SC.UFh6C0cLALoO11x/8hjP3GeefMJ6sOu' /*<- Number 1*/,
        '$2y$10$iOOmAx4kJLNP5H91tfoaz.SarIA1byrUgEE8rtt9llqth5l4v5ACC' /*<- Number 2*/
    ];

    // while password exist, generate new one
    do {
        // generate 5-digit number
        $output = rand(10000, 99999);
    } while( !empty(array_filter($pwds, fn($pwd) => password_verify($output, $pwd))) );

    return $output;
}

echo createLoginPassword();
</code>```

Body:
I am trying to create random 5-digit number that is not in database as PASSWORD_HASH.

This is an example I have tried to make:

function check($num, $pwdcheck) {
    if(password_verify($num, $pwdcheck)) {
        return "exist";
    } else {
        return $num;
    }
}

function createLoginPassword() {
    /* Passwords from database */$pwds = array('$2y$10$gPenW2YPLzoZOKb/PZ8SC.UFh6C0cLALoO11x/8hjP3GeefMJ6sOu' /*<- Number 1*/, '$2y$10$iOOmAx4kJLNP5H91tfoaz.SarIA1byrUgEE8rtt9llqth5l4v5ACC' /*<- Number 2*/);
    foreach ($pwds as $result) {
        do {
            $output_password = rand(0,4);
        } while (check($output_password, $result) == "exist");
        $out = $output_password;
    }
    return $out;
}
echo createLoginPassword();

But it doesn't seem to work, it doesn't generate unique number that is not in array

Body:
Try this

function createLoginPassword() {
    // Passwords from database
    $pwds = [
        '$2y$10$gPenW2YPLzoZOKb/PZ8SC.UFh6C0cLALoO11x/8hjP3GeefMJ6sOu' /*<- Number 1*/,
        '$2y$10$iOOmAx4kJLNP5H91tfoaz.SarIA1byrUgEE8rtt9llqth5l4v5ACC' /*<- Number 2*/
    ];

    // while password exist, generate new one
    do {
        // generate 5-digit number
        $output = rand(10000, 99999);
    } while( !empty(array_filter($pwds, fn($pwd) => password_verify($output, $pwd))) );

    return $output;
}

echo createLoginPassword();


问:
Python mayavi : How to draw spheres at random positions in 3D space
This is a code for generating random sized spheres with mayavi,

I want to make the spheres to be connected with each other by the surface or with a bond line:

Spheres must be at random positions in 3D space

Spheres must be with the same radius

```<code>from mayavi import mlab
import numpy as np

[phi,theta] = np.mgrid[0:2*np.pi:12j,0:np.pi:12j]
x = np.cos(phi)*np.sin(theta)
y = np.sin(phi)*np.sin(theta)
z = np.cos(theta)

def plot_sphere(p):

    r,a,b,c = p
    r=1
    return mlab.mesh(r*x+a, r*y+b, r*z )

for k in range(8):
    c = np.random.rand(4)
    c[0] /= 10.
    plot_sphere(c)

mlab.show()
</code>```

答:
What about just using the mayavi points3d function? By default the mode parameter is set to sphere and you can set the diameter by using the scale_factor parameter. You can also increase the resolution of the sphere by varying the resolution parameter.

Here is the code:

```<code>def draw_sphere(
        center_coordinates,
        radius,
        figure_title,
        color,
        background,
        foreground
):
    sphere = mlab.figure(figure_title)
    sphere.scene.background = background
    sphere.scene.foreground = foreground

    mlab.points3d(
        center_coordinates[0],
        center_coordinates[1],
        center_coordinates[2],
        color=color,
        resolution=256,
        scale_factor=2*radius,
        figure=sphere
    )
</code>```

Regarding the connected with each other by the surface issue, your explanation is poor. Maybe you mean just tangent spheres, but I would need more details.

Body:
This is a code for generating random sized spheres with mayavi,

I want to make the spheres to be connected with each other by the surface or with a bond line:

Spheres must be at random positions in 3D space

Spheres must be with the same radius

from mayavi import mlab
import numpy as np

[phi,theta] = np.mgrid[0:2*np.pi:12j,0:np.pi:12j]
x = np.cos(phi)*np.sin(theta)
y = np.sin(phi)*np.sin(theta)
z = np.cos(theta)

def plot_sphere(p):

    r,a,b,c = p
    r=1
    return mlab.mesh(r*x+a, r*y+b, r*z )

for k in range(8):
    c = np.random.rand(4)
    c[0] /= 10.
    plot_sphere(c)

mlab.show()

Body:
What about just using the mayavi points3d function? By default the mode parameter is set to sphere and you can set the diameter by using the scale_factor parameter. You can also increase the resolution of the sphere by varying the resolution parameter.

Here is the code:

def draw_sphere(
        center_coordinates,
        radius,
        figure_title,
        color,
        background,
        foreground
):
    sphere = mlab.figure(figure_title)
    sphere.scene.background = background
    sphere.scene.foreground = foreground

    mlab.points3d(
        center_coordinates[0],
        center_coordinates[1],
        center_coordinates[2],
        color=color,
        resolution=256,
        scale_factor=2*radius,
        figure=sphere
    )

Regarding the connected with each other by the surface issue, your explanation is poor. Maybe you mean just tangent spheres, but I would need more details.