问:
How can we create three tasks in airflow for multiple environments
I have three tasks, 1. AddEMRStep 2. Sensor 3. SQLstep. I just want it to be created for two environments.

```<code>with dag:
    run_this_task = PythonOperator(
        task_id = "run_this",
        python_callable=push_to_xcom,
        provide_context=True,
        retries=10,
        retry_delay=timedelta(seconds=1)
    )

    run_this_task2 = PythonOperator(
        task_id = "run_this2",
        python_callable=run_this_func,
        provide_context=True
    )

    run_this_task >> run_this_task2
</code>```

Now I need to create these dags for multiple environments

I am trying to do soemthing like this

```<code>envs = ["stg","prod"]
</code>```

How can i use a for loop to make it like this

```<code>with dag:
    run_this_task_stg = PythonOperator(
        task_id = "run_this_task_stg",
        python_callable=push_to_xcom,
        provide_context=True,
        retries=10,
        retry_delay=timedelta(seconds=1)
    )

    run_this_task2_stg = PythonOperator(
        task_id = "run_this_task2_stg",
        python_callable=run_this_func,
        provide_context=True
    )

    run_this_task_prod = PythonOperator(
        task_id = "run_this_task_prod",
        python_callable=push_to_xcom,
        provide_context=True,
        retries=10,
        retry_delay=timedelta(seconds=1)
    )

    run_this_task2_prod = PythonOperator(
        task_id = "run_this_task2_prod",
        python_callable=run_this_func,
        provide_context=True
    )

    start >> run_this_task_stg >> run_this_task2_stg
    start >> run_this_task_prod >> run_this_task2_prod
</code>```

答:
Absolutely! Try something like this:

from datetime import datetime, timedelta

from airflow.models import DAG
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator

def push_to_xcom():
    ...

def run_this_func():
    ...

dag = DAG(dag_id="loops", start_date=datetime(2022, 1, 1), schedule_interval=None)
envs = ["stg", "prod"]

with dag:
    start = DummyOperator(task_id="start")

    for env in envs:
        run_this_task = PythonOperator(
            task_id = f"run_this_task_{env}",
            python_callable=push_to_xcom,
            retries=10,
            retry_delay=timedelta(seconds=1)
        )

        run_this_task2 = PythonOperator(
            task_id = f"run_this_task2_{env}",
            python_callable=run_this_func,
        )

        start >> run_this_task >> run_this_task2
```
<p><strong>Graph View</strong>
<img src="https://i.stack.imgur.com/9OwFE.png" alt="enter image description here" /></p>
<p>Or with the TaskFlow API:</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime, timedelta

from airflow.models import DAG
from airflow.decorators import task
from airflow.operators.dummy import DummyOperator

dag = DAG(dag_id="loops", start_date=datetime(2022, 1, 1), schedule_interval=None)
envs = ["stg", "prod"]

with dag:
    start = DummyOperator(task_id="start")

    for env in envs:

        @task(task_id=f"run_this_task_{env}", retries=10, retry_delay=timedelta(seconds=1))
        def push_to_xcom():
            ...

        @task(task_id=f"run_this_task2_{env}")
        def run_this_func():
            ...

        start >> push_to_xcom() >> run_this_func()
</code>```

Body:
I have three tasks, 1. AddEMRStep 2. Sensor 3. SQLstep. I just want it to be created for two environments.

with dag:
    run_this_task = PythonOperator(
        task_id = "run_this",
        python_callable=push_to_xcom,
        provide_context=True,
        retries=10,
        retry_delay=timedelta(seconds=1)
    )

    run_this_task2 = PythonOperator(
        task_id = "run_this2",
        python_callable=run_this_func,
        provide_context=True
    )

    run_this_task >> run_this_task2

Now I need to create these dags for multiple environments

I am trying to do soemthing like this

envs = ["stg","prod"]

How can i use a for loop to make it like this

with dag:
    run_this_task_stg = PythonOperator(
        task_id = "run_this_task_stg",
        python_callable=push_to_xcom,
        provide_context=True,
        retries=10,
        retry_delay=timedelta(seconds=1)
    )

    run_this_task2_stg = PythonOperator(
        task_id = "run_this_task2_stg",
        python_callable=run_this_func,
        provide_context=True
    )

    run_this_task_prod = PythonOperator(
        task_id = "run_this_task_prod",
        python_callable=push_to_xcom,
        provide_context=True,
        retries=10,
        retry_delay=timedelta(seconds=1)
    )

    run_this_task2_prod = PythonOperator(
        task_id = "run_this_task2_prod",
        python_callable=run_this_func,
        provide_context=True
    )

    start >> run_this_task_stg >> run_this_task2_stg
    start >> run_this_task_prod >> run_this_task2_prod

Body:
Absolutely! Try something like this:

from datetime import datetime, timedelta

from airflow.models import DAG
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator

def push_to_xcom():
    ...

def run_this_func():
    ...

dag = DAG(dag_id="loops", start_date=datetime(2022, 1, 1), schedule_interval=None)
envs = ["stg", "prod"]

with dag:
    start = DummyOperator(task_id="start")

    for env in envs:
        run_this_task = PythonOperator(
            task_id = f"run_this_task_{env}",
            python_callable=push_to_xcom,
            retries=10,
            retry_delay=timedelta(seconds=1)
        )

        run_this_task2 = PythonOperator(
            task_id = f"run_this_task2_{env}",
            python_callable=run_this_func,
        )

        start >> run_this_task >> run_this_task2

Graph View

Or with the TaskFlow API:

from datetime import datetime, timedelta

from airflow.models import DAG
from airflow.decorators import task
from airflow.operators.dummy import DummyOperator

dag = DAG(dag_id="loops", start_date=datetime(2022, 1, 1), schedule_interval=None)
envs = ["stg", "prod"]

with dag:
    start = DummyOperator(task_id="start")

    for env in envs:

        @task(task_id=f"run_this_task_{env}", retries=10, retry_delay=timedelta(seconds=1))
        def push_to_xcom():
            ...

        @task(task_id=f"run_this_task2_{env}")
        def run_this_func():
            ...

        start >> push_to_xcom() >> run_this_func()


来源: stackexchange

问:
calva - how to stop the repl?
I'm using vs code with calva on Ubuntu. My clojure app listens on a port and I find that if I exit vs code, it leaves a java process bound to that port which I have to locate and kill before I can start again.

Is there any calva command to stop the repl?, or better still, a way of stopping the repl automatically when I exit vs code?

答:
You are right to expect that the process (if started by Calva) should be owned by Calva/VS Code and that exiting VS Code should kill it. Please report this as a bug on Calva: https://github.com/BetterThanTomorrow/calva This works on MacOS (and I think on Windows too) so please report this from VS Code's help menu so that your system info gets attached.

As for how to kill the REPL. You can press Ctrl+C in the terminal where the process is started. We should add a proper command for it as well, but that's for another day.  (That it gets killed when you disconnect the REPL is a also a bug, I would say.)

ContentLicense: CC BY-SA 4.0

Title: calva - how to stop the repl?


问:
Embed reaction role collector is not working
I'm running into this issue where the embed reaction role doesn't work. Can someone help me?
Its most likely just the collector bit.</p>
```<code>let playingMessage = await queue.textChannel.send(playingEmbed)

      await playingMessage.react("⏭");
      await playingMessage.react("⏯");
      await playingMessage.react("");
      await playingMessage.react("");
      await playingMessage.react("");
      await playingMessage.react("");
      await playingMessage.react("⏹");

    } catch (error) {
      console.error(error);
    }

    const filter = (reaction, user) => user.id === message.author.id;
      filter: ({reaction, user}) => user.id === message.author.id
    var collector = playingMessage.createReactionCollector(filter, {
      time: song.duration > 0 ? song.duration * 1000 : 600000
    });

    collector.on("collect", (reaction, user) => {
      if (!queue) return;
      const member = playingMessage.guild.member(user);
</code>```

答:
last i checked in discord.js v13, the filter should be within the curly brackets, not outside of it.

so this line of code:

```<code> var collector = playingMessage.createReactionCollector(filter, {
   time: song.duration > 0 ? song.duration * 1000 : 600000
 });
</code>```

Should be:

```<code>var collector = playingMessage.createReactionCollector({
   filter, time: song.duration > 0 ? song.duration * 1000 : 600000
});
</code>```

Body:
I'm running into this issue where the embed reaction role doesn't work. Can someone help me?
Its most likely just the collector bit.

let playingMessage = await queue.textChannel.send(playingEmbed)

      await playingMessage.react("⏭");
      await playingMessage.react("⏯");
      await playingMessage.react("");
      await playingMessage.react("");
      await playingMessage.react("");
      await playingMessage.react("");
      await playingMessage.react("⏹");

    } catch (error) {
      console.error(error);
    }

    const filter = (reaction, user) => user.id === message.author.id;
      filter: ({reaction, user}) => user.id === message.author.id
    var collector = playingMessage.createReactionCollector(filter, {
      time: song.duration > 0 ? song.duration * 1000 : 600000
    });

    collector.on("collect", (reaction, user) => {
      if (!queue) return;
      const member = playingMessage.guild.member(user);

Body:
last i checked in discord.js v13, the filter should be within the curly brackets, not outside of it.

so this line of code:

 var collector = playingMessage.createReactionCollector(filter, {
   time: song.duration > 0 ? song.duration * 1000 : 600000
 });

Should be:

var collector = playingMessage.createReactionCollector({
   filter, time: song.duration > 0 ? song.duration * 1000 : 600000
});


问:
React Uncaught ReferenceError: process is not defined
I am getting issues with iframe.
Till today everything was working as expected. Today I added a very simple Modal component and somehow iframe started appearing. It appears when I am editing the file and hot reload is done. Also with this issue, it's showing an error in Console as "Uncaught ReferenceError: process is not defined".
Can someone please help me with this?</p>
```<code>import React, {useEffect} from 'react';
import ReactDOM from "react-dom";
import Close from "../static/assets/close-white.svg"

const trapStyles = {
    position: 'absolute',
    opacity: 0
}
const Test = () => {

    return ReactDOM.createPortal(
        <div data-react-modal-body-trap="" tabIndex="0" style={trapStyles}/>,
        document.getElementById("app")
    )
}

const Modal = ({ open, onClose, children }) => {

    useEffect(() => {

        if (open)document.getElementById("app").classList.add("ReactModal__Body--open");

        return () => {
            document.getElementById("app").classList.remove("ReactModal__Body--open")
        }
    })
    if (!open) return null

    return ReactDOM.createPortal(
        <>
            <Test />
            <div className="ReactModal__Overlay--after-open">
                <div className="modal-form-page"
                     tabIndex="-1" role="dialog" aria-modal="true">
                    <button onClick={onClose} className="close-modal">
                        <img id="close-button" alt="close" src={Close}/>
                    </button>
                    { children }
                </div>
            </div>
        </>,
        document.getElementById("ModalPortal")
    )
};

export default Modal;
</code>```
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <link href="%PUBLIC_URL%/favicon.ico" rel="icon"/>
    <meta content="width=device-width, initial-scale=1" name="viewport"/>
    <meta content="#000000" name="theme-color"/>
    <link href="%PUBLIC_URL%/logo192.png" rel="apple-touch-icon"/>
    <link href="%PUBLIC_URL%/manifest.json" rel="manifest"/>
    <title>React App</title>
</head>
<body id="app">
<noscript>You need to enable javascript to run this website</noscript>
<div id="content">
<-- All other content render here -->
</div>
<div class="ReactModalPortal" id="ModalPortal"></div>
</body>
</html>
</code>```
```<code>Uncaught ReferenceError: process is not defined
    at Object.4043 (<anonymous>:2:13168)
    at r (<anonymous>:2:306599)
    at Object.8048 (<anonymous>:2:9496)
    at r (<anonymous>:2:306599)
    at Object.8641 (<anonymous>:2:1379)
    at r (<anonymous>:2:306599)
    at <anonymous>:2:315627
    at <anonymous>:2:324225
    at <anonymous>:2:324229
    at HTMLIFrameElement.e.onload (index.js:1)
4043 @ VM128:2
r @ VM128:2
8048 @ VM128:2
r @ VM128:2
8641 @ VM128:2
r @ VM128:2
(anonymous) @ VM128:2
(anonymous) @ VM128:2
(anonymous) @ VM128:2
e.onload @ index.js:1
be @ index.js:1
he @ index.js:1
tryDismissErrorOverlay @ webpackHotDevClient.js:184
onHotUpdateSuccess @ webpackHotDevClient.js:109
handleApplyUpdates @ webpackHotDevClient.js:257
(anonymous) @ webpackHotDevClient.js:273
load (async)
be @ index.js:1
he @ index.js:1
tryDismissErrorOverlay @ webpackHotDevClient.js:184
onHotUpdateSuccess @ webpackHotDevClient.js:109
handleApplyUpdates @ webpackHotDevClient.js:257
(anonymous) @ webpackHotDevClient.js:273
Promise.then (async)
tryApplyUpdates @ webpackHotDevClient.js:271
handleSuccess @ webpackHotDevClient.js:106
push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @ webpackHotDevClient.js:203
</code>```

答:
A lot of answers suggest overriding the react-error-overlay to 6.0.9, but this didn't work for me (on February 11th, 2022). I was using react-scripts 5.0.0 and react-error-overlay 6.0.10 before trying out the overlay override.

Instead of going through the hastle of defining the webpack configuration in my CRA application (as suggested by smac89), I downgraded react-scripts to 4.0.3.

It works fine with react-scripts: 4.0.3, which resolved react-error-overlay to 6.0.10.

So, my fix is:

Set "react-scripts": "4.0.3" in package.json

Delete your lock file (yarn.lock or package-lock.json) and node_modules

Run install

Body:
I am getting issues with iframe.
Till today everything was working as expected. Today I added a very simple Modal component and somehow iframe started appearing. It appears when I am editing the file and hot reload is done. Also with this issue, it's showing an error in Console as "Uncaught ReferenceError: process is not defined".
Can someone please help me with this?

import React, {useEffect} from 'react';
import ReactDOM from "react-dom";
import Close from "../static/assets/close-white.svg"

const trapStyles = {
    position: 'absolute',
    opacity: 0
}
const Test = () => {

    return ReactDOM.createPortal(

,
        document.getElementById("app")
    )
}

const Modal = ({ open, onClose, children }) => {

    useEffect(() => {

        if (open)document.getElementById("app").classList.add("ReactModal__Body--open");

        return () => {
            document.getElementById("app").classList.remove("ReactModal__Body--open")
        }
    })
    if (!open) return null

    return ReactDOM.createPortal(
        <>
            <Test />

                    <button onClick={onClose} className="close-modal">

                    </button>
                    { children }

        </>,
        document.getElementById("ModalPortal")
    )
};

export default Modal;

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <link href="%PUBLIC_URL%/favicon.ico" rel="icon"/>
    <meta content="width=device-width, initial-scale=1" name="viewport"/>
    <meta content="#000000" name="theme-color"/>
    <link href="%PUBLIC_URL%/logo192.png" rel="apple-touch-icon"/>
    <link href="%PUBLIC_URL%/manifest.json" rel="manifest"/>
    <title>React App</title>

You need to enable javascript to run this website

<-- All other content render here -->

Uncaught ReferenceError: process is not defined
    at Object.4043 (<anonymous>:2:13168)
    at r (<anonymous>:2:306599)
    at Object.8048 (<anonymous>:2:9496)
    at r (<anonymous>:2:306599)
    at Object.8641 (<anonymous>:2:1379)
    at r (<anonymous>:2:306599)
    at <anonymous>:2:315627
    at <anonymous>:2:324225
    at <anonymous>:2:324229
    at HTMLIFrameElement.e.onload (index.js:1)
4043 @ VM128:2
r @ VM128:2
8048 @ VM128:2
r @ VM128:2
8641 @ VM128:2
r @ VM128:2
(anonymous) @ VM128:2
(anonymous) @ VM128:2
(anonymous) @ VM128:2
e.onload @ index.js:1
be @ index.js:1
he @ index.js:1
tryDismissErrorOverlay @ webpackHotDevClient.js:184
onHotUpdateSuccess @ webpackHotDevClient.js:109
handleApplyUpdates @ webpackHotDevClient.js:257
(anonymous) @ webpackHotDevClient.js:273
load (async)
be @ index.js:1
he @ index.js:1
tryDismissErrorOverlay @ webpackHotDevClient.js:184
onHotUpdateSuccess @ webpackHotDevClient.js:109
handleApplyUpdates @ webpackHotDevClient.js:257
(anonymous) @ webpackHotDevClient.js:273
Promise.then (async)
tryApplyUpdates @ webpackHotDevClient.js:271
handleSuccess @ webpackHotDevClient.js:106
push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @ webpackHotDevClient.js:203


问:
Apply Filters To MySql Query
Am Writing my own SQL Query to Fetch Data From Two Different Models and also i have some filters , since i was using Spatie Query Builder i just configure my filters in allowedFilters() method and everything is okay , but know am moving from Spatie to Raw Sql Query where i can manipulate each character of my query giving below 2 examples one using Spatie Query Builder and another using my Custom Query the question here is how to apply those filters into my SQL Query when they sent in the request

**Spatie Example **

```<code>$transactions = QueryBuilder::for(Transaction::class)
                        ->with(['payable' => function (MorphTo $morphTo) {
                            $morphTo->morphWith([
                                Reservation::class => ['unit', 'depositInsuranceTransactions' , 'withdrawInsuranceTransactions', 'creator', 'customer', 'customer.nationality', 'customer.highlight'],
                            ]);
                        }])
                        ->with(['wallet','creator','last_user_update'])
                        ->allowedFilters([
                            AllowedFilter::scope('by_number'),
                            AllowedFilter::scope('by_reservation_number'),
                            AllowedFilter::scope('by_customer_id_number'),
                            AllowedFilter::scope('by_unit_number'),
                            AllowedFilter::scope('by_creator'),
                            AllowedFilter::scope('by_payment_type'),
                            AllowedFilter::scope('by_date_from'),
                            AllowedFilter::scope('by_date_to'),
                            AllowedFilter::scope('by_term')
                        ])
                        ->allowedSorts([
                                'id',
                                '-id',
                                'created_at',
                                '-created_at'
                        ])
                        ->whereHasMorphIn('payable', ['App\\Team','App\\Reservation'], function ($query, $modelType) use($reservations_ids,$team_id , $type){

                            if ($modelType == 'App\\Team') {
                                $query->where('payable_type' , 'App\\Team')
                                ->where('payable_id',$team_id);
                            }

                            if ($modelType === 'App\\Reservation') {
                                $query->where('payable_type' , 'App\Reservation')
                                ->with('unit', 'depositInsuranceTransactions' , 'withdrawInsuranceTransactions' ,'customer','customer.nationality','customer.highlight')
                                ->whereIntegerInRaw('payable_id', $reservations_ids);
                            }
                        })
                        ->where('amount', '!=' , 0)
                        ->where('type' , '=' , $type)
                        ->where('is_public' , 1)
                        ->whereNull('deleted_at')
                        ->orderByDesc('number')
                        ->simplePaginate(20);
</code>```

And This is My Custom Query

```<code>$transactions  =
    DB::select(
            DB::raw("SELECT tr.*, w.decimal_places
                    FROM transactions tr
                        JOIN wallets w ON w.id = tr.wallet_id
                    where
                    (
                    -- I Wanna Put Here Some Conditions When the filter x is not null apply it to the query
                    )
                    AND (
                            (
                                tr.payable_type = :team_base_class
                                AND tr.payable_id = :team_id
                                AND tr.amount != 0
                                AND tr.type = :team_transaction_type
                                AND tr.is_public = 1
                                AND tr.deleted_at IS NULL
                            )
                            OR (
                                    tr.payable_type = :reservation_base_class
                                AND tr.payable_id IN ( $implodeded_reservations_ids
                            )
                            AND tr.amount != 0
                            AND tr.type = :reservation_transaction_type
                            AND tr.is_public = 1
                            AND tr.deleted_at IS NULL
                        )
                    )

                    ORDER BY tr.number DESC
            ") // End of DB RAW

            , array(
                'team_base_class' => 'App\\Team',
                'reservation_base_class' => 'App\\Reservation',
                'team_id' => $team_id,
                'team_transaction_type' => $type,
                'reservation_transaction_type' => $type
            )
    ); // End of DB SELECT
</code>```

**My Filters Coming From Request **

```<code>{
"by_number":"129",
"by_reservation_number":"120",
"by_date_from":"2022-02-01 12:00",
"by_date_to":"2022-02-11 12:00",
"by_payment_type":"cash",
"by_term":"36708"
}
</code>```

I Tried So Many Times Applying IF condition inside where but always getting syntax error and i don't know if what am doing right or wrong.

Why Am Moving To Custom Query Rather Than Spatie

Well am looking for the most optimized performance i can get and i really found that direct SQL Queries are so fast rather than any extra tooling like spatie or even eloquent

答:
The query you're trying to do doesn't seem to match the raw sql below.

As for the conditionals, if you used the query builder you could use its when method.

$transactions = DB::query()
    ->select('tr.*', 'w.decimal_places')
    ->from('transactions', 'tr'
    ->join('wallets w', 'w.id', 'tr.wallet_id')
    ->where(function ($query) use ($filters) {
        $query->when(isset($filters['a']), function ($query) use ($filters) { $query->where('a', $filters['a']); })
              ->when(isset($filters['b']), function ($query) use ($filters) { $query->where('b', $filters['b']); })
              ->when(isset($filters['c']), function ($query) use ($filters) { $query->where('c', $filters['c']); })
              ->when(isset($filters['d']), function ($query) use ($filters) { $query->where('d', $filters['d']); })
              ->when(isset($filters['e']), function ($query) use ($filters) { $query->where('e', $filters['e']); });
    })
    ->where(function ($query) use ($team_id, $type) {
        $query->where(function ($query) use ($team_id, $type) {
            $query->where('tr.payable_type', 'App\\Team')
                ->where('tr.payable_id', $team_id)
                ->where('tr.amount', '!=',  0)
                ->where('tr.type', $type)
                ->where('tr.is_public', 1)
                ->whereNull('tr.deleted')
        })
        ->orWhere(function ($query) use ($reservations_ids_array, $type) {
            $query->where('tr.payable_type', 'App\\Reservation')
                ->whereIn('tr.payable_id', $reservations_ids_array)
                ->where('tr.amount', '!=', 0)
                ->where('tr.type', $type)
                ->where('tr.is_public', 1)
                ->whereNull('tr.deleted_at')
        });
    })
    ->orderByDesc('tr.number')
    ->get();
```

Title: Apply Filters To MySql Query

Body:
Am Writing my own SQL Query to Fetch Data From Two Different Models and also i have some filters , since i was using Spatie Query Builder i just configure my filters in allowedFilters() method and everything is okay , but know am moving from Spatie to Raw Sql Query where i can manipulate each character of my query giving below 2 examples one using Spatie Query Builder and another using my Custom Query the question here is how to apply those filters into my SQL Query when they sent in the request

**Spatie Example **

$transactions = QueryBuilder::for(Transaction::class)
                        ->with(['payable' => function (MorphTo $morphTo) {
                            $morphTo->morphWith([
                                Reservation::class => ['unit', 'depositInsuranceTransactions' , 'withdrawInsuranceTransactions', 'creator', 'customer', 'customer.nationality', 'customer.highlight'],
                            ]);
                        }])
                        ->with(['wallet','creator','last_user_update'])
                        ->allowedFilters([
                            AllowedFilter::scope('by_number'),
                            AllowedFilter::scope('by_reservation_number'),
                            AllowedFilter::scope('by_customer_id_number'),
                            AllowedFilter::scope('by_unit_number'),
                            AllowedFilter::scope('by_creator'),
                            AllowedFilter::scope('by_payment_type'),
                            AllowedFilter::scope('by_date_from'),
                            AllowedFilter::scope('by_date_to'),
                            AllowedFilter::scope('by_term')
                        ])
                        ->allowedSorts([
                                'id',
                                '-id',
                                'created_at',
                                '-created_at'
                        ])
                        ->whereHasMorphIn('payable', ['App\\Team','App\\Reservation'], function ($query, $modelType) use($reservations_ids,$team_id , $type){

                            if ($modelType == 'App\\Team') {
                                $query->where('payable_type' , 'App\\Team')
                                ->where('payable_id',$team_id);
                            }

                            if ($modelType === 'App\\Reservation') {
                                $query->where('payable_type' , 'App\Reservation')
                                ->with('unit', 'depositInsuranceTransactions' , 'withdrawInsuranceTransactions' ,'customer','customer.nationality','customer.highlight')
                                ->whereIntegerInRaw('payable_id', $reservations_ids);
                            }
                        })
                        ->where('amount', '!=' , 0)
                        ->where('type' , '=' , $type)
                        ->where('is_public' , 1)
                        ->whereNull('deleted_at')
                        ->orderByDesc('number')
                        ->simplePaginate(20);

And This is My Custom Query

$transactions  =
    DB::select(
            DB::raw("SELECT tr.*, w.decimal_places
                    FROM transactions tr
                        JOIN wallets w ON w.id = tr.wallet_id
                    where
                    (
                    -- I Wanna Put Here Some Conditions When the filter x is not null apply it to the query
                    )
                    AND (
                            (
                                tr.payable_type = :team_base_class
                                AND tr.payable_id = :team_id
                                AND tr.amount != 0
                                AND tr.type = :team_transaction_type
                                AND tr.is_public = 1
                                AND tr.deleted_at IS NULL
                            )
                            OR (
                                    tr.payable_type = :reservation_base_class
                                AND tr.payable_id IN ( $implodeded_reservations_ids
                            )
                            AND tr.amount != 0
                            AND tr.type = :reservation_transaction_type
                            AND tr.is_public = 1
                            AND tr.deleted_at IS NULL
                        )
                    )

                    ORDER BY tr.number DESC
            ") // End of DB RAW

            , array(
                'team_base_class' => 'App\\Team',
                'reservation_base_class' => 'App\\Reservation',
                'team_id' => $team_id,
                'team_transaction_type' => $type,
                'reservation_transaction_type' => $type
            )
    ); // End of DB SELECT

**My Filters Coming From Request **

{
"by_number":"129",
"by_reservation_number":"120",
"by_date_from":"2022-02-01 12:00",
"by_date_to":"2022-02-11 12:00",
"by_payment_type":"cash",
"by_term":"36708"
}

I Tried So Many Times Applying IF condition inside where but always getting syntax error and i don't know if what am doing right or wrong.

Why Am Moving To Custom Query Rather Than Spatie

Well am looking for the most optimized performance i can get and i really found that direct SQL Queries are so fast rather than any extra tooling like spatie or even eloquent


问:
YouTube API - The API Key and the authentication credential are from different projects
I am trying to get videos from youtube with my C# application, with "https://youtube.googleapis.com/youtube/v3/search?forMine=true&order=date&type=video&part=snippet&key={key}&access_token={token}" but I receive this error:

```<code>"error": {
    "code": 400,
    "message": "The API Key and the authentication credential are from different
projects.",
    "errors": [
      {
        "message": "The API Key and the authentication credential are from
different projects.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developer console API key",
            "url":
"https://console.developers.google.com/project/{MyProjectCode}/apiui/credential"
          }
        ]
      },
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CONSUMER_INVALID",
        "domain": "googleapis.com",
        "metadata": {
          "consumer": "projects/{MyProjectCode}",
          "service": "youtube.googleapis.com"
        }
      }
    ]
  }
</code>```

But I can see only 1 API Key and 1 OAuth 2.0 Client ID (with Client ID and Client Secret) on https://console.cloud.google.com/apis/api/youtube.googleapis.com/credentials?authuser=1&project={MyProject} site

Could you please help how can I fix this ?

Code:

```<code>var token = Helper.Decrypt(ytConn.AccessToken);
var url = "https://youtube.googleapis.com/youtube/v3/search?
forMine=true&order=date&type=video&part=snippet&key=" + _key +
"&access_token=" + token;

videos = Helper.GetFromAPI<Videos>(url, token);
</code>```

it calls this:

```<code>public static T GetFromAPI<T>(string url, string token)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = "GET";

    ServicePointManager.SecurityProtocol =
    SecurityProtocolType.Tls12;
    request.Headers.Set("Authorization", "Bearer " + token);

    request.ContentType = "application/json; charset=utf-8";

    T type = default(T);

    try
    {
        using (WebResponse response = request.GetResponse())
        {
            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new
                StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    type = JsonConvert.DeserializeObject<T>
                    (responseFromServer);
                }
            }
        }
    }
}
</code>```

Thanks in advance

答: There was no need to change the code, on one day started working again, so most probably the issue was on Youtube side.</p>

Body:
I am trying to get videos from youtube with my C# application, with "https://youtube.googleapis.com/youtube/v3/search?forMine=true&order=date&type=video&part=snippet&key={key}&access_token={token}" but I receive this error:

"error": {
    "code": 400,
    "message": "The API Key and the authentication credential are from different
projects.",
    "errors": [
      {
        "message": "The API Key and the authentication credential are from
different projects.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developer console API key",
            "url":
"https://console.developers.google.com/project/{MyProjectCode}/apiui/credential"
          }
        ]
      },
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CONSUMER_INVALID",
        "domain": "googleapis.com",
        "metadata": {
          "consumer": "projects/{MyProjectCode}",
          "service": "youtube.googleapis.com"
        }
      }
    ]
  }

But I can see only 1 API Key and 1 OAuth 2.0 Client ID (with Client ID and Client Secret) on https://console.cloud.google.com/apis/api/youtube.googleapis.com/credentials?authuser=1&project={MyProject} site

Could you please help how can I fix this ?

Code:

var token = Helper.Decrypt(ytConn.AccessToken);
var url = "https://youtube.googleapis.com/youtube/v3/search?
forMine=true&order=date&type=video&part=snippet&key=" + _key +
"&access_token=" + token;

videos = Helper.GetFromAPI<Videos>(url, token);

it calls this:

public static T GetFromAPI<T>(string url, string token)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = "GET";

    ServicePointManager.SecurityProtocol =
    SecurityProtocolType.Tls12;
    request.Headers.Set("Authorization", "Bearer " + token);

    request.ContentType = "application/json; charset=utf-8";

    T type = default(T);

    try
    {
        using (WebResponse response = request.GetResponse())
        {
            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new
                StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    type = JsonConvert.DeserializeObject<T>
                    (responseFromServer);
                }
            }
        }
    }
}

Thanks in advance


问:
Hash string into RGB color
Is there a best practice on how to hash an arbitrary string into a RGB color value? Or to be more general: to 3 bytes.

You're asking: When will I ever need this? It doesn't matter to me, but imagine those tube graphs on any GitHub network page. There you can see something like this:

Where every colored line means a distinct git branch. The low tech approach to color these branches would be a CLUT (color lookup table). The more sophisticated version would be:

```<code>$branchColor = hashStringToColor(concat($username,$branchname));
</code>```

Because you want a static color every time you see the branches representation. And for bonus points: How do you ensure an even color distribution of that hash function?

So the answer to my question boils down to the implementation of hashStringToColor().

答:
If you are using C# and want HSL colors

Here is a class I wrote based on the library written by Zeno Zeng and mentioned in this answer .

The HSLColor class was written by Rich Newman, it is defined here

    public class ColorHash
    {

        // you can pass in a string hashing function of you choice
        public ColorHash(Func<string, int> hashFunction)
        {
            this.hashFunction = hashFunction;
        }

        // or use the default string.GetHashCode()
        public ColorHash()
        {
            this.hashFunction = (string s) => { return s.GetHashCode(); };
        }

        Func<string, int> hashFunction = null;

        static float[] defaultValues = new float[] { 0.35F, 0.5F, 0.65F };

        // HSLColor class is defined at https://richnewman.wordpress.com/about/code-listings-and-diagrams/hslcolor-class/
        public HSLColor HSL(string s) {
            return HSL(s, defaultValues, defaultValues);
        }

        // HSL function ported from https://github.com/zenozeng/color-hash/
        public HSLColor HSL(string s, float[] saturationValues, float[] lightnessValues)
        {

            double hue;
            double saturation;
            double luminosity;

            int hash = Math.Abs(this.hashFunction(s));

            hue = hash % 359;

            hash = (int)Math.Ceiling((double)hash / 360);
            saturation = saturationValues[hash % saturationValues.Length];

            hash = (int)Math.Ceiling((double)hash / saturationValues.Length);
            luminosity = lightnessValues[hash % lightnessValues.Length];

            return new HSLColor(hue, saturation, luminosity);
        }

    }

```

ContentLicense: CC BY-SA 3.0

Title: Hash string into RGB color

Body:
Is there a best practice on how to hash an arbitrary string into a RGB color value? Or to be more general: to 3 bytes.

You're asking: When will I ever need this? It doesn't matter to me, but imagine those tube graphs on any GitHub network page. There you can see something like this:

Where every colored line means a distinct git branch. The low tech approach to color these branches would be a CLUT (color lookup table). The more sophisticated version would be:

$branchColor = hashStringToColor(concat($username,$branchname));

Because you want a static color every time you see the branches representation. And for bonus points: How do you ensure an even color distribution of that hash function?

So the answer to my question boils down to the implementation of hashStringToColor().


问:
Custom function to summarize dataframe based on variable class
I am trying to write a custom function in R that takes the mean and standard deviation, if the variable is numeric; or counts the number of occurrences for each level, if the variable is categorical. As an additional twist, I would like the function to only count the number of "Yes" if the variable is categorical and its levels include "Yes". Ideally, I would like this to be an input parameter, which if called, only counts the number of "Yes".

To demonstrate, let's assume we have the following data:

```<code>Height <- round(rnorm(10, 175, 10), 0)
weight <- round(rnorm(10, 70, 10), 0)
smoke <- c(rep("Yes", 3), rep("No", 4), rep("Unknown", 3))
problem <- c(rep("depression", 3), rep("insomnia", 2), rep("IBS", 5))
data <- as.data.frame(cbind(Height, weight, smoke, problem))

data$Height <- as.numeric(data$Height)
data$weight <- as.numeric(data$weight)
data$smoke <- factor(data$smoke, levels = c("Yes", "No", "Unknown"))
data$problem <- factor(data$problem, levels = c("depression", "insomnia", "IBS"))
</code>```

The function I have is:

```<code>sumfun <- function(x){
  if(is.numeric(x)){
    m = round(mean(x, na.rm = T), digits = 2)
    s = round(sd(x, na.rm = T), digits = 2)
    return(list(cbind("", paste0(m, " ", "(", s, ")", " ", "/", " ", sum(!is.na(x))))))
  } else
    # (is.factor(x) | is.character(x)){
    n = table(x)
  pro = round(prop.table(n), 2)
  return(list(cbind("", levels(x), paste0(n, " ", "(", pro*100, ")", " ", "/", sum(!is.na(x))))))
}
</code>```

Because I want the output to be in a specific way, I wrote another function instead of using apply family. This function is:

```<code>tabsum <- function(table){
out <- data.frame()
  for(col in colnames(table)){
    # out <- rbind(out, list(col, "", ""))
    out[nrow(out) + 1, 1] <- col
    for(row in sumfun(table[, col])){
      if(is.numeric(table[,col])){
        out[nrow(out), 2:3] <- row
      } else {
        out[nrow(out), 2:3] <- c("", "")
        out <- rbind(out, as.data.frame(row))
      }
    }
  }
  colnames(out) <- c("Variable", "Levels", "Mean (SD) or N (%)")
  return(out)
}
</code>```

Using these two function on the data set above produces:

tabsum(data)

Variable
Levels
Mean (SD) or N (%)

Height

174.5 (8) / 10

weight

71.7 (8.68) / 10

smoke

Yes
3 (30) /10

No
4 (40) /10

Unknown
3 (30) /10

problem

depression
3 (30) /10

insomnia
2 (20) /10

IBS
5 (50) /10

What I would like to happen is:

tabsum(sumfun(data, "smoke"))

Variable
Levels
Mean (SD) or N (%)

Height

174.5 (8) / 10

weight

71.7 (8.68) / 10

smoke

Yes
3 (30) /10

problem

depression
3 (30) /10

insomnia
2 (20) /10

IBS
5 (50) /10

Any ideas are highly appreciated. Kindly note that there may be less painful ways to do this, but I am learning how to write R functions and would like to do it via a custom function.

Thanks

答:
Your code updated to only include factor level 'Yes' for the factor fields:

For the sumfun function:

I dropped the else statement altogether

I added another if statement because factor inclusion is conditional to containing a factor level "Yes"

Within this if statement, you used the function table. You used table as an object name in tabsum: I encourage you to use a different object name, so there is no confusion.

I modified the call to table to be conditional and remove empty levels.

I changed the return list quite a bit.

```<code>sumfun <- function(x){
  if(is.numeric(x)){
    m = round(mean(x, na.rm = T), digits = 2)
    s = round(sd(x, na.rm = T), digits = 2)
    return(list(cbind("", paste0(m, " ", "(", s, ")", " ", "/", " ", sum(!is.na(x))))))
  }
  if(is.factor(x)){
    if(length(x[x == "Yes"]) > 0){
      n = table(droplevels(x[x == "Yes"]))
      return(list(cbind("", "Yes", paste0(n, " ",
                                          "(" , n/sum(!is.na(x)) * 100, ")",
                                          " ", "/ ", sum(!is.na(x))))))
    }
  }
}
</code>```

In the tabsum function:

I removed out[nrow(out) + 1, 1] <- col, otherwise every column will be in the table. Column inclusion is conditional.

I added out[nrow(out) + 1, 1] <- col within the row loop, so that only names that return values from sumfun are included.

I changed the else statement to an if statement with conditions.

```<code>tabsum <- function(table){
  out <- data.frame()
  for(col in colnames(table)){
    for(row in sumfun(table[, col])){
      out[nrow(out) + 1, 1] <- col # moved this in row loop, col conditions**
      if(is.numeric(table[,col])){
        out[nrow(out), 2:3] <- row
      }
      if(is.factor(table[,col])){
        out[nrow(out), 2:3] <- c("", "")
        out <- rbind(out, as.data.frame(row))
      }
    }
  }
  colnames(out) <- c("Variable", "Levels", "Mean (SD) or N (%)")
  return(out)
}
tabsum(data)
#   Variable Levels Mean (SD) or N (%)
# 1   Height        174.2 (12.05) / 10
# 2   weight         71.3 (12.47) / 10
# 3    smoke
# 4             Yes        3 (30) / 10
</code>```

Now that smoke == 'Yes' is all that's included, you could put the information in one row.

To do this, in sumfun change the final return call by dropping the initial "":

```<code>return(list(cbind("Yes", paste0(n, " ",
                                "(" , n/sum(!is.na(x)) * 100, ")",
                                " ", "/ ", sum(!is.na(x))))))
</code>```

And in tabsum, change the if(is.factor... to only have one call to out, like so:

```<code>if(is.factor(table[,col])){
  out[nrow(out), 1:3] <- c(col, row)
}
</code>```

This modifies the table to the following:

```<code>tabsum(data)
#   Variable Levels Mean (SD) or N (%)
# 1   Height        174.2 (12.05) / 10
# 2   weight         71.3 (12.47) / 10
# 3    smoke    Yes        3 (30) / 10
</code>```

Body:
I am trying to write a custom function in R that takes the mean and standard deviation, if the variable is numeric; or counts the number of occurrences for each level, if the variable is categorical. As an additional twist, I would like the function to only count the number of "Yes" if the variable is categorical and its levels include "Yes". Ideally, I would like this to be an input parameter, which if called, only counts the number of "Yes".

To demonstrate, let's assume we have the following data:

Height <- round(rnorm(10, 175, 10), 0)
weight <- round(rnorm(10, 70, 10), 0)
smoke <- c(rep("Yes", 3), rep("No", 4), rep("Unknown", 3))
problem <- c(rep("depression", 3), rep("insomnia", 2), rep("IBS", 5))
data <- as.data.frame(cbind(Height, weight, smoke, problem))

data$Height <- as.numeric(data$Height)
data$weight <- as.numeric(data$weight)
data$smoke <- factor(data$smoke, levels = c("Yes", "No", "Unknown"))
data$problem <- factor(data$problem, levels = c("depression", "insomnia", "IBS"))

The function I have is:

sumfun <- function(x){
  if(is.numeric(x)){
    m = round(mean(x, na.rm = T), digits = 2)
    s = round(sd(x, na.rm = T), digits = 2)
    return(list(cbind("", paste0(m, " ", "(", s, ")", " ", "/", " ", sum(!is.na(x))))))
  } else
    # (is.factor(x) | is.character(x)){
    n = table(x)
  pro = round(prop.table(n), 2)
  return(list(cbind("", levels(x), paste0(n, " ", "(", pro*100, ")", " ", "/", sum(!is.na(x))))))
}

Because I want the output to be in a specific way, I wrote another function instead of using apply family. This function is:

tabsum <- function(table){
out <- data.frame()
  for(col in colnames(table)){
    # out <- rbind(out, list(col, "", ""))
    out[nrow(out) + 1, 1] <- col
    for(row in sumfun(table[, col])){
      if(is.numeric(table[,col])){
        out[nrow(out), 2:3] <- row
      } else {
        out[nrow(out), 2:3] <- c("", "")
        out <- rbind(out, as.data.frame(row))
      }
    }
  }
  colnames(out) <- c("Variable", "Levels", "Mean (SD) or N (%)")
  return(out)
}

Using these two function on the data set above produces:

tabsum(data)

Variable
Levels
Mean (SD) or N (%)

Height

174.5 (8) / 10

weight

71.7 (8.68) / 10

smoke

Yes
3 (30) /10

No
4 (40) /10

Unknown
3 (30) /10

problem

depression
3 (30) /10

insomnia
2 (20) /10

IBS
5 (50) /10

What I would like to happen is:

tabsum(sumfun(data, "smoke"))

Variable
Levels
Mean (SD) or N (%)

Height

174.5 (8) / 10

weight

71.7 (8.68) / 10

smoke

Yes
3 (30) /10

problem

depression
3 (30) /10

insomnia
2 (20) /10

IBS
5 (50) /10

Any ideas are highly appreciated. Kindly note that there may be less painful ways to do this, but I am learning how to write R functions and would like to do it via a custom function.

Thanks

Body:
Your code updated to only include factor level 'Yes' for the factor fields:

For the sumfun function:

I dropped the else statement altogether

I added another if statement because factor inclusion is conditional to containing a factor level "Yes"

Within this if statement, you used the function table. You used table as an object name in tabsum: I encourage you to use a different object name, so there is no confusion.

I modified the call to table to be conditional and remove empty levels.

I changed the return list quite a bit.

sumfun <- function(x){
  if(is.numeric(x)){
    m = round(mean(x, na.rm = T), digits = 2)
    s = round(sd(x, na.rm = T), digits = 2)
    return(list(cbind("", paste0(m, " ", "(", s, ")", " ", "/", " ", sum(!is.na(x))))))
  }
  if(is.factor(x)){
    if(length(x[x == "Yes"]) > 0){
      n = table(droplevels(x[x == "Yes"]))
      return(list(cbind("", "Yes", paste0(n, " ",
                                          "(" , n/sum(!is.na(x)) * 100, ")",
                                          " ", "/ ", sum(!is.na(x))))))
    }
  }
}

In the tabsum function:

I removed out[nrow(out) + 1, 1] <- col, otherwise every column will be in the table. Column inclusion is conditional.

I added out[nrow(out) + 1, 1] <- col within the row loop, so that only names that return values from sumfun are included.

I changed the else statement to an if statement with conditions.

tabsum <- function(table){
  out <- data.frame()
  for(col in colnames(table)){
    for(row in sumfun(table[, col])){
      out[nrow(out) + 1, 1] <- col # moved this in row loop, col conditions**
      if(is.numeric(table[,col])){
        out[nrow(out), 2:3] <- row
      }
      if(is.factor(table[,col])){
        out[nrow(out), 2:3] <- c("", "")
        out <- rbind(out, as.data.frame(row))
      }
    }
  }
  colnames(out) <- c("Variable", "Levels", "Mean (SD) or N (%)")
  return(out)
}
tabsum(data)
#   Variable Levels Mean (SD) or N (%)
# 1   Height        174.2 (12.05) / 10
# 2   weight         71.3 (12.47) / 10
# 3    smoke
# 4             Yes        3 (30) / 10

Now that smoke == 'Yes' is all that's included, you could put the information in one row.

To do this, in sumfun change the final return call by dropping the initial "":

return(list(cbind("Yes", paste0(n, " ",
                                "(" , n/sum(!is.na(x)) * 100, ")",
                                " ", "/ ", sum(!is.na(x))))))

And in tabsum, change the if(is.factor... to only have one call to out, like so:

if(is.factor(table[,col])){
  out[nrow(out), 1:3] <- c(col, row)
}

This modifies the table to the following:

tabsum(data)
#   Variable Levels Mean (SD) or N (%)
# 1   Height        174.2 (12.05) / 10
# 2   weight         71.3 (12.47) / 10
# 3    smoke    Yes        3 (30) / 10


问:
configuring image filepaths correctly in mkdocs
I have an issue with MkDocs not being able to find my images.  The images are in a subfolder, called microsatsFigures, in my docs folder.  So my /docs folder contains index.md, traces.md and the folder microsatsFigures which has the images.  In my Markdown file traces.md I am using html syntax for the images so the path to the image is:

```<code><img src="microsatsFigures/Figure_setLoci.png"/>
</code>```

This works perfectly in markdown editors that I am using (Typora and Macdown), and the image is displayed no problem.  However mkdocs can't find the image - I get

WARNING  -  [15:02:53] "GET /traces/microsatsFigures/Figure_setLoci.png HTTP/1.1" code 404

There is no "traces" folder, so its not surprising it cannot find the image.

If I change the image path to  , it works in Mkdocs but not in the markdown editor.

I don't understand why mkdocs can't use the relative path microsatsFigures/Figure_setLoci.png, and why it requires a / in front.  And why does it look for the image in a /traces folder that does not exist if I don't use the /?

I'm using html because I need additional formatting on the images, but the same issue occurs with standard markdown image syntax.

Is there something I need to configure in MkDocs to get it to recognise the path in the same way that the markdown editors do? I'd really like to be able to preview my images in the markdown editing tools I'm using but at the moment I can either get it to work in MkDocs or the editor, but not both.

答:
@Chris's answer is correct. However, if you really need links to be in raw HTML, then you could set the use_directory_urls config option to False. Then MkDocs will not change the URL/location of the rendered file from the source file and the relative links within raw HTML will work on both the rendered document and your Markdown editor.

By the way, this is why you need to make the links absolute (add a / to the beginning of the URL). The use_direstory_urls option is altering the location of the rendered document so that the relative URL to your image is no longer correct. When using Markdown links, MkDocs automatically adjusts relative links for this. But it ignores links within raw HTML. Disabling use_direstory_urls avoids this issue completely.

Body:
I have an issue with MkDocs not being able to find my images.  The images are in a subfolder, called microsatsFigures, in my docs folder.  So my /docs folder contains index.md, traces.md and the folder microsatsFigures which has the images.  In my Markdown file traces.md I am using html syntax for the images so the path to the image is:

This works perfectly in markdown editors that I am using (Typora and Macdown), and the image is displayed no problem.  However mkdocs can't find the image - I get

WARNING  -  [15:02:53] "GET /traces/microsatsFigures/Figure_setLoci.png HTTP/1.1" code 404

There is no "traces" folder, so its not surprising it cannot find the image.

If I change the image path to  , it works in Mkdocs but not in the markdown editor.

I don't understand why mkdocs can't use the relative path microsatsFigures/Figure_setLoci.png, and why it requires a / in front.  And why does it look for the image in a /traces folder that does not exist if I don't use the /?

I'm using html because I need additional formatting on the images, but the same issue occurs with standard markdown image syntax.

Is there something I need to configure in MkDocs to get it to recognise the path in the same way that the markdown editors do? I'd really like to be able to preview my images in the markdown editing tools I'm using but at the moment I can either get it to work in MkDocs or the editor, but not both.


问:
Scrolling 2 different elements in same time
If i have a textarea element and a div element how can i scroll them both in one time? ( when i scroll textarea i want the div to do the same )

I want to use pure javascript, as simple code as it is possible.

Ty.

答:
As answered here: synchronize two scrolling bars in multiple selection box</p>

```<code>var s1 = document.getElementById('Select1');
var s2 = document.getElementById('Select2');

function select_scroll_1(e) { s2.scrollTop = s1.scrollTop; }
function select_scroll_2(e) { s1.scrollTop = s2.scrollTop; }

s1.addEventListener('scroll', select_scroll_1, false);
s2.addEventListener('scroll', select_scroll_2, false);
</code>```

Body:
As answered here: synchronize two scrolling bars in multiple selection box

var s1 = document.getElementById('Select1');
var s2 = document.getElementById('Select2');

function select_scroll_1(e) { s2.scrollTop = s1.scrollTop; }
function select_scroll_2(e) { s1.scrollTop = s2.scrollTop; }

s1.addEventListener('scroll', select_scroll_1, false);
s2.addEventListener('scroll', select_scroll_2, false);


问:
Remove digits in CSV headers
I have a CSV file that has been converted from a dict - witch has added Numbers to get the columns unique. Now I want to remove the numbers.

Example of CSV headers now:

```<code>User,Comment,Comment1,Comment2,Created
</code>```

I would like to use something like this:

```<code>header = ''.join([i for i in header if not i.isdigit()])
</code>```

I uses this code to create the CSV without any empty columns.

```<code>with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd = csv.reader(fd)
    cols = set()
    _ = next(rd)  # skip header line
    for row in rd:
        for i, val in enumerate(row):
            if val != '':
                cols.add(i)
    _ = fd.seek(io.SEEK_SET)
    wr = csv.writer(fdout)
    for row in rd:
        _ = wr.writerow(val for i, val in enumerate(row) if i in cols)
</code>```

And my desired output are the same file but headers like this:

```<code>User,Comment,Comment,Comment,Created
</code>```

答:
You can make use of Python's itemgetter() which can be used to extract just the required values from each row.

If your header only contains numbers at the
start or end, a simple approach is to use .strip('0123456789') to remove them.

from operator import itemgetter
import csv
import io

with open('input.csv') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    header = next(csv_input)

    # Test the first row for empty values
    first_row = next(csv_input)
    required_cols = itemgetter(*(index for index, value in enumerate(first_row) if value))

    f_input.seek(io.SEEK_SET)   # restart
    header = next(csv_input)
    csv_output.writerow(value.strip('0123456789') for value in required_cols(header))

    for row in csv_input:
        csv_output.writerow(required_cols(row))
```
<p>For example, if the CSV contained the following:</p>
<pre class="lang-none prettyprint-override"><code>User,Comment,Comment1,Comment2,Created
Fred,a,b,,11-02-2022
Wilma,a,b,,11-02-2022
</code>```

The Comment2 column would be completely removed and also the digits from the header giving:

User,Comment,Comment,Created
Fred,a,b,11-02-2022
Wilma,a,b,11-02-2022
```

Title: Remove digits in CSV headers

Body:
I have a CSV file that has been converted from a dict - witch has added Numbers to get the columns unique. Now I want to remove the numbers.

Example of CSV headers now:

User,Comment,Comment1,Comment2,Created

I would like to use something like this:

header = ''.join([i for i in header if not i.isdigit()])

I uses this code to create the CSV without any empty columns.

with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd = csv.reader(fd)
    cols = set()
    _ = next(rd)  # skip header line
    for row in rd:
        for i, val in enumerate(row):
            if val != '':
                cols.add(i)
    _ = fd.seek(io.SEEK_SET)
    wr = csv.writer(fdout)
    for row in rd:
        _ = wr.writerow(val for i, val in enumerate(row) if i in cols)

And my desired output are the same file but headers like this:

User,Comment,Comment,Comment,Created

Body:
You can make use of Python's itemgetter() which can be used to extract just the required values from each row.

If your header only contains numbers at the
start or end, a simple approach is to use .strip('0123456789') to remove them.

from operator import itemgetter
import csv
import io

with open('input.csv') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    header = next(csv_input)

    # Test the first row for empty values
    first_row = next(csv_input)
    required_cols = itemgetter(*(index for index, value in enumerate(first_row) if value))

    f_input.seek(io.SEEK_SET)   # restart
    header = next(csv_input)
    csv_output.writerow(value.strip('0123456789') for value in required_cols(header))

    for row in csv_input:
        csv_output.writerow(required_cols(row))

For example, if the CSV contained the following:

User,Comment,Comment1,Comment2,Created
Fred,a,b,,11-02-2022
Wilma,a,b,,11-02-2022

The Comment2 column would be completely removed and also the digits from the header giving:

User,Comment,Comment,Created
Fred,a,b,11-02-2022
Wilma,a,b,11-02-2022


问:
D3.js - Issue creating normalised stacked bar chart using example function on Obsevablehq
I'm having issues using the function provided at:

https://observablehq.com/@d3/stacked-normalized-horizontal-bar

The data i'm passing into the function is in the format that is used as an example

```<code>{Airline: 'Virgin America', Sentiment: 'positive', Count: 11},
{Airline: 'Virgin America', Sentiment: 'neutral', Count: 8},
{Airline: 'Virgin America', Sentiment: 'negative', Count: 3},
{Airline: 'Delta', Sentiment: 'neutral', Count: 10}.....
</code>```

The data was not already in this format so I use the following code to process to this format, here is the original dataset

```<code>for (object of data){

    if (processed.length === 0){
        processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
    } else {
        objIndex = processed.findIndex((obj => obj.Airline === object.airline && obj.Sentiment === object.airline_sentiment))

        if (objIndex === -1){
            processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
        } else {
            processed[objIndex].Count += 1

        }
    }
}
</code>```

I'm also passing in a sentiment array as follows for zDomain values

```<code>sentiment = ['positive', 'neutral', 'negative']
</code>```

Here is the parameters i'm using for my function, basically the same as the example

```<code>chart = StackedBarChart(processed, {
    x: d => d.Count,
    y: d => d.Airline,
    z: d => d.Sentiment,
    yDomain: d3.groupSort(
        processed,
        D) => D[0].Count / d3.sum(D, d => d.Count),
        d => d.Airline
    ),
    colors: d3.schemeSpectral[sentiment.length],
    zDomain: sentiment
)
</code>```

In the StackedBarChar function i've noticed that the variable series is becoming undefined. Here is the code that defines this which I don't fully understand.

```<code>// Compute a nested array of series where each series is [[x1, x2], [x1, x2],
// [x1, x2], …] representing the x-extent of each stacked rect. In addition,
// each tuple has an i (index) property so that we can refer back to the
// original data point (data[i]). This code assumes that there is only one
// data point for a given unique y- and z-value.
const series = d3.stack()
    .keys(zDomain)
    .value(([, I], z) => X[I.get(z)])
    .order(order)
    .offset(offset)
(d3.rollup(I, ([i]) => i, i => Y[i], i => Z[i]))
    .map(s => s.map(d => Object.assign(d, {i: d.data[1].get(s.key)})));
</code>```

Also the error message is

```<code>   Uncaught TypeError: svg.append(...).selectAll(...).data(...).join is not a
   function
   at StackedBarChart (chart.js:132:8)
</code>```

which I believe is caused by series being undefined.

What could be causing this? could the format of my data must be wrong somehow?

答:
I am not able to reproduce your issue. The following code successfully draws the normalized stacked bar chart using the twitter airline dataset that you linked. What version of D3 are you using? Perhaps you are using an older version that does not have the selection.join function.

```<code><!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <script src="https://d3js.org/d3.v7.js"></script>
</head>

<body>
  <div id="chart"></div>

  <script>
    d3.csv('Tweets.csv').then(drawChart);

    function drawChart(data){
      const processed = [];

      for (object of data) {
        if (processed.length === 0){
          processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
        } else {
          objIndex = processed.findIndex((obj => obj.Airline === object.airline && obj.Sentiment === object.airline_sentiment))

          if (objIndex === -1){
            processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
          } else {
            processed[objIndex].Count += 1
          }
        }
      }

      const sentiment = ['positive', 'neutral', 'negative'];

      const yDomain = d3.groupSort(
        processed,
        D => D[0].Count / d3.sum(D, d => d.Count),
        d => d.Airline
      );

      const sbc = StackedBarChart(processed, {
        x: d => d.Count,
        y: d => d.Airline,
        z: d => d.Sentiment,
        yDomain: yDomain,
        colors: d3.schemeSpectral[sentiment.length],
        zDomain: sentiment
      });

      const div = document.getElementById('chart');
      div.append(sbc);
    }

    // Copyright 2021 Observable, Inc.
    // Released under the ISC license.
    // https://observablehq.com/@d3/stacked-normalized-horizontal-bar
    function StackedBarChart(data, {
      x = d => d, // given d in data, returns the (quantitative) x-value
      y = (d, i) => i, // given d in data, returns the (ordinal) y-value
      z = () => true, // given d in data, returns the (categorical) z-value
      title, // given d in data, returns the title text
      marginTop = 30, // top margin, in pixels
      marginRight = 20, // right margin, in pixels
      marginBottom = 0, // bottom margin, in pixels
      marginLeft = 40, // left margin, in pixels
      width = 640, // outer width, in pixels
      height, // outer height, in pixels
      xType = d3.scaleLinear, // type of x-scale
      xDomain, // [xmin, xmax]
      xRange = [marginLeft, width - marginRight], // [left, right]
      yDomain, // array of y-values
      yRange, // [bottom, top]
      yPadding = 0.1, // amount of y-range to reserve to separate bars
      zDomain, // array of z-values
      offset = d3.stackOffsetExpand, // stack offset method
      order = d3.stackOrderNone, // stack order method
      xFormat = "%", // a format specifier string for the x-axis
      xLabel, // a label for the x-axis
      colors = d3.schemeTableau10, // array of colors
    } = {}) {
      // Compute values.
      const X = d3.map(data, x);
      const Y = d3.map(data, y);
      const Z = d3.map(data, z);

      // Compute default y- and z-domains, and unique them.
      if (yDomain === undefined) yDomain = Y;
      if (zDomain === undefined) zDomain = Z;
      yDomain = new d3.InternSet(yDomain);
      zDomain = new d3.InternSet(zDomain);

      // Omit any data not present in the y- and z-domains.
      const I = d3.range(X.length).filter(i => yDomain.has(Y[i]) && zDomain.has(Z[i]));

      // If the height is not specified, derive it from the y-domain.
      if (height === undefined) height = yDomain.size * 25 + marginTop + marginBottom;
      if (yRange === undefined) yRange = [height - marginBottom, marginTop];

      // Compute a nested array of series where each series is [[x1, x2], [x1, x2],
      // [x1, x2], …] representing the x-extent of each stacked rect. In addition,
      // each tuple has an i (index) property so that we can refer back to the
      // original data point (data[i]). This code assumes that there is only one
      // data point for a given unique y- and z-value.
      const series = d3.stack()
          .keys(zDomain)
          .value(([, I], z) => X[I.get(z)])
          .order(order)
          .offset(offset)
        (d3.rollup(I, ([i]) => i, i => Y[i], i => Z[i]))
        .map(s => s.map(d => Object.assign(d, {i: d.data[1].get(s.key)})));

      // Compute the default y-domain. Note: diverging stacks can be negative.
      if (xDomain === undefined) xDomain = d3.extent(series.flat(2));

      // Construct scales, axes, and formats.
      const xScale = xType(xDomain, xRange);
      const yScale = d3.scaleBand(yDomain, yRange).paddingInner(yPadding);
      const color = d3.scaleOrdinal(zDomain, colors);
      const xAxis = d3.axisTop(xScale).ticks(width / 80, xFormat);
      const yAxis = d3.axisLeft(yScale).tickSizeOuter(0);

      // Compute titles.
      if (title === undefined) {
        title = i => `${Y[i]}\n${Z[i]}\n${X[i].toLocaleString()}`;
      } else {
        const O = d3.map(data, d => d);
        const T = title;
        title = i => T(O[i], i, data);
      }

      const svg = d3.create("svg")
          .attr("width", width)
          .attr("height", height)
          .attr("viewBox", [0, 0, width, height])
          .attr("style", "max-width: 100%; height: auto; height: intrinsic;");

      const bar = svg.append("g")
        .selectAll("g")
        .data(series)
        .join("g")
          .attr("fill", ([{i}]) => color(Z[i]))
        .selectAll("rect")
        .data(d => d)
        .join("rect")
          .attr("x", ([x1, x2]) => Math.min(xScale(x1), xScale(x2)))
          .attr("y", ({i}) => yScale(Y[i]))
          .attr("width", ([x1, x2]) => Math.abs(xScale(x1) - xScale(x2)))
          .attr("height", yScale.bandwidth());

      if (title) bar.append("title")
          .text(({i}) => title(i));

      svg.append("g")
          .attr("transform", `translate(0,${marginTop})`)
          .call(xAxis)
          .call(g => g.select(".domain").remove())
          .call(g => g.append("text")
              .attr("x", width - marginRight)
              .attr("y", -22)
              .attr("fill", "currentColor")
              .attr("text-anchor", "end")
              .text(xLabel));

      svg.append("g")
          .attr("transform", `translate(${xScale(0)},0)`)
          .call(yAxis);

      return Object.assign(svg.node(), {scales: {color}});
    }
  </script>
</body>

</html>
</code>```

Body:
I'm having issues using the function provided at:

https://observablehq.com/@d3/stacked-normalized-horizontal-bar

The data i'm passing into the function is in the format that is used as an example

{Airline: 'Virgin America', Sentiment: 'positive', Count: 11},
{Airline: 'Virgin America', Sentiment: 'neutral', Count: 8},
{Airline: 'Virgin America', Sentiment: 'negative', Count: 3},
{Airline: 'Delta', Sentiment: 'neutral', Count: 10}.....

The data was not already in this format so I use the following code to process to this format, here is the original dataset

for (object of data){

    if (processed.length === 0){
        processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
    } else {
        objIndex = processed.findIndex((obj => obj.Airline === object.airline && obj.Sentiment === object.airline_sentiment))

        if (objIndex === -1){
            processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
        } else {
            processed[objIndex].Count += 1

        }
    }
}

I'm also passing in a sentiment array as follows for zDomain values

sentiment = ['positive', 'neutral', 'negative']

Here is the parameters i'm using for my function, basically the same as the example

chart = StackedBarChart(processed, {
    x: d => d.Count,
    y: d => d.Airline,
    z: d => d.Sentiment,
    yDomain: d3.groupSort(
        processed,
        D) => D[0].Count / d3.sum(D, d => d.Count),
        d => d.Airline
    ),
    colors: d3.schemeSpectral[sentiment.length],
    zDomain: sentiment
)

In the StackedBarChar function i've noticed that the variable series is becoming undefined. Here is the code that defines this which I don't fully understand.

// Compute a nested array of series where each series is [[x1, x2], [x1, x2],
// [x1, x2], …] representing the x-extent of each stacked rect. In addition,
// each tuple has an i (index) property so that we can refer back to the
// original data point (data[i]). This code assumes that there is only one
// data point for a given unique y- and z-value.
const series = d3.stack()
    .keys(zDomain)
    .value(([, I], z) => X[I.get(z)])
    .order(order)
    .offset(offset)
(d3.rollup(I, ([i]) => i, i => Y[i], i => Z[i]))
    .map(s => s.map(d => Object.assign(d, {i: d.data[1].get(s.key)})));

Also the error message is

   Uncaught TypeError: svg.append(...).selectAll(...).data(...).join is not a
   function
   at StackedBarChart (chart.js:132:8)

which I believe is caused by series being undefined.

What could be causing this? could the format of my data must be wrong somehow?

Body:
I am not able to reproduce your issue. The following code successfully draws the normalized stacked bar chart using the twitter airline dataset that you linked. What version of D3 are you using? Perhaps you are using an older version that does not have the selection.join function.

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <script src="https://d3js.org/d3.v7.js"></script>
</head>

<body>
  <div id="chart"></div>

  <script>
    d3.csv('Tweets.csv').then(drawChart);

    function drawChart(data){
      const processed = [];

      for (object of data) {
        if (processed.length === 0){
          processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
        } else {
          objIndex = processed.findIndex((obj => obj.Airline === object.airline && obj.Sentiment === object.airline_sentiment))

          if (objIndex === -1){
            processed.push({Airline: object.airline, Sentiment: object.airline_sentiment, Count: 1})
          } else {
            processed[objIndex].Count += 1
          }
        }
      }

      const sentiment = ['positive', 'neutral', 'negative'];

      const yDomain = d3.groupSort(
        processed,
        D => D[0].Count / d3.sum(D, d => d.Count),
        d => d.Airline
      );

      const sbc = StackedBarChart(processed, {
        x: d => d.Count,
        y: d => d.Airline,
        z: d => d.Sentiment,
        yDomain: yDomain,
        colors: d3.schemeSpectral[sentiment.length],
        zDomain: sentiment
      });

      const div = document.getElementById('chart');
      div.append(sbc);
    }

    // Copyright 2021 Observable, Inc.
    // Released under the ISC license.
    // https://observablehq.com/@d3/stacked-normalized-horizontal-bar
    function StackedBarChart(data, {
      x = d => d, // given d in data, returns the (quantitative) x-value
      y = (d, i) => i, // given d in data, returns the (ordinal) y-value
      z = () => true, // given d in data, returns the (categorical) z-value
      title, // given d in data, returns the title text
      marginTop = 30, // top margin, in pixels
      marginRight = 20, // right margin, in pixels
      marginBottom = 0, // bottom margin, in pixels
      marginLeft = 40, // left margin, in pixels
      width = 640, // outer width, in pixels
      height, // outer height, in pixels
      xType = d3.scaleLinear, // type of x-scale
      xDomain, // [xmin, xmax]
      xRange = [marginLeft, width - marginRight], // [left, right]
      yDomain, // array of y-values
      yRange, // [bottom, top]
      yPadding = 0.1, // amount of y-range to reserve to separate bars
      zDomain, // array of z-values
      offset = d3.stackOffsetExpand, // stack offset method
      order = d3.stackOrderNone, // stack order method
      xFormat = "%", // a format specifier string for the x-axis
      xLabel, // a label for the x-axis
      colors = d3.schemeTableau10, // array of colors
    } = {}) {
      // Compute values.
      const X = d3.map(data, x);
      const Y = d3.map(data, y);
      const Z = d3.map(data, z);

      // Compute default y- and z-domains, and unique them.
      if (yDomain === undefined) yDomain = Y;
      if (zDomain === undefined) zDomain = Z;
      yDomain = new d3.InternSet(yDomain);
      zDomain = new d3.InternSet(zDomain);

      // Omit any data not present in the y- and z-domains.
      const I = d3.range(X.length).filter(i => yDomain.has(Y[i]) && zDomain.has(Z[i]));

      // If the height is not specified, derive it from the y-domain.
      if (height === undefined) height = yDomain.size * 25 + marginTop + marginBottom;
      if (yRange === undefined) yRange = [height - marginBottom, marginTop];

      // Compute a nested array of series where each series is [[x1, x2], [x1, x2],
      // [x1, x2], …] representing the x-extent of each stacked rect. In addition,
      // each tuple has an i (index) property so that we can refer back to the
      // original data point (data[i]). This code assumes that there is only one
      // data point for a given unique y- and z-value.
      const series = d3.stack()
          .keys(zDomain)
          .value(([, I], z) => X[I.get(z)])
          .order(order)
          .offset(offset)
        (d3.rollup(I, ([i]) => i, i => Y[i], i => Z[i]))
        .map(s => s.map(d => Object.assign(d, {i: d.data[1].get(s.key)})));

      // Compute the default y-domain. Note: diverging stacks can be negative.
      if (xDomain === undefined) xDomain = d3.extent(series.flat(2));

      // Construct scales, axes, and formats.
      const xScale = xType(xDomain, xRange);
      const yScale = d3.scaleBand(yDomain, yRange).paddingInner(yPadding);
      const color = d3.scaleOrdinal(zDomain, colors);
      const xAxis = d3.axisTop(xScale).ticks(width / 80, xFormat);
      const yAxis = d3.axisLeft(yScale).tickSizeOuter(0);

      // Compute titles.
      if (title === undefined) {
        title = i => `${Y[i]}\n${Z[i]}\n${X[i].toLocaleString()}`;
      } else {
        const O = d3.map(data, d => d);
        const T = title;
        title = i => T(O[i], i, data);
      }

      const svg = d3.create("svg")
          .attr("width", width)
          .attr("height", height)
          .attr("viewBox", [0, 0, width, height])
          .attr("style", "max-width: 100%; height: auto; height: intrinsic;");

      const bar = svg.append("g")
        .selectAll("g")
        .data(series)
        .join("g")
          .attr("fill", ([{i}]) => color(Z[i]))
        .selectAll("rect")
        .data(d => d)
        .join("rect")
          .attr("x", ([x1, x2]) => Math.min(xScale(x1), xScale(x2)))
          .attr("y", ({i}) => yScale(Y[i]))
          .attr("width", ([x1, x2]) => Math.abs(xScale(x1) - xScale(x2)))
          .attr("height", yScale.bandwidth());

      if (title) bar.append("title")
          .text(({i}) => title(i));

      svg.append("g")
          .attr("transform", `translate(0,${marginTop})`)
          .call(xAxis)
          .call(g => g.select(".domain").remove())
          .call(g => g.append("text")
              .attr("x", width - marginRight)
              .attr("y", -22)
              .attr("fill", "currentColor")
              .attr("text-anchor", "end")
              .text(xLabel));

      svg.append("g")
          .attr("transform", `translate(${xScale(0)},0)`)
          .call(yAxis);

      return Object.assign(svg.node(), {scales: {color}});
    }
  </script>
</body>

</html>


问:
Regex - capture character before pattern until a specific character
I'm trying to match h.Z.getAssetUrl("/FullLogo.svg") from the following string

```<code>4H18V5.2H2z"})),t)})),p=t(7103),h=t(1313),m=function(){return(0,o.jsx)(a.Ee,{src:`h.Z.getAssetUrl("/FullLogo.svg")`,width:"195px",height:"36px"})},g=function(e){var r=e.toggle,t=e.isOpen;return(0,o.jsx)(i.xu,{display:{base:"block",md:"none"}
</code>```

I've tried /getAssetUrl\(.+?\)/, this matches getAssetUrl("/FullLogo.svg"). How do I also match the h.Z. before it. I want to match ahead until a : is encounterd.

答:
With your shown samples, please try following regex. Here is the Online demo for following regex.

```<code>^.*?:\K(?:.*?\.){2}(?:.*?"){2}\)
</code>```

Explanation: Adding detailed explanation for above.

```<code>^.*?:         ##From starting of value matching till very first occurrence of : using lazy match here.
\K            ##Forget previous match by \K option till here so that we can print only required output.
(?:           ##Opening a non-capturing group here.
  .*?\.       ##Matching till dot by doing a lazy match here.
){2}          ##Match 2 occurrence of lazy matches(means match till 2 dots only).
(?:.*?"){2}\) ##In a non-capturing group matching till " as a lazy match and by mentioning {2} means perform two matches of it followed by a \ to get needed value.
</code>```

Body:
I'm trying to match h.Z.getAssetUrl("/FullLogo.svg") from the following string

4H18V5.2H2z"})),t)})),p=t(7103),h=t(1313),m=function(){return(0,o.jsx)(a.Ee,{src:`h.Z.getAssetUrl("/FullLogo.svg")`,width:"195px",height:"36px"})},g=function(e){var r=e.toggle,t=e.isOpen;return(0,o.jsx)(i.xu,{display:{base:"block",md:"none"}

I've tried /getAssetUrl\(.+?\)/, this matches getAssetUrl("/FullLogo.svg"). How do I also match the h.Z. before it. I want to match ahead until a : is encounterd.

Body:
With your shown samples, please try following regex. Here is the Online demo for following regex.

^.*?:\K(?:.*?\.){2}(?:.*?"){2}\)

Explanation: Adding detailed explanation for above.

^.*?:         ##From starting of value matching till very first occurrence of : using lazy match here.
\K            ##Forget previous match by \K option till here so that we can print only required output.
(?:           ##Opening a non-capturing group here.
  .*?\.       ##Matching till dot by doing a lazy match here.
){2}          ##Match 2 occurrence of lazy matches(means match till 2 dots only).
(?:.*?"){2}\) ##In a non-capturing group matching till " as a lazy match and by mentioning {2} means perform two matches of it followed by a \ to get needed value.


问:
How to Set config params in Slick-HikariCP
I am using Slick and Mysql. Getting the Error:

```<code>Failed to validate connection com.mysql.jdbc.JDBC4Connection@58e7cfcd (No operations allowed after connection closed.). Possibly consider using a shorter maxLifetime value."
</code>```

I understand the issue but don't know how to set maxLifetime  in slick on config. Here is my config:

```<code>mysqldb {
    driver = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306"
    user = root
    password = root
    connectionTimeout = 10000
    queueSize = 50000
    minConnections = 20
    maxConnections = 40
    numThreads = 40
}

</code>```

Any help would be appreciated.

答:
you can set under db config:</p>
```<code>mysqldb {
    driver = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306"
    user = root
    password = root
    connectionTimeout = 10000
    queueSize = 50000
    minConnections = 20
    maxConnections = 40
    numThreads = 40
    idleTimeout = 85000 // should be less than maxLifetime
    maxLifetime = 90000 //time is in millsecods and should be less than database wait_timeout
}

</code>```

Body:
I am using Slick and Mysql. Getting the Error:

Failed to validate connection com.mysql.jdbc.JDBC4Connection@58e7cfcd (No operations allowed after connection closed.). Possibly consider using a shorter maxLifetime value."

I understand the issue but don't know how to set maxLifetime  in slick on config. Here is my config:

mysqldb {
    driver = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306"
    user = root
    password = root
    connectionTimeout = 10000
    queueSize = 50000
    minConnections = 20
    maxConnections = 40
    numThreads = 40
}

Any help would be appreciated.

Body:
you can set under db config:

mysqldb {
    driver = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306"
    user = root
    password = root
    connectionTimeout = 10000
    queueSize = 50000
    minConnections = 20
    maxConnections = 40
    numThreads = 40
    idleTimeout = 85000 // should be less than maxLifetime
    maxLifetime = 90000 //time is in millsecods and should be less than database wait_timeout
}


问:
Detect the next line in flex box containing div
I need to add the vertical line splitter between the div. But the div which is present at the end of the line should not contain the splitter. The div will be placed dynamically.

https://stackblitz.com/edit/angular-ivy-lxhcuu?file=src%2Fapp%2Fapp.component.css

document.addEventListener('DOMContentLoaded', () => {
  const parent = document.querySelector(".parent");
  const node = parent.firstElementChild;
  for (let i = 1; i < 30; i++) {
    parent.appendChild(node.cloneNode(true));
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  font-family: Lato;
}

.parent {
  display: flex;
  flex-flow: wrap;
}

.paddingDta {
  padding: 5px;
}

.divider {
  border-left: 1px solid red;
}

.dividerPadding {
  margin: 2px;
}</code>```

      {{ data }}

```

答:
Well... This is kinda sophisticated problem, that can be solved in many different ways depending on usecase.

But long story short, I don't know any "tricky" way to fix this issue without "bruteforcing" it with checking position of every element on the list:

```<code>// I've used custom directive for this example for easier hook
// But you can use local variables as well
<div class="paddingDta" [someName]="i"> <-- content --> </div>

// View Children to hook to HTMLElement of our list items
@ViewChildren(FlexBorderDirective) els: QueryList<FlexBorderDirective>;
</code>```

Then you need to check offset position of every element and check which is further from left side of the screen. I've used function like this, however you might think about better way to check each element:

```<code>checkLastElements(_elements: Array<HTMLDivElement>) {
  // Clear table for resize
  this.lastElementsIndexes = [];

  // Not optimal, but good enough for example
  for (let i = 0; i < _elements.length; i++) {
    if (i + 1 < _elements.length)
      if (_elements[i].offsetLeft > _elements[i + 1].offsetLeft) {
        // Push "last element index" to another array for checking
        this.lastElementsIndexes.push(i);
      }
  }

  // "Force push" last element to our list
  this.lastElementsIndexes.push(_elements.length - 1);
}
</code>```

We also have to wait for View to init, so we should call this function inside "AfterViewInit" lifecycle hook

```<code>  ngAfterViewInit() {
    // Its just to prevent "checking error", I don't have time to
       resolve this :)
    setTimeout(() => {
       this.checkLastElements(this.els.map((_element) => _element.el));
    }, 0);
  }
</code>```

setTimeout is used because Angular was checking variables before they've changed. It wasn't critical bug, however it's the simplest way to resolve this warning/error message in console.

The last "tweak" would be checking "last elements" on window resize event. Angular helps us a lot with this task, and you can simply call our checkLastElements function in our HostListener

```<code>  // Handle resize window event
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.checkLastElements(this.els.map((_element) => _element.el));
  }
</code>```

full stackblitz example:

https://stackblitz.com/edit/angular-ivy-jskkaf?file=src%2Fapp%2Fapp.component.ts

However, for example if you have some "static container" like in bootstrap-css .container class, you might want to use css pseudo element :nth-child/:nth-of-type and @media.

Body:
I need to add the vertical line splitter between the div. But the div which is present at the end of the line should not contain the splitter. The div will be placed dynamically.

https://stackblitz.com/edit/angular-ivy-lxhcuu?file=src%2Fapp%2Fapp.component.css

document.addEventListener('DOMContentLoaded', () => {
  const parent = document.querySelector(".parent");
  const node = parent.firstElementChild;
  for (let i = 1; i < 30; i++) {
    parent.appendChild(node.cloneNode(true));
  }
});

p {
  font-family: Lato;
}

.parent {
  display: flex;
  flex-flow: wrap;
}

.paddingDta {
  padding: 5px;
}

.divider {
  border-left: 1px solid red;
}

.dividerPadding {
  margin: 2px;
}

      {{ data }}

Body:
Well... This is kinda sophisticated problem, that can be solved in many different ways depending on usecase.

But long story short, I don't know any "tricky" way to fix this issue without "bruteforcing" it with checking position of every element on the list:

// I've used custom directive for this example for easier hook
// But you can use local variables as well
<div class="paddingDta" [someName]="i"> <-- content --> </div>

// View Children to hook to HTMLElement of our list items
@ViewChildren(FlexBorderDirective) els: QueryList<FlexBorderDirective>;

Then you need to check offset position of every element and check which is further from left side of the screen. I've used function like this, however you might think about better way to check each element:

checkLastElements(_elements: Array<HTMLDivElement>) {
  // Clear table for resize
  this.lastElementsIndexes = [];

  // Not optimal, but good enough for example
  for (let i = 0; i < _elements.length; i++) {
    if (i + 1 < _elements.length)
      if (_elements[i].offsetLeft > _elements[i + 1].offsetLeft) {
        // Push "last element index" to another array for checking
        this.lastElementsIndexes.push(i);
      }
  }

  // "Force push" last element to our list
  this.lastElementsIndexes.push(_elements.length - 1);
}

We also have to wait for View to init, so we should call this function inside "AfterViewInit" lifecycle hook

  ngAfterViewInit() {
    // Its just to prevent "checking error", I don't have time to
       resolve this :)
    setTimeout(() => {
       this.checkLastElements(this.els.map((_element) => _element.el));
    }, 0);
  }

setTimeout is used because Angular was checking variables before they've changed. It wasn't critical bug, however it's the simplest way to resolve this warning/error message in console.

The last "tweak" would be checking "last elements" on window resize event. Angular helps us a lot with this task, and you can simply call our checkLastElements function in our HostListener

  // Handle resize window event
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.checkLastElements(this.els.map((_element) => _element.el));
  }

full stackblitz example:

https://stackblitz.com/edit/angular-ivy-jskkaf?file=src%2Fapp%2Fapp.component.ts

However, for example if you have some "static container" like in bootstrap-css .container class, you might want to use css pseudo element :nth-child/:nth-of-type and @media.


问:
Vue Uncaught ReferenceError: process is not defined
I'm working on a Vue + typescript project. I want to use process.env.var_name to adjust the project is in development mode or production mode, just like

```<code>const isProduct = process.env.APP_ENV === "prod";
</code>```

; however I got an error below. I never meet this error before, so could any one give me a clue why this would happen so I can try to figure out what happend in the project and then fix it.

答:
Env's variables must start with VUE_APP_, so try to change APP_ENV into VUE_APP_ENV.
About the CORS error you have to enable your FE from your BE.

Body:
I'm working on a Vue + typescript project. I want to use process.env.var_name to adjust the project is in development mode or production mode, just like

const isProduct = process.env.APP_ENV === "prod";

; however I got an error below. I never meet this error before, so could any one give me a clue why this would happen so I can try to figure out what happend in the project and then fix it.


问:
Jupyter nbextensions does not appear
I tried to install jupyter_contrib_nbextensions : http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html

Everything worked fine but when I open a notebook nothing changes. I can't see the new tool bar that I'm supposed to see.

When I reinstall the Extension, the process is the same (I don't have a message tellign me that the files already exists). I don't have an error. So I can't figure out why it doesn't work.

Thanks a lot.

答:
Following steps with Anaconda Prompt  ->

1)Open Anaconda Prompt.

2)Type in -

conda install -c conda-forge jupyter_contrib_nbextensions

Enter 'y' for installation.

type in jupyter contrib nbextension install --sys-prefix

4)Exit the Anacodna prompt.

5)Relaunch Jupyter notebook. (You will now see nbextensions tab)

Screenshot of my installation

Title: Jupyter nbextensions does not appear


问:
Accordion with Icons to the Left
I'm looking for an accordion with Icons to the left of the text instead of the right.

Currently using one off W3 Schools but I can't get the icons on the left side.

Help please!

答:
I do not quite understand the question, but maybe the solution lies in the study of Bootstrap, there you can connect different elements and get Accordion with Icons to the Left

For example, connect this:

https://getbootstrap.com/docs/4.0/layout/media-object/

https://getbootstrap.com/docs/5.0/components/accordion/

Title: Accordion with Icons to the Left


问:
R install.packages unable to find gcc
I am unable to compile packages from source on Windows. The issue seems to be related to resolving paths in the compilation step. Following the example from the Rtools4 installation page, I get an error as follows:

```<code>> install.packages("jsonlite", type = "source")
trying URL 'https://cran.rstudio.com/src/contrib/jsonlite_1.7.3.tar.gz'
Content type 'application/x-gzip' length 1051573 bytes (1.0 MB)
downloaded 1.0 MB

* installing *source* package 'jsonlite' ...
** package 'jsonlite' successfully unpacked and MD5 sums checked
** using staged installation
** libs

*** arch - i386
C:\Rtools\mingw_64gcc  -I"C:/Users/<username>/DOCUME~1/R/R-41~1.2/include" -DNDEBUG -Iyajl/api       -D__USE_MINGW_ANSI_STDIO   -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c base64.c -o base64.o
sh: line 1: C:Rtoolsmingw_64gcc: command not found
make: *** [C:/Users/<username>/DOCUME~1/R/R-41~1.2/etc/i386/Makeconf:238: base64.o] Error 127
ERROR: compilation failed for package 'jsonlite'
* removing 'C:/Users/<username>/Documents/R/R-4.1.2/library/jsonlite'
* restoring previous 'C:/Users/<username>/Documents/R/R-4.1.2/library/jsonlite'
Warning in install.packages :
  installation of package ‘jsonlite’ had non-zero exit status
</code>```

I find it very odd that there's no file separators in the line that starts with sh:. There ought to be path separators, but the call to gcc seems to be missing them. Is there somewhere I can correct this path? I will also note that I have confirmed that gcc exists, but it's in C:\Rtools\mingw_64\bin, not C:\Rtools\mingw_64 as that line would seem to suggest that it's looking for it. I can confirm that the folder containing the gcc .exe file is on my path. Any suggestions on how to ensure that the correct path to gcc will be called is appreciated.

This is on a new installation of R 4.1.2 with RTools4.

For reference,

```<code>> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] devtools_2.4.3 usethis_2.1.5

loaded via a namespace (and not attached):
 [1] magrittr_2.0.2    pkgload_1.2.4     R6_2.5.1          rlang_1.0.1       fastmap_1.1.0     tools_4.1.2
 [7] pkgbuild_1.3.1    sessioninfo_1.2.2 cli_3.1.1         withr_2.4.3       ellipsis_0.3.2    remotes_2.4.2
[13] rprojroot_2.0.2   lifecycle_1.0.1   crayon_1.4.2      brio_1.1.3        processx_3.5.2    purrr_0.3.4
[19] callr_3.7.0       fs_1.5.2          ps_1.6.0          testthat_3.1.2    memoise_2.0.1     glue_1.6.1
[25] cachem_1.0.6      compiler_4.1.2    desc_1.4.0        prettyunits_1.1.1
</code>```

答:
I am unsure what the root cause of this issue was, but I was able to solve it by editing both Makeconf files at C:\Users\<username>\Documents\R\R-4.1.2\etc\i386 and C:\Users\<username>\Documents\R\R-4.1.2\etc\x64. The two changes I made there were to set

```<code>RTOOLS40_HOME ?= c:/rtools
</code>```

and

```<code>BINPREF = "$(RTOOLS40_ROOT)/mingw32/bin/"
</code>```

If there is an explanation for why this solves the problem, I would appreciate hearing it!

Title: R install.packages unable to find gcc

Body:
I am unable to compile packages from source on Windows. The issue seems to be related to resolving paths in the compilation step. Following the example from the Rtools4 installation page, I get an error as follows:

> install.packages("jsonlite", type = "source")
trying URL 'https://cran.rstudio.com/src/contrib/jsonlite_1.7.3.tar.gz'
Content type 'application/x-gzip' length 1051573 bytes (1.0 MB)
downloaded 1.0 MB

* installing *source* package 'jsonlite' ...
** package 'jsonlite' successfully unpacked and MD5 sums checked
** using staged installation
** libs

*** arch - i386
C:\Rtools\mingw_64gcc  -I"C:/Users/<username>/DOCUME~1/R/R-41~1.2/include" -DNDEBUG -Iyajl/api       -D__USE_MINGW_ANSI_STDIO   -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c base64.c -o base64.o
sh: line 1: C:Rtoolsmingw_64gcc: command not found
make: *** [C:/Users/<username>/DOCUME~1/R/R-41~1.2/etc/i386/Makeconf:238: base64.o] Error 127
ERROR: compilation failed for package 'jsonlite'
* removing 'C:/Users/<username>/Documents/R/R-4.1.2/library/jsonlite'
* restoring previous 'C:/Users/<username>/Documents/R/R-4.1.2/library/jsonlite'
Warning in install.packages :
  installation of package ‘jsonlite’ had non-zero exit status

I find it very odd that there's no file separators in the line that starts with sh:. There ought to be path separators, but the call to gcc seems to be missing them. Is there somewhere I can correct this path? I will also note that I have confirmed that gcc exists, but it's in C:\Rtools\mingw_64\bin, not C:\Rtools\mingw_64 as that line would seem to suggest that it's looking for it. I can confirm that the folder containing the gcc .exe file is on my path. Any suggestions on how to ensure that the correct path to gcc will be called is appreciated.

This is on a new installation of R 4.1.2 with RTools4.

For reference,

> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] devtools_2.4.3 usethis_2.1.5

loaded via a namespace (and not attached):
 [1] magrittr_2.0.2    pkgload_1.2.4     R6_2.5.1          rlang_1.0.1       fastmap_1.1.0     tools_4.1.2
 [7] pkgbuild_1.3.1    sessioninfo_1.2.2 cli_3.1.1         withr_2.4.3       ellipsis_0.3.2    remotes_2.4.2
[13] rprojroot_2.0.2   lifecycle_1.0.1   crayon_1.4.2      brio_1.1.3        processx_3.5.2    purrr_0.3.4
[19] callr_3.7.0       fs_1.5.2          ps_1.6.0          testthat_3.1.2    memoise_2.0.1     glue_1.6.1
[25] cachem_1.0.6      compiler_4.1.2    desc_1.4.0        prettyunits_1.1.1

Body:
I am unsure what the root cause of this issue was, but I was able to solve it by editing both Makeconf files at C:\Users\<username>\Documents\R\R-4.1.2\etc\i386 and C:\Users\<username>\Documents\R\R-4.1.2\etc\x64. The two changes I made there were to set

RTOOLS40_HOME ?= c:/rtools

and

BINPREF = "$(RTOOLS40_ROOT)/mingw32/bin/"

If there is an explanation for why this solves the problem, I would appreciate hearing it!