问:
Javascript: formatting a rounded number to N decimals
in JavaScript, the typical way to round a number to N decimal places is something like:

function roundNumber(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function roundNumber(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));</code>```

However this approach will round to a maximum of N decimal places while I want to always round to N decimal places. For example "2.0" would be rounded to "2".

Any ideas?

答:
I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.

simply write:

```<code>var myNumber = 2;

myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
</code>```

etc...

Body:
in JavaScript, the typical way to round a number to N decimal places is something like:

function roundNumber(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

function roundNumber(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));

However this approach will round to a maximum of N decimal places while I want to always round to N decimal places. For example "2.0" would be rounded to "2".

Any ideas?

Body:
I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.

simply write:

var myNumber = 2;

myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"

etc...


来源: stackexchange

问:
Chrome isn't picking the source map, although it is enabled
Chrome doesn't pick up the js source map and dumps the error from the original minified source. Source map clearly lays beside the minified js file, with the same name but a .map extension. And there is a proper reference to it at the end of minified js file:

//# sourceMappingURL=main.2635fcfe.js.map

Enable JavaScript source maps setting is also checked in the Dev Tools:

All the resources on the web state that it should just work. Any ideas on why it might not? Is there anyway to debug the source map inclusion process, maybe witness the path that Chrome is testing?

答:
Edit:

Sharing my steps here:

check Enable JavaScript source maps, doesn't work.

I assume it may have something to do with my extensions? So I tried open a incognito window, works fine.

go back to normal mode, works fine.

I had the same issue. Works fine on Firefox but not Chrome.

Got solved by open incognito window~

ContentLicense: CC BY-SA 4.0


问:
Deserializing JSON data from Kafka stream - Kafka connect to PostgreSQL
I'm streaming topic with Kafka_2.12-3.0.0 on Ubuntu in standalone mode to PosgreSQL and getting deserialization error.

Using confluent_kafka from pip package to produce kafka stream in python (works ok):

```<code>{"pmu_id": 2, "time": 1644329854.08, "stream_id": 2, "stat": "ok", "ph_i1_r": 27.682000117654074, "ph_i1_j": -1.546410917622178, "ph_i2_r": 25.055846468243697, "ph_i2_j": 2.6658974347348012, "ph_i3_r": 25.470616978816988, "ph_i3_j": 0.5585993153435624, "ph_v4_r": 3338.6901623241415, "ph_v4_j": -1.6109426103444193, "ph_v5_r": 3149.0595421490525, "ph_v5_j": 2.5863594222073076, "ph_v6_r": 3071.4231229187553, "ph_v6_j": 0.4872377558335442, "ph_7_r": 0.0, "ph_7_j": 0.0, "ph_8_r": 3186.040175515683, "ph_8_j": -1.6065850592620299, "analog": [], "digital": 0, "frequency": 50.014, "rocof": 1}
</code>```

Configuration for storing in PostgreSQL

In my kafka_2.12-3.0.0/config/connect-standalone.properties I've added connector and converter:

```<code>plugin.path=/home/user/kafkaConnectors/confluentinc-kafka-connect-jdbc-10.3.2,/home/user/kafkaConverters/confluentinc-kafka-connect-json-schema-converter-7.0.1
</code>```

I'm executing with:

```<code>bin/connect-standalone.sh config/connect-standalone.properties config/sink-postgres.properties
</code>```

My full config/sink-postgres.properties :

```<code>name=sinkIRIpostgre
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
connection.url=jdbc:postgresql://localhost:5432/pgdb
topics=pmu1
key.converter=io.confluent.connect.json.JsonSchemaConverter
key.converter.schema.registry.url=http://localhost:8081
value.converter=io.confluent.connect.json.JsonSchemaConverter
value.converter.schema.registry.url=http://localhost:8081
connection.user=pguser
connection.password=pgpass
auto.create=true
auto.evolve=true
insert.mode=insert
pk.mode=record_key
pk.fields=MESSAGE_KEY
</code>```

Getting error:

```<code>ERROR [sinkIRIpostgre|task-0] WorkerSinkTask{id=sinkIRIpostgre-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted (org.apache.kafka.connect.runtime.WorkerTask:193)
org.apache.kafka.connect.errors.ConnectException: Tolerance exceeded in error handler
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:206)
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execute(RetryWithToleranceOperator.java:132)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.convertAndTransformRecord(WorkerSinkTask.java:493)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.convertMessages(WorkerSinkTask.java:473)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:328)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:232)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:201)
        at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:186)
        at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:241)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.apache.kafka.connect.errors.DataException: Converting byte[] to Kafka Connect data failed due to serialization error of topic pmu214:
        at io.confluent.connect.json.JsonSchemaConverter.toConnectData(JsonSchemaConverter.java:119)
        at org.apache.kafka.connect.storage.Converter.toConnectData(Converter.java:87)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.convertKey(WorkerSinkTask.java:530)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.lambda$convertAndTransformRecord$1(WorkerSinkTask.java:493)
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:156)
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:190)
        ... 13 more
Caused by: org.apache.kafka.common.errors.SerializationException: Error deserializing JSON message for id -1
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaDeserializer.deserialize(AbstractKafkaJsonSchemaDeserializer.java:177)
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaDeserializer.deserializeWithSchemaAndVersion(AbstractKafkaJsonSchemaDeserializer.java:235)
        at io.confluent.connect.json.JsonSchemaConverter$Deserializer.deserialize(JsonSchemaConverter.java:165)
        at io.confluent.connect.json.JsonSchemaConverter.toConnectData(JsonSchemaConverter.java:108)
        ... 18 more
Caused by: org.apache.kafka.common.errors.SerializationException: Unknown magic byte!
        at io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe.getByteBuffer(AbstractKafkaSchemaSerDe.java:250)
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaDeserializer.deserialize(AbstractKafkaJsonSchemaDeserializer.java:112)
</code>```

EDIT (Python code)

Here is python code used for generating kafka producer:

```<code>from confluent_kafka import Producer
..
p = Producer({'bootstrap.servers': self.kafka_bootstrap_servers})
...
record_key = str(uuid.uuid4())
record_value = self.createKafkaJSON(base_message)
p.produce(self.kafka_topic, key=record_key, value=record_value)
                p.poll(0)
</code>```

function createKafkaJSON is returning json.dumps(kafkaDictFinal).encode('utf-8') where is kafkaDictFinal is Python dictionary.

Producer is called in main with:

```<code>  KafkaPMUProducer(pdc_id=2, pmu_ip="x.x.x.x", pmu_port=4712, kafka_bootstrap_servers ="localhost:9092", kafka_topic="pmu214").kafka_producer()
</code>```

答:
If you're writing straight JSON from your Python app then you'll need to use the org.apache.kafka.connect.json.JsonConverter converter, but your messages will need a schema and payload attribute.

io.confluent.connect.json.JsonSchemaConverter relies on the Schema Registry wire format which includes a "magic byte" (hence the error).

You can learn more in this deep-dive article about serialisation and Kafka Connect, and see how Python can produce JSON data with a schema using SerializingProducer

Body:
I'm streaming topic with Kafka_2.12-3.0.0 on Ubuntu in standalone mode to PosgreSQL and getting deserialization error.

Using confluent_kafka from pip package to produce kafka stream in python (works ok):

{"pmu_id": 2, "time": 1644329854.08, "stream_id": 2, "stat": "ok", "ph_i1_r": 27.682000117654074, "ph_i1_j": -1.546410917622178, "ph_i2_r": 25.055846468243697, "ph_i2_j": 2.6658974347348012, "ph_i3_r": 25.470616978816988, "ph_i3_j": 0.5585993153435624, "ph_v4_r": 3338.6901623241415, "ph_v4_j": -1.6109426103444193, "ph_v5_r": 3149.0595421490525, "ph_v5_j": 2.5863594222073076, "ph_v6_r": 3071.4231229187553, "ph_v6_j": 0.4872377558335442, "ph_7_r": 0.0, "ph_7_j": 0.0, "ph_8_r": 3186.040175515683, "ph_8_j": -1.6065850592620299, "analog": [], "digital": 0, "frequency": 50.014, "rocof": 1}

Configuration for storing in PostgreSQL

In my kafka_2.12-3.0.0/config/connect-standalone.properties I've added connector and converter:

plugin.path=/home/user/kafkaConnectors/confluentinc-kafka-connect-jdbc-10.3.2,/home/user/kafkaConverters/confluentinc-kafka-connect-json-schema-converter-7.0.1

I'm executing with:

bin/connect-standalone.sh config/connect-standalone.properties config/sink-postgres.properties

My full config/sink-postgres.properties :

name=sinkIRIpostgre
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
connection.url=jdbc:postgresql://localhost:5432/pgdb
topics=pmu1
key.converter=io.confluent.connect.json.JsonSchemaConverter
key.converter.schema.registry.url=http://localhost:8081
value.converter=io.confluent.connect.json.JsonSchemaConverter
value.converter.schema.registry.url=http://localhost:8081
connection.user=pguser
connection.password=pgpass
auto.create=true
auto.evolve=true
insert.mode=insert
pk.mode=record_key
pk.fields=MESSAGE_KEY

Getting error:

ERROR [sinkIRIpostgre|task-0] WorkerSinkTask{id=sinkIRIpostgre-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted (org.apache.kafka.connect.runtime.WorkerTask:193)
org.apache.kafka.connect.errors.ConnectException: Tolerance exceeded in error handler
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:206)
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execute(RetryWithToleranceOperator.java:132)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.convertAndTransformRecord(WorkerSinkTask.java:493)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.convertMessages(WorkerSinkTask.java:473)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:328)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:232)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:201)
        at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:186)
        at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:241)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.apache.kafka.connect.errors.DataException: Converting byte[] to Kafka Connect data failed due to serialization error of topic pmu214:
        at io.confluent.connect.json.JsonSchemaConverter.toConnectData(JsonSchemaConverter.java:119)
        at org.apache.kafka.connect.storage.Converter.toConnectData(Converter.java:87)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.convertKey(WorkerSinkTask.java:530)
        at org.apache.kafka.connect.runtime.WorkerSinkTask.lambda$convertAndTransformRecord$1(WorkerSinkTask.java:493)
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:156)
        at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:190)
        ... 13 more
Caused by: org.apache.kafka.common.errors.SerializationException: Error deserializing JSON message for id -1
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaDeserializer.deserialize(AbstractKafkaJsonSchemaDeserializer.java:177)
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaDeserializer.deserializeWithSchemaAndVersion(AbstractKafkaJsonSchemaDeserializer.java:235)
        at io.confluent.connect.json.JsonSchemaConverter$Deserializer.deserialize(JsonSchemaConverter.java:165)
        at io.confluent.connect.json.JsonSchemaConverter.toConnectData(JsonSchemaConverter.java:108)
        ... 18 more
Caused by: org.apache.kafka.common.errors.SerializationException: Unknown magic byte!
        at io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe.getByteBuffer(AbstractKafkaSchemaSerDe.java:250)
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaDeserializer.deserialize(AbstractKafkaJsonSchemaDeserializer.java:112)

EDIT (Python code)

Here is python code used for generating kafka producer:

from confluent_kafka import Producer
..
p = Producer({'bootstrap.servers': self.kafka_bootstrap_servers})
...
record_key = str(uuid.uuid4())
record_value = self.createKafkaJSON(base_message)
p.produce(self.kafka_topic, key=record_key, value=record_value)
                p.poll(0)

function createKafkaJSON is returning json.dumps(kafkaDictFinal).encode('utf-8') where is kafkaDictFinal is Python dictionary.

Producer is called in main with:

  KafkaPMUProducer(pdc_id=2, pmu_ip="x.x.x.x", pmu_port=4712, kafka_bootstrap_servers ="localhost:9092", kafka_topic="pmu214").kafka_producer()


问:
discord.py on_reaction event not detecting messages after the bot is run
Whenever we add a reaction to a message that was sent before the bot has started, it goes undetected. Any fixes?

Code: (doesn't really matter to the question)

```<code>@client.event
async def on_reaction_add(reaction, user):
  if not user.bot:
    if reaction.message.author.id == bot_id:
      global reactions
      if f'{reaction}' in reactions:
        await VoteAdded(reaction, user)
        await reaction.message.remove_reaction(reaction, user)
      else:
        await reaction.message.remove_reaction(reaction, user)
</code>```

答:
```<code>@client.event
async def on_reaction_add
</code>```

About the reaction_add event the discord.py documentation says:

[...] if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_add() instead.

Doing it would probably solve your problem.

Body:
Whenever we add a reaction to a message that was sent before the bot has started, it goes undetected. Any fixes?

Code: (doesn't really matter to the question)

@client.event
async def on_reaction_add(reaction, user):
  if not user.bot:
    if reaction.message.author.id == bot_id:
      global reactions
      if f'{reaction}' in reactions:
        await VoteAdded(reaction, user)
        await reaction.message.remove_reaction(reaction, user)
      else:
        await reaction.message.remove_reaction(reaction, user)

Body:
@client.event
async def on_reaction_add

About the reaction_add event the discord.py documentation says:

[...] if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_add() instead.

Doing it would probably solve your problem.


问:
Creating a folder when I run file_put_contents()
I have uploaded a lot of images from the website, and need to organize files in a better way.
Therefore, I decide to create a folder by months.

```<code>$month  = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);
</code>```

after I tried this one, I get error result.

Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory

If I tried to put only file in exist folder, it worked. However, it failed to create a new folder.

Is there a way to solve this problem?

答:
Easy Laravel solution:

```<code>use Illuminate\Support\Facades\File;

// If the directory does not exist, it will be create
// Works recursively, with unlimited number of subdirectories
File::ensureDirectoryExists('my/super/directory');

// Write file content
File::put('my/super/directory/my-file.txt', 'this is file content');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have uploaded a lot of images from the website, and need to organize files in a better way.
Therefore, I decide to create a folder by months.

$month  = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);

after I tried this one, I get error result.

Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory

If I tried to put only file in exist folder, it worked. However, it failed to create a new folder.

Is there a way to solve this problem?

Body:
Easy Laravel solution:

use Illuminate\Support\Facades\File;

// If the directory does not exist, it will be create
// Works recursively, with unlimited number of subdirectories
File::ensureDirectoryExists('my/super/directory');

// Write file content
File::put('my/super/directory/my-file.txt', 'this is file content');


问:
Form.Close() doesn't close window immediately
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

```<code>public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }
</code>```

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

答:
Why dont you just use </p>

```<code>Application.Exit();
</code>```

Body:
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

Body:
Why dont you just use

Application.Exit();


问:
Line 27:15: 'item' is not defined no-undef
when i add product in cart there is nothing displayed in car and "items not found" error is displayed on the screen and when i try to use null check and npm start then  error is not shown but still balnk page is displayed.</p>
```<code>import React  from 'react';
import Header from './Front/Header/Header';

const Cart = ({ cartitems ,handleAddProduct,handleRemoveProduct} ) => {

  return (
    <>
<Header />
        <div className="cart-items">
          <div className="cart-items-header"> cartitems</div>
          {!cartitems?.length ? (
            <div className="cart-items-empty"> No items added in cart</div>
          ) : null}
          <div>
            {cartitems?.length ? cartitems.map((item,name ,price ,image ,id) => (
              <img
                key={item.id}
                className="cart-items-image"
                src={item.image}
                alt={item.name}
              />
            )) : null}
          </div>
          <div>

            <h3 className='cart-items-name'>
             {item.name}</h3>
          </div>
          <div className='cart-items-function'>

          <button className='cart-items-add' onClick={() =>handleAddProduct(item)}>
             +
         </button>
         <button
           className='cart-items-remove' onClick={()=>handleRemoveProduct(item)}>
            -
         </button>
          </div>
          <div
            className='cart-items-price'>
            {item.quantity}* ${item.price}
          </div>
        </div>
      </>
  );
}

export default Cart;
</code>```

答:
I think there are 2 problems in your code :

Firstly, I suppose that each item in your cartitems has the following structure :

item = {
id: 1,
name: "my item",
price: 2,
image: "http://mybeautifulurl.org/image.png"
}

If that is the case, you should pass item as the only argument in the map function, and access each props with item.id, item.name, item.price and item.image.

Some of your code is not in the map function but needs the item, so it cannot display anything.

Here is your updated code :

```<code>import React from "react";
import Header from "./Front/Header/Header";

const Cart = ({ cartitems, handleAddProduct, handleRemoveProduct }) => {
  return (
    <>
      <Header />
      <div className="cart-items">
        <div className="cart-items-header"> cartitems</div>
        {!cartitems?.length ? (
          <div className="cart-items-empty"> No items added in cart</div>
        ) : null}
        <div>
          {cartitems?.length
            ? cartitems.map((item) => (
                <>
                  <img
                    key={item.id}
                    className="cart-items-image"
                    src={item.image}
                    alt={item.name}
                  />
                  <div>
                    <h3 className="cart-items-name">{item.name}</h3>
                  </div>
                  <div className="cart-items-function">
                    <button
                      className="cart-items-add"
                      onClick={() => handleAddProduct(item)}
                    >
                      +
                    </button>
                    <button
                      className="cart-items-remove"
                      onClick={() => handleRemoveProduct(item)}
                    >
                      -
                    </button>
                  </div>
                  <div className="cart-items-price">
                    {item.quantity}* ${item.price}
                  </div>
                </>
              ))
            : null}
        </div>
      </div>
    </>
  );
};

export default Cart;
</code>```

Let me know if this solves the problem :)

Body:
when i add product in cart there is nothing displayed in car and "items not found" error is displayed on the screen and when i try to use null check and npm start then  error is not shown but still balnk page is displayed.

import React  from 'react';
import Header from './Front/Header/Header';

const Cart = ({ cartitems ,handleAddProduct,handleRemoveProduct} ) => {

  return (
    <>

 cartitems

          {!cartitems?.length ? (

 No items added in cart

          ) : null}

            {cartitems?.length ? cartitems.map((item,name ,price ,image ,id) => (

            )) : null}

             {item.name}

          <button className='cart-items-add' onClick={() =>handleAddProduct(item)}>
             +
         </button>
         <button
           className='cart-items-remove' onClick={()=>handleRemoveProduct(item)}>
            -
         </button>

            {item.quantity}* ${item.price}

      </>
  );
}

export default Cart;

Body:
I think there are 2 problems in your code :

Firstly, I suppose that each item in your cartitems has the following structure :

item = {
id: 1,
name: "my item",
price: 2,
image: "http://mybeautifulurl.org/image.png"
}

If that is the case, you should pass item as the only argument in the map function, and access each props with item.id, item.name, item.price and item.image.

Some of your code is not in the map function but needs the item, so it cannot display anything.

Here is your updated code :

import React from "react";
import Header from "./Front/Header/Header";

const Cart = ({ cartitems, handleAddProduct, handleRemoveProduct }) => {
  return (
    <>
      <Header />
      <div className="cart-items">
        <div className="cart-items-header"> cartitems</div>
        {!cartitems?.length ? (
          <div className="cart-items-empty"> No items added in cart</div>
        ) : null}
        <div>
          {cartitems?.length
            ? cartitems.map((item) => (
                <>
                  <img
                    key={item.id}
                    className="cart-items-image"
                    src={item.image}
                    alt={item.name}
                  />
                  <div>
                    <h3 className="cart-items-name">{item.name}</h3>
                  </div>
                  <div className="cart-items-function">
                    <button
                      className="cart-items-add"
                      onClick={() => handleAddProduct(item)}
                    >
                      +
                    </button>
                    <button
                      className="cart-items-remove"
                      onClick={() => handleRemoveProduct(item)}
                    >
                      -
                    </button>
                  </div>
                  <div className="cart-items-price">
                    {item.quantity}* ${item.price}
                  </div>
                </>
              ))
            : null}
        </div>
      </div>
    </>
  );
};

export default Cart;

Let me know if this solves the problem :)


Title: Multiple pattern matching guided string replacements with sed

Body:
File1 is an hard formatted pdb file containing protein coordinates:

ATOM      1  N   MET A   1     -37.809  27.446  34.618  1.00 43.34           N
ATOM      2  CA  MET A   1     -37.480  26.307  33.746  1.00 43.34           C
ATOM      3  C   MET A   1     -36.495  25.493  34.556  1.00 43.34           C
ATOM      4  CB  MET A   1     -36.919  26.801  32.394  1.00 43.34           C
ATOM      5  O   MET A   1     -35.346  25.898  34.661  1.00 43.34           O
ATOM      6  CG  MET A   1     -36.980  25.729  31.301  1.00 43.34           C
ATOM      7  SD  MET A   1     -35.977  26.080  29.826  1.00 43.34           S
ATOM      8  CE  MET A   1     -36.833  27.479  29.055  1.00 43.34           C
ATOM      9  N   GLU A   2     -36.991  24.516  35.314  1.00 37.48           N
ATOM     10  CA  GLU A   2     -36.090  23.617  36.039  1.00 37.48           C
ATOM     11  C   GLU A   2     -35.250  22.852  35.010  1.00 37.48           C
ATOM     12  CB  GLU A   2     -36.860  22.659  36.957  1.00 37.48           C
ATOM     13  O   GLU A   2     -35.776  22.534  33.938  1.00 37.48           O
ATOM     14  CG  GLU A   2     -37.467  23.407  38.153  1.00 37.48           C
..............................................................................
..............................................................................
..............................................................................
ATOM    981  N   CYS A 123     -15.659  -7.164  13.998  1.00 90.53           N
ATOM    982  CA  CYS A 123     -16.801  -7.332  13.106  1.00 90.53           C
ATOM    983  C   CYS A 123     -17.894  -8.234  13.699  1.00 90.53           C
ATOM    984  CB  CYS A 123     -16.321  -7.886  11.757  1.00 90.53           C
ATOM    985  O   CYS A 123     -18.918  -8.425  13.046  1.00 90.53           O
ATOM    986  SG  CYS A 123     -15.266  -6.683  10.904  1.00 90.53           S
ATOM    987  N   GLY A 124     -17.679  -8.840  14.874  1.00 90.37           N
ATOM    988  CA  GLY A 124     -18.641  -9.764  15.474  1.00 90.37           C
ATOM    989  C   GLY A 124     -18.851 -11.029  14.637  1.00 90.37           C
ATOM    990  O   GLY A 124     -19.970 -11.514  14.513  1.00 90.37           O
ATOM    991  N   SER A 125     -17.793 -11.536  13.996  1.00 92.09           N
ATOM    992  CA  SER A 125     -17.837 -12.749  13.159  1.00 92.09           C
ATOM    993  C   SER A 125     -17.220 -13.976  13.833  1.00 92.09           C
ATOM    994  CB  SER A 125     -17.117 -12.481  11.840  1.00 92.09           C
ATOM    995  O   SER A 125     -17.538 -15.108  13.459  1.00 92.09           O
ATOM    996  OG  SER A 125     -17.831 -11.523  11.084  1.00 92.09           O
....................... plus many more lines .................................

File2 is a list of representative lines obtained from fields 3,4, and 5 of the above
pdb file. To keep all simple, let's consider just to lines:

GLU A   2
GLY A 124

The desired output is:

ATOM      1  N   MET A   1     -37.809  27.446  34.618  1.00 43.34           N
ATOM      2  CA  MET A   1     -37.480  26.307  33.746  1.00 43.34           C
ATOM      3  C   MET A   1     -36.495  25.493  34.556  1.00 43.34           C
ATOM      4  CB  MET A   1     -36.919  26.801  32.394  1.00 43.34           C
ATOM      5  O   MET A   1     -35.346  25.898  34.661  1.00 43.34           O
ATOM      6  CG  MET A   1     -36.980  25.729  31.301  1.00 43.34           C
ATOM      7  SD  MET A   1     -35.977  26.080  29.826  1.00 43.34           S
ATOM      8  CE  MET A   1     -36.833  27.479  29.055  1.00 43.34           C
ATOM      9  N   GLU A   2     -36.991  24.516  35.314  1.00 00.00           N
ATOM     10  CA  GLU A   2     -36.090  23.617  36.039  1.00 00.00           C
ATOM     11  C   GLU A   2     -35.250  22.852  35.010  1.00 00.00           C
ATOM     12  CB  GLU A   2     -36.860  22.659  36.957  1.00 00.00           C
ATOM     13  O   GLU A   2     -35.776  22.534  33.938  1.00 00.00           O
ATOM     14  CG  GLU A   2     -37.467  23.407  38.153  1.00 00.00           C
..............................................................................
..............................................................................
..............................................................................
ATOM    981  N   CYS A 123     -15.659  -7.164  13.998  1.00 90.53           N
ATOM    982  CA  CYS A 123     -16.801  -7.332  13.106  1.00 90.53           C
ATOM    983  C   CYS A 123     -17.894  -8.234  13.699  1.00 90.53           C
ATOM    984  CB  CYS A 123     -16.321  -7.886  11.757  1.00 90.53           C
ATOM    985  O   CYS A 123     -18.918  -8.425  13.046  1.00 90.53           O
ATOM    986  SG  CYS A 123     -15.266  -6.683  10.904  1.00 90.53           S
ATOM    987  N   GLY A 124     -17.679  -8.840  14.874  1.00 00.00           N
ATOM    988  CA  GLY A 124     -18.641  -9.764  15.474  1.00 00.00           C
ATOM    989  C   GLY A 124     -18.851 -11.029  14.637  1.00 00.00           C
ATOM    990  O   GLY A 124     -19.970 -11.514  14.513  1.00 00.00           O
ATOM    991  N   SER A 125     -17.793 -11.536  13.996  1.00 92.09           N
ATOM    992  CA  SER A 125     -17.837 -12.749  13.159  1.00 92.09           C
ATOM    993  C   SER A 125     -17.220 -13.976  13.833  1.00 92.09           C
ATOM    994  CB  SER A 125     -17.117 -12.481  11.840  1.00 92.09           C
ATOM    995  O   SER A 125     -17.538 -15.108  13.459  1.00 92.09           O
ATOM    996  OG  SER A 125     -17.831 -11.523  11.084  1.00 92.09           O

i.e. a modified pdb with 00.00 in the 11th field if a File1's line contain a
File2 occurrence.

I already know how to do that with Bash while-read and awk but because these tools
change the format and require reformatting and/or specify the output format, in this
particular case dealing with hundreds of files they are not practical.
In order to avoid these problems I decided to look for a solution based on sed.
I got a working solution if I explicitly give a single search pattern. i.e. the
following code works:

digits=00.00
sed "/GLU A   2/s/\(.\{61\}\)\(.\{5\}\)/\1$digits/" File1.pdb  > out.pdb

but the following does not (the File1 lines are unchanged) and I did not manage
to figure out why:

digits=00.00
while read pattern; do
    sed "/$pattern/s/\(.\{61\}\)\(.\{5\}\)/\1$digits/" File1.pdb > out.pdb ;
done < File2.txt

Sorry for the lengthy message. Thanks in advance for any help.

@anubhava:

using my real data this is what happen at the first substitution site:

ATOM    293  CE1 HIS A  38     -18.278  19.735  13.486  1.00 67.94           C
ATOM    294  NE2 HIS A  38     -18.518  18.594  14.144  1.00 67.94           N
ATOM    295  N   GLY A  39     -13.836  00.00   9.206  1.00 71.50           N
ATOM    296  CA  GLY A  39     -12.628  00.00   8.447  1.00 71.50           C
ATOM    297  C   GLY A  39     -11.358  00.00   9.286  1.00 71.50           C
ATOM    298  O   GLY A  39     -11.411  18.636  10.344  1.00 00.00           O
ATOM    299  N   PRO A  40     -10.180  17.577   8.797  1.00 71.93           N
ATOM    300  CA  PRO A  40      -8.908  17.719   9.520  1.00 71.93           C
ATOM    301  C   PRO A  40      -8.580  19.169   9.912  1.00 71.93           C

In this case the site is /GLY A  39/. As you can see there is a shift in some lines and unwanted substitutions in the 8th field.
Strange enough such problems occur only for the first replacement i.e. the remaning output is just perfect. Thanks.

Body:
awk suites this role better:

awk 'FNR==NR {a[$1,$2,$3]; next} ($4,$5,$6) in a {$11="00.00"} 1' file2 file1 | column -t

ATOM  1    N   MET  A  1    -37.809  27.446   34.618  1.00  43.34  N
ATOM  2    CA  MET  A  1    -37.480  26.307   33.746  1.00  43.34  C
ATOM  3    C   MET  A  1    -36.495  25.493   34.556  1.00  43.34  C
ATOM  4    CB  MET  A  1    -36.919  26.801   32.394  1.00  43.34  C
ATOM  5    O   MET  A  1    -35.346  25.898   34.661  1.00  43.34  O
ATOM  6    CG  MET  A  1    -36.980  25.729   31.301  1.00  43.34  C
ATOM  7    SD  MET  A  1    -35.977  26.080   29.826  1.00  43.34  S
ATOM  8    CE  MET  A  1    -36.833  27.479   29.055  1.00  43.34  C
ATOM  9    N   GLU  A  2    -36.991  24.516   35.314  1.00  00.00  N
ATOM  10   CA  GLU  A  2    -36.090  23.617   36.039  1.00  00.00  C
ATOM  11   C   GLU  A  2    -35.250  22.852   35.010  1.00  00.00  C
ATOM  12   CB  GLU  A  2    -36.860  22.659   36.957  1.00  00.00  C
ATOM  13   O   GLU  A  2    -35.776  22.534   33.938  1.00  00.00  O
ATOM  14   CG  GLU  A  2    -37.467  23.407   38.153  1.00  00.00  C
ATOM  981  N   CYS  A  123  -15.659  -7.164   13.998  1.00  90.53  N
ATOM  982  CA  CYS  A  123  -16.801  -7.332   13.106  1.00  90.53  C
ATOM  983  C   CYS  A  123  -17.894  -8.234   13.699  1.00  90.53  C
ATOM  984  CB  CYS  A  123  -16.321  -7.886   11.757  1.00  90.53  C
ATOM  985  O   CYS  A  123  -18.918  -8.425   13.046  1.00  90.53  O
ATOM  986  SG  CYS  A  123  -15.266  -6.683   10.904  1.00  90.53  S
ATOM  987  N   GLY  A  124  -17.679  -8.840   14.874  1.00  00.00  N
ATOM  988  CA  GLY  A  124  -18.641  -9.764   15.474  1.00  00.00  C
ATOM  989  C   GLY  A  124  -18.851  -11.029  14.637  1.00  00.00  C
ATOM  990  O   GLY  A  124  -19.970  -11.514  14.513  1.00  00.00  O
ATOM  991  N   SER  A  125  -17.793  -11.536  13.996  1.00  92.09  N
ATOM  992  CA  SER  A  125  -17.837  -12.749  13.159  1.00  92.09  C
ATOM  993  C   SER  A  125  -17.220  -13.976  13.833  1.00  92.09  C
ATOM  994  CB  SER  A  125  -17.117  -12.481  11.840  1.00  92.09  C
ATOM  995  O   SER  A  125  -17.538  -15.108  13.459  1.00  92.09  O
ATOM  996  OG  SER  A  125  -17.831  -11.523  11.084  1.00  92.09  O

Used column -t for tabular output display only.


问:
Slack API upload string as file
I have a sting variable of a csv. I want to upload it to a slack channel as a .csv file, not as text.

```<code>async function run() {
    const csvData = 'foo,bar,baz';
    const url = 'https://slack.com/api/files.upload';
    const res = await axios.post(url, {
        channel: '#csvchannel',
        filename: 'CSVTest.csv',
        content: csvData
    }, { headers: { authorization: `Bearer ${slackToken}` } });

    console.log('Done', res.data);
}
</code>```

This code returns: error: 'no_file_data', Changing content to file gives the same response.

What do I have to do to convert the csv sting into a file that can be uploaded? I can't use fs to write out the file.

I have tried to use fs.createReadStream(csvData) but that needs a file, not a string.

Slack API documentation: https://api.slack.com/methods/files.upload

答:
You don't need to convert the CSV into a file, seems you are missing a couple of things here:

fileType property, it needs to be CSV.

Slack file upload API supports multipart/form-data and
application/x-www-form-urlencoded content types.
You're missing the Content-Type.

Check out a working example of how you could send the data using application/x-www-form-urlencoded

Send a CSV to Slack
View in Fusebit

const csvData = 'foo,bar,baz';
const url = 'https://slack.com/api/files.upload';
const params = new URLSearchParams()
params.append('channels', slackUserId);
params.append('content', csvData);
params.append('title', 'CSVTest');
params.append('filetype', 'csv');

const result = await axios.post(url, params,
  {
    headers:
  {
    authorization: `Bearer ${access_token}`,
    'Content-Type': 'application/x-www-form-urlencoded'
    }
 });

ctx.body = { message: `Successfully sent a CSV file to Slack user ${slackUserId}!` };

```

Title: Slack API upload string as file

Body:
I have a sting variable of a csv. I want to upload it to a slack channel as a .csv file, not as text.

async function run() {
    const csvData = 'foo,bar,baz';
    const url = 'https://slack.com/api/files.upload';
    const res = await axios.post(url, {
        channel: '#csvchannel',
        filename: 'CSVTest.csv',
        content: csvData
    }, { headers: { authorization: `Bearer ${slackToken}` } });

    console.log('Done', res.data);
}

This code returns: error: 'no_file_data', Changing content to file gives the same response.

What do I have to do to convert the csv sting into a file that can be uploaded? I can't use fs to write out the file.

I have tried to use fs.createReadStream(csvData) but that needs a file, not a string.

Slack API documentation: https://api.slack.com/methods/files.upload


问:
How to use jenkins ssh-steps plugin to copy a remote directory
Im trying to copy a remote directory using jenkins ssh-steps plugin. But when i ran the script i get

```<code>4: not supported to get directory /home/jenkins/app-performance/target/gatling
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:930)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:892)
at com.jcraft.jsch.ChannelSftp$get.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:141)
at org.hidetake.groovy.ssh.operation.SftpOperations$_getFile_closure1.doCall(SftpOperations.groovy:39)
at org.hidetake.groovy.ssh.operation.SftpOperations$_getFile_closure1.doCall(SftpOperations.groovy)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
</code>```

my pipeline code is

```<code>stage('Download report'){
            steps{
                script{
                    sshGet remote: remote, from: "app-performance/target/gatling" , into: "${env.WORKSPACE}/app-performance/"
                }
            }
        }
</code>```

according to the plugin readme it should be possible to download directories using sshGet. any idea ?

答:
The following piece of code worked for me in my scripted pipeline:

```<code>def source='./deployments/logs/'
def destination='deployments/'
sshGet remote: remote, from: source, into: destination, override: true
</code>```

At the end i could copy the log directory from the remote into the node.

Body:
Im trying to copy a remote directory using jenkins ssh-steps plugin. But when i ran the script i get

4: not supported to get directory /home/jenkins/app-performance/target/gatling
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:930)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:892)
at com.jcraft.jsch.ChannelSftp$get.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:141)
at org.hidetake.groovy.ssh.operation.SftpOperations$_getFile_closure1.doCall(SftpOperations.groovy:39)
at org.hidetake.groovy.ssh.operation.SftpOperations$_getFile_closure1.doCall(SftpOperations.groovy)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)

my pipeline code is

stage('Download report'){
            steps{
                script{
                    sshGet remote: remote, from: "app-performance/target/gatling" , into: "${env.WORKSPACE}/app-performance/"
                }
            }
        }

according to the plugin readme it should be possible to download directories using sshGet. any idea ?

Body:
The following piece of code worked for me in my scripted pipeline:

def source='./deployments/logs/'
def destination='deployments/'
sshGet remote: remote, from: source, into: destination, override: true

At the end i could copy the log directory from the remote into the node.


问:
Room Auto migration not works : Fatal exception for new Table (Entity)
After trying to use auto migration for a new entity/table i found this error.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.sharetrip.b2b, PID: 8861
java.lang.IllegalStateException: Migration didn't properly handle: QuickPassenger(net.sharetrip.b2b.view.more.model.QuickPassenger).
 Expected:
TableInfo{name='QuickPassenger', columns={passportNumber=Column{name='passportNumber', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, lastName=Column{name='lastName', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, wheelChair=Column{name='wheelChair', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, gender=Column{name='gender', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, mealPreference=Column{name='mealPreference', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, mobileNumber=Column{name='mobileNumber', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, dateOfBirth=Column{name='dateOfBirth', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, firstName=Column{name='firstName', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, seatPreference=Column{name='seatPreference', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, titleName=Column{name='titleName', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, nationality=Column{name='nationality', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, frequentFlyerNumber=Column{name='frequentFlyerNumber', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, passportCopy=Column{name='passportCopy', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, passportExpireDate=Column{name='passportExpireDate', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=1, defaultValue='null'}, visaCopy=Column{name='visaCopy', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, travellerType=Column{name='travellerType', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, email=Column{name='email', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}
 Found:
TableInfo{name='QuickPassenger', columns={}, foreignKeys=[], indices=[]}
    at androidx.room.RoomOpenHelper.onUpgrade(RoomOpenHelper.java:103)
</code>```

It seems that no columns found when the migration occurs. I declared my entitity like below.

```<code>@Entity
data class QuickPassenger(
    @PrimaryKey
    @ColumnInfo(name = "id")
    var id: String,
    var titleName: String?,
    var firstName: String?,
    var lastName: String?,
    var gender: String? = Gender.male,
    var nationality: String = "BD",
    var dateOfBirth: String?,
    var passportNumber: String?,
    var frequentFlyerNumber: String?,
    var passportExpireDate: String?,
    var seatPreference: String?,
    var mealPreference: String?,
    var wheelChair: String?,
    var passportCopy: String?,
    var visaCopy: String?,
    val travellerType: String?,
    val email: String?,
    val mobileNumber: String?
)
</code>```

I am using 2.4.0-alpha04 version of room for all

```<code>androidx.room:room-compiler
androidx.room:room-ktx
androidx.room:room-runtime.
</code>```

Any help is highly appreciated.

答:
It's related to your database version and schemas. After entity creation (or other database schemas changes), if you build and run the project without increasing the database version or defining the auto-migration, then the app database may be damaged.

So, you need to increase the database version (e.g. from v1 to v2) and define the auto-migration (as the docs) first, then build and run the project.

In your case (that the app database is probably broken), I suggest you uninstall the app, rollback (or stash) your changes, run the project, apply all the entity creation and auto-migration stuffs again, and re-run the project.

But before re-run, be sure that your old database schemas file has not changed (look for file 1.json as my example). Instead, by increasing the database version and re-run the project, the new database schemas file should be auto-generated (look for file 2.json as my example).

Note) The official Google docs may be out-of-date (This is the case at the time of writing!), so I can offer this article about Room auto-migrations.

Body:
After trying to use auto migration for a new entity/table i found this error.

E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.sharetrip.b2b, PID: 8861
java.lang.IllegalStateException: Migration didn't properly handle: QuickPassenger(net.sharetrip.b2b.view.more.model.QuickPassenger).
 Expected:
TableInfo{name='QuickPassenger', columns={passportNumber=Column{name='passportNumber', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, lastName=Column{name='lastName', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, wheelChair=Column{name='wheelChair', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, gender=Column{name='gender', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, mealPreference=Column{name='mealPreference', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, mobileNumber=Column{name='mobileNumber', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, dateOfBirth=Column{name='dateOfBirth', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, firstName=Column{name='firstName', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, seatPreference=Column{name='seatPreference', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, titleName=Column{name='titleName', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, nationality=Column{name='nationality', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, frequentFlyerNumber=Column{name='frequentFlyerNumber', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, passportCopy=Column{name='passportCopy', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, passportExpireDate=Column{name='passportExpireDate', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=1, defaultValue='null'}, visaCopy=Column{name='visaCopy', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, travellerType=Column{name='travellerType', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, email=Column{name='email', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}
 Found:
TableInfo{name='QuickPassenger', columns={}, foreignKeys=[], indices=[]}
    at androidx.room.RoomOpenHelper.onUpgrade(RoomOpenHelper.java:103)

It seems that no columns found when the migration occurs. I declared my entitity like below.

@Entity
data class QuickPassenger(
    @PrimaryKey
    @ColumnInfo(name = "id")
    var id: String,
    var titleName: String?,
    var firstName: String?,
    var lastName: String?,
    var gender: String? = Gender.male,
    var nationality: String = "BD",
    var dateOfBirth: String?,
    var passportNumber: String?,
    var frequentFlyerNumber: String?,
    var passportExpireDate: String?,
    var seatPreference: String?,
    var mealPreference: String?,
    var wheelChair: String?,
    var passportCopy: String?,
    var visaCopy: String?,
    val travellerType: String?,
    val email: String?,
    val mobileNumber: String?
)

I am using 2.4.0-alpha04 version of room for all

androidx.room:room-compiler
androidx.room:room-ktx
androidx.room:room-runtime.

Any help is highly appreciated.


问:
Perforce Stream Graph missing changes to child stream (red arrow to parent)
in Perforce I go to the Stream Graph every morning to bring updates from parent stream to my feature stream. I always see a red arrow going from my feature stream to the parent. This marks that there are changes in my stream that the parent is missing, so that's normal.
Today that red arrow is gone and in history I can't see anyone merging my branch to the parent (And no one would have any reason to do so since the feature just started development and had some minor changes merged with no actual functionality yet)
I closed Perforce and re-opened it but the arrow is still gone, I fear I messed something up somehow.

Any ideas/suggestions/things I can check?

答: I found what was causing this behavior, somehow the checkbox to allow merging to parent was unchecked. I did not do this so I'm not sure how it changed, I will ask the team if someone changed it since I got no message about it.


问:
where to find or how to set htmlWebpackPlugin.options.title in project created with vue cli 3?
I wanted to set title to my webpage created with vue cli 3 and thus looked into public/index.html. There, I found <title><%= htmlWebpackPlugin.options.title %></title>.

How do I set and modify htmlWebpackPlugin.options.title in vue cli 3 project?

答:
Simple and I think the best way is to update the name inside the packer.json and you need to restart your app

package.json file:

```<code>{
  "name": "my title app",
}
</code>```

Body:
Simple and I think the best way is to update the name inside the packer.json and you need to restart your app

package.json file:

{
  "name": "my title app",
}


问:
Is there any url regex validator that fits this criteria?
I need a url validator regex with this criteria:

protocol (HTTP, HTTPS) is optional. But if any protocol is given, it must be in the correct format, i.e. protocol:domain, or protocol://domain.

www is optional

it's possible to use direct IP address for this.

So based on the criteria, these should pass:

http://www.google.com

google.com

abc.def.ghi/hij

https:216.239.38.120

216.239.38.120

These should not pass:

hello

hello/world

abc://def.ghi

ftp:google.com

The closest regex I've found is from here:

```<code>^((?:.|\n)*?)((http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)([-A-Z0-9.]+)(/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#/%=~_|!:,.;]*)?)
</code>```

But unfortunately, google.com doesn't pass. It needs to have www. as a prefix. Can you improve this regex so www. becomes optional?

答:
It looks like the following pattern matches your criteria:

^(?:https?:\/\/(?:www\.)?|https:(?:\/\/)?)?\w+(?:[-.]\w+)+(?:\/[^\/\s]+)*$
```

See the regex demo. Details:

^ - start of the string

(?:https?:\/\/(?:www\.)?|https:(?:\/\/)?)? - an optional sequence of:

https?:\/\/(?:www\.)? - http or https, :// and then an optional www. substring

| - or

https:(?:\/\/)? - https: and then an optional // string

\w+ - one or more word chars

(?:[-.]\w+)+- one or more sequences of a . or - followed with one or more word chars

(?:\/[^\/\s]+)* - an optional sequence of a / an then one or more chars other than / and whitespace

$ -  end of string.

Body:
I need a url validator regex with this criteria:

protocol (HTTP, HTTPS) is optional. But if any protocol is given, it must be in the correct format, i.e. protocol:domain, or protocol://domain.

www is optional

it's possible to use direct IP address for this.

So based on the criteria, these should pass:

http://www.google.com

google.com

abc.def.ghi/hij

https:216.239.38.120

216.239.38.120

These should not pass:

hello

hello/world

abc://def.ghi

ftp:google.com

The closest regex I've found is from here:

^((?:.|\n)*?)((http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)([-A-Z0-9.]+)(/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#/%=~_|!:,.;]*)?)

But unfortunately, google.com doesn't pass. It needs to have www. as a prefix. Can you improve this regex so www. becomes optional?

Body:
It looks like the following pattern matches your criteria:

^(?:https?:\/\/(?:www\.)?|https:(?:\/\/)?)?\w+(?:[-.]\w+)+(?:\/[^\/\s]+)*$

See the regex demo. Details:

^ - start of the string

(?:https?:\/\/(?:www\.)?|https:(?:\/\/)?)? - an optional sequence of:

https?:\/\/(?:www\.)? - http or https, :// and then an optional www. substring

| - or

https:(?:\/\/)? - https: and then an optional // string

\w+ - one or more word chars

(?:[-.]\w+)+- one or more sequences of a . or - followed with one or more word chars

(?:\/[^\/\s]+)* - an optional sequence of a / an then one or more chars other than / and whitespace

$ -  end of string.


问:
How to send events directly from Phoenix Live View to a component
I have a question about the Phoenix LiveView Component (v0.15.4).

In the documentation, there is an example code:

```<code>def handle_info({:updated_card, card}, socket) do
  send_update CardComponent, id: card.id, board_id: socket.assigns.id
  {:noreply, socket}
end
</code>```

LiveView components do not have a handle_info/2 callback, so send_update/3 is called to redirect events from the parent LiveView to a specific component.

However, I want to send events directly from the parent LiveView to the specific component, because I want to do something like this

```<code># parent LiveView
def handle_info({:new_card, card_id}, socket) do
  send_event CardStackComponent, id: :card_stack, event: "add_card", params: %{"card_id" => card_id}
  {:noreply, socket}
end

# component
def handle_event("add_card", %{"card_id" => card_id} = _params, socket) do
  card = get_card(card_id)

  socket =
    update(socket, :cards, fn cards ->)
      [card | cards]
    end)

  {:noreply, socket}
end
</code>```

Of course, there is no such function as Phoenix.LiveView.send_event/2. The above is a fictional code to illustrate my intention.

I know how to send events from a client (browser) to a specific component, either by adding the phx-target="<%= @myself %>" attribute to an HTML element, or by using the pushEventTo method in a JavaScript program.

However, as far as I know, there is no way to send an event directly from a parent LiveView to a specific component.

Is there any workaround or better way?

答:
you can also do

```<code># parent LiveView
def handle_info({:new_card, card_id}, socket) do
  send_update CardStackComponent, id: :card_stack, card_id: card_id
  {:noreply, socket}
end

#component
def update(%{card_id: card_id} = _assigns, socket) do
  card = get_card(card_id)

  socket =
    update(socket, :cards, fn cards ->
      [card | cards]
    end)
  {:ok, socket}
end
</code>```

you have to have in mind that update/2 is going to be called on each render. More info about this here

Is also worth mention that you may want to maintain the state either in the LiveView or the LiveComponent but not both, as is mentioned here

Body:
I have a question about the Phoenix LiveView Component (v0.15.4).

In the documentation, there is an example code:

def handle_info({:updated_card, card}, socket) do
  send_update CardComponent, id: card.id, board_id: socket.assigns.id
  {:noreply, socket}
end

LiveView components do not have a handle_info/2 callback, so send_update/3 is called to redirect events from the parent LiveView to a specific component.

However, I want to send events directly from the parent LiveView to the specific component, because I want to do something like this

# parent LiveView
def handle_info({:new_card, card_id}, socket) do
  send_event CardStackComponent, id: :card_stack, event: "add_card", params: %{"card_id" => card_id}
  {:noreply, socket}
end

# component
def handle_event("add_card", %{"card_id" => card_id} = _params, socket) do
  card = get_card(card_id)

  socket =
    update(socket, :cards, fn cards ->)
      [card | cards]
    end)

  {:noreply, socket}
end

Of course, there is no such function as Phoenix.LiveView.send_event/2. The above is a fictional code to illustrate my intention.

I know how to send events from a client (browser) to a specific component, either by adding the phx-target="<%= @myself %>" attribute to an HTML element, or by using the pushEventTo method in a JavaScript program.

However, as far as I know, there is no way to send an event directly from a parent LiveView to a specific component.

Is there any workaround or better way?

Body:
you can also do

# parent LiveView
def handle_info({:new_card, card_id}, socket) do
  send_update CardStackComponent, id: :card_stack, card_id: card_id
  {:noreply, socket}
end

#component
def update(%{card_id: card_id} = _assigns, socket) do
  card = get_card(card_id)

  socket =
    update(socket, :cards, fn cards ->
      [card | cards]
    end)
  {:ok, socket}
end

you have to have in mind that update/2 is going to be called on each render. More info about this here

Is also worth mention that you may want to maintain the state either in the LiveView or the LiveComponent but not both, as is mentioned here


问:
How to get the MethodInfo of a Java 14 method reference?
I'm essentially asking the same as this old question, but for Java 14 instead of Java 8. To spare answerers the trouble of navigating to the old question, I'll rephrase it here.
I want to get the name of a function from a referenced method. The following Java code should give you the idea:

```<code>public class Main
{
    public static void main(String[] args)
    {
       printMethodName(Main::main);
    }

    private static void printMethodName(Consumer<String[]> theFunc)
    {
        String funcName = // somehow get name from theFunc
        System.out.println(funcName)
    }
 }
</code>```

The equivalent in C# would be:

```<code>public class Main
{
    public static void Main()
    {
        var method = Main.Main;
        PrintMethodName(method)
    }

    private static void PrintMethodName(Action action)
    {
        Console.WriteLine(action.GetMethodInfo().Name);
    }
}
</code>```

According to the accepted answer of the old question, this was not possible in Java 8 without considerable work, such as this solution. Is there a more elegant solution in Java 14?

答:
Getting a method info from a method reference never was a goal on the JDK developer’s side, so no effort was made to change the situation.

However, the approach shown in your link can be simplified. Instead of serializing the information, patching the serialized data, and restoring the information using a replacement object, you can simply intercept the original SerializedLambda object while serializing.

E.g.

public class GetSerializedLambda extends ObjectOutputStream {
    public static void main(String[] args) { // example case
        var lambda = (Consumer<String[]>&Serializable)GetSerializedLambda::main;
        SerializedLambda sl = GetSerializedLambda.get(lambda);
        System.out.println(sl.getImplClass() + " " + sl.getImplMethodName());
    }

    private SerializedLambda info;

    GetSerializedLambda() throws IOException {
      super(OutputStream.nullOutputStream());
      super.enableReplaceObject(true);
    }

    @Override protected Object replaceObject(Object obj) throws IOException {
      if(obj instanceof SerializedLambda) {
        info = (SerializedLambda)obj;
        obj = null;
      }
      return obj;
    }

    public static SerializedLambda get(Object obj) {
        try {
            GetSerializedLambda getter = new GetSerializedLambda();
            getter.writeObject(obj);
            return getter.info;
        } catch(IOException ex) {
            throw new IllegalArgumentException("not a serializable lambda", ex);
        }
    }
}
```

which will print GetSerializedLambda main. The only newer feature used here, is the OutputStream.nullOutputStream() to drop the written information immediately. Prior to JDK 11, you could write into a ByteArrayOutputStream and drop the information after the operation which is only slightly less efficient. The example also using var, but this is irrelevant to the actual operation of getting the method information.

The limitations are the same as in JDK 8. It requires a serializable method reference. Further, there is no guaranty that the implementation will map to a method directly. E.g., if you change the example’s declaration to public static void main(String... args), it will print something like lambda$1 when being compiled with Eclipse. When also changing the next line to var lambda = (Consumer<String>&Serializable)GetSerializedLambda::main;, the code will always print a synthetic method name, as using a helper method is unavoidable. But in case of javac, the name is rather something like lambda$main$f23f6912$1 instead of Eclipse’s lambda$1.

In other words, you can expect encountering surprising implementation details. Do not write applications relying on the availability of such information.

Body:
I'm essentially asking the same as this old question, but for Java 14 instead of Java 8. To spare answerers the trouble of navigating to the old question, I'll rephrase it here.
I want to get the name of a function from a referenced method. The following Java code should give you the idea:

public class Main
{
    public static void main(String[] args)
    {
       printMethodName(Main::main);
    }

    private static void printMethodName(Consumer<String[]> theFunc)
    {
        String funcName = // somehow get name from theFunc
        System.out.println(funcName)
    }
 }

The equivalent in C# would be:

public class Main
{
    public static void Main()
    {
        var method = Main.Main;
        PrintMethodName(method)
    }

    private static void PrintMethodName(Action action)
    {
        Console.WriteLine(action.GetMethodInfo().Name);
    }
}

According to the accepted answer of the old question, this was not possible in Java 8 without considerable work, such as this solution. Is there a more elegant solution in Java 14?

Body:
Getting a method info from a method reference never was a goal on the JDK developer’s side, so no effort was made to change the situation.

However, the approach shown in your link can be simplified. Instead of serializing the information, patching the serialized data, and restoring the information using a replacement object, you can simply intercept the original SerializedLambda object while serializing.

E.g.

public class GetSerializedLambda extends ObjectOutputStream {
    public static void main(String[] args) { // example case
        var lambda = (Consumer<String[]>&Serializable)GetSerializedLambda::main;
        SerializedLambda sl = GetSerializedLambda.get(lambda);
        System.out.println(sl.getImplClass() + " " + sl.getImplMethodName());
    }

    private SerializedLambda info;

    GetSerializedLambda() throws IOException {
      super(OutputStream.nullOutputStream());
      super.enableReplaceObject(true);
    }

    @Override protected Object replaceObject(Object obj) throws IOException {
      if(obj instanceof SerializedLambda) {
        info = (SerializedLambda)obj;
        obj = null;
      }
      return obj;
    }

    public static SerializedLambda get(Object obj) {
        try {
            GetSerializedLambda getter = new GetSerializedLambda();
            getter.writeObject(obj);
            return getter.info;
        } catch(IOException ex) {
            throw new IllegalArgumentException("not a serializable lambda", ex);
        }
    }
}

which will print GetSerializedLambda main. The only newer feature used here, is the OutputStream.nullOutputStream() to drop the written information immediately. Prior to JDK 11, you could write into a ByteArrayOutputStream and drop the information after the operation which is only slightly less efficient. The example also using var, but this is irrelevant to the actual operation of getting the method information.

The limitations are the same as in JDK 8. It requires a serializable method reference. Further, there is no guaranty that the implementation will map to a method directly. E.g., if you change the example’s declaration to public static void main(String... args), it will print something like lambda$1 when being compiled with Eclipse. When also changing the next line to var lambda = (Consumer<String>&Serializable)GetSerializedLambda::main;, the code will always print a synthetic method name, as using a helper method is unavoidable. But in case of javac, the name is rather something like lambda$main$f23f6912$1 instead of Eclipse’s lambda$1.

In other words, you can expect encountering surprising implementation details. Do not write applications relying on the availability of such information.


问:
Would this login function be secure?
Would this login function be secure, I put the url data straight into the function, but would this be unsafe? Could this be injected, I know it has no SQL, but is it venerable?

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $login = check_login($_POST['emailusername'], $_POST['password']);
    if ($login) {
        // Registration Success
       header("location: /");
    } else {
        // Registration Failed
        echo 'Username / password wrong';
    }
}
</code>```

function:

```<code>// CHECK LOGIN SCRIPT
   function check_login($emailusername, $password)
    {

$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'example';
$username1 = 'root';
$password1 = 'root';

$dsn = "mysql:host=$host;port=$port;dbname=$database";
$db = new PDO($dsn, $username1, $password1);

                $password = md5($password);

$statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?');
$statement->execute(array($emailusername, $emailusername, $password));

if ($result = $statement->fetchObject()) {
    $_SESSION['login'] = true;
    $_SESSION['uid'] = $result->uid;
    return TRUE;
}else{
    return FALSE;
}    }
</code>```

答: I don't see a reason why it would be unsecure, but I'd suggest you to follow authentication best practices though.

Title: Would this login function be secure?

Body:
Would this login function be secure, I put the url data straight into the function, but would this be unsafe? Could this be injected, I know it has no SQL, but is it venerable?

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $login = check_login($_POST['emailusername'], $_POST['password']);
    if ($login) {
        // Registration Success
       header("location: /");
    } else {
        // Registration Failed
        echo 'Username / password wrong';
    }
}

function:

// CHECK LOGIN SCRIPT
   function check_login($emailusername, $password)
    {

$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'example';
$username1 = 'root';
$password1 = 'root';

$dsn = "mysql:host=$host;port=$port;dbname=$database";
$db = new PDO($dsn, $username1, $password1);

                $password = md5($password);

$statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?');
$statement->execute(array($emailusername, $emailusername, $password));

if ($result = $statement->fetchObject()) {
    $_SESSION['login'] = true;
    $_SESSION['uid'] = $result->uid;
    return TRUE;
}else{
    return FALSE;
}    }


问:
split cell at special character if comma found after first word
hi i've got some budget data with names and titles that read "Last, First - Title" and other rows in same column position that read "anything really - ,asd;flkajsd". I'd like to split the column IF first word ends in a "," at the "-" position that follows it.

ive tried this:

```<code>C22$ITEM2 <- ifelse(grepl(",", C22$ITEM), C22$ITEM,  NA)
test <- str_split_fixed(C22$ITEM2, "-", 2)
C22 <- cbind(C22, test)
</code>```

but i'm getting other cells with commas elsewhere, need to limit to just "if first word ends in comma"

答:
```<code>library(tidyverse)

data <- tibble(data = c("Doe, John - Mr", "Anna, Anna - Ms", " ,asd;flkajsd"))
data
data %>%
  # first word must ed with a
  filter(data %>% str_detect("^[A-z]+a")) %>%
  separate(data, into = c("Last", "First", "Title"), sep = "[,-]") %>%
  mutate_all(str_trim)
# A tibble: 1 × 3
#  Last  First Title
#  <chr> <chr> <chr>
#1 Anna  Anna  Ms
</code>```

Body:
hi i've got some budget data with names and titles that read "Last, First - Title" and other rows in same column position that read "anything really - ,asd;flkajsd". I'd like to split the column IF first word ends in a "," at the "-" position that follows it.

ive tried this:

C22$ITEM2 <- ifelse(grepl(",", C22$ITEM), C22$ITEM,  NA)
test <- str_split_fixed(C22$ITEM2, "-", 2)
C22 <- cbind(C22, test)

but i'm getting other cells with commas elsewhere, need to limit to just "if first word ends in comma"


问:
Is it possible to put this np.where function in a loop?
I'm trying to move all values in the data frame that contains "Applicant Age" data (there is only one "Applicant Age" value per row) into a new column "applicant_age", but there are 17 columns that I have to iterate over to find them - the data is all mixed up at the moment.

```<code>df_merged['applicant_age'] = np.where(df_merged.rule0_evaluationstring.str.contains('Applicant Age'),
                                           df_merged['rule0_evaluationstring'],
                                           df_merged['applicant_age'])
</code>```

I'm using an np.where function, and it is giving me the desired result, but now I have to change the number in "rule0_evaluationstring" from 0 - 16 to go through all 17 columns.

Is there a loop that I can use to automate this?

答:
Wrapping your code in a for loop would look like this:

for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].str.contains('Applicant Age')
    df_merged['applicant_age'] = np.where(matches, df_merged[rule_col], df_merged['applicant_age'])
```
<p>BTW, Instead of using <code>np.where</code>, I think it's slightly more idiomatic to select the rows via pandas syntax:</p>
```for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].str.contains('Applicant Age')
    df_merged.loc[matches, 'applicant_age'] = df_merged.loc[matches, rule_col]
```

Body:
I'm trying to move all values in the data frame that contains "Applicant Age" data (there is only one "Applicant Age" value per row) into a new column "applicant_age", but there are 17 columns that I have to iterate over to find them - the data is all mixed up at the moment.

df_merged['applicant_age'] = np.where(df_merged.rule0_evaluationstring.str.contains('Applicant Age'),
                                           df_merged['rule0_evaluationstring'],
                                           df_merged['applicant_age'])

I'm using an np.where function, and it is giving me the desired result, but now I have to change the number in "rule0_evaluationstring" from 0 - 16 to go through all 17 columns.

Is there a loop that I can use to automate this?

Body:
Wrapping your code in a for loop would look like this:

for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].str.contains('Applicant Age')
    df_merged['applicant_age'] = np.where(matches, df_merged[rule_col], df_merged['applicant_age'])

BTW, Instead of using np.where, I think it's slightly more idiomatic to select the rows via pandas syntax:

for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].str.contains('Applicant Age')
    df_merged.loc[matches, 'applicant_age'] = df_merged.loc[matches, rule_col]


问:
how to create a dictionary whose keys are (i,j) integer pairs with i < j
I intend to create thousands of integer pairs, number them and store them in a dictionary. Given a number n, my goal is to generate every (i,j) pair such that i<j.

For instance, if n=4, the pairs will be then the dictionary will look like {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5}.

I can generate this dictionary by using nested for loops, but it is not efficient when n is large. Could someone help me to perform this operation quicker than I currently do?

```<code>d={}
n=4
temp =0

for i in range(n):
    for j in range(n):
        if i <j:
            d.update({(i,j): temp})
            temp+= 1
</code>```

答:
This is a perfect job for itertools.combinations as it will only produce the required combinations:

from itertools import combinations

n = 4
out = {k:v for v,k in enumerate(combinations(range(n), 2))}
```
<p>output: <code>{(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5}</code></p>
<h5>Using your code</h5>
<p><em>Note that you could rework your code to only produce the required combinations:</em></p>
<pre class="lang-py prettyprint-override"><code>d={}
n=4
temp = 0

for j in range(n):
    for i in range(j):
        d[(i,j)] = temp
        temp += 1

# {(0, 1): 0, (0, 2): 1, (1, 2): 2, (0, 3): 3, (1, 3): 4, (2, 3): 5}
</code>```

Body:
I intend to create thousands of integer pairs, number them and store them in a dictionary. Given a number n, my goal is to generate every (i,j) pair such that i<j.

For instance, if n=4, the pairs will be then the dictionary will look like {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5}.

I can generate this dictionary by using nested for loops, but it is not efficient when n is large. Could someone help me to perform this operation quicker than I currently do?

d={}
n=4
temp =0

for i in range(n):
    for j in range(n):
        if i <j:
            d.update({(i,j): temp})
            temp+= 1

Body:
This is a perfect job for itertools.combinations as it will only produce the required combinations:

from itertools import combinations

n = 4
out = {k:v for v,k in enumerate(combinations(range(n), 2))}

output: {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5}

Using your code

Note that you could rework your code to only produce the required combinations:

d={}
n=4
temp = 0

for j in range(n):
    for i in range(j):
        d[(i,j)] = temp
        temp += 1

# {(0, 1): 0, (0, 2): 1, (1, 2): 2, (0, 3): 3, (1, 3): 4, (2, 3): 5}


问:
Rounding the corners of an SVG
I'm using a package that generates a rectangular Treemap with this structure:

svg (wrapper with width=100% and height=100%)

svg (the outer rectangle of the Treemap, also width=100% and height=100%)

g (one for each Treemap node)

rect

clipPath

text

I need to round the four corners of the entire Treemap (not the rx ry of each rect within).

Is it possible to do that by creating a clipPath either as a child of the wrapper or the inner svg that defines a rounded rectangle? If so, can it expose whatever the background color is behind the svg?

UPDATE: @web-tiki - here's what the code looks like...

<svg width="100%" height="100%" style="border-radius: 4px;">
  <svg width="100%" height="100%">

```

Looks great on Safari and Firefox but Chrome appears to ignore it. Wondering if it's a combination of Carbon Charts Treemap and Chrome?

答:
The easiest solution is probably to use the border-radius CSS property on the svg wrapper element. It will allow you to clip round corners on your svg element and expose the background color behind the svg.
Here is an example :

body {
  background: darkorange;
}

#wrapper {
  display: block;
  width: 100%;
  border-radius: 50px;
  overflow: hidden;
  border:10px solid pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg id="wrapper" viewBox="0 0 100 100">
  <svg>
    <rect fill="teal" x="0" y="0" width="100" height="100"/>
   </svg>
</svg></code>```

On a side note, you can also wrap the entire svg inside a div and apply the border-radius on that div like this :

body {
  background: darkorange;
}

#wrapper {
  border-radius: 50px;
  overflow: hidden;
  border: 10px solid pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <svg viewBox="0 0 100 100">
    <svg>
      <rect fill="teal" x="0" y="0" width="100" height="100"/>
     </svg>
  </svg>
</div></code>```

Title: Rounding the corners of an SVG

Body:
I'm using a package that generates a rectangular Treemap with this structure:

svg (wrapper with width=100% and height=100%)

svg (the outer rectangle of the Treemap, also width=100% and height=100%)

g (one for each Treemap node)

rect

clipPath

text

I need to round the four corners of the entire Treemap (not the rx ry of each rect within).

Is it possible to do that by creating a clipPath either as a child of the wrapper or the inner svg that defines a rounded rectangle? If so, can it expose whatever the background color is behind the svg?

UPDATE: @web-tiki - here's what the code looks like...

<svg width="100%" height="100%" style="border-radius: 4px;">
  <svg width="100%" height="100%">

Looks great on Safari and Firefox but Chrome appears to ignore it. Wondering if it's a combination of Carbon Charts Treemap and Chrome?

Body:
The easiest solution is probably to use the border-radius CSS property on the svg wrapper element. It will allow you to clip round corners on your svg element and expose the background color behind the svg.
Here is an example :

body {
  background: darkorange;
}

#wrapper {
  display: block;
  width: 100%;
  border-radius: 50px;
  overflow: hidden;
  border:10px solid pink;
}

<svg id="wrapper" viewBox="0 0 100 100">
  <svg>
    <rect fill="teal" x="0" y="0" width="100" height="100"/>
   </svg>
</svg>

On a side note, you can also wrap the entire svg inside a div and apply the border-radius on that div like this :

body {
  background: darkorange;
}

#wrapper {
  border-radius: 50px;
  overflow: hidden;
  border: 10px solid pink;
}

<div id="wrapper">
  <svg viewBox="0 0 100 100">
    <svg>
      <rect fill="teal" x="0" y="0" width="100" height="100"/>
     </svg>
  </svg>
</div>


问:
Simple Question: How to split date (08-17-2011) into month, day, year? PHP
I have a variable called $orderdate and it is set to a date format like this mm-dd-yyyy.

In PHP how would I split this variable into $month, $day, $year?

Thanks for your help.

答:
If you're sure about the format of input value, then:

```<code>$orderdate = explode('-', $orderdate);
$month = $orderdate[0];
$day   = $orderdate[1];
$year  = $orderdate[2];
</code>```

You could also use preg_match():

```<code>if (preg_match('#^(\d{2})-(\d{2})-(\d{4})$#', $orderdate, $matches)) {
    $month = $matches[1];
    $day   = $matches[2];
    $year  = $matches[3];
} else {
    echo 'invalid format';
}
</code>```

Additionally, you can use checkdate() to validate the date.

Body:
If you're sure about the format of input value, then:

$orderdate = explode('-', $orderdate);
$month = $orderdate[0];
$day   = $orderdate[1];
$year  = $orderdate[2];

You could also use preg_match():

if (preg_match('#^(\d{2})-(\d{2})-(\d{4})$#', $orderdate, $matches)) {
    $month = $matches[1];
    $day   = $matches[2];
    $year  = $matches[3];
} else {
    echo 'invalid format';
}

Additionally, you can use checkdate() to validate the date.


问:
splunk extraction from the log entries
Need to extract payload data from logs entries and extract the PlatformVersion and PlatformClient values. Need in python code.</p>
```<code>"tracking~2015~526F3D98","2015:1302",164,1,"2022-02-07 11:10:08.744 INFO  [threadPoolTaskExecutorTransformed5 - ?] saving event to log =core-server-event-tracking-api, payload={""PlatformVersion"":""6.34.36 - 4.18.6"",""PlatformClient"":""html""},53
"tracking~2015~526F3D98","2015:130",164423,1,"2022-02-07 11:10:08.744 INFO  [threadPoolTaskExecutorTransformed5 - ?] saving event to log =core-server-event-tracking-api, payload={""PlatformVersion"":""6.34.37 - 4.18.7"",""PlatformClient"":""xml""},54
</code>```

答:
Not sure how Python and Splunk are relating here - but this is just a matter of doing some field extractions.

Something like this should do it:

```<code>index=ndx sourcetype=srctp
| field field=_raw "PlatformVersion\W+(?<platform_version>[^\"]+)"
| rex field=_raw "PlatformClient\W+(?<platform_client>[^\"]+)"
</code>```

Title: splunk extraction from the log entries

Body:
Need to extract payload data from logs entries and extract the PlatformVersion and PlatformClient values. Need in python code.

"tracking~2015~526F3D98","2015:1302",164,1,"2022-02-07 11:10:08.744 INFO  [threadPoolTaskExecutorTransformed5 - ?] saving event to log =core-server-event-tracking-api, payload={""PlatformVersion"":""6.34.36 - 4.18.6"",""PlatformClient"":""html""},53
"tracking~2015~526F3D98","2015:130",164423,1,"2022-02-07 11:10:08.744 INFO  [threadPoolTaskExecutorTransformed5 - ?] saving event to log =core-server-event-tracking-api, payload={""PlatformVersion"":""6.34.37 - 4.18.7"",""PlatformClient"":""xml""},54

Body:
Not sure how Python and Splunk are relating here - but this is just a matter of doing some field extractions.

Something like this should do it:

index=ndx sourcetype=srctp
| field field=_raw "PlatformVersion\W+(?<platform_version>[^\"]+)"
| rex field=_raw "PlatformClient\W+(?<platform_client>[^\"]+)"


问:
How can I prevent two jobs running at the same time with database locks?
Assuming I've a Job table with data like id, start_date, start_time, status. A job should not be able to start if there's any other job in a non-final state.

So it could happen that two requests SELECT at the same time, see no data, and INSERT with a new generated id.

Is Serializable enough here to prevent the second SELECT from happening until after the first transaction is finished? Or how can I achieve this?

答:
Serializable will not block.  It will let both jobs run, then one of them gets thrown an error when it tries to commit.  That is probably not desirable.

You could use an advisory lock in which all job runners agree on what integers to use to identify their job.  Then they take the advisory lock when they start, and release it when they enter the "final state", whatever that is.


问:
Fading in/out of 2 forms parallel in Delphi with Firemonkey
I have a Delphi 10.4.2 FMX application running on Windows 10 with 2 forms in which images are moving. Both are on top of each other. I want to slowly fade out of form 1 and fade in form 2 at the same time. Is there a solution for this?</p>

答:
This is quite easy to do.  In the code below, I have created two forms, each with Transparency set to True.
Each has a TLayout on it aligned by client.
Each TLayout has a TImageControl.  I chose TImageControl only because it has a LoadFromFile method which make this demonstration easy.  You could use a different image control instead.  (TImageControl does have a border which you mightn't want to see.)
The reason for the TLayouts is because I want an OnClick handler for the demo, but clicking on a TImageControl opens an open file dialog.  So I had to set HitTest to False on the TImageControl, and have the TLayouts to handle the mouse clicks.  With a different image control you should be able to do without the TLayouts.

The first form has a TFloatAnimation linked to the TLayout's Opacity property.  That TFloatAnimation's OnProgress event updates the opacity of the TLayout on the other form.

Clicking a form triggers the fade out/fade in.  Double-clicking closes the application.  (There needs to be some way to close it as a transparent form doesn't have the normal close button.)

Form1 .fmx:

```<code>object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form6'
  ClientHeight = 480
  ClientWidth = 680
  Transparency = True
  Visible = True
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
  object Layout1: TLayout
    Align = Client
    HitTest = True
    Size.Width = 680.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 0
    OnClick = Layout1Click
    OnDblClick = Layout1DblClick
    object ImageControl1: TImageControl
      Align = Client
      HitTest = False
      Size.Width = 680.000000000000000000
      Size.Height = 480.000000000000000000
      Size.PlatformDefault = False
      TabOrder = 0
    end
    object FloatAnimation1: TFloatAnimation
      Duration = 2.000000000000000000
      OnProcess = FloatAnimation1Process
      OnFinish = FloatAnimation1Finish
      PropertyName = 'Opacity'
      StartValue = 1.000000000000000000
      StopValue = 0.000000000000000000
    end
  end
end
</code>```

Form2 .fmx

```<code>object Form2: TForm2
  Left = 0
  Top = 0
  Caption = 'Form7'
  ClientHeight = 480
  ClientWidth = 680
  Transparency = True
  Visible = True
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
  object Layout1: TLayout
    Align = Client
    HitTest = True
    Opacity = 0.000000000000000000
    Size.Width = 680.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 0
    OnClick = Layoutl1Click
    OnDblClick = Layout1DblClick
    object ImageControl1: TImageControl
      Align = Client
      HitTest = False
      Size.Width = 680.000000000000000000
      Size.Height = 480.000000000000000000
      Size.PlatformDefault = False
      TabOrder = 0
    end
  end
end
</code>```

Form1 code:

```<code>unit MainForm;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Effects,
  FMX.Filter.Effects, FMX.StdCtrls, FMX.Ani, FMX.Layouts;

type
  TForm1 = class(TForm)
    ImageControl1: TImageControl;
    FloatAnimation1: TFloatAnimation;
    Layout1: TLayout;
    procedure Layout1Click(Sender: TObject);
    procedure FloatAnimation1Process(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Layout1DblClick(Sender: TObject);
    procedure FloatAnimation1Finish(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

uses  FormTwo;

procedure TForm1.FloatAnimation1Finish(Sender: TObject);
begin
  FloatAnimation1.Inverse:=not FloatAnimation1.Inverse;
end;

procedure TForm1.FloatAnimation1Process(Sender: TObject);
begin
  if Assigned(Form2) then Form2.Layout1.Opacity:=1-Layout1.Opacity;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ImageControl1.LoadFromFile({your image path here});
end;

procedure TForm1.Layout1Click(Sender: TObject);
begin
  FloatAnimation1.Start;
end;

procedure TForm1.Layout1DblClick(Sender: TObject);
begin
  Application.Terminate;
end;

end.
</code>```

Form2 code:

```<code>unit FormTwo;

interface

uses
  MainForm,
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
  FMX.Layouts;

type
  TForm2 = class(TForm)
    ImageControl1: TImageControl;
    Layout1: TLayout;
    procedure FormCreate(Sender: TObject);
    procedure Layoutl1Click(Sender: TObject);
    procedure Layout1DblClick(Sender: TObject);
  end;

var
  Form2: TForm2;

implementation

{$R *.fmx}

procedure TForm2.FormCreate(Sender: TObject);
begin
  Top:=Form1.Top;
  Left:=Form1.Left;
  IMageControl1.LoadFromFile({your image path here});
end;

procedure TForm2.Layoutl1Click(Sender: TObject);
begin
  Form1.FloatAnimation1.Start;
end;

procedure TForm2.Layout1DblClick(Sender: TObject);
begin
  Application.Terminate;
end;

end.
</code>```

Body:
This is quite easy to do.  In the code below, I have created two forms, each with Transparency set to True.
Each has a TLayout on it aligned by client.
Each TLayout has a TImageControl.  I chose TImageControl only because it has a LoadFromFile method which make this demonstration easy.  You could use a different image control instead.  (TImageControl does have a border which you mightn't want to see.)
The reason for the TLayouts is because I want an OnClick handler for the demo, but clicking on a TImageControl opens an open file dialog.  So I had to set HitTest to False on the TImageControl, and have the TLayouts to handle the mouse clicks.  With a different image control you should be able to do without the TLayouts.

The first form has a TFloatAnimation linked to the TLayout's Opacity property.  That TFloatAnimation's OnProgress event updates the opacity of the TLayout on the other form.

Clicking a form triggers the fade out/fade in.  Double-clicking closes the application.  (There needs to be some way to close it as a transparent form doesn't have the normal close button.)

Form1 .fmx:

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form6'
  ClientHeight = 480
  ClientWidth = 680
  Transparency = True
  Visible = True
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
  object Layout1: TLayout
    Align = Client
    HitTest = True
    Size.Width = 680.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 0
    OnClick = Layout1Click
    OnDblClick = Layout1DblClick
    object ImageControl1: TImageControl
      Align = Client
      HitTest = False
      Size.Width = 680.000000000000000000
      Size.Height = 480.000000000000000000
      Size.PlatformDefault = False
      TabOrder = 0
    end
    object FloatAnimation1: TFloatAnimation
      Duration = 2.000000000000000000
      OnProcess = FloatAnimation1Process
      OnFinish = FloatAnimation1Finish
      PropertyName = 'Opacity'
      StartValue = 1.000000000000000000
      StopValue = 0.000000000000000000
    end
  end
end

Form2 .fmx

object Form2: TForm2
  Left = 0
  Top = 0
  Caption = 'Form7'
  ClientHeight = 480
  ClientWidth = 680
  Transparency = True
  Visible = True
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
  object Layout1: TLayout
    Align = Client
    HitTest = True
    Opacity = 0.000000000000000000
    Size.Width = 680.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 0
    OnClick = Layoutl1Click
    OnDblClick = Layout1DblClick
    object ImageControl1: TImageControl
      Align = Client
      HitTest = False
      Size.Width = 680.000000000000000000
      Size.Height = 480.000000000000000000
      Size.PlatformDefault = False
      TabOrder = 0
    end
  end
end

Form1 code:

unit MainForm;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Effects,
  FMX.Filter.Effects, FMX.StdCtrls, FMX.Ani, FMX.Layouts;

type
  TForm1 = class(TForm)
    ImageControl1: TImageControl;
    FloatAnimation1: TFloatAnimation;
    Layout1: TLayout;
    procedure Layout1Click(Sender: TObject);
    procedure FloatAnimation1Process(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Layout1DblClick(Sender: TObject);
    procedure FloatAnimation1Finish(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

uses  FormTwo;

procedure TForm1.FloatAnimation1Finish(Sender: TObject);
begin
  FloatAnimation1.Inverse:=not FloatAnimation1.Inverse;
end;

procedure TForm1.FloatAnimation1Process(Sender: TObject);
begin
  if Assigned(Form2) then Form2.Layout1.Opacity:=1-Layout1.Opacity;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ImageControl1.LoadFromFile({your image path here});
end;

procedure TForm1.Layout1Click(Sender: TObject);
begin
  FloatAnimation1.Start;
end;

procedure TForm1.Layout1DblClick(Sender: TObject);
begin
  Application.Terminate;
end;

end.

Form2 code:

unit FormTwo;

interface

uses
  MainForm,
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
  FMX.Layouts;

type
  TForm2 = class(TForm)
    ImageControl1: TImageControl;
    Layout1: TLayout;
    procedure FormCreate(Sender: TObject);
    procedure Layoutl1Click(Sender: TObject);
    procedure Layout1DblClick(Sender: TObject);
  end;

var
  Form2: TForm2;

implementation

{$R *.fmx}

procedure TForm2.FormCreate(Sender: TObject);
begin
  Top:=Form1.Top;
  Left:=Form1.Left;
  IMageControl1.LoadFromFile({your image path here});
end;

procedure TForm2.Layoutl1Click(Sender: TObject);
begin
  Form1.FloatAnimation1.Start;
end;

procedure TForm2.Layout1DblClick(Sender: TObject);
begin
  Application.Terminate;
end;

end.