问:
"Failed to load module script / MIME" error when trying to use JS with a pdf.js library on a live-server through VScode
I'm currently working on a project that will automatically fill a specific PDF document with user input information in an HTML form.

Before even getting to the actual JS coding, I've been having issues with getting the PDF.js library imported properly. The initial error I got basically told me that I cannot import the PDF.js library when running the index.html on my own machine, so I need to use a live server. Que VSCode live-server extension.

Now that I have the Live-server extension running, this is the new error in the console:

```<code>Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. --- :5500/node_modules/pdf.js/:1
</code>```

I've been using a combination of ChatGPT and Google in order to find the issue. The picture attached shows what ChatGPT is recommending ChatGPT recommendation

Based one that, it seems that by default, the VSCode live-server extension doesn't work well with modules and JS? (or am I misunderstanding that?)

It basically sent me to the .ritwickdey.liveserver directory within ./vscode/extensions looking for a mime.types file. However, the closest thing I've found is a mime.types folder, containing the following: History.md, index.js, LICENSE, package.json, and README.md. I understand that things might not be exactly as the AI (or google) says, but for the life of me, I cannot find the file that needs to be changed in order to allow the module to work. Does anyone have any idea?

I linked my main.js file in the HTML.index, and imported the pdfjs library within the main.js file. Is that correct?

```<code> <script src="./main.js" type="module"></script>
</code>```
```<code> import * as pdfjs from './node_modules/pdf.js';
</code>```

Also... am I just going about this in an extremely round about way? Like is there a simple solution to this that I'm just completely overlooking? I feel like it shouldn't be this complicated. I'm still fairly new to this though so I guess it could be.

P.S - This is my first post on Stack Overflow, so hopefully it is well written :) Please let me know if I need to add any more information

I have tried looking for the mime.types file mentioned above, but have had no luck locating it.

I've played around with the  and importing

Body:
I'm currently working on a project that will automatically fill a specific PDF document with user input information in an HTML form.

Before even getting to the actual JS coding, I've been having issues with getting the PDF.js library imported properly. The initial error I got basically told me that I cannot import the PDF.js library when running the index.html on my own machine, so I need to use a live server. Que VSCode live-server extension.

Now that I have the Live-server extension running, this is the new error in the console:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. --- :5500/node_modules/pdf.js/:1

I've been using a combination of ChatGPT and Google in order to find the issue. The picture attached shows what ChatGPT is recommending ChatGPT recommendation

Based one that, it seems that by default, the VSCode live-server extension doesn't work well with modules and JS? (or am I misunderstanding that?)

It basically sent me to the .ritwickdey.liveserver directory within ./vscode/extensions looking for a mime.types file. However, the closest thing I've found is a mime.types folder, containing the following: History.md, index.js, LICENSE, package.json, and README.md. I understand that things might not be exactly as the AI (or google) says, but for the life of me, I cannot find the file that needs to be changed in order to allow the module to work. Does anyone have any idea?

I linked my main.js file in the HTML.index, and imported the pdfjs library within the main.js file. Is that correct?

 import * as pdfjs from './node_modules/pdf.js';

Also... am I just going about this in an extremely round about way? Like is there a simple solution to this that I'm just completely overlooking? I feel like it shouldn't be this complicated. I'm still fairly new to this though so I guess it could be.

P.S - This is my first post on Stack Overflow, so hopefully it is well written :) Please let me know if I need to add any more information

I have tried looking for the mime.types file mentioned above, but have had no luck locating it.

I've played around with the  and importing


来源: stackexchange

问:
Discord Bot is online but non of my commands are working
I'm currently starting up and old discord project for a bot. When I start the bot everything loads how it supposed to be until I go into discord to go do the command in discord it doesnt work here is my main.js code and my command handler.

Main.Js

```<code>const Discord = require('discord.js')
const Levels = require('discord-xp');
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION"] })
const prefix = '!';
require('dotenv').config();
const mongoose = require("mongoose")
const keepAlive = require("./server");

keepAlive();

client.commands = new Discord.Collection();
client.events = new Discord.Collection();

['command_handler', 'event_handler'].forEach(handler => {
  require(`./handlers/${handler}`)(client, Discord);
})
client.on('ready', () => {
  client.user.setActivity(`!help`)
  console.log(`${client.user.username} ✅`)
})
mongoose.connect(process.env.MONGODB_SRV, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false
}).then(() => {
  console.log('connected to the database')
}).catch((err) => {
  console.log.err
})
Levels.setURL(``);

client.login(process.env.DISCORD_TOKEN);

Command Handler

</code>```

const fs = require('fs');

module.exports = (client, Discord) =>{
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

```<code>for(const file of command_files){
    const command = require(`../commands/${file}`);
    if(command.name){
        client.commands.set(command.name, command);
    } else {
        continue;
    }
    }
}
</code>```
```<code>

</code>```

const fs = require('fs');

module.exports = (client, Discord) =>{
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

```<code>for(const file of command_files){
    const command = require(`../commands/${file}`);
    if(command.name){
        client.commands.set(command.name, command);
    } else {
        continue;
    }
    }
}
</code>```
```<code>
</code>```

It still doesnt work after googling and trying please help me.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently starting up and old discord project for a bot. When I start the bot everything loads how it supposed to be until I go into discord to go do the command in discord it doesnt work here is my main.js code and my command handler.

Main.Js

const Discord = require('discord.js')
const Levels = require('discord-xp');
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION"] })
const prefix = '!';
require('dotenv').config();
const mongoose = require("mongoose")
const keepAlive = require("./server");

keepAlive();

client.commands = new Discord.Collection();
client.events = new Discord.Collection();

['command_handler', 'event_handler'].forEach(handler => {
  require(`./handlers/${handler}`)(client, Discord);
})
client.on('ready', () => {
  client.user.setActivity(`!help`)
  console.log(`${client.user.username} ✅`)
})
mongoose.connect(process.env.MONGODB_SRV, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false
}).then(() => {
  console.log('connected to the database')
}).catch((err) => {
  console.log.err
})
Levels.setURL(``);

client.login(process.env.DISCORD_TOKEN);

Command Handler

const fs = require('fs');

module.exports = (client, Discord) =>{
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

for(const file of command_files){
    const command = require(`../commands/${file}`);
    if(command.name){
        client.commands.set(command.name, command);
    } else {
        continue;
    }
    }
}

const fs = require('fs');

module.exports = (client, Discord) =>{
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

for(const file of command_files){
    const command = require(`../commands/${file}`);
    if(command.name){
        client.commands.set(command.name, command);
    } else {
        continue;
    }
    }
}

It still doesnt work after googling and trying please help me.


问:
Telepresence.io can't intercept a service running on the namespace kube-system
I installed telepresence by using the curl command on a Kubernetes cluster running on GKE. I can correctly interact with other services deployed in the cluster and I can intercept services (like the one in this post) running on the default namespace but when the same service is deployed on the kube-system namespace I can't intercept it. I don't get any useful errors, just a timeout when Telepresence tries to install the agent.

I am already aware of a similar issue happening on GKE when some firewall ports are not correctly opened. I followed already the docs and I have already opened those ports. That's how I managed to run the same service on the default namespace correctly.

Steps to reproduce the behavior:

I started an Nginx service with the following manifest. I have created a docker image gsantoro/my-nginx:latest which is a modified version of Nginx just to expose port 3000 instead of 80

apiVersion: apps/v1
kind: Deployment
metadata:
  name:  nginx
  labels:
    app:  nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1
  template:
    metadata:
      labels:
        app:  nginx
    spec:
      containers:
      - name:  nginx
        image: gsantoro/my-nginx:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: default
spec:
  selector:
    app: nginx
  type: ClusterIP
  ports:
  - protocol: TCP
    port: 3000
```
<ol start="2">
<li>When I run 'telepresence intercept nginx --namespace kube-system --port 49729:3000`, I see 'telepresence intercept: error: request timed out while waiting for agent my-nginx.kube-system to arrive'</li>
</ol>
<p>Versions:</p>
<ul>
<li>Output of <code>telepresence version</code></li>
</ul>
<pre class="lang-bash prettyprint-override"><code>❯ telepresence version
Enhanced Client: v2.9.4
Root Daemon    : v2.9.4
User Daemon    : v2.9.4
Traffic Manager: v2.9.4
</code>```

Operating system of workstation running telepresence commands. MacOs v12.6.1, Apple M1 Max chipset

Kubernetes environment and Version [e.g. Minikube, bare metal, Google Kubernetes Engine]. v1.24.7-gke.900 on GKE

Additional context:
logs from traffic-manager:

│ 2022-12-07 14:54:19.1972 debug   httpd/conn=127.0.0.1:8081 : PrepareIntercept called : session_id="203deb44-fe3a-4e28-a53a-e3739c7e5cb3"                                                                           │
│ 2022-12-07 14:54:19.2188 debug   agent-configs : MODIFIED telepresence-agents.kube-system                                                                                │
│ 2022-12-07 14:54:19.2189 debug   agent-configs : add my-nginx.kube-system                                                                                │
│ 2022-12-07 14:54:19.2868 info    agent-configs : Successfully rolled out my-nginx.kube-system                                                                                │
│ 2022-12-07 14:54:19.3669 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:19.3680 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:22.8172 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:22.8208 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:23.2490 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:23.2507 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:23.2594 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:23.2607 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:23.2665 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:23.2674 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully
```
<pre class="lang-bash prettyprint-override"><code>telepresence status
User Daemon: Running
  Version           : v2.9.4 (api 3)
  Executable        : /usr/local/bin/telepresence
  Install ID        : *****
  Status            : Connected
  Kubernetes server : https://*****
  Kubernetes context: *****
  Intercepts        : 0 total
Root Daemon: Running
  Version: v2.9.4 (api 3)
  DNS    :
    Remote IP       : 127.0.0.1
    Exclude suffixes: [.com .io .net .org .ru]
    Include suffixes: []
    Timeout         : 8s
  Also Proxy : (0 subnets)
  Never Proxy: (1 subnets)
    - *****
Ambassador Cloud:
  Status      : Logged in
  User ID     : *****
  Account ID  : *****
  User Name   : *****
  Email       : *****
  Account Name: *****
</code>```

Am I missing something?

Body:
I installed telepresence by using the curl command on a Kubernetes cluster running on GKE. I can correctly interact with other services deployed in the cluster and I can intercept services (like the one in this post) running on the default namespace but when the same service is deployed on the kube-system namespace I can't intercept it. I don't get any useful errors, just a timeout when Telepresence tries to install the agent.

I am already aware of a similar issue happening on GKE when some firewall ports are not correctly opened. I followed already the docs and I have already opened those ports. That's how I managed to run the same service on the default namespace correctly.

Steps to reproduce the behavior:

I started an Nginx service with the following manifest. I have created a docker image gsantoro/my-nginx:latest which is a modified version of Nginx just to expose port 3000 instead of 80

apiVersion: apps/v1
kind: Deployment
metadata:
  name:  nginx
  labels:
    app:  nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1
  template:
    metadata:
      labels:
        app:  nginx
    spec:
      containers:
      - name:  nginx
        image: gsantoro/my-nginx:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: default
spec:
  selector:
    app: nginx
  type: ClusterIP
  ports:
  - protocol: TCP
    port: 3000

When I run 'telepresence intercept nginx --namespace kube-system --port 49729:3000`, I see 'telepresence intercept: error: request timed out while waiting for agent my-nginx.kube-system to arrive'

Versions:

Output of telepresence version

❯ telepresence version
Enhanced Client: v2.9.4
Root Daemon    : v2.9.4
User Daemon    : v2.9.4
Traffic Manager: v2.9.4

Operating system of workstation running telepresence commands. MacOs v12.6.1, Apple M1 Max chipset

Kubernetes environment and Version [e.g. Minikube, bare metal, Google Kubernetes Engine]. v1.24.7-gke.900 on GKE

Additional context:
logs from traffic-manager:

│ 2022-12-07 14:54:19.1972 debug   httpd/conn=127.0.0.1:8081 : PrepareIntercept called : session_id="203deb44-fe3a-4e28-a53a-e3739c7e5cb3"                                                                           │
│ 2022-12-07 14:54:19.2188 debug   agent-configs : MODIFIED telepresence-agents.kube-system                                                                                │
│ 2022-12-07 14:54:19.2189 debug   agent-configs : add my-nginx.kube-system                                                                                │
│ 2022-12-07 14:54:19.2868 info    agent-configs : Successfully rolled out my-nginx.kube-system                                                                                │
│ 2022-12-07 14:54:19.3669 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:19.3680 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:22.8172 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:22.8208 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:23.2490 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:23.2507 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:23.2594 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:23.2607 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully                                                                                │
│ 2022-12-07 14:54:23.2665 debug   agent-injector/conn=10.24.0.9:8443 : Received webhook request...                                                                                │
│ 2022-12-07 14:54:23.2674 debug   agent-injector/conn=10.24.0.9:8443 : Webhook request handled successfully

telepresence status
User Daemon: Running
  Version           : v2.9.4 (api 3)
  Executable        : /usr/local/bin/telepresence
  Install ID        : *****
  Status            : Connected
  Kubernetes server : https://*****
  Kubernetes context: *****
  Intercepts        : 0 total
Root Daemon: Running
  Version: v2.9.4 (api 3)
  DNS    :
    Remote IP       : 127.0.0.1
    Exclude suffixes: [.com .io .net .org .ru]
    Include suffixes: []
    Timeout         : 8s
  Also Proxy : (0 subnets)
  Never Proxy: (1 subnets)
    - *****
Ambassador Cloud:
  Status      : Logged in
  User ID     : *****
  Account ID  : *****
  User Name   : *****
  Email       : *****
  Account Name: *****

Am I missing something?


问:
Cypress test do not run using Jenkins but run fine from command line. Throws Failed to construct 'URL': Invalid URL Error
We run our E2E tests against Chrome 70 on windows machine in headed mode using command npm install && cypress run --browser chrome --headed "--config" "baseUrl=http:serveraddress:8080" "--env" "Host=serveraddress". The tests connect to a server url hosted on a Linux machine (hosted on our network). We recently upgraded our cypress version from 7.7.0 to 11.2.0 and the tests started failing where the tests fail at visit step as shown in the img uploaded. We tried to debug, logged into these machines from the profile and manually ran them from command prompt and they seem to work fine. But when we kick off our Jenkins build, they start failing.

We did add the command set CYPRESS_RUN_BINARY=C:\Users\Administrator\AppData\Local\Cypress\Cache\11.2.0\Cypress\Cypress.exe before run the cypress cases in the jenkins job. But that did not fix the error. The Jenkins build goes fine for the machines where the tests connect to localhost url. We are using cy.visit("/") in our beforeAll block to visit the page and here is our jenkins script below:

```<code>env.cypressFFBaseUrl=cypressFFBaseUrl.trim()
     env.FFHost=FFHost.trim()
     bat  script: """
                                 setlocal
                                 set ERRORLEVEL=0
                                 set PATH=C:\\Program Files (x86)\\OpenJDK\\jdk-8.0.262.10-hotspot\\bin;$PATH
                                 set CYPRESS_BASE_URL=${cypressFFBaseUrl};
                                 set Host=${FFHost};
                                 set CYPRESS_RUN_BINARY=C:\\Users\\Admin\\AppData\\Local\\Cypress\\Cache\\11.2.0\\Cypress\\Cypress.exe
                                 cd $WORKSPACE/ui/e2e
                                 npm run cy:run-firefox-headed -- --config baseUrl=${cypressFFBaseUrl} --env Host=${FFHost}  >> e2e_err.log
     """
</code>```

Please help!

Body:
We run our E2E tests against Chrome 70 on windows machine in headed mode using command npm install && cypress run --browser chrome --headed "--config" "baseUrl=http:serveraddress:8080" "--env" "Host=serveraddress". The tests connect to a server url hosted on a Linux machine (hosted on our network). We recently upgraded our cypress version from 7.7.0 to 11.2.0 and the tests started failing where the tests fail at visit step as shown in the img uploaded. We tried to debug, logged into these machines from the profile and manually ran them from command prompt and they seem to work fine. But when we kick off our Jenkins build, they start failing.

We did add the command set CYPRESS_RUN_BINARY=C:\Users\Administrator\AppData\Local\Cypress\Cache\11.2.0\Cypress\Cypress.exe before run the cypress cases in the jenkins job. But that did not fix the error. The Jenkins build goes fine for the machines where the tests connect to localhost url. We are using cy.visit("/") in our beforeAll block to visit the page and here is our jenkins script below:

env.cypressFFBaseUrl=cypressFFBaseUrl.trim()
     env.FFHost=FFHost.trim()
     bat  script: """
                                 setlocal
                                 set ERRORLEVEL=0
                                 set PATH=C:\\Program Files (x86)\\OpenJDK\\jdk-8.0.262.10-hotspot\\bin;$PATH
                                 set CYPRESS_BASE_URL=${cypressFFBaseUrl};
                                 set Host=${FFHost};
                                 set CYPRESS_RUN_BINARY=C:\\Users\\Admin\\AppData\\Local\\Cypress\\Cache\\11.2.0\\Cypress\\Cypress.exe
                                 cd $WORKSPACE/ui/e2e
                                 npm run cy:run-firefox-headed -- --config baseUrl=${cypressFFBaseUrl} --env Host=${FFHost}  >> e2e_err.log
     """

Please help!


问:
SCSS and @layers - how to make them work together?
In my styles.scss file I have few imports with generic classes and functions:

@import "css/generic.scss";
@import "css/functions.scss";
@import "css/layout.scss";
```
<p>I'm trying to make those imports work in layers. I've tried the following:</p>
```@import "css/generic.scss" layer(utilities);
```
```@layer utilitites {
  @import "css/generic.scss";
}
```

or wrapping all CSS code in the imports.

Every time I get the same error - that something from functions file is not available to be used later on. Usually it's a mixin defined in functions.scss that is being used in layout.scss but it's not available.

Is there a way to make it work? I'm guessing it's because of the SCSS components like mixins having some kind of scope?

Body:
In my styles.scss file I have few imports with generic classes and functions:

@import "css/generic.scss";
@import "css/functions.scss";
@import "css/layout.scss";

I'm trying to make those imports work in layers. I've tried the following:

@import "css/generic.scss" layer(utilities);

@layer utilitites {
  @import "css/generic.scss";
}

or wrapping all CSS code in the imports.

Every time I get the same error - that something from functions file is not available to be used later on. Usually it's a mixin defined in functions.scss that is being used in layout.scss but it's not available.

Is there a way to make it work? I'm guessing it's because of the SCSS components like mixins having some kind of scope?


问:
many dynamic tasks crashing airflow
I have created an airflow DAG that needs to create around 200k instances of a dynamic task. The problem is that once the scheduler gets the list of parameters it is getting stuck without any further errors. It is staying in the state of successfully finished the first task and no status of the second dynamic task. I also do not notice any higher cpu or memory usage. I have tried both standalone and with a Postgres backend.

I created a minimal example to reproduce the behavior.

```<code>from datetime import datetime
from typing import List

from airflow import DAG
from airflow.decorators import task

with DAG(dag_id="example", start_date=datetime(2022, 3, 4), schedule=None) as dag:
   @task
   def get_list() -> List[int]:
      return [1] * 200000

   @task
   def dynamic_task(x: int):
      return x

   added_values = dynamic_task.expand(x=get_list())
</code>```

I would really appreciate any help to solve this issue.

Title: many dynamic tasks crashing airflow

Body:
I have created an airflow DAG that needs to create around 200k instances of a dynamic task. The problem is that once the scheduler gets the list of parameters it is getting stuck without any further errors. It is staying in the state of successfully finished the first task and no status of the second dynamic task. I also do not notice any higher cpu or memory usage. I have tried both standalone and with a Postgres backend.

I created a minimal example to reproduce the behavior.

from datetime import datetime
from typing import List

from airflow import DAG
from airflow.decorators import task

with DAG(dag_id="example", start_date=datetime(2022, 3, 4), schedule=None) as dag:
   @task
   def get_list() -> List[int]:
      return [1] * 200000

   @task
   def dynamic_task(x: int):
      return x

   added_values = dynamic_task.expand(x=get_list())

I would really appreciate any help to solve this issue.


问:
How to add a primary key on a bucket in couchbase?
I have created a couchbase cluster with 1 node.

and I have 2 buckets with data in it.

when i'm trying to run a select command in the query section, i am getting this error

I have tried a few ways to create primary indexes, but none seems to works.

This is the error i get when i try to create a promary key.

```<code>[
  {
    "code": 5000,
    "msg": "GSI CreatePrimaryIndex() - cause: Index creation for index List2_index, bucket List2, scope _default, collection _default cannot start. Reason: Fails to create index.  There is no available index service that can process this request at this time. Index Service can be in bootstrap, recovery, or non-reachable. Please retry the operation at a later time..",
    "query": "CREATE PRIMARY INDEX `List2_index` ON `List2` ;"
  }
]
</code>```

Body:
I have created a couchbase cluster with 1 node.

and I have 2 buckets with data in it.

when i'm trying to run a select command in the query section, i am getting this error

I have tried a few ways to create primary indexes, but none seems to works.

This is the error i get when i try to create a promary key.

[
  {
    "code": 5000,
    "msg": "GSI CreatePrimaryIndex() - cause: Index creation for index List2_index, bucket List2, scope _default, collection _default cannot start. Reason: Fails to create index.  There is no available index service that can process this request at this time. Index Service can be in bootstrap, recovery, or non-reachable. Please retry the operation at a later time..",
    "query": "CREATE PRIMARY INDEX `List2_index` ON `List2` ;"
  }
]


问:
Visual Studios DevExpress error LC0000: 'Method 'OnDirectXPaintDisabled'
I am trying to run a build but keep getting this error-

1>LC : error LC0000: 'Method 'OnDirectXPaintDisabled' in type 'DevExpress.XtraGrid.GridControl' from assembly 'DevExpress.XtraGrid.v18.1, Version=18.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a' does not have an implementation.'

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Anyone knows what needs fixing here?

I am trying to load a previous software build which uses DevExpress front end. I just tried to run the build and was expecting to see this front end to load up.


问:
Program stuck while sorting 20million element with this quickSort
i have to sort an array of a specific struct called Data. There are 3 field but for now i want to sort only for string field. The array is filled by reading from a file. So far no problem, if i read 8k row from the file the array is sorted correctly and the value can be printed. But the request is to sort a file with 20milion row. When i try to run with this file it seems to stuck but doesn't give segmentation fault neither compiling with address sanitaizer. What would be the problem with this quickSort?

Why with a pivot in the first element it doesn't sort the array?Did i miss something in the algorithm?

I just try to change the pivot in the function but if i take the first element or the middle too, it doesn't sort correctly.

```<code>typedef struct _data
{
    int id;
    char field1[50];
    int field2;
    float field3;
}Data;

typedef struct _GenericArray{
  void **array;
  int size;
  int capacity;
  int (*compare)(void*, void*);
}GenericArray;

void swap(Data* x,Data* y){
     if(x == NULL){
        printf("Can't swap a NULL element(x is NULL)!");
        exit(EXIT_FAILURE);
    }
    if(y == NULL){
        printf("Can't swap a NULL element(y is NULL)!");
        exit(EXIT_FAILURE);
    }
    Data temp = *x;
    *x = *y;
    *y=temp;
}

int partition(GenericArray* generic_array,int first,int last){

    if(generic_array == NULL){
        printf("Can't do quickSort in an empty array!");
        exit(EXIT_FAILURE);
    }
    Data *pivot = generic_array->array[last];
    int i = first;

    for (int j = first; j < last ;j++)
    {
        if(generic_array->compare(generic_array->array[j],pivot)<=0){
            swap(generic_array->array[i],generic_array->array[j]);
            i++;
        }
    }

    swap(generic_array->array[i],generic_array->array[last]);

    return i;
}

int quick_sort(GenericArray* generic_array,int first,int last){

    if(generic_array == NULL){
        //printf("Can't do quickSort in an empty array!");
        return -1;
    }

    if(first<last){
        int p = partition(generic_array,first,last);
        quick_sort(generic_array,first,p-1);
        quick_sort(generic_array,p+1,last);
    }
    return 0;
}

int compare_string(void* item1, void* item2){  //function in generic_array->compare
    Data *a = (Data*)item1;
    Data *b = (Data*)item2;
    if(strcmp(a->field1,b->field1)==0) return 0;
    else if(strcmp(a->field1,b->field1)>0) return 1;
    else return -1;

}
</code>```

Body:
i have to sort an array of a specific struct called Data. There are 3 field but for now i want to sort only for string field. The array is filled by reading from a file. So far no problem, if i read 8k row from the file the array is sorted correctly and the value can be printed. But the request is to sort a file with 20milion row. When i try to run with this file it seems to stuck but doesn't give segmentation fault neither compiling with address sanitaizer. What would be the problem with this quickSort?

Why with a pivot in the first element it doesn't sort the array?Did i miss something in the algorithm?

I just try to change the pivot in the function but if i take the first element or the middle too, it doesn't sort correctly.

typedef struct _data
{
    int id;
    char field1[50];
    int field2;
    float field3;
}Data;

typedef struct _GenericArray{
  void **array;
  int size;
  int capacity;
  int (*compare)(void*, void*);
}GenericArray;

void swap(Data* x,Data* y){
     if(x == NULL){
        printf("Can't swap a NULL element(x is NULL)!");
        exit(EXIT_FAILURE);
    }
    if(y == NULL){
        printf("Can't swap a NULL element(y is NULL)!");
        exit(EXIT_FAILURE);
    }
    Data temp = *x;
    *x = *y;
    *y=temp;
}

int partition(GenericArray* generic_array,int first,int last){

    if(generic_array == NULL){
        printf("Can't do quickSort in an empty array!");
        exit(EXIT_FAILURE);
    }
    Data *pivot = generic_array->array[last];
    int i = first;

    for (int j = first; j < last ;j++)
    {
        if(generic_array->compare(generic_array->array[j],pivot)<=0){
            swap(generic_array->array[i],generic_array->array[j]);
            i++;
        }
    }

    swap(generic_array->array[i],generic_array->array[last]);

    return i;
}

int quick_sort(GenericArray* generic_array,int first,int last){

    if(generic_array == NULL){
        //printf("Can't do quickSort in an empty array!");
        return -1;
    }

    if(first<last){
        int p = partition(generic_array,first,last);
        quick_sort(generic_array,first,p-1);
        quick_sort(generic_array,p+1,last);
    }
    return 0;
}

int compare_string(void* item1, void* item2){  //function in generic_array->compare
    Data *a = (Data*)item1;
    Data *b = (Data*)item2;
    if(strcmp(a->field1,b->field1)==0) return 0;
    else if(strcmp(a->field1,b->field1)>0) return 1;
    else return -1;

}


问:
MapReduce Key type mismatch
I am new to MapReduce, in my MapReduce program I got a key type mismatch error:
Error: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.LongWritable, received org.apache.hadoop.io.Text can someone tell why I got this error? Thanks!

Main code:

Mapper:

Reducer:

Title: MapReduce Key type mismatch


问:
MUI: You have provided an out-of-range value `18:00` for the select component
I use react with Mui;

```<code><Select
  disabled={disable}
  renderValue={(value) => renderValue(value as number)}
  size="small"
  value={object.time}
  onChange={({ target }) => onChange(target.value as string)}
>
  {hours.map((hour) => (
    <MenuItem key={hour.id} value={hour.val1}>
      <ListItemText title={hour.time} primary={hour.time} />
    </MenuItem>
  ))}
</Select>
</code>```

I tried using many solutions like add defaultValue="" or stringify the value but none helped

Body:
I use react with Mui;

<Select
  disabled={disable}
  renderValue={(value) => renderValue(value as number)}
  size="small"
  value={object.time}
  onChange={({ target }) => onChange(target.value as string)}
>
  {hours.map((hour) => (
    <MenuItem key={hour.id} value={hour.val1}>
      <ListItemText title={hour.time} primary={hour.time} />
    </MenuItem>
  ))}
</Select>

I tried using many solutions like add defaultValue="" or stringify the value but none helped


问:
Constructing while loop that involves reading in a text file and determining if the term "ERROR" is present
I would like to integrate the following into a while loop: I am using a function that produces a dataset for a model (line 2). I run the model afterwards (line 5). I then read in the output of said model ("meanimpactscript.out") (line 8) and determine of the term "ERROR" is present (line 11). If the term ERROR is present, I would like to continually repeat lines 2-11 (generating a fresh dataset each time in line 2, running the model on it, reading in the output) until ERROR is no longer present in the model output. Would appreciate any help.

Below is the code and pseudocode for what I would like to include in the while loop:

```<code>1 #generate data for model
2 aMNLFA.sample(ob)
3
4 #run model
5 runModels("meanimpactscript.inp")
6
7 #read in the output
8 txt <- readLines("meanimpactscript.out")
9
10 #determine if the term "ERROR" is present (ix empty if not present)
11 ix <- grep("ERROR", txt)
12
13 #if the word "ERROR" is present, repeat lines 2-11 until "ERROR" is no longer present.
</code>```

Body:
I would like to integrate the following into a while loop: I am using a function that produces a dataset for a model (line 2). I run the model afterwards (line 5). I then read in the output of said model ("meanimpactscript.out") (line 8) and determine of the term "ERROR" is present (line 11). If the term ERROR is present, I would like to continually repeat lines 2-11 (generating a fresh dataset each time in line 2, running the model on it, reading in the output) until ERROR is no longer present in the model output. Would appreciate any help.

Below is the code and pseudocode for what I would like to include in the while loop:

1 #generate data for model
2 aMNLFA.sample(ob)
3
4 #run model
5 runModels("meanimpactscript.inp")
6
7 #read in the output
8 txt <- readLines("meanimpactscript.out")
9
10 #determine if the term "ERROR" is present (ix empty if not present)
11 ix <- grep("ERROR", txt)
12
13 #if the word "ERROR" is present, repeat lines 2-11 until "ERROR" is no longer present.


问:
How to connect mongodb to other devices connected to a MERN application
In college, we had a group project, making a MERN application. It works fine on my laptop, but if any other device connects to the IP address and port number, all that comes up is the client-side React to stuff.

How could I have the data from MongoDB show up on other connected devices?

On my phone, I tried connecting to the port the laptop was using, hoping the phone would also display the information that the laptop did. It did not.


问:
How to multiprocess from request to SQL (SQLite)
So I want to make requests to an api, transform the data somewhat and upload it to an SQLite database. Since this is generally a slow process, especially when the api may take around 5 seconds per request, I'm looking to use multiprocessing, mainly to send at least one new request while processing the previous. However, I tried some things and found it a bit tricky with the upload to SQL not to lose anything.

Simplified code example:

import sqlite3, requests
import pandas as pd
con = sqlite3.Connection('testDB')
cur = con.cursor()
urllist = [url1,url2,…urln]

def getData(url):
    r = requests.get(url)
    data = pd.read_json(r.text)
    return data
def uploadData(row,cur,con):
    cur.execute(f"INSERT OR REPLACE INTO test VALUES {row['valA']}, '{row['valB']}');")
    con.commit()
def dataLoop(url,cur,con):
    data = getData(url)
    data.apply(uploadData,cur=cur,con=con,axis=1)

for url in urllist:
    dataLoop(url,cur,con)
```

So, conceptually, I would like to know which kind of multiprocessing to use, which modules would fit this and how to make sure not to lose data (making sure to only work on new data once the old data has been fully processed and uploaded).

Body:
So I want to make requests to an api, transform the data somewhat and upload it to an SQLite database. Since this is generally a slow process, especially when the api may take around 5 seconds per request, I'm looking to use multiprocessing, mainly to send at least one new request while processing the previous. However, I tried some things and found it a bit tricky with the upload to SQL not to lose anything.

Simplified code example:

import sqlite3, requests
import pandas as pd
con = sqlite3.Connection('testDB')
cur = con.cursor()
urllist = [url1,url2,…urln]

def getData(url):
    r = requests.get(url)
    data = pd.read_json(r.text)
    return data
def uploadData(row,cur,con):
    cur.execute(f"INSERT OR REPLACE INTO test VALUES {row['valA']}, '{row['valB']}');")
    con.commit()
def dataLoop(url,cur,con):
    data = getData(url)
    data.apply(uploadData,cur=cur,con=con,axis=1)

for url in urllist:
    dataLoop(url,cur,con)

So, conceptually, I would like to know which kind of multiprocessing to use, which modules would fit this and how to make sure not to lose data (making sure to only work on new data once the old data has been fully processed and uploaded).


问:
Java import AWS Access Keys from Session
I am writing a script in Java that calls an API Gateway endpoint. However in order for my script to work I need to it pass the AWS access keys and session token. Currently my code works but the AWS keys are hard-coded. How can I pass the keys without hardcoding them? Here is my current code:

```<code>import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import auth.AWS4SignerBase;
import auth.AWS4SignerForAuthorizationHeader;
import util.HttpUtils;

class Main {
  public static void main(String[] args) throws Exception {

    URL endpointUrl = new URL("https://lmno456.execute-api.us-east-1.amazonaws.com/prod/controlplane/model/a1");

    var regionName = "us-east-1";
    var awsAccessKey = "abc123";
    var awsSecretKey = "def234";
    var awsSessionToken = "xyz789==";

    // for a simple GET, we have no body so supply the precomputed 'empty' hash
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("x-amz-content-sha256", AWS4SignerBase.EMPTY_BODY_SHA256);
    headers.put("X-Amz-Security-Token", awsSessionToken);

    AWS4SignerForAuthorizationHeader signer = new AWS4SignerForAuthorizationHeader(endpointUrl, "GET", "execute-api", regionName);

    String authorization = signer.computeSignature(headers,
                                            null, // no query parameters
                                            AWS4SignerBase.EMPTY_BODY_SHA256,
                                            awsAccessKey,
                                            awsSecretKey);

    headers.put("Authorization", authorization);
    String response = HttpUtils.invokeHttpRequest(endpointUrl, "GET", headers, null);
    System.out.println("--------- Response content ---------");
    System.out.println(response);
    System.out.println("------------------------------------");
  }
}
</code>```

Ideally I'm looking for something similar to python's boto3 credentials = session.get_credentials() to retrieve the access and session keys. I am doing this for an AWS lambda function.

Body:
I am writing a script in Java that calls an API Gateway endpoint. However in order for my script to work I need to it pass the AWS access keys and session token. Currently my code works but the AWS keys are hard-coded. How can I pass the keys without hardcoding them? Here is my current code:

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import auth.AWS4SignerBase;
import auth.AWS4SignerForAuthorizationHeader;
import util.HttpUtils;

class Main {
  public static void main(String[] args) throws Exception {

    URL endpointUrl = new URL("https://lmno456.execute-api.us-east-1.amazonaws.com/prod/controlplane/model/a1");

    var regionName = "us-east-1";
    var awsAccessKey = "abc123";
    var awsSecretKey = "def234";
    var awsSessionToken = "xyz789==";

    // for a simple GET, we have no body so supply the precomputed 'empty' hash
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("x-amz-content-sha256", AWS4SignerBase.EMPTY_BODY_SHA256);
    headers.put("X-Amz-Security-Token", awsSessionToken);

    AWS4SignerForAuthorizationHeader signer = new AWS4SignerForAuthorizationHeader(endpointUrl, "GET", "execute-api", regionName);

    String authorization = signer.computeSignature(headers,
                                            null, // no query parameters
                                            AWS4SignerBase.EMPTY_BODY_SHA256,
                                            awsAccessKey,
                                            awsSecretKey);

    headers.put("Authorization", authorization);
    String response = HttpUtils.invokeHttpRequest(endpointUrl, "GET", headers, null);
    System.out.println("--------- Response content ---------");
    System.out.println(response);
    System.out.println("------------------------------------");
  }
}

Ideally I'm looking for something similar to python's boto3 credentials = session.get_credentials() to retrieve the access and session keys. I am doing this for an AWS lambda function.


问:
parsing http referer in cloudwatch
I am currently running a query in cloudwatch aws but I can't figure out how / if I actually can parse information about requests http referer data on an application im running. Is anyone able to asssit me on this?

I read cloudwatch documentation and tried running some querys blindly but unable to parse any http referer data

Title: parsing http referer in cloudwatch


问:
arabic in kivy in text in put with app in pyhon use bidi and arabic reshaper
I tried a way to write in the Arabic language in textinput  in the Kivi application, but I encountered a problem

try this code

```<code><Textinp>
    RelativeLayout:

        TextInput:
            id: main_input
            size_hint:0.8,0.1
            font_name: "arial"
            font_size: "15sp"
            halign: "right"

        TextInput:
            opacity: 0
            size_hint:0.8,0.1
            font_name: "arial"
            font_size: "15sp"
            halign: "right"
            on_text: root.ids["main_input"].text = get_display(reshaper.reshape(self.text))
</code>```

and this error after crash >>>

```<code>     on_text: root.ids["main_input"].text = get_display(reshaper.reshape(self.text))
 NameError: name 'get_display' is not defined
</code>```

i am import all lib.like

```<code>from bidi.algorithm import get_display

</code>```

Body:
I tried a way to write in the Arabic language in textinput  in the Kivi application, but I encountered a problem

try this code

<Textinp>
    RelativeLayout:

        TextInput:
            id: main_input
            size_hint:0.8,0.1
            font_name: "arial"
            font_size: "15sp"
            halign: "right"

        TextInput:
            opacity: 0
            size_hint:0.8,0.1
            font_name: "arial"
            font_size: "15sp"
            halign: "right"
            on_text: root.ids["main_input"].text = get_display(reshaper.reshape(self.text))

and this error after crash >>>

     on_text: root.ids["main_input"].text = get_display(reshaper.reshape(self.text))
 NameError: name 'get_display' is not defined

i am import all lib.like

from bidi.algorithm import get_display


问:
Nasm: invalid combination of opcode and operands
I'm trying to put my .asm (version x8086) file in the nasm And I get

```<code>nums.asm:7: error: invalid combination of opcode and operands
nums.asm:9: error: invalid combination of opcode and operands
</code>```
```<code>JMP MAIN
ADDRESS_MEMORY dw 0
JUMPS dw 0
DIVIDE equ 50

MAIN:
    mov ADDRESS_MEMORY, ax ; <- Error
    JMP RANDOM_NUMBER
    mov JUMPS, cx ; <-    Error
</code>```

What is the issue? Help. I really need to use this like that. How can I move the value to the global variables without error?

Body:
I'm trying to put my .asm (version x8086) file in the nasm And I get

nums.asm:7: error: invalid combination of opcode and operands
nums.asm:9: error: invalid combination of opcode and operands

JMP MAIN
ADDRESS_MEMORY dw 0
JUMPS dw 0
DIVIDE equ 50

MAIN:
    mov ADDRESS_MEMORY, ax ; <- Error
    JMP RANDOM_NUMBER
    mov JUMPS, cx ; <-    Error

What is the issue? Help. I really need to use this like that. How can I move the value to the global variables without error?


问:
Mahalanobis distance in fastslam?
I'm very new to slam in general. I have a question regarding if the Maximum likelihood methods in the fastslam algorithm utilise mahalanobis distance, because according to this text: http://robots.stanford.edu/papers/Thrun03g.pdf , it states at page 18 for regular EKF SLAM that it utilises the mahalanobis distance to determine the most likely landmark:

However when the same conditional probability is presented for the fastslam algorithm, but now since it's particles each particle will have its own hypothesis of the state variables, they never mention the mahalanobis distance term, even though the algorithm utilises the covariance matrix for features (page 18):

See page 21 for pseudocode of the fastslam1 algorithm.

Does the fastslam 1.0 algorithm presented in the text utilise mahalanobis distance to calculate the most likely corresponding landmark to the current measurement we have? Why? Why not? Is there a way to incorporate mahalanobis distance to a data association ML-function in fastslam in that case? I may have uttered some things wrong here so feel free to correct me.

Title: Mahalanobis distance in fastslam?


问:
Rendering a Quarto blog post trips an error when reading in a brms file object
First, I'll apologize for not having a fuller reproducable example, but I'm not entirely sure how to go about that given the various layers to the question/problem.

I'm moving a blog over from Blogdown to a new Quarto-based website and blog. I have three saved brms object files that I'm trying to read into a code chunk in one of the posts. The code chunks work fine when I run them manually, but when I try to render the blog post I get the following error:

```<code>Quitting from lines 75-86 (tables-modelsummary-brms.qmd)
Error in stri_replace_all_charclass(str, "[\\u0020\\r\\n\\t]", " ", merge = TRUE) :
  invalid UTF-8 byte sequence detected; try calling stri_enc_toutf8()
Calls: .main ... stri_trim -> stri_trim_both -> stri_replace_all_charclass
Execution halted
</code>```

I've checked the primary data frame contained in the brms model object and all of the character vectors there are valid UTF-8 vectors. These models objects can be quite large, so it's possible I'm missing something buried deep within the model object, but so far it's nothing apparent.

I tried re-running the models again to ensure that the model objects' files weren't corrupted, and also to make sure that the encoding issue wasn't somehow introduced the last time they were run, which would have been on a Windows machine and a different version of brms.

I've also moved the brms files around to different directories to see if it's a file path issue. The same error comes up regardless of whether the files are in the same folder as the blog post qmd file or in a parent directory file I use for storing site data.

I've also migrated several other posts to the new Quarto site successfully, and some of them also contain R code, but it's all rendering without a problem.

Finally, I don't quite understand how to implement the suggersted alternate function found in the error message either.

Body:
First, I'll apologize for not having a fuller reproducable example, but I'm not entirely sure how to go about that given the various layers to the question/problem.

I'm moving a blog over from Blogdown to a new Quarto-based website and blog. I have three saved brms object files that I'm trying to read into a code chunk in one of the posts. The code chunks work fine when I run them manually, but when I try to render the blog post I get the following error:

Quitting from lines 75-86 (tables-modelsummary-brms.qmd)
Error in stri_replace_all_charclass(str, "[\\u0020\\r\\n\\t]", " ", merge = TRUE) :
  invalid UTF-8 byte sequence detected; try calling stri_enc_toutf8()
Calls: .main ... stri_trim -> stri_trim_both -> stri_replace_all_charclass
Execution halted

I've checked the primary data frame contained in the brms model object and all of the character vectors there are valid UTF-8 vectors. These models objects can be quite large, so it's possible I'm missing something buried deep within the model object, but so far it's nothing apparent.

I tried re-running the models again to ensure that the model objects' files weren't corrupted, and also to make sure that the encoding issue wasn't somehow introduced the last time they were run, which would have been on a Windows machine and a different version of brms.

I've also moved the brms files around to different directories to see if it's a file path issue. The same error comes up regardless of whether the files are in the same folder as the blog post qmd file or in a parent directory file I use for storing site data.

I've also migrated several other posts to the new Quarto site successfully, and some of them also contain R code, but it's all rendering without a problem.

Finally, I don't quite understand how to implement the suggersted alternate function found in the error message either.


问:
Passing specific delivery instructions through to ChowNow from online ordering link
I'm helping develop an online ordering process for a local business, and they are offering food delivery to their location from specific partnered restaurants. The problem we're looking to solve is making the experience as smooth as possible for the user, so we're aiming to fill out these specific data fields to make the process smoother. They have QR codes on their tables, that link directly to their websites ordering page, from there the user can select from a few local restaurants, and are linked to their online ChowNow menus.

Does anyone have any experience using ChowNow, and knows if there is any way to pass off specific delivery instructions to ChowNow, specifically an address, from the link provided to the users from the QR code on their table?

We haven't found anything too helpful on this problem from ChowNow's official documentation or support. There are alternate ways that we have in mind to solve this problem if need be, but this is the desired solution from the client, and we would like to have stick with this method if possible.


问:
Aggrid update/delete row and save to DataFrame in local folder
I'me new on this forum, and sorry If I make some mistakes.

I have one question and It's about using Python, Streamlit and Aggrid.

In the previous days, I've tried to make some code to enable users to delete a row in Aggrid table, and to update that new state (state without deleted row) in a Dataframe saved in local folder. But, when I check an row, click delete button, row disapear in aggrid table, but after reload of streamlit page everything back in the state as before deleting row (deleted row is in table again). Also, the new state (state without deleted row) isn't saved in Dataframe in local folder. Can you pls check my code bellow to see what could be a problem?

Also, what is the syntax to enable user to update an row in aggrid table, and also to save it to Dataframe in local folder also?

Thx in advance,

best regards,

Adnan

```<code>import js as js
import pandas as pd
import streamlit as st
from st_aggrid import AgGrid, GridOptionsBuilder, JsCode, GridUpdateMode

file_dir = r'C:\Users\....\'
file_name = 'Wi_Fi_DB.xlsx'
filepath = f"{file_dir}/{file_name}"

def display_table(df: pd.DataFrame) -> AgGrid:
    sel_mode = st.selectbox('Choose row or rows', options=['single', 'multiple'])
    gb = GridOptionsBuilder.from_dataframe(df)
    gb.configure_selection('single', use_checkbox=True)
    gb.configure_selection(selection_mode=sel_mode, use_checkbox=True)

    string_to_delete = "\n\n function(e) { \n \
    let api = e.api; \n \
     let sel = api.getSelectedRows(); \n \
    api.applyTransaction({remove: sel}); \n \
        }; \n \n"

    cell_button_delete = JsCode('''
        class BtnCellRenderer {
            init(params) {
                console.log(params.api.getSelectedRows());
                this.params = params;
                this.eGui = document.createElement('div');
                this.eGui.innerHTML = `
                 <span>
                    <style>
                    .btn {
                      background-color: #F94721;
                      border: none;
                      color: white;
                      font-size: 10px;
                      font-weight: bold;
                      height: 2.5em;
                      width: 8em;
                      cursor: pointer;
                    }

                    .btn:hover {
                      background-color: #FB6747;
                    }
                    </style>
                    <button id='click-button'
                        class="btn"
                        >🗑 Delete</button>
                 </span>
              `;
            }

            getGui() {
                return this.eGui;
            }

        };
        ''')

    gb.configure_column('Delete', headerTooltip='Click on Button to remove row',
                        editable=False, filter=False, onCellClicked=JsCode(string_to_delete),
                        cellRenderer=cell_button_delete,
                        autoHeight=True, suppressMovable='true')

    gb.configure_default_column(editable=True)
    gb.configure_selection(use_checkbox=True, selection_mode="multiple")
    grid_options = gb.build()
    grid_return = AgGrid(df, gridOptions=grid_options, allow_unsafe_jscode=True, theme="streamlit")

    with st.form(file_name):
        if JsCode(string_to_delete):
            df = grid_return["data"]
            df = df.append(df, ignore_index=True)
            df.to_excel(filepath, index=False)

df = pd.read_excel("Wi_Fi_DB.xlsx")
st.info("Select a row to remove it")
response = display_table(df)
df.to_excel("Wi_Fi_DB.xlsx", index=False)

</code>```

Body:
I'me new on this forum, and sorry If I make some mistakes.

I have one question and It's about using Python, Streamlit and Aggrid.

In the previous days, I've tried to make some code to enable users to delete a row in Aggrid table, and to update that new state (state without deleted row) in a Dataframe saved in local folder. But, when I check an row, click delete button, row disapear in aggrid table, but after reload of streamlit page everything back in the state as before deleting row (deleted row is in table again). Also, the new state (state without deleted row) isn't saved in Dataframe in local folder. Can you pls check my code bellow to see what could be a problem?

Also, what is the syntax to enable user to update an row in aggrid table, and also to save it to Dataframe in local folder also?

Thx in advance,

best regards,

Adnan

import js as js
import pandas as pd
import streamlit as st
from st_aggrid import AgGrid, GridOptionsBuilder, JsCode, GridUpdateMode

file_dir = r'C:\Users\....\'
file_name = 'Wi_Fi_DB.xlsx'
filepath = f"{file_dir}/{file_name}"

def display_table(df: pd.DataFrame) -> AgGrid:
    sel_mode = st.selectbox('Choose row or rows', options=['single', 'multiple'])
    gb = GridOptionsBuilder.from_dataframe(df)
    gb.configure_selection('single', use_checkbox=True)
    gb.configure_selection(selection_mode=sel_mode, use_checkbox=True)

    string_to_delete = "\n\n function(e) { \n \
    let api = e.api; \n \
     let sel = api.getSelectedRows(); \n \
    api.applyTransaction({remove: sel}); \n \
        }; \n \n"

    cell_button_delete = JsCode('''
        class BtnCellRenderer {
            init(params) {
                console.log(params.api.getSelectedRows());
                this.params = params;
                this.eGui = document.createElement('div');
                this.eGui.innerHTML = `

                    <button id='click-button'
                        class="btn"
                        >🗑 Delete</button>

              `;
            }

            getGui() {
                return this.eGui;
            }

        };
        ''')

    gb.configure_column('Delete', headerTooltip='Click on Button to remove row',
                        editable=False, filter=False, onCellClicked=JsCode(string_to_delete),
                        cellRenderer=cell_button_delete,
                        autoHeight=True, suppressMovable='true')

    gb.configure_default_column(editable=True)
    gb.configure_selection(use_checkbox=True, selection_mode="multiple")
    grid_options = gb.build()
    grid_return = AgGrid(df, gridOptions=grid_options, allow_unsafe_jscode=True, theme="streamlit")

    with st.form(file_name):
        if JsCode(string_to_delete):
            df = grid_return["data"]
            df = df.append(df, ignore_index=True)
            df.to_excel(filepath, index=False)

df = pd.read_excel("Wi_Fi_DB.xlsx")
st.info("Select a row to remove it")
response = display_table(df)
df.to_excel("Wi_Fi_DB.xlsx", index=False)


问:
DAX/Power BI - Filter Two Unrelated Tables
I need to filter a table based on another table, however there is not a direct relationship between the two. Here is the data model.

attr_Tkpr_vw contains all company employees, both current and historical.

attr_Time_vw contains date/time info.

My goal is to filter attr_Tkpr_vw for all employees between arbitrary hire and termination dates. These dates are supplied by a slicer based on the column attr_Time_vw[DateFull]

Here are my results. My slicer is set to dates between 1/1/2022 and 3/31/2022. When I put the measues "MinDate" and "MaxDate" into a vizualization I get the expected results. However, when I try and use these measures to filter attr_Tkpr the formula returns a table with ALL dates.

I'm clearly missing something key about how filter contexts work.

I have tried using the fuctions VALUES, SELECTEDVALUE, ALLSELECTED. None returns expected results.


问:
Python Selenium- Message: binary is not a Firefox executable with portable Firefox
I am using:
Selenium 4.2 (Python)

Geckodriver 0.32.0

Portable Firefox 107 installed on a USB key

Pycharm installed on the same USB key

The below code (run via Pycharm on the USB) gives me: "Message: binary is not a Firefox executable with portable Firefox".

```<code>url = "https://www.youtube.com/"

options = webdriver.FirefoxOptions()
options.binary_location = r'X:\Browser\FirefoxPortable\firefoxPortable.exe'

service = Service(executable_path="geckodriver.exe")
driver = webdriver.Firefox(service=service, options=options)

driver.get(url)
driver.quit()

</code>```

Any idea why ? if I use the .exe of the firefox installed on my machine (C:) it does work. Thanks !

Body:
I am using:
Selenium 4.2 (Python)

Geckodriver 0.32.0

Portable Firefox 107 installed on a USB key

Pycharm installed on the same USB key

The below code (run via Pycharm on the USB) gives me: "Message: binary is not a Firefox executable with portable Firefox".

url = "https://www.youtube.com/"

options = webdriver.FirefoxOptions()
options.binary_location = r'X:\Browser\FirefoxPortable\firefoxPortable.exe'

service = Service(executable_path="geckodriver.exe")
driver = webdriver.Firefox(service=service, options=options)

driver.get(url)
driver.quit()

Any idea why ? if I use the .exe of the firefox installed on my machine (C:) it does work. Thanks !


问:
Where is it determined if an app (once installed) will be added to the Windows 10 Start Menu?
I have a couple of electron apps I’ve made. One gets added to the Start Menu bar, and the other app doesn’t. I want to have both apps to where the app gets added to the Start Menu after installation.

I don’t see anything that stands out when comparing the package.json or setupEvents.js that might determine this.

Where in the code is this set up, or is there a tutorial on how to add it?

Thanks!


问:
In ruby on rails, can you detect if the app you create is being used from your PWA or from the web?
I have a finished web page/PWA, but I need to remove an option for mobile but leave it for web, is there a way to know when the application is opened from the PWA on any mobile device? And if yes, in what ways could it be done?</p>


问:
Push image to gcr registry through REST calls
I have a golang app running in a kubernetes cluster which must push an image it builds periodically to gcr.io using REST endpoint (There are project constraints that does not allow me to use libraries such as go-containerregistry, docker cli for the push). I understand from documentation that I need to add "X-Registry-Auth" header to the requests to handle authorization. I am retrieving dockerconfigjson from imagePullSecret on the cluster (that works well for pod creation) and adding it as header value. However, I get an unauthorized error from gcr endpoint.

```<code>secret, err := secretsClient.Get(context.TODO(), "imagePullSecret", metaV1.GetOptions{})
secrets := []corev1.Secret{*secret}
keychain, _ := k8schain.NewFromPullSecrets(context.TODO(), secrets)

reg, _ := name.NewRegistry("gcr.io")
authorizer, _ := keychain.Resolve(reg)
auth, _ := authorizer.Authorization()

encodedJSON, err := json.Marshal(*auth)
if err != nil {
   panic(err)
}
authStr := base64.URLEncoding.EncodeToString(encodedJSON) //being used as auth header value
</code>```

Content of authStr created above has the following:

```<code>{
  "username":"_json_key",
  "password":
    "{\n  \"type\": \"service_account\",
      \n  \"project_id\": \"project\",
      \n  \"private_key_id\": \"porject-key-id\",
      \n  \"private_key\": \"-----BEGIN PRIVATE KEY-----
      \n  <validkeyhash>
      \n-----END PRIVATE KEY-----\\n\",
      \n  \"client_email\": \"something@something.iam.gserviceaccount.com\",
      \n  \"client_id\": \"123344567678786\",
      \n  \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",
      \n  \"token_uri\": \"https://oauth2.googleapis.com/token\",
      \n  \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",
      \n  \"client_x509_cert_url\":       \"https://www.googleapis.com/robot/v1/metadata/x509/manager%40something.iam.gserviceaccount.com\"
  \n}\n",
"auth":"<base64-encoded-imagePullSecret>"}
</code>```

Body:
I have a golang app running in a kubernetes cluster which must push an image it builds periodically to gcr.io using REST endpoint (There are project constraints that does not allow me to use libraries such as go-containerregistry, docker cli for the push). I understand from documentation that I need to add "X-Registry-Auth" header to the requests to handle authorization. I am retrieving dockerconfigjson from imagePullSecret on the cluster (that works well for pod creation) and adding it as header value. However, I get an unauthorized error from gcr endpoint.

secret, err := secretsClient.Get(context.TODO(), "imagePullSecret", metaV1.GetOptions{})
secrets := []corev1.Secret{*secret}
keychain, _ := k8schain.NewFromPullSecrets(context.TODO(), secrets)

reg, _ := name.NewRegistry("gcr.io")
authorizer, _ := keychain.Resolve(reg)
auth, _ := authorizer.Authorization()

encodedJSON, err := json.Marshal(*auth)
if err != nil {
   panic(err)
}
authStr := base64.URLEncoding.EncodeToString(encodedJSON) //being used as auth header value

Content of authStr created above has the following:

{
  "username":"_json_key",
  "password":
    "{\n  \"type\": \"service_account\",
      \n  \"project_id\": \"project\",
      \n  \"private_key_id\": \"porject-key-id\",
      \n  \"private_key\": \"-----BEGIN PRIVATE KEY-----
      \n  <validkeyhash>
      \n-----END PRIVATE KEY-----\\n\",
      \n  \"client_email\": \"something@something.iam.gserviceaccount.com\",
      \n  \"client_id\": \"123344567678786\",
      \n  \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",
      \n  \"token_uri\": \"https://oauth2.googleapis.com/token\",
      \n  \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",
      \n  \"client_x509_cert_url\":       \"https://www.googleapis.com/robot/v1/metadata/x509/manager%40something.iam.gserviceaccount.com\"
  \n}\n",
"auth":"<base64-encoded-imagePullSecret>"}


问:
Java 11 Filename validation to prevent OS command injection
I am trying to resolve coverity issue 'OS _Command_injection'.

filename is read from user uploaded multipart file as below

```<code>                    String filename = item.getName();
                    String regex = "^[a-zA-Z0-9_-]*$";
                    if(filename.matches(regex)) {

                        if(filename.contains("../") || filename.contains("..") || filename.contains("./") || filename.contains("/")) {
                            throw new BRException("Invalid filename");
                        }
                        Path filePath = Paths.get(location, filename);
                        try ( OutputStream out = new FileOutputStream(filePath.toString()); ) {
                            IOUtils.copy(stream, out);
                            params.put("filename", filename);
                            params.put("filePath", filePath);
                        }
                    } else {

                        throw new FSException("filename is Invalid");
                    }
</code>```

'subsequent call to invoke shell script using 'filename' complains about OS command injection,                       this filePath is passed to shellscript which invokes malware scan tool on the file to check for viruses below is scanFile method accepting filepath

EDITED

```<code>                    scanScriptPath = /scantool/scan.sh; // resolves to path of shell sript

                    StringBuilder scriptNfile = new StringBuilder("").append(scanScriptPath.toString()).append(" ").append(filePath.toString());

                    String[] cmd = {"sh","-c",scriptNfile.toString() };

                    ProcessBuilder pb = new ProcessBuilder(cmd);    // OS_Command_Sink
                    Process proc = pb.start();
                    proc.waitFor();

</code>```

Coverity error message:OS Command Injection (OS_CMD_INJECTION)7. os_cmd_sink: Calling scanFile. Passing the tainted value filename to the process-invoking API may allow an attacker to modify the intention of the command. (The virtual call resolves to com.xyz.scanFile(java.lang.String, java.lang.String, java.lang.String)

regex validation of filename and checking if filename has path traversal characters is not resolving issue.
what else am i missing?

Body:
I am trying to resolve coverity issue 'OS _Command_injection'.

filename is read from user uploaded multipart file as below

                    String filename = item.getName();
                    String regex = "^[a-zA-Z0-9_-]*$";
                    if(filename.matches(regex)) {

                        if(filename.contains("../") || filename.contains("..") || filename.contains("./") || filename.contains("/")) {
                            throw new BRException("Invalid filename");
                        }
                        Path filePath = Paths.get(location, filename);
                        try ( OutputStream out = new FileOutputStream(filePath.toString()); ) {
                            IOUtils.copy(stream, out);
                            params.put("filename", filename);
                            params.put("filePath", filePath);
                        }
                    } else {

                        throw new FSException("filename is Invalid");
                    }

'subsequent call to invoke shell script using 'filename' complains about OS command injection,                       this filePath is passed to shellscript which invokes malware scan tool on the file to check for viruses below is scanFile method accepting filepath

EDITED

                    scanScriptPath = /scantool/scan.sh; // resolves to path of shell sript

                    StringBuilder scriptNfile = new StringBuilder("").append(scanScriptPath.toString()).append(" ").append(filePath.toString());

                    String[] cmd = {"sh","-c",scriptNfile.toString() };

                    ProcessBuilder pb = new ProcessBuilder(cmd);    // OS_Command_Sink
                    Process proc = pb.start();
                    proc.waitFor();

Coverity error message:OS Command Injection (OS_CMD_INJECTION)7. os_cmd_sink: Calling scanFile. Passing the tainted value filename to the process-invoking API may allow an attacker to modify the intention of the command. (The virtual call resolves to com.xyz.scanFile(java.lang.String, java.lang.String, java.lang.String)

regex validation of filename and checking if filename has path traversal characters is not resolving issue.
what else am i missing?


问:
How to create migration for entities with properties that have relation @ManyToOne and @OneToMany with TypeORM?
I have 5 entities: User, Todos, Project, Section and Label. Relationships happen as follows:

Each User is associated with multiples Todo.

Each Todo is associated with a single User, Project and Section, and is associated with multiples Label.

Each Project is associated with a single User.

Each Section is associated with a single Project.

Each Label is associated with a single Todo.

The migration code to the @OneToOne relationship is done using the createForeignKey method, as done for project_id column at Section entity:

```<code>import {
  MigrationInterface,
  QueryRunner,
  TableColumn,
  TableForeignKey,
} from 'typeorm';

export class AddProjectIdToSections1669830961233 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.addColumn(
      'sections',
      new TableColumn({
        name: 'project_id',
        type: 'uuid',
        isNullable: true,
      })
    );

    await queryRunner.createForeignKey(
      'sections',
      new TableForeignKey({
        name: 'SectionsProject',
        columnNames: ['project_id'],
        referencedTableName: 'projects',
        referencedColumnNames: ['id'],
        onDelete: 'SET NULL',
      })
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropForeignKey('sections', 'SectionsProject');
    await queryRunner.dropColumn('sections', 'project_id');
  }
}
</code>```

However, how do you use createForeignkey for relations of @OneToMany and @ManyToOne, and especially when the two happen round trip?

Entities code:

// User.entity.ts

```<code>import {
  Column,
  CreateDateColumn,
  Entity,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Todo } from './Todo.entity';

@Entity('users')
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column()
  email: string;

  @Column()
  password: string;

  @Column({ nullable: true })
  photoURL: string;

  @Column()
  language: string;

  @CreateDateColumn()
  created_at: Date;

  @OneToMany(() => Todo, (todo) => todo.user)
  todos: Todo[];
}
</code>```

// Todo.entity.ts

```<code>import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { IProject } from '../types';
import { Label } from './Label.entity';
import { Project } from './Project.entity';
import { Section } from './Section.entity';
import { User } from './User.entity';

@Entity('todos')
export class Todo {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  title: string;

  @Column()
  description?: string;

  @Column()
  type: string;

  @Column({ type: 'timestamptz' })
  date: Date;

  @Column()
  priority: number;

  @Column()
  isCompleted: boolean;

  @OneToOne(() => Project)
  @JoinColumn({ name: 'project_id' })
  project: IProject;

  @OneToOne(() => Section)
  @JoinColumn({ name: 'section_id' })
  section?: Section;

  @OneToMany(() => Label, (label) => label.todo, {
    cascade: true,
  })
  labels: Label[];

  @ManyToOne(() => User, (user) => user.todos)
  @JoinColumn({ name: 'user_id' })
  user: User;
}
</code>```

// Project.entity.ts

```<code>import {
  Column,
  Entity,
  JoinColumn,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from './User.entity';

@Entity('projects')
export class Project {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  type: string;

  @Column()
  title: string;

  @Column()
  colorName: string;

  @Column()
  class: string;

  @OneToOne(() => User)
  @JoinColumn({ name: 'user_id' })
  user: User;
}
</code>```

// Section.entity.ts

```<code>import {
  Column,
  Entity,
  JoinColumn,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Project } from './Project.entity';

@Entity('sections')
export class Section {
  @PrimaryGeneratedColumn('uuid')
  readonly id: string;

  @Column()
  index: number;

  @Column()
  type: string;

  @Column()
  title: string;

  @Column({ type: 'timestamptz' })
  readonly date: Date;

  @OneToOne(() => Project)
  @JoinColumn({ name: 'project_id' })
  project: Project;
}
</code>```

// label.entity.ts

```<code>import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Todo } from './Todo.entity';

@Entity('labels')
export class Label {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  type: string;

  @Column()
  title: string;

  @Column()
  colorName: string;

  @Column()
  class: string;

  @ManyToOne(() => Todo, (todo) => todo.labels)
  @JoinColumn({ name: 'todo_id' })
  todo: Todo;
}
</code>```

Body:
I have 5 entities: User, Todos, Project, Section and Label. Relationships happen as follows:

Each User is associated with multiples Todo.

Each Todo is associated with a single User, Project and Section, and is associated with multiples Label.

Each Project is associated with a single User.

Each Section is associated with a single Project.

Each Label is associated with a single Todo.

The migration code to the @OneToOne relationship is done using the createForeignKey method, as done for project_id column at Section entity:

import {
  MigrationInterface,
  QueryRunner,
  TableColumn,
  TableForeignKey,
} from 'typeorm';

export class AddProjectIdToSections1669830961233 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.addColumn(
      'sections',
      new TableColumn({
        name: 'project_id',
        type: 'uuid',
        isNullable: true,
      })
    );

    await queryRunner.createForeignKey(
      'sections',
      new TableForeignKey({
        name: 'SectionsProject',
        columnNames: ['project_id'],
        referencedTableName: 'projects',
        referencedColumnNames: ['id'],
        onDelete: 'SET NULL',
      })
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropForeignKey('sections', 'SectionsProject');
    await queryRunner.dropColumn('sections', 'project_id');
  }
}

However, how do you use createForeignkey for relations of @OneToMany and @ManyToOne, and especially when the two happen round trip?

Entities code:

// User.entity.ts

import {
  Column,
  CreateDateColumn,
  Entity,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Todo } from './Todo.entity';

@Entity('users')
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column()
  email: string;

  @Column()
  password: string;

  @Column({ nullable: true })
  photoURL: string;

  @Column()
  language: string;

  @CreateDateColumn()
  created_at: Date;

  @OneToMany(() => Todo, (todo) => todo.user)
  todos: Todo[];
}

// Todo.entity.ts

import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { IProject } from '../types';
import { Label } from './Label.entity';
import { Project } from './Project.entity';
import { Section } from './Section.entity';
import { User } from './User.entity';

@Entity('todos')
export class Todo {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  title: string;

  @Column()
  description?: string;

  @Column()
  type: string;

  @Column({ type: 'timestamptz' })
  date: Date;

  @Column()
  priority: number;

  @Column()
  isCompleted: boolean;

  @OneToOne(() => Project)
  @JoinColumn({ name: 'project_id' })
  project: IProject;

  @OneToOne(() => Section)
  @JoinColumn({ name: 'section_id' })
  section?: Section;

  @OneToMany(() => Label, (label) => label.todo, {
    cascade: true,
  })
  labels: Label[];

  @ManyToOne(() => User, (user) => user.todos)
  @JoinColumn({ name: 'user_id' })
  user: User;
}

// Project.entity.ts

import {
  Column,
  Entity,
  JoinColumn,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from './User.entity';

@Entity('projects')
export class Project {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  type: string;

  @Column()
  title: string;

  @Column()
  colorName: string;

  @Column()
  class: string;

  @OneToOne(() => User)
  @JoinColumn({ name: 'user_id' })
  user: User;
}

// Section.entity.ts

import {
  Column,
  Entity,
  JoinColumn,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Project } from './Project.entity';

@Entity('sections')
export class Section {
  @PrimaryGeneratedColumn('uuid')
  readonly id: string;

  @Column()
  index: number;

  @Column()
  type: string;

  @Column()
  title: string;

  @Column({ type: 'timestamptz' })
  readonly date: Date;

  @OneToOne(() => Project)
  @JoinColumn({ name: 'project_id' })
  project: Project;
}

// label.entity.ts

import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Todo } from './Todo.entity';

@Entity('labels')
export class Label {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  type: string;

  @Column()
  title: string;

  @Column()
  colorName: string;

  @Column()
  class: string;

  @ManyToOne(() => Todo, (todo) => todo.labels)
  @JoinColumn({ name: 'todo_id' })
  todo: Todo;
}


问:
How can I use If-statements for proper and optimal way to filter properties by date and keyword properly without affecting the other filter component
I'm trying to optimize this code, its basically a cycle of ifs that checks if a type of filter is active, I initially started with a basic filter by dates that looks like this:

```<code>if (this.start_date && this.end_date) {
    return all_transactions.filter(
      (item) =>
        new Date(item.date.toDate()).getTime() >=
          new Date(this.start_date).getTime() &&
        new Date(item.date.toDate()).getTime() <=
          new Date(this.end_date).getTime()
    );
  } else if (this.start_date) {
    return all_transactions.filter(
      (item) =>
        new Date(item.date.toDate()).getTime() >=
          new Date(this.start_date).getTime()
    );
  } else if (this.end_date) {
    return all_transactions.filter(
      (item) =>
        new Date(item.date.toDate()).getTime() <=
          new Date(this.end_date).getTime()
    );
  } else {
    return all_transactions;
  }
</code>```

What this does is basically I have two components of filtering by date with a start_date and end_date for my transactions, If I select 1 date by itself It should work to the extreme of the other. For example;

```<code>start date: MM/DD/YYYY
end date: 12/05/2022

output: **all transactions <= 12/05/2022**
</code>```

You get the idea, This works perfectly on any case. 3 cases in total. (When only start_date is active, when only end_date is active, and when both start_date and end_date are active)

This all became a little bit complex when I decided to implement the searchbar for this piece.

The searchbar basically looks for a string inside of name of the transactions and check for the active date as well. To check that the searchbar is active I implemented the following

```<code>searching() {
      return this.searchBarFilter != ("" || " ");
    },
</code>```

If its searching then the searchbar is 'active', so I added the searchbar filter to the code and it end up pretty spaghetti and disgusting look.
On the methods we have searching()

and my computed properties:

```<code>computed: {
    filtered_transactions(): Array<{
      date: any;
      amount: number;
      name: string;
      notes: string;
      payment_type: string;
      category: string;
    }> {
      let all_transactions = [] as Array<{
        date: any;
        amount: number;
        name: string;
        notes: string;
        payment_type: string;
        category: string;
      }>;
      if (
        Object.keys(this.$store.state.selected_budget.categories).length === 0
      ) {
        return all_transactions;
      }

      this.$store.state.selected_budget.categories.forEach((category) => {
        if (!category.transactions) {
          return;
        }
        category.transactions.forEach((transaction) => {
          transaction.category = category.name;
          all_transactions.push(transaction);
        });
      });

      // This will filter by search if search is the only filter active
      if (this.searching() && !(this.start_date && this.end_date)) {
        return all_transactions.filter((item) =>
          item.name.toLowerCase().includes(this.searchBarFilter.toLowerCase())
        );
      }
      //filter by date to and from if they are set, handle if only one is set
      if (this.start_date && this.end_date && this.searching()) {
        return all_transactions.filter(
          (item) =>
            new Date(item.date.toDate()).getTime() >=
              new Date(this.start_date).getTime() &&
            new Date(item.date.toDate()).getTime() <=
              new Date(this.end_date).getTime() &&
            item.name
              .toLocaleLowerCase()
              .includes(this.searchBarFilter.toLowerCase())
        );
      } else if (this.start_date && this.searching()) {
        return all_transactions.filter(
          (item) =>
            new Date(item.date.toDate()).getTime() >=
              new Date(this.start_date).getTime() &&
            item.name
              .toLocaleLowerCase()
              .includes(this.searchBarFilter.toLowerCase())
        );
      } else if (this.end_date && this.searching()) {
        return all_transactions.filter(
          (item) =>
            new Date(item.date.toDate()).getTime() <=
              new Date(this.end_date).getTime() &&
            item.name
              .toLocaleLowerCase()
              .includes(this.searchBarFilter.toLowerCase())
        );
      } else {
        return all_transactions;
      }
    },
    transactions_exist(): boolean {
      return this.filtered_transactions.length > 0;
    },
  },
});
</code>```

So I don't think this is the smartest algorithm I don't like the idea of If 1!=2 then 1, and if 2!=1 then 2, and if 1=2 then return all 1=>2 and 2=>1 if that makes sense.

Also, at the moment of only searching by either end_date or start_date by itself (when only one is active), because the searchbar is now inside of this code, for some reason, it won't search until I active both or I type something on the searchbar.

Adding also the data() for reference.

```<code>  data() {
    return {
      start_date: null as any,
      end_date: null as any,
      selected_budget: this.$store.state.selected_budget.name,
      searchBarFilter: "",
    };
</code>```

Any thoughts on how to make the start_date and end_date by itself with the searchbar included on this code. Also what algorithm should I use so I don't have more than 6 if cases?

Body:
I'm trying to optimize this code, its basically a cycle of ifs that checks if a type of filter is active, I initially started with a basic filter by dates that looks like this:

if (this.start_date && this.end_date) {
    return all_transactions.filter(
      (item) =>
        new Date(item.date.toDate()).getTime() >=
          new Date(this.start_date).getTime() &&
        new Date(item.date.toDate()).getTime() <=
          new Date(this.end_date).getTime()
    );
  } else if (this.start_date) {
    return all_transactions.filter(
      (item) =>
        new Date(item.date.toDate()).getTime() >=
          new Date(this.start_date).getTime()
    );
  } else if (this.end_date) {
    return all_transactions.filter(
      (item) =>
        new Date(item.date.toDate()).getTime() <=
          new Date(this.end_date).getTime()
    );
  } else {
    return all_transactions;
  }

What this does is basically I have two components of filtering by date with a start_date and end_date for my transactions, If I select 1 date by itself It should work to the extreme of the other. For example;

start date: MM/DD/YYYY
end date: 12/05/2022

output: **all transactions <= 12/05/2022**

You get the idea, This works perfectly on any case. 3 cases in total. (When only start_date is active, when only end_date is active, and when both start_date and end_date are active)

This all became a little bit complex when I decided to implement the searchbar for this piece.

The searchbar basically looks for a string inside of name of the transactions and check for the active date as well. To check that the searchbar is active I implemented the following

searching() {
      return this.searchBarFilter != ("" || " ");
    },

If its searching then the searchbar is 'active', so I added the searchbar filter to the code and it end up pretty spaghetti and disgusting look.
On the methods we have searching()

and my computed properties:

computed: {
    filtered_transactions(): Array<{
      date: any;
      amount: number;
      name: string;
      notes: string;
      payment_type: string;
      category: string;
    }> {
      let all_transactions = [] as Array<{
        date: any;
        amount: number;
        name: string;
        notes: string;
        payment_type: string;
        category: string;
      }>;
      if (
        Object.keys(this.$store.state.selected_budget.categories).length === 0
      ) {
        return all_transactions;
      }

      this.$store.state.selected_budget.categories.forEach((category) => {
        if (!category.transactions) {
          return;
        }
        category.transactions.forEach((transaction) => {
          transaction.category = category.name;
          all_transactions.push(transaction);
        });
      });

      // This will filter by search if search is the only filter active
      if (this.searching() && !(this.start_date && this.end_date)) {
        return all_transactions.filter((item) =>
          item.name.toLowerCase().includes(this.searchBarFilter.toLowerCase())
        );
      }
      //filter by date to and from if they are set, handle if only one is set
      if (this.start_date && this.end_date && this.searching()) {
        return all_transactions.filter(
          (item) =>
            new Date(item.date.toDate()).getTime() >=
              new Date(this.start_date).getTime() &&
            new Date(item.date.toDate()).getTime() <=
              new Date(this.end_date).getTime() &&
            item.name
              .toLocaleLowerCase()
              .includes(this.searchBarFilter.toLowerCase())
        );
      } else if (this.start_date && this.searching()) {
        return all_transactions.filter(
          (item) =>
            new Date(item.date.toDate()).getTime() >=
              new Date(this.start_date).getTime() &&
            item.name
              .toLocaleLowerCase()
              .includes(this.searchBarFilter.toLowerCase())
        );
      } else if (this.end_date && this.searching()) {
        return all_transactions.filter(
          (item) =>
            new Date(item.date.toDate()).getTime() <=
              new Date(this.end_date).getTime() &&
            item.name
              .toLocaleLowerCase()
              .includes(this.searchBarFilter.toLowerCase())
        );
      } else {
        return all_transactions;
      }
    },
    transactions_exist(): boolean {
      return this.filtered_transactions.length > 0;
    },
  },
});

So I don't think this is the smartest algorithm I don't like the idea of If 1!=2 then 1, and if 2!=1 then 2, and if 1=2 then return all 1=>2 and 2=>1 if that makes sense.

Also, at the moment of only searching by either end_date or start_date by itself (when only one is active), because the searchbar is now inside of this code, for some reason, it won't search until I active both or I type something on the searchbar.

Adding also the data() for reference.

  data() {
    return {
      start_date: null as any,
      end_date: null as any,
      selected_budget: this.$store.state.selected_budget.name,
      searchBarFilter: "",
    };

Any thoughts on how to make the start_date and end_date by itself with the searchbar included on this code. Also what algorithm should I use so I don't have more than 6 if cases?