问:
Need to add similar customer into array after performing grouBy
I am fetching customer contacts from salesforce which are coming as array of objects as shown below

```<code>[
    {
        "customerID": 1,
        "customerName": "Jonhn1"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn2"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn3"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn4"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn5"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn6"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn7"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn8"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn9"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn10"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn11"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn12"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn13"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn14"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn15"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn16"
    },
    {
        "customerID": 6,
        "customerName": "Jonhn17"
    },
    {
        "customerID": 7,
        "customerName": "Jonhn17"
    }
]
</code>```

I need output to be array of arrays, each sub array should have all the customer details of atmost three different customers.

Reuired output:

```<code>[
    [
        {
            "customerID": 1,
            "customerName": "Jonhn1"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn2"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn3"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn4"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn5"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn7"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn8"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn9"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn10"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn11"
        }
    ],
    [
        {
            "customerID": 4,
            "customerName": "Jonhn12"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn13"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn14"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn15"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn16"
        },
        {
            "customerID": 6,
            "customerName": "Jonhn17"
        }
    ],
    [
        {
            "customerID": 7,
            "customerName": "Jonhn18"
        }
    ]
]
</code>```

Need to send this array of arrays to parallel for each for parallel processing.

答:
GroupBy for grouping according to customerID.

pluck for converting object with key as numbers to array.

divideBy 3 for seggregating into group of numbers eg [[[1],[2],[3]],[[4],[5],[6]],[[7]]]

map for iterating through nested array[array of objects]

flatten for converting nested array [[[]]] to single array [[]]

```<code>%dw 2.0
output application/json
import * from dw::core::Arrays
---
payload groupBy $.customerID pluck $ divideBy 3 map((flatten($)))
</code>```

Output

```<code>[
  [
    {
      "customerID": 1,
      "customerName": "Jonhn1"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn2"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn3"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn4"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn5"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn6"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn7"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn8"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn9"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn10"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn11"
    }
  ],
  [
    {
      "customerID": 4,
      "customerName": "Jonhn12"
    },
    {
      "customerID": 4,
      "customerName": "Jonhn13"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn14"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn15"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn16"
    },
    {
      "customerID": 6,
      "customerName": "Jonhn17"
    }
  ],
  [
    {
      "customerID": 7,
      "customerName": "Jonhn17"
    }
  ]
]
</code>```

Body:
I am fetching customer contacts from salesforce which are coming as array of objects as shown below

[
    {
        "customerID": 1,
        "customerName": "Jonhn1"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn2"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn3"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn4"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn5"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn6"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn7"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn8"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn9"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn10"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn11"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn12"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn13"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn14"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn15"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn16"
    },
    {
        "customerID": 6,
        "customerName": "Jonhn17"
    },
    {
        "customerID": 7,
        "customerName": "Jonhn17"
    }
]

I need output to be array of arrays, each sub array should have all the customer details of atmost three different customers.

Reuired output:

[
    [
        {
            "customerID": 1,
            "customerName": "Jonhn1"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn2"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn3"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn4"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn5"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn7"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn8"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn9"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn10"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn11"
        }
    ],
    [
        {
            "customerID": 4,
            "customerName": "Jonhn12"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn13"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn14"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn15"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn16"
        },
        {
            "customerID": 6,
            "customerName": "Jonhn17"
        }
    ],
    [
        {
            "customerID": 7,
            "customerName": "Jonhn18"
        }
    ]
]

Need to send this array of arrays to parallel for each for parallel processing.

Body:
GroupBy for grouping according to customerID.

pluck for converting object with key as numbers to array.

divideBy 3 for seggregating into group of numbers eg [[[1],[2],[3]],[[4],[5],[6]],[[7]]]

map for iterating through nested array[array of objects]

flatten for converting nested array [[[]]] to single array [[]]

%dw 2.0
output application/json
import * from dw::core::Arrays
---
payload groupBy $.customerID pluck $ divideBy 3 map((flatten($)))

Output

[
  [
    {
      "customerID": 1,
      "customerName": "Jonhn1"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn2"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn3"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn4"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn5"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn6"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn7"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn8"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn9"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn10"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn11"
    }
  ],
  [
    {
      "customerID": 4,
      "customerName": "Jonhn12"
    },
    {
      "customerID": 4,
      "customerName": "Jonhn13"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn14"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn15"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn16"
    },
    {
      "customerID": 6,
      "customerName": "Jonhn17"
    }
  ],
  [
    {
      "customerID": 7,
      "customerName": "Jonhn17"
    }
  ]
]


来源: stackexchange

问:
How many celery workers we can spawn on a machine?
Tech stack: celery 5.0.5, flask, python, Windows OS(8 CPUs).

To give a background, my usage requires spawning one worker, one queue per country as per the request payload

I am using celery.control.inspect().active() to see list of active workers and see if worker with {country}_worker exists in that list. If no, spawn a new worker using:

```<code>python subprocess.Popen('celery -A main.celery worker --loglevel=info -Q {queue_name} --logfile=logs\\{queue_name}.log --concurrency=1 -n {worker_name}')
</code>```

This basically starts a new celery worker and a new queue.

My initial understanding was that we can spawn only n number of workers where n is the cpu_count(). So with this understanding, while testing my code I found that when my 9th worker was spawned, I assumed it will wait for any one of the previous 8 workers to finish execution before taking up the task, but as soon as it was spawned it started consuming from the queue while rest 8 workers were also executing and same happened when I spawned more workers(15 workers in total).

This brings me to my question that the --concurrency argument in a  celery process is responsible for parallel execution within that worker? If I spawned 15 independent workers does that mean 15 different processes can be executed in parallel?

Any help is appreciated in understanding this concept.

Edit: I also noticed that each new task received in the corresponding worker spawns a new python.exe process(as per the task manager) and the previous python process spawned remains in memory unused. This does not happen when I spawn worker as "solo" rather than "prefork". Problem with using solo? celery.inspect().active() does not return anything if the workers are executing something and respond back when no tasks are in progress.

答:
If your tasks are I/O bound, and it seems they are, then perhaps you should change the concurrency type to Eventlet. Then you can in theory have concurrency set even to 1000. However, it is a different execution model so you need to write your tasks carefully to avoid deadlocks.

If the tasks are CPU-bound, then I suggest you have concurrency set to N-1, where N is number of cores, unless you want to overutilise, in which case you can pick a slightly bigger number.

PS. you CAN spawn many worker-processes, but since they all run concurrently (separate processes in this case) their CPU utilisation would be low so it really makes no sense to go above the number of available cores.

ContentLicense: CC BY-SA 4.0

Body:
Tech stack: celery 5.0.5, flask, python, Windows OS(8 CPUs).

To give a background, my usage requires spawning one worker, one queue per country as per the request payload

I am using celery.control.inspect().active() to see list of active workers and see if worker with {country}_worker exists in that list. If no, spawn a new worker using:

python subprocess.Popen('celery -A main.celery worker --loglevel=info -Q {queue_name} --logfile=logs\\{queue_name}.log --concurrency=1 -n {worker_name}')

This basically starts a new celery worker and a new queue.

My initial understanding was that we can spawn only n number of workers where n is the cpu_count(). So with this understanding, while testing my code I found that when my 9th worker was spawned, I assumed it will wait for any one of the previous 8 workers to finish execution before taking up the task, but as soon as it was spawned it started consuming from the queue while rest 8 workers were also executing and same happened when I spawned more workers(15 workers in total).

This brings me to my question that the --concurrency argument in a  celery process is responsible for parallel execution within that worker? If I spawned 15 independent workers does that mean 15 different processes can be executed in parallel?

Any help is appreciated in understanding this concept.

Edit: I also noticed that each new task received in the corresponding worker spawns a new python.exe process(as per the task manager) and the previous python process spawned remains in memory unused. This does not happen when I spawn worker as "solo" rather than "prefork". Problem with using solo? celery.inspect().active() does not return anything if the workers are executing something and respond back when no tasks are in progress.


问:
Kafka topic creation: Timed out waiting for a node assignment
Ive got a local kafka running using the following docker-compose.yml

```<code>version: '2'
services:
  zookeeper:
    image: "confluentinc/cp-zookeeper:5.0.1"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: "confluentinc/cp-enterprise-kafka:5.0.1"
    ports:
      - '9092:9092'
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 100
</code>```

Trying to run a basic create topic using kafka-client 2.1.0 in Scala:

```<code>val props = new Properties()
props.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")

val adminClient: AdminClient = AdminClient.create(props)
val newTopic = new NewTopic("test", 1, 1.toShort)
val topicsF = adminClient.createTopics(List(newTopic).asJavaCollection)
val result = topicsF.all().get()
</code>```

but after some time I get:

```<code>org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
</code>```

I can create a topic using the command line:

```<code>kafka-topics --create \
    --zookeeper localhost:2181 \
    --replication-factor 1 \
    --partitions 1 \
    --topic test
Created topic "test".
</code>```

kafka AdminClient API Timed out waiting for node assignment describes a similar problem using Java but the comment suggests that a system restart fixed the issue which is not the case on my side.

答:
My advertised listeners were wrong and i did not have KAFKA_LISTENER_SECURITY_PROTOCOL_MAP configured.

A good example i found here:

```<code>KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,SSL:SSL,SSL_HOST:SSL,SASL_SSL:SASL_SSL,SASL_SSL_HOST:SASL_SSL
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka1:29092,PLAINTEXT_HOST://localhost:9092,SSL://kafka1:29093,SSL_HOST://localhost:9093,SASL_SSL://kafka1:29094,SASL_SSL_HOST://localhost:9094
</code>```

P.S: Use only what you need, for me it was SASL_SSL & SASL_SSL_HOST.

Body:
Ive got a local kafka running using the following docker-compose.yml

version: '2'
services:
  zookeeper:
    image: "confluentinc/cp-zookeeper:5.0.1"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: "confluentinc/cp-enterprise-kafka:5.0.1"
    ports:
      - '9092:9092'
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 100

Trying to run a basic create topic using kafka-client 2.1.0 in Scala:

val props = new Properties()
props.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")

val adminClient: AdminClient = AdminClient.create(props)
val newTopic = new NewTopic("test", 1, 1.toShort)
val topicsF = adminClient.createTopics(List(newTopic).asJavaCollection)
val result = topicsF.all().get()

but after some time I get:

org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.

I can create a topic using the command line:

kafka-topics --create \
    --zookeeper localhost:2181 \
    --replication-factor 1 \
    --partitions 1 \
    --topic test
Created topic "test".

kafka AdminClient API Timed out waiting for node assignment describes a similar problem using Java but the comment suggests that a system restart fixed the issue which is not the case on my side.

Body:
My advertised listeners were wrong and i did not have KAFKA_LISTENER_SECURITY_PROTOCOL_MAP configured.

A good example i found here:

KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,SSL:SSL,SSL_HOST:SSL,SASL_SSL:SASL_SSL,SASL_SSL_HOST:SASL_SSL
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka1:29092,PLAINTEXT_HOST://localhost:9092,SSL://kafka1:29093,SSL_HOST://localhost:9093,SASL_SSL://kafka1:29094,SASL_SSL_HOST://localhost:9094

P.S: Use only what you need, for me it was SASL_SSL & SASL_SSL_HOST.


问:
Laravel migrations run with no error but integer field is not created
I'm trying to migrate a migration file. Some integer fields triggered an error:

$table->integer('age',11)->default('0');

There were a few of those. After reading other posts, and trying a few things, I changed it to:

$table->integer('age',11)->default(0)->change();

This time, no error raised, but the created table miss and those fields!

Please find the whole file below:

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateReservationAnniversairesTable extends Migration
{
    public function up()
    {
        Schema::create('reservation_anniversaires', function (Blueprint $table) {

        $table->increments('id',11);
        $table->string('nom',50)->nullable()->default('NULL');
        $table->string('gsm',30)->nullable()->default('NULL');
        $table->string('prenom',50)->nullable()->default('NULL');
        $table->string('email',100);
        $table->integer('age',11)->default(0)->change();
        $table->time('heure_debut');
        $table->time('heure_fin');
        $table->string('gateau',100)->nullable()->default('NULL');
        $table->string('impression',100)->nullable()->default('NULL');
        $table->integer('nbre_enfants',11)->default(0)->change();
        $table->integer('acompte',11)->default(0)->change();
        $table->text('remarques');
        $table->tinyInteger('salle',4)->default(0)->change();
        $table->time('heure_gouter');
        $table->date('date');
        $table->string('formule',50)->nullable()->default('NULL');
        $table->integer('actif',11)->default(1)->change();
        $table->string('couleur',30)->nullable()->default('NULL');
        $table->integer('rappel',11)->default(0)->change();
        $table->integer('confirm',11)->default(0)->change();
        $table->integer('pizzas',11)->default(0)->change();
        $table->integer('sandwiches',11)->default(0)->change();
        $table->string('options')->nullable()->default('NULL');
        $table->integer('annif_confirme',11)->default(0)->change();
        $table->string('created',30);
        $table->string('modified',30);
        $table->tinyInteger('confirm_enfants',1)->default(0)->change();
        $table->tinyInteger('invitations',1)->default(0)->change();
        $table->string('adresse')->nullable()->default('NULL');
        $table->integer('invitsEnvoyees',11)->default(0)->change();
        $table->float('paiement')->default(0)->change();
        $table->string('paiement_methode',50)->nullable()->default('NULL');
        $table->integer('enfants_presents',11)->default(0)->change();
        $table->integer('parts_gateau',11)->default(0)->change();
        $table->float('options_montant')->default(0)->change();
        $table->string('deco_salle',50)->nullable()->default('NULL');
        $table->string('formule_theme',50)->nullable()->default('NULL');
        $table->string('photos',50)->nullable()->default('NULL');
        $table->string('grimage',50)->nullable()->default('NULL');
        $table->string('clown',50)->nullable()->default('NULL');
        $table->string('sculpture',50)->nullable()->default('NULL');

        });
    }

    public function down()
    {
        Schema::dropIfExists('reservation_anniversaires');
    }
}
</code>```

答:
The second parameter of all the integer fields is autoincrement, not size. Setting this to anything that's truthy will result in the field being auto incremented. This is probably not what you're attempting here.

I suggest you use any of the available methods for the size:

tinyInteger, smallInteger, mediumInteger, integer, bigInteger,
unsignedTinyInteger, unsignedSmallInteger, unsignedMediumInteger, unsignedInteger, unsignedBigInteger

Or any of the auto incrementing helpers:
tinyIncrements, smallIncrements, mediumIncrements, increments, bigIncrements

Also, you don't need change() unless you're actually changing the table structure in a follow-up migration.

Source: https://github.com/laravel/framework/blob/8.x/src/Illuminate/Database/Schema/Blueprint.php#L756-L759

Available column types: https://laravel.com/docs/8.x/migrations#available-column-types

Modifying columns: https://laravel.com/docs/8.x/migrations#updating-column-attributes

Body:
I'm trying to migrate a migration file. Some integer fields triggered an error:

$table->integer('age',11)->default('0');

There were a few of those. After reading other posts, and trying a few things, I changed it to:

$table->integer('age',11)->default(0)->change();

This time, no error raised, but the created table miss and those fields!

Please find the whole file below:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateReservationAnniversairesTable extends Migration
{
    public function up()
    {
        Schema::create('reservation_anniversaires', function (Blueprint $table) {

        $table->increments('id',11);
        $table->string('nom',50)->nullable()->default('NULL');
        $table->string('gsm',30)->nullable()->default('NULL');
        $table->string('prenom',50)->nullable()->default('NULL');
        $table->string('email',100);
        $table->integer('age',11)->default(0)->change();
        $table->time('heure_debut');
        $table->time('heure_fin');
        $table->string('gateau',100)->nullable()->default('NULL');
        $table->string('impression',100)->nullable()->default('NULL');
        $table->integer('nbre_enfants',11)->default(0)->change();
        $table->integer('acompte',11)->default(0)->change();
        $table->text('remarques');
        $table->tinyInteger('salle',4)->default(0)->change();
        $table->time('heure_gouter');
        $table->date('date');
        $table->string('formule',50)->nullable()->default('NULL');
        $table->integer('actif',11)->default(1)->change();
        $table->string('couleur',30)->nullable()->default('NULL');
        $table->integer('rappel',11)->default(0)->change();
        $table->integer('confirm',11)->default(0)->change();
        $table->integer('pizzas',11)->default(0)->change();
        $table->integer('sandwiches',11)->default(0)->change();
        $table->string('options')->nullable()->default('NULL');
        $table->integer('annif_confirme',11)->default(0)->change();
        $table->string('created',30);
        $table->string('modified',30);
        $table->tinyInteger('confirm_enfants',1)->default(0)->change();
        $table->tinyInteger('invitations',1)->default(0)->change();
        $table->string('adresse')->nullable()->default('NULL');
        $table->integer('invitsEnvoyees',11)->default(0)->change();
        $table->float('paiement')->default(0)->change();
        $table->string('paiement_methode',50)->nullable()->default('NULL');
        $table->integer('enfants_presents',11)->default(0)->change();
        $table->integer('parts_gateau',11)->default(0)->change();
        $table->float('options_montant')->default(0)->change();
        $table->string('deco_salle',50)->nullable()->default('NULL');
        $table->string('formule_theme',50)->nullable()->default('NULL');
        $table->string('photos',50)->nullable()->default('NULL');
        $table->string('grimage',50)->nullable()->default('NULL');
        $table->string('clown',50)->nullable()->default('NULL');
        $table->string('sculpture',50)->nullable()->default('NULL');

        });
    }

    public function down()
    {
        Schema::dropIfExists('reservation_anniversaires');
    }
}


问:
Blazor insists taking wrong initial namespace
I have weird problem in Blazor (in .cs files works just fine)
there are two different namespaces:

Sports.Entities.Metadata.*

Vision.Sports.Entities.Metadata.*

for some reason all the razor files insists that Sports must be Vision.Sports although i need the first namespace described, i find  no explanation to this behavior and no way using the first namespace inside razor files, in the cs file on the other hand no such problem.

any idea what causes this behavior?

[![file path structure][2]][2]

file path structure
[2]: https://i.stack.imgur.com/bGsB6.png

答: Solved by merging the 2 namespaces (removed the Vision prefix in 2 classes that had it), i think there is an issue with Blazor there, for some reason it mixes up namespaces when there is a prefix to one in two different namespaces.</p>


问:
Problem with position of new view using presentModalViewController
I am trying to add a new view to my app using presentModalViewController.

```<code>ASpotImageViewController *aSpotImage = [[ASpotImageViewController alloc] initWithNibName:@"ASpotImageView" bundle:nil spotID:spotid];
aSpotImage.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//NSLog(@"frame is %@", aSpotImage.view.frame);
//NSLog(@"origin is %@", aSpotImage.view.frame.origin);
NSLog(@"description is %@", aSpotImage.description);
[aSpotImage setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentModalViewController:aSpotImage animated:YES];
</code>```

But when I use this, the new view appears about 40 pixels or so down the screen, and the bottom is cut off. What could be causing this? I don't have this problem in other cases where I use this code.

答:
Gurooj, are you implementing try this

```<code>UINavigationController *nextController = [[UINavigationController alloc] initWithRootViewController:aSpotImage];
[self presentModalViewController: nextController animated: YES];
</code>```

the white space is usually the height of navigation bar, I guess?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add a new view to my app using presentModalViewController.

ASpotImageViewController *aSpotImage = [[ASpotImageViewController alloc] initWithNibName:@"ASpotImageView" bundle:nil spotID:spotid];
aSpotImage.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//NSLog(@"frame is %@", aSpotImage.view.frame);
//NSLog(@"origin is %@", aSpotImage.view.frame.origin);
NSLog(@"description is %@", aSpotImage.description);
[aSpotImage setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentModalViewController:aSpotImage animated:YES];

But when I use this, the new view appears about 40 pixels or so down the screen, and the bottom is cut off. What could be causing this? I don't have this problem in other cases where I use this code.

Body:
Gurooj, are you implementing try this

UINavigationController *nextController = [[UINavigationController alloc] initWithRootViewController:aSpotImage];
[self presentModalViewController: nextController animated: YES];

the white space is usually the height of navigation bar, I guess?


问:
How can I make a new array from a event emitter ( gives bytes array), where new arrays first element will be '10' and last '13'?
I have incoming bytes of arrays once a time. It kind of looks like this

[10,12,34,58,62]

[83,33,23,44,13]

[10,12,34,58,62]

[34, 77,54,23,87]

[83,33,23,44,13]

[10,12,34,58,62]

[83,33,23,44,66]

[13]
…continues.

So, it renders each array every time. I needed them to be rendered like

[10,12,34,58,62,83,33,23,44,13]

[10,12,34,58,62,34,77,54,23,87,83,33,23,44,13]

[10,12,34,58,62,83,33,23,44,66,13].

The first element will be 10 and the last 13.
Can anyone help me with the code? Thanks in advance.

答:
```<code>// @param {accumulator} is array of array of numbers
// @param {chunk} is the array of numbers
// @return {accumulator}
const process_bytes = (accumulator, chunk) => {
    if (accumulator && accumulator.length) {
        if (chunk && chunk.length) {
            if (chunk[0] === 10) {
                return [...accumulator, chunk];
            } else {
                return [...accumulator.slice(0, accumulator.length - 1), [...accumulator[accumulator.length - 1], ...chunk]];
            }
        }
    }
    return chunk && chunk.length && [chunk] || [];
};
</code>```

Assumption

The following code follows the provided input data and the expected output in the OP

RUN THE CODE

const process_bytes = (accumulator, chunk) => {
  if (accumulator && accumulator.length) {
    if (chunk && chunk.length) {
      if (chunk[0] === 10) {
        return [...accumulator, chunk];
      } else {
        return [...accumulator.slice(0, accumulator.length - 1), [...accumulator[accumulator.length - 1], ...chunk]];
      }
    }
  }
  return chunk && chunk.length && [chunk] || [];
};

const testData = [
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [34, 77, 54, 23, 87],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 66]
];

let processed_bytes = [];

testData.forEach(x => {
  processed_bytes = process_bytes(processed_bytes, x);
});
console.log(processed_bytes);```

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Body:
// @param {accumulator} is array of array of numbers
// @param {chunk} is the array of numbers
// @return {accumulator}
const process_bytes = (accumulator, chunk) => {
    if (accumulator && accumulator.length) {
        if (chunk && chunk.length) {
            if (chunk[0] === 10) {
                return [...accumulator, chunk];
            } else {
                return [...accumulator.slice(0, accumulator.length - 1), [...accumulator[accumulator.length - 1], ...chunk]];
            }
        }
    }
    return chunk && chunk.length && [chunk] || [];
};

Assumption

The following code follows the provided input data and the expected output in the OP

RUN THE CODE

const process_bytes = (accumulator, chunk) => {
  if (accumulator && accumulator.length) {
    if (chunk && chunk.length) {
      if (chunk[0] === 10) {
        return [...accumulator, chunk];
      } else {
        return [...accumulator.slice(0, accumulator.length - 1), [...accumulator[accumulator.length - 1], ...chunk]];
      }
    }
  }
  return chunk && chunk.length && [chunk] || [];
};

const testData = [
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [34, 77, 54, 23, 87],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 66]
];

let processed_bytes = [];

testData.forEach(x => {
  processed_bytes = process_bytes(processed_bytes, x);
});
console.log(processed_bytes);

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET


问:
Shell redirection doesn't move file position for stdout
I have a minimal complete example where the Linux API behavior seems to be a bit ambiguous. The stdout is closed, reopened and used as a regular file's descriptor:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main(void) {
     system("echo > testfile");
     fclose(stdout);
     int fd = open("testfile", O_WRONLY);
     if (fd < 0) {
          perror("open():");
          return -1;
     }

     dprintf(fd, "Test\n");
     system("echo Test2");
     system("echo TestFFFFFFFFFFFF >> /proc/$$/fd/1"); // problem line
     sleep(5);
     dprintf(fd, "Test4\n");
     system("echo Test5");

     return 0;
}
</code>```

Before sleep in testfile I see

```<code>Test
Test2
TestFFFFFFFFFFFF
</code>```

But after sleep this line is overwritten:

```<code>Test
Test2
Test4
Test5
FFFF
</code>```

It seems that for regular files this behavior is strange: if we write something to file - we change its position an appropriate way (to the end).

But for stdout it looks quite reasonable: if we write to stdout - we rewind its position back after finish writing (to the start).

Is this a bug or the right way?

P.S. Besides the bash I also tried dash and ksh - the same thing.

答:
The question is:

Is this a bug or the right way?

It is the right way.

/proc/$$/fd/1 is a symlink to testfile, so >> /proc/$$/fd/1 is the same as >> testfile. It is a separate child process that writes to testfile. When this child process terminates, you see the stuff it has written in the file. It has no effect on your parent process.

STDOUT_FILENO is not special, it's just like any other file descriptor.

Why child processes affect your parent process file descriptor position? Because duplicated file descriptors refer to the same open file description. Read it twice - "file descriptor" != "file description". It is like a double-mapping. We say, file descriptors are not copied, they are duplicated, they share the file offset and file status flags, because they share the file description. See man 2 dup and man 2 open.

When a separate process opens the same file, it has a separate file description, so it does not affect your process file description.

(It is so badly named. I mentally call "file descriptor" like "system handle" (because it can refer to anything kernel wants to) and call "file description" like "file data" (if it's a file, it can be anything kernel wants to). It's then clear - this "system handle" refers to this "file data" and "system handle" is duplicated between processes that means that two "system handles" refer to the same open "file data". And "file data" stores file position and file locks and such. Processes have "handles", not "data". "File data" are removed automatically, when the last "system handle" is getting removed (the confusing man 2 unlink).)

Body:
I have a minimal complete example where the Linux API behavior seems to be a bit ambiguous. The stdout is closed, reopened and used as a regular file's descriptor:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main(void) {
     system("echo > testfile");
     fclose(stdout);
     int fd = open("testfile", O_WRONLY);
     if (fd < 0) {
          perror("open():");
          return -1;
     }

     dprintf(fd, "Test\n");
     system("echo Test2");
     system("echo TestFFFFFFFFFFFF >> /proc/$$/fd/1"); // problem line
     sleep(5);
     dprintf(fd, "Test4\n");
     system("echo Test5");

     return 0;
}

Before sleep in testfile I see

Test
Test2
TestFFFFFFFFFFFF

But after sleep this line is overwritten:

Test
Test2
Test4
Test5
FFFF

It seems that for regular files this behavior is strange: if we write something to file - we change its position an appropriate way (to the end).

But for stdout it looks quite reasonable: if we write to stdout - we rewind its position back after finish writing (to the start).

Is this a bug or the right way?

P.S. Besides the bash I also tried dash and ksh - the same thing.


问:
Alternative to performSelector in Swift?
The performSelector family of methods are not available in Swift. So how can you call a method on an @objc object, where the method to be called is chosen at runtime, and not known at compile time? NSInvocation is apparently also not available in Swift.

I know that in Swift, you can send any method (for which there is an @objc method declaration visible) to the type AnyObject, similar to id in Objective-C. However, that still requires you to hard-code the method name at compile-time. Is there a way to dynamically choose it at runtime?

答:
You didn't really explain what your where trying to actually achieve, so here's sone ideas that might lead your to a solution.
Firstly, and I would encourage you to to do this unless you haven to, but you can dynamical generate a selection from a String in swift

```<code>Selector("myMehodA:")
Selector("myMehodB:")
</code>```

But functions are first rate objects in swift so why not just use a dictionary

```<code>func bMethod() { print("B") }

let dict = ["aThing": { print("A") },
            "bThing": bMethod]

dict["aThing"]?()
dict["bThing"]?()
</code>```

Body:
You didn't really explain what your where trying to actually achieve, so here's sone ideas that might lead your to a solution.
Firstly, and I would encourage you to to do this unless you haven to, but you can dynamical generate a selection from a String in swift

Selector("myMehodA:")
Selector("myMehodB:")

But functions are first rate objects in swift so why not just use a dictionary

func bMethod() { print("B") }

let dict = ["aThing": { print("A") },
            "bThing": bMethod]

dict["aThing"]?()
dict["bThing"]?()


问:
Camel AtlasMap UnrecognizedPropertyException
I'm test driving atlasmap in a camel route. I have created a very simple test input xml file, an adm file, and a route. I get an exception.

```<code>public class ImportRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {

        from(file("/edi/test/test_file_origin/").include("^.*\\.xml$"))
                .autoStartup(true)
                .to(
                        atlasmap("mapping/xml_to_json.adm")
                )
                .to(log("Done"));
    }
}
</code>```

test.xml @ '"/edi/test/test_file_origin/"':

```<code><test>
    <id>3</id>
</test>
</code>```

My exception:

```<code>io.atlasmap.api.AtlasException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "id" (class io.atlasmap.v2.DataSourceMetadata), not marked as ignorable (8 known properties: "documentType", "documentId", "name", "inspectionType", "dataSourceType", "isSource", "source", "inspectionParameters"])
 at [Source: (GZIPInputStream); line: 1, column: 2083] (through reference chain: io.atlasmap.v2.ADMDigest["exportMeta"]->java.lang.Object[][0]->io.atlasmap.v2.DataSourceMetadata["id"])
    at io.atlasmap.core.ADMArchiveHandler.getDataSourceMetadataMap(ADMArchiveHandler.java:327)
    at io.atlasmap.core.DefaultAtlasContext.<init>(DefaultAtlasContext.java:119)
    at io.atlasmap.core.DefaultAtlasContextFactory.createContext(DefaultAtlasContextFactory.java:191)
    at org.apache.camel.component.atlasmap.AtlasMapEndpoint.getOrCreateAtlasContext(AtlasMapEndpoint.java:253)
    at org.apache.camel.component.atlasmap.AtlasMapEndpoint.onExchange(AtlasMapEndpoint.java:198)
    at org.apache.camel.support.ProcessorEndpoint$1.process(ProcessorEndpoint.java:61)
    at org.apache.camel.support.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:66)
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:169)
    at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:395)
    at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:148)
    at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:60)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:147)
    at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:312)
    at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:483)
    at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:237)
    at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:198)
    at org.apache.camel.support.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:190)
    at org.apache.camel.support.ScheduledPollConsumer.run(ScheduledPollConsumer.java:107)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "id" (class io.atlasmap.v2.DataSourceMetadata), not marked as ignorable (8 known properties: "documentType", "documentId", "name", "inspectionType", "dataSourceType", "isSource", "source", "inspectionParameters"])
 at [Source: (GZIPInputStream); line: 1, column: 2083] (through reference chain: io.atlasmap.v2.ADMDigest["exportMeta"]->java.lang.Object[][0]->io.atlasmap.v2.DataSourceMetadata["id"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:855)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1212)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1604)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1582)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:299)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:195)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:21)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3505)
    at io.atlasmap.core.ADMArchiveHandler.getDataSourceMetadataMap(ADMArchiveHandler.java:315)
</code>```

Is Jackson possibly configured incorrectly somewhere else in the project? Ultimately, I want to map the json output of the adm file to a Java object, which I would persist via JPA.

答: It looks like a version mismatch, make sure you're using the same version of AtlasMap UI with the one used by camel-atlasmap component.</p>

Body:
I'm test driving atlasmap in a camel route. I have created a very simple test input xml file, an adm file, and a route. I get an exception.

public class ImportRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {

        from(file("/edi/test/test_file_origin/").include("^.*\\.xml$"))
                .autoStartup(true)
                .to(
                        atlasmap("mapping/xml_to_json.adm")
                )
                .to(log("Done"));
    }
}

test.xml @ '"/edi/test/test_file_origin/"':

<test>
    <id>3</id>
</test>

My exception:

io.atlasmap.api.AtlasException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "id" (class io.atlasmap.v2.DataSourceMetadata), not marked as ignorable (8 known properties: "documentType", "documentId", "name", "inspectionType", "dataSourceType", "isSource", "source", "inspectionParameters"])
 at [Source: (GZIPInputStream); line: 1, column: 2083] (through reference chain: io.atlasmap.v2.ADMDigest["exportMeta"]->java.lang.Object[][0]->io.atlasmap.v2.DataSourceMetadata["id"])
    at io.atlasmap.core.ADMArchiveHandler.getDataSourceMetadataMap(ADMArchiveHandler.java:327)
    at io.atlasmap.core.DefaultAtlasContext.<init>(DefaultAtlasContext.java:119)
    at io.atlasmap.core.DefaultAtlasContextFactory.createContext(DefaultAtlasContextFactory.java:191)
    at org.apache.camel.component.atlasmap.AtlasMapEndpoint.getOrCreateAtlasContext(AtlasMapEndpoint.java:253)
    at org.apache.camel.component.atlasmap.AtlasMapEndpoint.onExchange(AtlasMapEndpoint.java:198)
    at org.apache.camel.support.ProcessorEndpoint$1.process(ProcessorEndpoint.java:61)
    at org.apache.camel.support.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:66)
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:169)
    at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:395)
    at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:148)
    at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:60)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:147)
    at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:312)
    at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:483)
    at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:237)
    at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:198)
    at org.apache.camel.support.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:190)
    at org.apache.camel.support.ScheduledPollConsumer.run(ScheduledPollConsumer.java:107)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "id" (class io.atlasmap.v2.DataSourceMetadata), not marked as ignorable (8 known properties: "documentType", "documentId", "name", "inspectionType", "dataSourceType", "isSource", "source", "inspectionParameters"])
 at [Source: (GZIPInputStream); line: 1, column: 2083] (through reference chain: io.atlasmap.v2.ADMDigest["exportMeta"]->java.lang.Object[][0]->io.atlasmap.v2.DataSourceMetadata["id"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:855)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1212)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1604)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1582)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:299)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:195)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:21)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3505)
    at io.atlasmap.core.ADMArchiveHandler.getDataSourceMetadataMap(ADMArchiveHandler.java:315)

Is Jackson possibly configured incorrectly somewhere else in the project? Ultimately, I want to map the json output of the adm file to a Java object, which I would persist via JPA.


问:
React Custom Drop-Down - remove click event
I have made a custom dropDown with a div that I set an onClick attribute to open dropDown and close it. but also I want to close it when the user clicks to another part of the site.

```<code> <div
    onClick={() => setIsDropDownOpen(!isDropDownOpen)}
    className="selected-drop-down"
 >
    <span className="dropDownText">{selectedQuoteCurrency}</span>
    <img
      className="dropDownIcon"
      src={require("../assets/image/arrow/dropDown-Arrow.png")}
      width="15px"
      alt="arrow"
    />
 </div>
</code>```

I also do this logic

```<code>useEffect(() => {
    if(isDropDownOpen) {
      window.addEventListener('click',changeDD )
    }else {
      window.removeEventListener('click',changeDD )
    }
  },[isDropDownOpen])

  function changeDD() {
    setIsBaseDropDownOpen(false)
  }

</code>```

But I was faced with a problem that when the component didmount for the first time everything is okay and dropDown opened and when click over there it closed, but for the second time, the dropdown didn't open because the state did not change to true.

furthermore, I tried to handle this click event by tabindex attribute according to this document => developerMozila but I didn't succeed

答:
You can use hover in css like this. when mouse go away from loc of dropdown menu, automatic close.

.options:hover{
    display: flex;
    flex-direction: column;
    position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div className="options">
   <button>Add</button>
   <button>Logout</button>
 </div></code>```

Body:
I have made a custom dropDown with a div that I set an onClick attribute to open dropDown and close it. but also I want to close it when the user clicks to another part of the site.

 setIsDropDownOpen(!isDropDownOpen)}
    className="selected-drop-down"
 >
    {selectedQuoteCurrency}

I also do this logic

useEffect(() => {
    if(isDropDownOpen) {
      window.addEventListener('click',changeDD )
    }else {
      window.removeEventListener('click',changeDD )
    }
  },[isDropDownOpen])

  function changeDD() {
    setIsBaseDropDownOpen(false)
  }

But I was faced with a problem that when the component didmount for the first time everything is okay and dropDown opened and when click over there it closed, but for the second time, the dropdown didn't open because the state did not change to true.

furthermore, I tried to handle this click event by tabindex attribute according to this document => developerMozila but I didn't succeed

Body:
You can use hover in css like this. when mouse go away from loc of dropdown menu, automatic close.

.options:hover{
    display: flex;
    flex-direction: column;
    position: absolute;
}

<div className="options">
   <button>Add</button>
   <button>Logout</button>
 </div>


问:
What does this elasticsearch query mean?
I want to find best movie/webseries from past 6 months to now and it should have good rating also.

```<code>POST sample-movie-2022.02.08/_search
{
  "query": {
    "function_score": {
      "functions": [
        {
          "gauss": {
            "rating": {
              "origin": "10",
              "scale": "1"
            }
          }
        },
        {
          "gauss": {
            "release_date": {
              "origin": "now",
              "scale": "180d"
            }
          }
        }
      ]
    }
  }
}

</code>```

The query gives different score when i change rating scale like 1,7,8.I actually don't know what does it mean in rating but i understood origin and scaling in relase_date

答:
You're using a decay functions (i.e. gauss) and the parameters to that function mean:

origin: the point of origin from where the "distance" is computed

offset (default 0 as in your case): means that the decay starts right at the origin (i.e. origin ± offset = origin in your case)

scale: the point at which the function will take the value of decay (i.e. origin ± offset ± scale)

decay (default 0.5 as in your case): the score at the scale point (i.e. the score at origin ± offset ± scale

So, concretely in your case what it means is that:

documents with a rating of 10 will score 1

documents with a rating of 9 or 11 (scale = 10 ± 1) will score 0.5

documents with a rating <9 or >11 will score below 0.5

So the offset and scale parameters allow you to define the inflection point from which the scoring will decay.

Body:
I want to find best movie/webseries from past 6 months to now and it should have good rating also.

POST sample-movie-2022.02.08/_search
{
  "query": {
    "function_score": {
      "functions": [
        {
          "gauss": {
            "rating": {
              "origin": "10",
              "scale": "1"
            }
          }
        },
        {
          "gauss": {
            "release_date": {
              "origin": "now",
              "scale": "180d"
            }
          }
        }
      ]
    }
  }
}

The query gives different score when i change rating scale like 1,7,8.I actually don't know what does it mean in rating but i understood origin and scaling in relase_date


问:
TortoiseSVN error The XML response contains invalid XML and Malformed XML: no element found
My TortoiseSVN Checkout and Update error

The XML response contains invalid XML
   Malformed XML: no element found

What do you do
Please help me.

答:
old Q maybe the following ans will help someone

Cause
The error indicates that the URL used to address the repository using Subversion client is inappropriate.

Most likely, the URL was copied from the web browser's address bar when exploring the repository through the web interface of VisualSVN Server. Subversion client programs are not capable of handling the syntax of such URLs. The appropriate URLs should be obtained by clicking the Checkout button in the web interface.

Resolution
When you are going to check out a working copy or one way or another use a Subversion client to access a repository, you should obtain the appropriate repository URL by clicking the Checkout button.

Follow these steps to obtain the Subversion repository URL that can be used with a Subversion client program:

On the VisualSVN Server web interface, navigate to the desired repository path.
Click the Checkout button at the top right-hand side of the web interface and copy the repository URL to clipboard.


问:
Print all text within child elements - Selenium - Python
I want to print all the text within the child elements of this div id "dataWarnings". Typing until
I can post the question. Seems like I have to keep typing more text. Holy moly now even more text is being typed.

My code -

```<code>def check_warnings():
    driver.find_element(By.ID,'Warnings-tab').click()
    container1 = driver.find_elements(By.ID,'dataWarnings')

    for items in container1:
        mytext = items.find_element(By.XPATH,"//*[@id="JobStatusOkWithWarnings"]")
        print (mytext.text)
</code>```

My modules -

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from time import sleep
</code>```

HTML -

```<code><div class="tab-pane fade active show" id="dataWarnings" role="tabpanel" aria-labelledby="profile-tab">
    <div id="JobStatusOkWithWarnings">
        <b><u>1 Jobs Process successfully for Product Code WIP04499</u></b><br />
        <br />
        <b>No Activity Messages</b><br />
        <br />
        <b>No General Errors</b><br />
        <br />
        Jobs that have been created<br />
        --------------------------------------------------------------------------------------------------------<br />
        <b>Job Number: WIP04499-622</b><br />
        <br />
        <b>1 Job Activity Messages</b><br />
        <br />
        Failed to generate task [Reason :There were no mapped By-Products found for stage [Company :Freshcut Foods] [Process :Prepped By Hand] [Version :1] [Stage :Material Output (By-Product)]] <br />
        <br />
        <b>No Job Errors</b><br />
        <br />
        <b>4 Job Tasks</b><br />
        <br />
        4458 - Batch Finish Time<br />
        4459 - Batch Start Time<br />
        4460 - Output Quantity And Batch Number<br />
        4461 - Input Quantity And Batch Number<br />
        <br />
        --------------------------------------------------------------------------------------------------------<br />
        <br />
    </div>
</div>

</code>```

Desired output -

```<code>1 Jobs Process successfully for Product Code WIP04499
No Activity Messages
No General Errors
Jobs that have been created
--------------------------------------------------------------------------------------------------------
Job Number: WIP04499-601
1 Job Activity Messages
Failed to generate task [Reason :There were no mapped By-Products found for stage [Company :Freshcut Foods] [Process :Prepped By Hand] [Version :1] [Stage :Material Output (By-Product)]]
No Job Errors
4 Job Tasks
4374 - Batch Finish Time
4375 - Batch Start Time
4376 - Output Quantity And Batch Number
4377 - Input Quantity And Batch Number
--------------------------------------------------------------------------------------------------------
</code>```

Current Output -

```<code>(literally blank)
</code>```

答:
Can't believe this took me so long to realize, I used</p>
```<code>    parent = WebDriverWait(driver,delay).until(EC.presence_of_element_located((By.ID,'dataWarnings')))
    text = parent.get_attribute('innerText')
    print (text)
</code>```

Body:
I want to print all the text within the child elements of this div id "dataWarnings". Typing until
I can post the question. Seems like I have to keep typing more text. Holy moly now even more text is being typed.

My code -

def check_warnings():
    driver.find_element(By.ID,'Warnings-tab').click()
    container1 = driver.find_elements(By.ID,'dataWarnings')

    for items in container1:
        mytext = items.find_element(By.XPATH,"//*[@id="JobStatusOkWithWarnings"]")
        print (mytext.text)

My modules -

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from time import sleep

HTML -

        1 Jobs Process successfully for Product Code WIP04499

        No Activity Messages

        No General Errors

        Jobs that have been created

        --------------------------------------------------------------------------------------------------------

        Job Number: WIP04499-622

        1 Job Activity Messages

        Failed to generate task [Reason :There were no mapped By-Products found for stage [Company :Freshcut Foods] [Process :Prepped By Hand] [Version :1] [Stage :Material Output (By-Product)]]

        No Job Errors

        4 Job Tasks

        4458 - Batch Finish Time

        4459 - Batch Start Time

        4460 - Output Quantity And Batch Number

        4461 - Input Quantity And Batch Number

        --------------------------------------------------------------------------------------------------------

Desired output -

1 Jobs Process successfully for Product Code WIP04499
No Activity Messages
No General Errors
Jobs that have been created
--------------------------------------------------------------------------------------------------------
Job Number: WIP04499-601
1 Job Activity Messages
Failed to generate task [Reason :There were no mapped By-Products found for stage [Company :Freshcut Foods] [Process :Prepped By Hand] [Version :1] [Stage :Material Output (By-Product)]]
No Job Errors
4 Job Tasks
4374 - Batch Finish Time
4375 - Batch Start Time
4376 - Output Quantity And Batch Number
4377 - Input Quantity And Batch Number
--------------------------------------------------------------------------------------------------------

Current Output -

(literally blank)

Body:
Can't believe this took me so long to realize, I used

    parent = WebDriverWait(driver,delay).until(EC.presence_of_element_located((By.ID,'dataWarnings')))
    text = parent.get_attribute('innerText')
    print (text)


问:
PHP-Isset function is not working
I am new to PHP. My isset function is not working .It does not not show  error .It always insert the table. I have given my code. Kindly advice what i done wrong on this

```<code><?php
if(isset($_POST['submit'])) {
    $a= $_POST['companyname'];
    $b= $_POST['ballpark_url'];
    $c= $_POST['username'];
    $d= $_POST['email'];
    $e= $_POST['login1'];
    $f= $_POST['pass'];
    $error = false;
    if(validname($a) ==false) {
        echo $nameerror = "enter the valid name";
    }
    if(validemail($d) ==false) {
        echo $nameerror = "enter the valid email";
    }
    if(isset($_POST['companyname'])) {
        if($error==false) {
            $query= "INSERT INTO user VALUES ('$a','$b','$c','$d','$e','$f','');";
            if(!mysql_query($query)) {
                die ('error:'.mysql_error());
            }
            mysql_close($conn);
        }
        include("templats/header_1.html");
        include("templats/content.html");
        include("templats/footer.html");
    }
?>
</code>```

kindly rectify the issue in my code and send back to me...

答:
Use !empty($a) instead of isset($_POST['companyname']).

However then your page wouldn't display. Why not:

```<code><?php
if(isset($_POST['submit'])) {

    $company_name = $_POST['companyname'];
    $ballpark_url = $_POST['ballpark_url'];
    $username     = $_POST['username'];
    $email        = $_POST['email'];
    $login1       = $_POST['login1'];
    $pass         = $_POST['pass'];

    $error = false;

    if( !validname( $company_name ) ) {
        echo "enter the valid name";
        $error = true;
    }

    if( !validemail( $email ) ) {
        echo "enter the valid email";
        $error = true;
    }

    if( empty($_POST['companyname']) ) {
        echo "enter a company name";
        $error = true;
    }

    if( !$error ) {
        $query= "INSERT INTO user VALUES ('$company_name',
                                          '$ballpark_url',
                                          '$username',
                                          '$email',
                                          '$login1',
                                          '$pass','');";

        if(!mysql_query($query)) {
         die ( 'error:' . mysql_error() );

         mysql_close( $conn );
    }

    include("templats/header_1.html");
    include("templats/content.html");
    include("templats/footer.html");
}
?>
</code>```

Title: PHP-Isset function is not working

Body:
I am new to PHP. My isset function is not working .It does not not show  error .It always insert the table. I have given my code. Kindly advice what i done wrong on this

<?php
if(isset($_POST['submit'])) {
    $a= $_POST['companyname'];
    $b= $_POST['ballpark_url'];
    $c= $_POST['username'];
    $d= $_POST['email'];
    $e= $_POST['login1'];
    $f= $_POST['pass'];
    $error = false;
    if(validname($a) ==false) {
        echo $nameerror = "enter the valid name";
    }
    if(validemail($d) ==false) {
        echo $nameerror = "enter the valid email";
    }
    if(isset($_POST['companyname'])) {
        if($error==false) {
            $query= "INSERT INTO user VALUES ('$a','$b','$c','$d','$e','$f','');";
            if(!mysql_query($query)) {
                die ('error:'.mysql_error());
            }
            mysql_close($conn);
        }
        include("templats/header_1.html");
        include("templats/content.html");
        include("templats/footer.html");
    }
?>

kindly rectify the issue in my code and send back to me...

Body:
Use !empty($a) instead of isset($_POST['companyname']).

However then your page wouldn't display. Why not:

<?php
if(isset($_POST['submit'])) {

    $company_name = $_POST['companyname'];
    $ballpark_url = $_POST['ballpark_url'];
    $username     = $_POST['username'];
    $email        = $_POST['email'];
    $login1       = $_POST['login1'];
    $pass         = $_POST['pass'];

    $error = false;

    if( !validname( $company_name ) ) {
        echo "enter the valid name";
        $error = true;
    }

    if( !validemail( $email ) ) {
        echo "enter the valid email";
        $error = true;
    }

    if( empty($_POST['companyname']) ) {
        echo "enter a company name";
        $error = true;
    }

    if( !$error ) {
        $query= "INSERT INTO user VALUES ('$company_name',
                                          '$ballpark_url',
                                          '$username',
                                          '$email',
                                          '$login1',
                                          '$pass','');";

        if(!mysql_query($query)) {
         die ( 'error:' . mysql_error() );

         mysql_close( $conn );
    }

    include("templats/header_1.html");
    include("templats/content.html");
    include("templats/footer.html");
}
?>


问:
First click on Nav Menu Button Giving Error and working fine after that ReactJs
I am trying to make a hide/show navbar in ReactJS.
But on the first click I am getting this error and its working fine after the first click.

Note: Its twice and i have no idea why

Here is my code and its only working (after first error) when

setMenu(!menu);

is before

nav.classList.toggle("nav-open");

otherwise the error just keeps coming.

```<code>export default function Navbar() {
  const [menu, setMenu] = useState(true);
  const nav = document.querySelector("nav");

  const openNav = () => {
    setMenu(!menu);
    nav.classList.toggle("nav-open");
  };

  return (
    <nav id="nav-wrapper">
      <header className="nav-header">
        <div
          className="arrow-btn"
          onClick={() => {
            openNav();
          }}
        >
          {menu ? (
            <Icon.HiChevronDoubleLeft size={20} className="arrows" />
          ) : (
            <Icon.HiChevronDoubleRight size={20} className="arrows" />
          )}
        </div>
        <img src={Profiledp} alt="." />
        <p className="name">Naman Pokhriyal</p>
      </header>
  </nav>
</code>```

答:
This isn't the right way of doing this in React in the first place.  You're already using the menu state value to determine if the menu is open is not, so why not continue to use the menu state value to determine if the menu is open or not?  Something like this:

```<code>const openNav = () => {
    setMenu(!menu);
};

return (
  <nav id="nav-wrapper" className={menu ? "nav-open" : ""}>
  // etc.
);
</code>```

Basically any time you're trying to directly manipulate the DOM in React, take a step back and try to find a way to manage that via state instead.  Direct DOM manipulation in React almost always leads to bugs unless you really know what you're doing under the hood in the framework.

Body:
I am trying to make a hide/show navbar in ReactJS.
But on the first click I am getting this error and its working fine after the first click.

Note: Its twice and i have no idea why

Here is my code and its only working (after first error) when

setMenu(!menu);

is before

nav.classList.toggle("nav-open");

otherwise the error just keeps coming.

export default function Navbar() {
  const [menu, setMenu] = useState(true);
  const nav = document.querySelector("nav");

  const openNav = () => {
    setMenu(!menu);
    nav.classList.toggle("nav-open");
  };

  return (

 {
            openNav();
          }}
        >
          {menu ? (
            <Icon.HiChevronDoubleLeft size={20} className="arrows" />
          ) : (
            <Icon.HiChevronDoubleRight size={20} className="arrows" />
          )}

Naman Pokhriyal

Body:
This isn't the right way of doing this in React in the first place.  You're already using the menu state value to determine if the menu is open is not, so why not continue to use the menu state value to determine if the menu is open or not?  Something like this:

const openNav = () => {
    setMenu(!menu);
};

return (
  <nav id="nav-wrapper" className={menu ? "nav-open" : ""}>
  // etc.
);

Basically any time you're trying to directly manipulate the DOM in React, take a step back and try to find a way to manage that via state instead.  Direct DOM manipulation in React almost always leads to bugs unless you really know what you're doing under the hood in the framework.


问:
Matching content between 2 CSVs and write the values
Each user has a domain1.com and domain2.com separate email address. I would like to compare email addresses within CSV1 & CSV2 and if the prefix name on their emails match, pull the value into CSV1.  This will later allow me to run other powershell commands on a source / target kind of scenario.

I have it somewhat, working below although the domain2_email column isn't matching the user row. It looks to be trying to import all of them into an array.

I have used Joe.Bloggs here to test if the IF is working, but ideally - I would like to have it search each entry in CSV1.

End Goal:

Search CSV2 with the name part of the primarySMTPAddress value and if match, put them into another column within CSV1.

CSV1 will have a user with domain1.com and domain2.com values within the row.

```<code># Pull in mailbox data
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain1.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain1export.csv'
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain2.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain2xexport.csv'

$outfile = './outfile.csv'
$finalOutfile = './finalOutfile.csv'

# Check if outfile.csv exists, if it does - delete.
if (test-path $outfile) {
    Remove-Item $outfile
    Write-Host "$outfile has been deleted"
}

$CSV1 = Import-Csv -Path './domain1export.csv'
$CSV2 = Import-Csv -Path './domain2export.csv'

$CVS1 | foreach {
    # Splits the name prefix from email
    $_ | Select-Object *,@{Name='Name_Prefix';Expression={$_.PrimarySmtpAddress.Split("@")[0] }} | Export-Csv -Path $outfile -Append -NoTypeInformation
}

$outfile2 = Import-Csv -Path $outfile
foreach ($item in $outfile2) {
    if ($outfile2.Name_Prefix -match "Joe.Bloggs") {
        $item | Select-Object *,@{Name='Domain2_email';Expression={$CSV2.PrimarySmtpAddress}} | Export-Csv -Path $finalOutfile -Append -NoTypeInformation
    }
}
</code>```

Data

CSV1

```<code>UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain1.com,d1bloggsj,Domain1 Joe Bloggs,SIP:joe.blogggs@domain1.com SMTP:joe.blogggs@domain1.com,Joe.Bloggs@domain1.com,UserMailbox,UserMailbox
foo.bar@domain1.com,d1barf,Domain1 Foo Bar,SIP:foo.bar@domain1.com SMTP:foo.bar@domain1.com  ,foo.bar@domain1.com,UserMailbox,UserMailbox
</code>```

CSV2

```<code>UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain2.com,d2bloggsj,Domain2 Joe Bloggs,SIP:joe.blogggs@domain2.com SMTP:joe.blogggs@domain2.com,Joe.Bloggs@domain2.com,UserMailbox,UserMailbox
foo.bar@domain2.com,d1barf,Domain2 Foo Bar,SIP:foo.bar@domain2.com SMTP:foo.bar@domain2.com  ,foo.bar@domain2.com,UserMailbox,UserMailbox

</code>```

答:
So both CSV1 and CSV2 would contain a column called PrimarySmtpAddress and you need to match those, correct?

Try

```<code>$CSV1 = Import-Csv -Path './domain1export.csv'
$CSV2 = Import-Csv -Path './domain2export.csv'

$result = foreach ($item in $csv1) {
    $prefix = $item.PrimarySmtpAddress.Split("@")[0]
    # try and find a match
    $matching = $csv2 | Where-Object { $_.PrimarySmtpAddress.Split("@")[0] -eq $prefix }
    $item | Select-Object *, @{Name = 'Name_Prefix'; Expression = {$prefix }},
                             @{Name = 'Domain2_email';Expression = {$matching.PrimarySmtpAddress }}
}

$finalOutfile = './finalOutfile.csv'
$result | Export-Csv -Path $finalOutfile -NoTypeInformation
</code>```

BTW. According to the docs, the -Filter parameter is a string, not a scriptblock, so you should use

```<code>Get-EXOMailbox  -Filter "EmailAddresses -like '*@domain1.com' -and RecipientTypeDetails -ne 'SharedMailbox'"
</code>```

Body:
Each user has a domain1.com and domain2.com separate email address. I would like to compare email addresses within CSV1 & CSV2 and if the prefix name on their emails match, pull the value into CSV1.  This will later allow me to run other powershell commands on a source / target kind of scenario.

I have it somewhat, working below although the domain2_email column isn't matching the user row. It looks to be trying to import all of them into an array.

I have used Joe.Bloggs here to test if the IF is working, but ideally - I would like to have it search each entry in CSV1.

End Goal:

Search CSV2 with the name part of the primarySMTPAddress value and if match, put them into another column within CSV1.

CSV1 will have a user with domain1.com and domain2.com values within the row.

# Pull in mailbox data
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain1.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain1export.csv'
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain2.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain2xexport.csv'

$outfile = './outfile.csv'
$finalOutfile = './finalOutfile.csv'

# Check if outfile.csv exists, if it does - delete.
if (test-path $outfile) {
    Remove-Item $outfile
    Write-Host "$outfile has been deleted"
}

$CSV1 = Import-Csv -Path './domain1export.csv'
$CSV2 = Import-Csv -Path './domain2export.csv'

$CVS1 | foreach {
    # Splits the name prefix from email
    $_ | Select-Object *,@{Name='Name_Prefix';Expression={$_.PrimarySmtpAddress.Split("@")[0] }} | Export-Csv -Path $outfile -Append -NoTypeInformation
}

$outfile2 = Import-Csv -Path $outfile
foreach ($item in $outfile2) {
    if ($outfile2.Name_Prefix -match "Joe.Bloggs") {
        $item | Select-Object *,@{Name='Domain2_email';Expression={$CSV2.PrimarySmtpAddress}} | Export-Csv -Path $finalOutfile -Append -NoTypeInformation
    }
}

Data

CSV1

UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain1.com,d1bloggsj,Domain1 Joe Bloggs,SIP:joe.blogggs@domain1.com SMTP:joe.blogggs@domain1.com,Joe.Bloggs@domain1.com,UserMailbox,UserMailbox
foo.bar@domain1.com,d1barf,Domain1 Foo Bar,SIP:foo.bar@domain1.com SMTP:foo.bar@domain1.com  ,foo.bar@domain1.com,UserMailbox,UserMailbox

CSV2

UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain2.com,d2bloggsj,Domain2 Joe Bloggs,SIP:joe.blogggs@domain2.com SMTP:joe.blogggs@domain2.com,Joe.Bloggs@domain2.com,UserMailbox,UserMailbox
foo.bar@domain2.com,d1barf,Domain2 Foo Bar,SIP:foo.bar@domain2.com SMTP:foo.bar@domain2.com  ,foo.bar@domain2.com,UserMailbox,UserMailbox

Body:
So both CSV1 and CSV2 would contain a column called PrimarySmtpAddress and you need to match those, correct?

Try

$CSV1 = Import-Csv -Path './domain1export.csv'
$CSV2 = Import-Csv -Path './domain2export.csv'

$result = foreach ($item in $csv1) {
    $prefix = $item.PrimarySmtpAddress.Split("@")[0]
    # try and find a match
    $matching = $csv2 | Where-Object { $_.PrimarySmtpAddress.Split("@")[0] -eq $prefix }
    $item | Select-Object *, @{Name = 'Name_Prefix'; Expression = {$prefix }},
                             @{Name = 'Domain2_email';Expression = {$matching.PrimarySmtpAddress }}
}

$finalOutfile = './finalOutfile.csv'
$result | Export-Csv -Path $finalOutfile -NoTypeInformation

BTW. According to the docs, the -Filter parameter is a string, not a scriptblock, so you should use

Get-EXOMailbox  -Filter "EmailAddresses -like '*@domain1.com' -and RecipientTypeDetails -ne 'SharedMailbox'"


答:
```<code>select
    main.stuid,
    main.in_date,
    case when main.out_date is null then localtimestamp(0) else main.out_date end as out_date,
    case when main.out_date is null then localtimestamp(0)::timestamp - main.in_date else main.out_date - main.in_date end as stay_in_class,
    case when main.out_date is null then 'in class now' else 'came out' end as stu_status
from
    (
        select
            t_in.stuid,
            t_in.recorded as in_date,
            min(t_out.out_date) as out_date
        from
            test.in_class t_in
        left join
            (
                select stuid, recorded as out_date
                from test.in_class
                where actions = 'OUT'
            ) t_out on t_in.stuid = t_out.stuid and t_in.recorded < t_out.out_date
        where
            t_in.actions = 'IN'
        group by t_in.stuid, t_in.recorded
        order by t_in.stuid, in_date, out_date
    ) main
</code>```

Result of this query:

stuid
in_date
out_date
stay_in
stu_status

1
2022-02-08 10:00:00.000
2022-02-08 14:00:00.000
04:00:00
came out

1
2022-02-08 16:00:00.000
2022-02-08 20:00:00.000
04:00:00
came out

2
2022-02-08 09:00:00.000
2022-02-08 13:00:00.000
04:00:00
came out

2
2022-02-08 15:00:00.000
2022-02-08 16:55:50.000
01:55:50
in class now

Title: Calculating total Hour spent by student in class room using PostgreSQL

Body:
A classroom records its student movement IN and Out of the classroom in a table as shown below:

+-------+---------+---------------------+
| stuId | actions | recorded            |
+-------+---------+---------------------+
| 1     | IN      | 2021-05-01 10:00:00 |
+-------+---------+---------------------+
| 1     | OUT     | 2021-05-01 14:00:00 |
+-------+---------+---------------------+
| 1     | IN      | 2021-05-01 16:00:00 |
+-------+---------+---------------------+
| 1     | OUT     | 2021-05-01 20:00:00 |
+-------+---------+---------------------+
| 2     | IN      | 2021-05-01 09:00:00 |
+-------+---------+---------------------+
| 2     | OUT     | 2021-05-01 13:00:00 |
+-------+---------+---------------------+
| 2     | IN      | 2021-05-01 15:00:00 |
+-------+---------+---------------------+

We have to calculate the amount of hour spent by each student inside the classroom.

Also, for student 2 the last action is 'IN'. So, that student is still studying inside the class. So we have to add this hour also while the student is still studying. We can use current time to calculate it.

What is the proper way to solve this problem statement?

Body:
select
    main.stuid,
    main.in_date,
    case when main.out_date is null then localtimestamp(0) else main.out_date end as out_date,
    case when main.out_date is null then localtimestamp(0)::timestamp - main.in_date else main.out_date - main.in_date end as stay_in_class,
    case when main.out_date is null then 'in class now' else 'came out' end as stu_status
from
    (
        select
            t_in.stuid,
            t_in.recorded as in_date,
            min(t_out.out_date) as out_date
        from
            test.in_class t_in
        left join
            (
                select stuid, recorded as out_date
                from test.in_class
                where actions = 'OUT'
            ) t_out on t_in.stuid = t_out.stuid and t_in.recorded < t_out.out_date
        where
            t_in.actions = 'IN'
        group by t_in.stuid, t_in.recorded
        order by t_in.stuid, in_date, out_date
    ) main

Result of this query:

stuid
in_date
out_date
stay_in
stu_status

1
2022-02-08 10:00:00.000
2022-02-08 14:00:00.000
04:00:00
came out

1
2022-02-08 16:00:00.000
2022-02-08 20:00:00.000
04:00:00
came out

2
2022-02-08 09:00:00.000
2022-02-08 13:00:00.000
04:00:00
came out

2
2022-02-08 15:00:00.000
2022-02-08 16:55:50.000
01:55:50
in class now


问:
Python program to number rows
i have a file with data as such.

```<code>>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>3_DL_2021.1214
>4_DL_2021.1214
>4_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214
</code>```

now as you can see the data is not numbered properly and hence needs to be numbered.
what im aiming for is this:

```<code>>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>4_DL_2021.1214
>5_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214
>9_DL_2021.1214
</code>```

now the file has a lot of other stuff between these lines starting with > sign. i want only the > sign stuff affected.

could someone please help me out with this.
also there are 563 such lines so manually doing it is out of question.

答:
sudden_appearance already provided a good answer.
In case you don't like regex too much you can use this code instead:

```<code>new_lines = []
with open('test_file.txt', 'r') as f:
    c = 1
    for line in f:
        if line[0] == '>':
            after_dash = line.split('_',1)[1]
            new_line = '>' + str(c) + '_' + after_dash
            c += 1
            new_lines.append(new_line)
        else:
            new_lines.append(line)

with open('test_file.txt', 'w') as f:
    f.writelines(new_lines)

</code>```

Also you can have a look at this split tutorial for more information about how to use split.

Title: Python program to number rows

Body:
i have a file with data as such.

>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>3_DL_2021.1214
>4_DL_2021.1214
>4_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214

now as you can see the data is not numbered properly and hence needs to be numbered.
what im aiming for is this:

>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>4_DL_2021.1214
>5_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214
>9_DL_2021.1214

now the file has a lot of other stuff between these lines starting with > sign. i want only the > sign stuff affected.

could someone please help me out with this.
also there are 563 such lines so manually doing it is out of question.

Body:
sudden_appearance already provided a good answer.
In case you don't like regex too much you can use this code instead:

new_lines = []
with open('test_file.txt', 'r') as f:
    c = 1
    for line in f:
        if line[0] == '>':
            after_dash = line.split('_',1)[1]
            new_line = '>' + str(c) + '_' + after_dash
            c += 1
            new_lines.append(new_line)
        else:
            new_lines.append(line)

with open('test_file.txt', 'w') as f:
    f.writelines(new_lines)

Also you can have a look at this split tutorial for more information about how to use split.


问:
Meta data is exposed and landing page of WCF service is shown, even with httpHelpPageEnabled="false" and serviceMetadata httpGetEnabled="false"
I need to deploy a WCF service. So I changed my web.config

To prevent that somebody calls:

```<code>svcutil.exe http://anysite.de/MyJobServer/MyJob.Service.svc/mex
</code>```

I have this entry

```<code><serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
</code>```

To prevent that a start page with the text: "You have created a service..." so I changed the web.config and added:

```<code>httpHelpPageEnabled="false"
</code>```

But I can still call svcutil and it creates a service.cs and the starting web page is still shown.

This is the complete web.config system.serviceModel section.

```<code><system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
        <service name="MyJob.Service"
                 behaviorConfiguration="behaviorDeployed">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfiguration" contract="MyJob.IService">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:8733/Design_Time_Addresses/MyJobService/Service1/" />
                </baseAddresses>
            </host>
        </service>
    </services>

    <behaviors>
        <serviceBehaviors>
            <behavior name="behaviorDeployed">
                <!-- To avoid disclosing metadata information,
                     set the values below to false before deployment -->
                <serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
                <!-- To receive exception details in faults for debugging purposes,
                     set the value below to true.  Set to false before deployment
                     to avoid disclosing exception information -->
                <serviceDebug includeExceptionDetailInFaults="false" httpHelpPageEnabled="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>

    <bindings>
        <basicHttpBinding>
            <binding name="basicHttpBindingConfiguration"
                     openTimeout="00:01:00" receiveTimeout="00:01:00"
                     maxBufferSize="1048576" maxReceivedMessageSize="1048576" maxBufferPoolSize="1048576" >
                <!-- Using HTTPS, set security mode="Transport" -->
                <!-- Using HTTP, set security mode="None" -->
                <security mode="Transport">
                    <transport clientCredentialType="None"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
</system.serviceModel>
</code>```

答:
The problem ist the mex binding.

The wsdl data can't be queried by this setting shown in the question.. The problem is that there is another endpoint: The mex endpoint. This also shows the meta data and it's own landing page.

I disabled the endpoint

```<code><!--
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
-->
</code>```

And now I get a neutral landing page that this page doesn't provide any meta data.

Body:
I need to deploy a WCF service. So I changed my web.config

To prevent that somebody calls:

svcutil.exe http://anysite.de/MyJobServer/MyJob.Service.svc/mex

I have this entry

<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />

To prevent that a start page with the text: "You have created a service..." so I changed the web.config and added:

httpHelpPageEnabled="false"

But I can still call svcutil and it creates a service.cs and the starting web page is still shown.

This is the complete web.config system.serviceModel section.

<system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
        <service name="MyJob.Service"
                 behaviorConfiguration="behaviorDeployed">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfiguration" contract="MyJob.IService">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:8733/Design_Time_Addresses/MyJobService/Service1/" />
                </baseAddresses>
            </host>
        </service>
    </services>

    <behaviors>
        <serviceBehaviors>
            <behavior name="behaviorDeployed">

                <serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />

                <serviceDebug includeExceptionDetailInFaults="false" httpHelpPageEnabled="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>

    <bindings>
        <basicHttpBinding>
            <binding name="basicHttpBindingConfiguration"
                     openTimeout="00:01:00" receiveTimeout="00:01:00"
                     maxBufferSize="1048576" maxReceivedMessageSize="1048576" maxBufferPoolSize="1048576" >

                <security mode="Transport">
                    <transport clientCredentialType="None"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
</system.serviceModel>

Body:
The problem ist the mex binding.

The wsdl data can't be queried by this setting shown in the question.. The problem is that there is another endpoint: The mex endpoint. This also shows the meta data and it's own landing page.

I disabled the endpoint

<!--
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
-->

And now I get a neutral landing page that this page doesn't provide any meta data.


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答:
Optimization is almost tautologically a tradeoff: you gain runtime efficiency at the cost of other things (readability, maintainability, flexibility, compile times, etc.).  As such, it's really never a good idea to do unless you know what the tradeoff is and why it's worthwhile.

Even worse, thinking about "how do I do X fast" can be very distracting.  To much energy in that direction can easily lead to you misisng out on method Y which is much better (and often faster --- this is how "optimization" can make your code slower).  Particularly if you do too much of this on a big project from the beginning, it represents a lot of momentum.  If you can't afford to overcome that momentum, you can easily become locked into a bad design because you can't afford the time to restructure it.  This way lie dragons

What your boss may be thinking of is more of an issue of writing bad code via inappropriate representations and algorithms.  It's not really the same thing as optimizing, but an approach where you pay no attention whatsoever to appropriate data structures etc. can result in a codebase that is slow everywhere, and (much like the above "lock in") requires heroic effort to fix.

In general though, premature optimization really honestly is a terrible idea.  Particularly when you end up with a complex, finely tuned, well documented (because that's the only way you can understand it) piece of code you end up not using anyway.  And that's not even getting into the issue of subtle bugs that are often introduced when "optimizing"

[edit:  pshaw, of course a Knuth quote encapsulates this well.  That's what I get for typing too much]

OwnerDisplayName: dicroce

ContentLicense: CC BY-SA 2.5

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: simon


问:
How to get id from URL in codeigniter?
I am trying to get 'id' from URL in order to delete that specific selected product. I have used $this->uri->segment(3) but its not getting any value from URL. Although i can see the 'product_id' in my URL.

If i used $this->url->segment(2) it gives me the second value form URL, but i am unable to get product Id.
Following is my code. Kindly guide me.

VIEW

```<code>echo "<a href='delete_controller?product_id=$product_id'>";
echo $name;
echo "</a>";
</code>```

The following URL is generating when i click on $name.

```<code>http://localhost/designs2/index.php/products_controller/delete_controller?product_id=70
</code>```

Controller

```<code>public function delete_controller()
    {
        echo $product_id =$this->uri->segment(3);
        echo "Taha";
        $this->load->view('delete_confirmation');
    }
</code>```

答:
n = is your last sagment of you url
$id = $this->uri->segment(n);</p>

Title: How to get id from URL in codeigniter?

Body:
I am trying to get 'id' from URL in order to delete that specific selected product. I have used $this->uri->segment(3) but its not getting any value from URL. Although i can see the 'product_id' in my URL.

If i used $this->url->segment(2) it gives me the second value form URL, but i am unable to get product Id.
Following is my code. Kindly guide me.

VIEW

echo "";
echo $name;
echo "";

The following URL is generating when i click on $name.

http://localhost/designs2/index.php/products_controller/delete_controller?product_id=70

Controller

public function delete_controller()
    {
        echo $product_id =$this->uri->segment(3);
        echo "Taha";
        $this->load->view('delete_confirmation');
    }