问:
Flexdashboard: Storyboard does not work with ODBC and temporal environment variables
I am using flexdashboard (0.5.2), ODBC (1.3.3) in R 4.1.0 and IDE RStudio (2021.09.2) on a Server (not in my local machine)
I have being building flexdashboard storyboards and I wanted to "level up" my stories, connecting the data of the stories to the source (postgres database).
to do this, I normally:

1 - stablish system enviroment variables for password, user, and other parameters.
2 - Create a function that is loaded when the page is loaded, that open connection, extract table, close connection, and return data
Problem: when I Knit, it raise the error
(Tab Render)

```<code>Line XX Error: nanodbc/nanodbc.cpp:1021: 00000: [unixODBC][RStudio][PostgreSQL] (10) Error occurred while trying to connect: [SQLState 28000] FATAL:  password authentication failed for user "myuser"
FATAL:  password authentication failed for user "myuser"

Execution halted
</code>```

(Tab Issue)

```<code>Quitting from lines 63-66 (main_flexdashboard.Rmd)
Error: nanodbc/nanodbc.cpp:1021: 00000: [unixODBC][RStudio][PostgreSQL] (10) Error occurred while trying to connect: [SQLState 28000] FATAL:  password authentication failed for user "myuser"
FATAL:  password authentication failed for user "myuser"

Execution halted
</code>```

Code to reproduce this error:

```<code>library(DBI)
library(odbc)

get_db_table <- function(){
  #======================================================
  # 0. connection:
  print("connecting...")
  print(connList)
  con <- dbConnect(odbc::odbc(),
                        Driver = "PostgreSQL",
                        Database = "mydb",
                        #encoding = "windows-1252",
                        #encoding = "UTF-16",
                        UID = Sys.getenv("myuser"),
                        PWD = Sys.getenv("mypasswordwithspecialcharacters"),
                        host = myhost,
                        Port = 8888,
                        MultipleActiveResultSets = "True"
                        )

  #..........
  # In a normal case, here some code to get the table of interest ....
  #...............
  print("connected!")
  dbDisconnect(con)
  return("done----")
 #======================================================
}

 # here calling the function
 myT <- get_db_table ()
</code>```

On the other hand:
I ) If I write the string with the password (something NOT recommendable) in the PWD field, it will work fine and smooth.
II) Also If I run the chuncks of code manually, instead of Knit the Rmd, it works fine too (it connects and return the table)

I already reported this in the flexdashboard repository issues but maybe anybody on this community knows about how to work around this issue.
Please let me know (I already tried several approaches, unsuccessfully)

Body:
I am using flexdashboard (0.5.2), ODBC (1.3.3) in R 4.1.0 and IDE RStudio (2021.09.2) on a Server (not in my local machine)
I have being building flexdashboard storyboards and I wanted to "level up" my stories, connecting the data of the stories to the source (postgres database).
to do this, I normally:

1 - stablish system enviroment variables for password, user, and other parameters.
2 - Create a function that is loaded when the page is loaded, that open connection, extract table, close connection, and return data
Problem: when I Knit, it raise the error
(Tab Render)

Line XX Error: nanodbc/nanodbc.cpp:1021: 00000: [unixODBC][RStudio][PostgreSQL] (10) Error occurred while trying to connect: [SQLState 28000] FATAL:  password authentication failed for user "myuser"
FATAL:  password authentication failed for user "myuser"

Execution halted

(Tab Issue)

Quitting from lines 63-66 (main_flexdashboard.Rmd)
Error: nanodbc/nanodbc.cpp:1021: 00000: [unixODBC][RStudio][PostgreSQL] (10) Error occurred while trying to connect: [SQLState 28000] FATAL:  password authentication failed for user "myuser"
FATAL:  password authentication failed for user "myuser"

Execution halted

Code to reproduce this error:

library(DBI)
library(odbc)

get_db_table <- function(){
  #======================================================
  # 0. connection:
  print("connecting...")
  print(connList)
  con <- dbConnect(odbc::odbc(),
                        Driver = "PostgreSQL",
                        Database = "mydb",
                        #encoding = "windows-1252",
                        #encoding = "UTF-16",
                        UID = Sys.getenv("myuser"),
                        PWD = Sys.getenv("mypasswordwithspecialcharacters"),
                        host = myhost,
                        Port = 8888,
                        MultipleActiveResultSets = "True"
                        )

  #..........
  # In a normal case, here some code to get the table of interest ....
  #...............
  print("connected!")
  dbDisconnect(con)
  return("done----")
 #======================================================
}

 # here calling the function
 myT <- get_db_table ()

On the other hand:
I ) If I write the string with the password (something NOT recommendable) in the PWD field, it will work fine and smooth.
II) Also If I run the chuncks of code manually, instead of Knit the Rmd, it works fine too (it connects and return the table)

I already reported this in the flexdashboard repository issues but maybe anybody on this community knows about how to work around this issue.
Please let me know (I already tried several approaches, unsuccessfully)


来源: stackexchange

问:
Telegraf is sending incorrect data to influxdb2?
I'm new to telegraf / influxdb2 :)

I've made a quick docker setup to monitor a cloud Ubuntu VM. To do so, I've created a "default like" docker-compose file with telegraf, influxdb2 & grafana. It works just fine on my ubuntu laptop.
When I run it on the ubuntu cloud VM, I have very strange numbers for my metrics.

For example

load15 : running top (or uptime) load15 is 0,07, but in influxdb2 I have 21.39

uptime: real uptime is like 2hours right now and the value store in influxdb is like 27177833 (44 Weeks ...)

Memory used : free -h tells  590Mi, influx has 95025573888 (87Gb, my VM has 3 Gb..)

....

What is very strange to me is that the docker inputs is working fine :/

This is driving me crazy :) did someone has already encounter the same kind of thing ?
And again, works just fine on my laptop :)

docker-compose.yml

```<code>version: '3.1'
services:
  grafana:
    image: grafana/grafana
    container_name: grafana
    restart: unless-stopped
    depends_on:
      - telegraf
    volumes:
      - ./grafana/provisioning/:/etc/grafana/provisioning/
      - ./grafana/dashboards/:/var/lib/grafana/dashboards/
      - ./grafana/grafana.ini:/etc/grafana/grafana.ini
    ports:
      - 3000:3000
  influxdb:
    image: influxdb:2.5.1
    container_name: influxdb
    restart: unless-stopped
    ports:
      - 8086:8086
    environment:
      - DOCKER_INFLUXDB_INIT_USERNAME=xxxx
      - DOCKER_INFLUXDB_INIT_PASSWORD=yyyyy
      - DOCKER_INFLUXDB_INIT_ORG=myorg
      - DOCKER_INFLUXDB_INIT_BUCKET=mybucket
      - DOCKER_INFLUXDB_INIT_RETENTION=3w
      - DOCKER_INFLUXDB_INIT_MODE=setup
      - DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=my-token
    volumes:
      - data-influx:/var/lib/influxdb2
  telegraf:
    image: telegraf:1.24.3-alpine
    container_name: telegraf
    restart: unless-stopped
    depends_on:
      - influxdb
    volumes:
      - ./telegraf/etc/telegraf.conf:/etc/telegraf/telegraf.conf:ro
      - /var/run/docker.sock:/var/run/docker.sock
      - /sys:/rootfs/sys:ro
      - /proc:/rootfs/proc:ro
      - /etc:/rootfs/etc:ro
    user: telegraf:999

volumes:
  data-influx:
</code>```

telegraf.conf

```<code>[global_tags]

[agent]
  interval = "10s"
  round_interval = true
  metric_batch_size = 1000
  metric_buffer_limit = 10000
  flush_buffer_when_full = true
  collection_jitter = "0s"
  flush_interval = "10s"
  flush_jitter = "0s"
  debug = false
  quiet = false
  hostname = "LoubVM"

[[outputs.influxdb_v2]]
  urls = ["http://influxdb:8086"]
  token = "my-token"
  organization = "myorg"
  bucket = "mybucket"
[[inputs.statsd]]
  protocol = "udp"
  max_tcp_connections = 250
  tcp_keep_alive = false
  service_address = ":8125"
  delete_gauges = true
  delete_counters = true
  delete_sets = true
  delete_timings = true
  percentiles = [90]
  metric_separator = "_"
  parse_data_dog_tags = false
  allowed_pending_messages = 10000
  percentile_limit = 1000

[[inputs.cpu]]
  percpu = true
  totalcpu = true

[[inputs.disk]]
  mount_points = ["/"]

[[inputs.diskio]]

[[inputs.kernel]]

[[inputs.mem]]

[[inputs.processes]]

[[inputs.swap]]

[[inputs.system]]

[[inputs.net]]

[[inputs.netstat]]

[[inputs.interrupts]]

[[inputs.linux_sysctl_fs]]

[[inputs.docker]]
  endpoint = "unix:///var/run/docker.sock"
  gather_services = false
  source_tag = false
  container_name_include = []
  container_name_exclude = []
  timeout = "5s"
  total = false
  docker_label_include = []
  docker_label_exclude = []

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to telegraf / influxdb2 :)

I've made a quick docker setup to monitor a cloud Ubuntu VM. To do so, I've created a "default like" docker-compose file with telegraf, influxdb2 & grafana. It works just fine on my ubuntu laptop.
When I run it on the ubuntu cloud VM, I have very strange numbers for my metrics.

For example

load15 : running top (or uptime) load15 is 0,07, but in influxdb2 I have 21.39

uptime: real uptime is like 2hours right now and the value store in influxdb is like 27177833 (44 Weeks ...)

Memory used : free -h tells  590Mi, influx has 95025573888 (87Gb, my VM has 3 Gb..)

....

What is very strange to me is that the docker inputs is working fine :/

This is driving me crazy :) did someone has already encounter the same kind of thing ?
And again, works just fine on my laptop :)

docker-compose.yml

version: '3.1'
services:
  grafana:
    image: grafana/grafana
    container_name: grafana
    restart: unless-stopped
    depends_on:
      - telegraf
    volumes:
      - ./grafana/provisioning/:/etc/grafana/provisioning/
      - ./grafana/dashboards/:/var/lib/grafana/dashboards/
      - ./grafana/grafana.ini:/etc/grafana/grafana.ini
    ports:
      - 3000:3000
  influxdb:
    image: influxdb:2.5.1
    container_name: influxdb
    restart: unless-stopped
    ports:
      - 8086:8086
    environment:
      - DOCKER_INFLUXDB_INIT_USERNAME=xxxx
      - DOCKER_INFLUXDB_INIT_PASSWORD=yyyyy
      - DOCKER_INFLUXDB_INIT_ORG=myorg
      - DOCKER_INFLUXDB_INIT_BUCKET=mybucket
      - DOCKER_INFLUXDB_INIT_RETENTION=3w
      - DOCKER_INFLUXDB_INIT_MODE=setup
      - DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=my-token
    volumes:
      - data-influx:/var/lib/influxdb2
  telegraf:
    image: telegraf:1.24.3-alpine
    container_name: telegraf
    restart: unless-stopped
    depends_on:
      - influxdb
    volumes:
      - ./telegraf/etc/telegraf.conf:/etc/telegraf/telegraf.conf:ro
      - /var/run/docker.sock:/var/run/docker.sock
      - /sys:/rootfs/sys:ro
      - /proc:/rootfs/proc:ro
      - /etc:/rootfs/etc:ro
    user: telegraf:999

volumes:
  data-influx:

telegraf.conf

[global_tags]

[agent]
  interval = "10s"
  round_interval = true
  metric_batch_size = 1000
  metric_buffer_limit = 10000
  flush_buffer_when_full = true
  collection_jitter = "0s"
  flush_interval = "10s"
  flush_jitter = "0s"
  debug = false
  quiet = false
  hostname = "LoubVM"

[[outputs.influxdb_v2]]
  urls = ["http://influxdb:8086"]
  token = "my-token"
  organization = "myorg"
  bucket = "mybucket"
[[inputs.statsd]]
  protocol = "udp"
  max_tcp_connections = 250
  tcp_keep_alive = false
  service_address = ":8125"
  delete_gauges = true
  delete_counters = true
  delete_sets = true
  delete_timings = true
  percentiles = [90]
  metric_separator = "_"
  parse_data_dog_tags = false
  allowed_pending_messages = 10000
  percentile_limit = 1000

[[inputs.cpu]]
  percpu = true
  totalcpu = true

[[inputs.disk]]
  mount_points = ["/"]

[[inputs.diskio]]

[[inputs.kernel]]

[[inputs.mem]]

[[inputs.processes]]

[[inputs.swap]]

[[inputs.system]]

[[inputs.net]]

[[inputs.netstat]]

[[inputs.interrupts]]

[[inputs.linux_sysctl_fs]]

[[inputs.docker]]
  endpoint = "unix:///var/run/docker.sock"
  gather_services = false
  source_tag = false
  container_name_include = []
  container_name_exclude = []
  timeout = "5s"
  total = false
  docker_label_include = []
  docker_label_exclude = []


问:
Pyspark - DataFrame Merge Column data
I have a DataFrame like this ;

```<code>+---+------+-----+-----+-------+
| id|status|Flag1|Flag2|   type|
+---+------+-----+-----+-------+
|123|   N/A| null|false|Prepaid|
|123|   N/A| true| null|Prepaid|
+---+------+-----+-----+-------+
</code>```

i want to do like this ;

```<code>+---+------+-----+-----+-------+
| id|status|Flag1|Flag2|   type|
+---+------+-----+-----+-------+
|123|   N/A| true|false|Prepaid|
+---+------+-----+-----+-------+

 Flag1 -> Flag2
 ---------------
 True -> False = True
 True -> null = True
 False -> null = False
 True -> True = True
 False -> False = False
</code>```

The reverse logic is the same.
Flag1 and Flag2 both cannot be empty

How can I do it with Pyspark?

Title: Pyspark - DataFrame Merge Column data

Body:
I have a DataFrame like this ;

+---+------+-----+-----+-------+
| id|status|Flag1|Flag2|   type|
+---+------+-----+-----+-------+
|123|   N/A| null|false|Prepaid|
|123|   N/A| true| null|Prepaid|
+---+------+-----+-----+-------+

i want to do like this ;

+---+------+-----+-----+-------+
| id|status|Flag1|Flag2|   type|
+---+------+-----+-----+-------+
|123|   N/A| true|false|Prepaid|
+---+------+-----+-----+-------+

 Flag1 -> Flag2
 ---------------
 True -> False = True
 True -> null = True
 False -> null = False
 True -> True = True
 False -> False = False

The reverse logic is the same.
Flag1 and Flag2 both cannot be empty

How can I do it with Pyspark?


问:
Node/Express API connection refusal by local Postgres
Trying to diagnose a problem as I build a Sequelize skeleton for my API.

I'm using WSL, and I have a Postgres server set up in PGAdmin. Assuming my creds aren't the issue, am I missing something?

const app = require("./app");
const http = require("http");
const server = http.createServer(app);

const { Sequelize } = require("sequelize");
const sequelize = new Sequelize('postgres://fakeuser:fakepass@localhost:5432/kobold_condominium') // Example for postgres

server.listen(3000);

server.on("listening", async () => {
    console.log("Server is listening for requests on port 3000.");
    try {
        await sequelize.authenticate();
        console.log("Database connection successful.");
    } catch (error) {
        console.log("Database connection:" + error);
    }
});
```

I consistently get this output:

Database connection:SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432

Am I missing something? I didn't think there would be Windows/WSL issues; any ideas?

Body:
Trying to diagnose a problem as I build a Sequelize skeleton for my API.

I'm using WSL, and I have a Postgres server set up in PGAdmin. Assuming my creds aren't the issue, am I missing something?

const app = require("./app");
const http = require("http");
const server = http.createServer(app);

const { Sequelize } = require("sequelize");
const sequelize = new Sequelize('postgres://fakeuser:fakepass@localhost:5432/kobold_condominium') // Example for postgres

server.listen(3000);

server.on("listening", async () => {
    console.log("Server is listening for requests on port 3000.");
    try {
        await sequelize.authenticate();
        console.log("Database connection successful.");
    } catch (error) {
        console.log("Database connection:" + error);
    }
});

I consistently get this output:

Database connection:SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432

Am I missing something? I didn't think there would be Windows/WSL issues; any ideas?


问:
ArrayList is returning duplicate values instead of listing out all values
When I run my code its meant to display the playCount of each AudioFile in descending order. it can manage this if all of the playCounts are unique however if two playCounts are the same it will just return the same AudioFile twice instead of the two seperate AudioFiles

I am still quite new so i apologize if the mistake is very obvious or i haven't explained properly

This is for a HomeWork Assignment so for ArrayList i am only limited to get,  add,  size  and  remove  methods as well as i can`t include any external libraries other than Scanner and ArrayList

This is my code which relates to the issue

Top 10 Method

```<code>public String topTen() {
        int[] playcount = new int[audioData.size()];
        if (audioData.size() <= 0) {
            System.out.println("\nNothing here to display\n");
            return null;
        }
        for (int index = 0; index < audioData.size(); index++) {
            playcount[index] = audioData.get(index).getPlayCount();
        }
        bubbleSort(playcount, false);
        if (audioData != null) {
            System.out.println("\nThese are your top 10 tracks\n");
            if (playcount.length < 10) {
                display(playcount);
            } else if (playcount.length >= 10) {
                display(playcount, 10);
            }
        }
        return null;
    }
</code>```

Display for less than 10 AudioFiles

```<code>private void display(int data[]) {
        if (data != null && data.length > 0) {

            for (int index = 0; index < audioData.size(); index++) {

                AudioFile audio = searchPlay(audioData.get(index).getPlayCount());
                System.out.println("Code: " + audio.getCode() + ", " + "Title: " + audio.getTitle() + ", " + "Plays: "
                        + audio.getPlayCount() + "\n");
            }
        } else {
            System.out.println("No data to display.\n");
        }
    }

</code>```

Display for 10 or more AudioFiles

```<code>private void display(int data[], int count) {
        if (data != null && data.length > 0 && data.length >= count && count > 0) {

            for (int index = 0; index < count; index++) {

                AudioFile audio = searchPlay(data[index]);
                System.out.println("Code: " + audio.getCode() + ", " + "Title: " + audio.getTitle() + ", " + "Plays: "
                        + audio.getPlayCount());
            }
        } else {
            System.out.println("No data to display.\n");
        }
    }
</code>```

Sorting playCount in desc order

```<code>private void bubbleSort(int[] data, boolean ascending) {
        int swaps;
        do {
            swaps = 0;
            for (int index = 0; index < data.length - 1; index++) {
                if (data[index] > data[index + 1] && ascending || data[index] < data[index + 1] && !ascending) {
                    int temp = data[index];
                    data[index] = data[index + 1];
                    data[index + 1] = temp;
                    swaps++;
                }
            }
        } while (swaps > 0);
    }

</code>```
```<code>private AudioFile searchPlay(int id) {
        AudioFile target = null;
        for (int index = 0; index < audioData.size(); index++) {
            AudioFile audio = audioData.get(index);
            if (audio.getPlayCount() == id) {
                target = audio;

                break;
            }
        }
        return target;
    }

</code>```

Body:
When I run my code its meant to display the playCount of each AudioFile in descending order. it can manage this if all of the playCounts are unique however if two playCounts are the same it will just return the same AudioFile twice instead of the two seperate AudioFiles

I am still quite new so i apologize if the mistake is very obvious or i haven't explained properly

This is for a HomeWork Assignment so for ArrayList i am only limited to get,  add,  size  and  remove  methods as well as i can`t include any external libraries other than Scanner and ArrayList

This is my code which relates to the issue

Top 10 Method

public String topTen() {
        int[] playcount = new int[audioData.size()];
        if (audioData.size() <= 0) {
            System.out.println("\nNothing here to display\n");
            return null;
        }
        for (int index = 0; index < audioData.size(); index++) {
            playcount[index] = audioData.get(index).getPlayCount();
        }
        bubbleSort(playcount, false);
        if (audioData != null) {
            System.out.println("\nThese are your top 10 tracks\n");
            if (playcount.length < 10) {
                display(playcount);
            } else if (playcount.length >= 10) {
                display(playcount, 10);
            }
        }
        return null;
    }

Display for less than 10 AudioFiles

private void display(int data[]) {
        if (data != null && data.length > 0) {

            for (int index = 0; index < audioData.size(); index++) {

                AudioFile audio = searchPlay(audioData.get(index).getPlayCount());
                System.out.println("Code: " + audio.getCode() + ", " + "Title: " + audio.getTitle() + ", " + "Plays: "
                        + audio.getPlayCount() + "\n");
            }
        } else {
            System.out.println("No data to display.\n");
        }
    }

Display for 10 or more AudioFiles

private void display(int data[], int count) {
        if (data != null && data.length > 0 && data.length >= count && count > 0) {

            for (int index = 0; index < count; index++) {

                AudioFile audio = searchPlay(data[index]);
                System.out.println("Code: " + audio.getCode() + ", " + "Title: " + audio.getTitle() + ", " + "Plays: "
                        + audio.getPlayCount());
            }
        } else {
            System.out.println("No data to display.\n");
        }
    }

Sorting playCount in desc order

private void bubbleSort(int[] data, boolean ascending) {
        int swaps;
        do {
            swaps = 0;
            for (int index = 0; index < data.length - 1; index++) {
                if (data[index] > data[index + 1] && ascending || data[index] < data[index + 1] && !ascending) {
                    int temp = data[index];
                    data[index] = data[index + 1];
                    data[index + 1] = temp;
                    swaps++;
                }
            }
        } while (swaps > 0);
    }

private AudioFile searchPlay(int id) {
        AudioFile target = null;
        for (int index = 0; index < audioData.size(); index++) {
            AudioFile audio = audioData.get(index);
            if (audio.getPlayCount() == id) {
                target = audio;

                break;
            }
        }
        return target;
    }


问:
Flask wtforms 'The view function did not return a valid response'
I am having issues with my flask login form. When I run on local host I get this error.

TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a LoginForm.

What am I doing wrong? please help

Here is my .py file

```<code>from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

#Create Flask Instance
app = Flask(__name__)
app.config['SECRET_KEY'] = "AAAAA"

#Create route decorator
@app.route('/')

#Create a Form Class
class LoginForm(FlaskForm):
    user = StringField("Enter Your Username", validators=[DataRequired()] )
    password = StringField("Enter Your Password", validators=[DataRequired()] )
    submit = SubmitField("Submit")

#Create Login Page
@app.route('/login', methods=['GET', 'POST'])
def login():
    user = None
    password = None
    form = LoginForm()
    #Validate Form
    if form.validate_on_submit():
        user = form.user.data
        password = form.password.data
        form.password.data = ''
        form.user.data = ''

    return render_template("login.html", user = user, password = password, form = form)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

And here us my html form

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Log In page to the zoo</title>
    </head>
    <body>
        <h1>Welcome to our zoo</h1>
        <br>
        <p>Please fill in your credentials</p>
        <form method="POST" action="/login.py">
            Username: <input type="text" name="username" required>
            Password: <input type="password" name="password" required>
            <input type="submit">
        </form>
        <a href="{{url_for('register')}}">Create a new account</a>
    </body>
</html>

</code>```

Body:
I am having issues with my flask login form. When I run on local host I get this error.

TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a LoginForm.

What am I doing wrong? please help

Here is my .py file

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

#Create Flask Instance
app = Flask(__name__)
app.config['SECRET_KEY'] = "AAAAA"

#Create route decorator
@app.route('/')

#Create a Form Class
class LoginForm(FlaskForm):
    user = StringField("Enter Your Username", validators=[DataRequired()] )
    password = StringField("Enter Your Password", validators=[DataRequired()] )
    submit = SubmitField("Submit")

#Create Login Page
@app.route('/login', methods=['GET', 'POST'])
def login():
    user = None
    password = None
    form = LoginForm()
    #Validate Form
    if form.validate_on_submit():
        user = form.user.data
        password = form.password.data
        form.password.data = ''
        form.user.data = ''

    return render_template("login.html", user = user, password = password, form = form)

if __name__ == '__main__':
    app.run(debug=True)

And here us my html form

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Log In page to the zoo</title>

Welcome to our zoo

Please fill in your credentials

        <form method="POST" action="/login.py">
            Username: <input type="text" name="username" required>
            Password: <input type="password" name="password" required>
            <input type="submit">
        </form>
        Create a new account


问:
Flutter SearchDelegates BuildResults isn'a a valid override
I'm trying to build a networkbased search. It works so far, that I get the results I want from my API. Now I want to build the results but get two error messages I don't know how to resolve.

Error 1:

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr', is a potentially non-nullable type.\nTry adding either a return or a throw statement at the end.

Error 2:

FoodSearch.buildResults' ('Future Function(BuildContext)') isn't a valid override of 'SearchDelegate.buildResults' ('Widget Function(BuildContext)').

My buildResult:

```<code>@override
  Future<Widget> buildResults(BuildContext context) async {
    var split_kat = query.split('|');
    String fumiID = split_kat[2];
    FutureBuilder<FutterModell>(
      future: FumiFibelAPI.getSingleFood(fumiID),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          default:
            if (snapshot.hasError) {
              return Container(
                color: Colors.black,
                alignment: Alignment.center,
                child: Text(
                  'Something went wrong!',
                  style: TextStyle(fontSize: 28, color: Colors.white),
                ),
              );
            } else {
              return Container();
            }
        }
      },
    );
  }
</code>```

The API for the Future-List:

```<code>static Future<FutterModell> getSingleFood(String futtermittelID) async {
    const storage = FlutterSecureStorage();
    var token = await storage.read(key: "_authToken");
    int futtermittel = int.parse(futtermittelID);

    var url = Uri.parse('${Constants.BASE_URL}/futtermittel/$futtermittel');

    var headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    };

    var body = {
      "futtermittel_id": futtermittel,
    };

    var res = await http.post(url, headers: headers, body: jsonEncode(body));
    final result = json.decode(res.body);
    return result.map<FutterModell>(FutterModell.fromJson).toList();
  }
</code>```

Thanks for the help!

Body:
I'm trying to build a networkbased search. It works so far, that I get the results I want from my API. Now I want to build the results but get two error messages I don't know how to resolve.

Error 1:

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr', is a potentially non-nullable type.\nTry adding either a return or a throw statement at the end.

Error 2:

FoodSearch.buildResults' ('Future Function(BuildContext)') isn't a valid override of 'SearchDelegate.buildResults' ('Widget Function(BuildContext)').

My buildResult:

@override
  Future<Widget> buildResults(BuildContext context) async {
    var split_kat = query.split('|');
    String fumiID = split_kat[2];
    FutureBuilder<FutterModell>(
      future: FumiFibelAPI.getSingleFood(fumiID),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          default:
            if (snapshot.hasError) {
              return Container(
                color: Colors.black,
                alignment: Alignment.center,
                child: Text(
                  'Something went wrong!',
                  style: TextStyle(fontSize: 28, color: Colors.white),
                ),
              );
            } else {
              return Container();
            }
        }
      },
    );
  }

The API for the Future-List:

static Future<FutterModell> getSingleFood(String futtermittelID) async {
    const storage = FlutterSecureStorage();
    var token = await storage.read(key: "_authToken");
    int futtermittel = int.parse(futtermittelID);

    var url = Uri.parse('${Constants.BASE_URL}/futtermittel/$futtermittel');

    var headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    };

    var body = {
      "futtermittel_id": futtermittel,
    };

    var res = await http.post(url, headers: headers, body: jsonEncode(body));
    final result = json.decode(res.body);
    return result.map<FutterModell>(FutterModell.fromJson).toList();
  }

Thanks for the help!


问:
vscode keeps printing path to python and cwd every time I run a script
As title, vscode keeps printing the path to python.exe and cwd every time I run a script. This started happening after I set up a venv and someone on reddit suggested that it was due to the venv. However, it continues to happen outside of the venv.

I know that I can do something with code runner but I'd rather understand exactly why this happens and how to stop it without using code runner, as it didn't happen before. Thank you for your time.

I tried setting "console": "internalConsole" in launch.json, but it didn't work. I tried setting the interpreter to a different path, no dice.


问:
Android: Is it possible to change sensor reporting modes?
I am interested in using the significant motion sensor, but I realized that this is a one-shot reporting sensor. So after it reports an event once, it no longer reports anymore until I re-register the sensor.

My goal is to detect significant motion at all times, for example when a user picks up their phone, shakes it, throws it, etc... Based on that triggered event I will do something.

I'm wondering now if there is an alternative or a way to continuously listen for significant motion sensor events.

I honestly thought about just continuously re-registering the sensor but I think there are consequences to that approach and it's a hack.


问:
Delete duplicate rows in MySQL Workbench
I'm trying to remove some duplicate values that appear in the Nashville Housing Data for Data Cleaning dataset but my query doesn't work. I am using MySQL Workbench and this is the error I am getting.

Error Code: 1093. You can't specify target table 'Tb1' for update in FROM clause

Can someone explain to me how I can solve it?

```<code>DELETE FROM PortafolioProject.NashvilleHousing AS Tb1
WHERE EXISTS (SELECT 1 FROM PortafolioProject.NashvilleHousing AS Tb2
              WHERE Tb2.ParcelID = Tb1.ParcelID AND
                    Tb2.PropertyAddress = Tb1.PropertyAddress AND
                    Tb2.SalePrice = Tb1.SalePrice AND
                    Tb2.SaleDate = Tb1.SaleDate AND
                    Tb2.LegalReference = Tb1.LegalReference AND
                    Tb2.UniqueID < Tb1.UniqueID);
</code>```

Body:
I'm trying to remove some duplicate values that appear in the Nashville Housing Data for Data Cleaning dataset but my query doesn't work. I am using MySQL Workbench and this is the error I am getting.

Error Code: 1093. You can't specify target table 'Tb1' for update in FROM clause

Can someone explain to me how I can solve it?

DELETE FROM PortafolioProject.NashvilleHousing AS Tb1
WHERE EXISTS (SELECT 1 FROM PortafolioProject.NashvilleHousing AS Tb2
              WHERE Tb2.ParcelID = Tb1.ParcelID AND
                    Tb2.PropertyAddress = Tb1.PropertyAddress AND
                    Tb2.SalePrice = Tb1.SalePrice AND
                    Tb2.SaleDate = Tb1.SaleDate AND
                    Tb2.LegalReference = Tb1.LegalReference AND
                    Tb2.UniqueID < Tb1.UniqueID);


问:
POST method not working via JavaScript (OK, via form submission with button)
The "/" route renders "form1.ejs", this file contains an HTML dropdown box. When a change is detected within the dropdown, it triggers the execution of a function which perform a POST to route "/form", which then redirects to GET route "/form2" which is then supposed to render "form2.ejs". It appears that the POST worked because a console.log seems to confirm it, with "About to redirect to "/form2"", which seems to occur, because inside this GET route, two more console.logs are triggered, except that the browser does not show the GET route as "/form2" it still says "/form1" and the "form2.ejs" is not rendered.

If I were to manually enter the "/form2" route by typing it into the browser URL, the browser  then displays "form2.ejs", as expected (along with the "/form2" route. Also, to test the routing, I added a submit button to the form in "form1.ejs", and when I click on submit, the POST occurs fine, it redirects to the GET and "form2.ejs" is rendered.

So in summary, I can make a POST request via the button and receive the expected chain of events, but not so, when executing a POST via JavaScript ... even though the console.log(s) appear to indicate that all routes along the chain were triggered.

For those curious enough to want to reproduce:
https://github.com/timholmez/POST-using-JavaScript

app.js

```<code>let http = require('http');
const path = require('path');
const bodyParser = require('body-parser')
const session = require('express-session');

let express = require('express');
var jsonParser = bodyParser.json();
let app = express();
let http_port = 8080;
let httpServer = http.createServer(app);

httpServer.listen(http_port, () => {
    console.log(`Listenting on Port:${http_port}`);
});

app.use(express.static(`public`));
app.use(express.urlencoded({ extended: true}));

const sessionConfig = {
    secret: `notagoodsecret`,
    resave:false,
    saveUninitialized: false,
    cookie: {
        httpOnly: true,
        expires: Date.now() + 1000 * 60 * 60 * 24, // 24 hours
        maxAge: 1000 * 60 * 60 * 24
    }
}
app.use(session(sessionConfig));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/', function (req, res) {
    res.render('form1');
});

app.post('/form', jsonParser, (req, res) => {
    req.session.action = JSON.stringify(req.body.action);
    console.log(`About to redirect to "/form2"`);
    res.redirect(`/form2`);
});

app.get(`/form2`, (req, res) => {
    console.log(`Inside The "/form2" Route`);
    const action = req.session.action
    console.log(`Action:${req.session.action}`);
    res.render(`form2`, {action})
});
</code>```

form1.ejs

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
  </head>
<body>

<script type="text/javascript">

  async function postData(url, data) {
    console.log(`postData got called within form1.ejs`);
    const response = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {'Content-type': 'application/json; charset=UTF-8'}
    })
      .then(response => {
          if (!response.ok) {
              throw new Error("Could not reach desired route.");
          }
          return response.text();
      })

      .catch((err) => {
        console.log(`Error Occured Executing function "postData"`);
        console.error(err);
      })
  }

  function firstAction(dropdown) {
    var optionValue = dropdown.options[dropdown.selectedIndex].value;
    const data = {"action": optionValue}

    postData('/form', data)
  }
</script>

<div>
  <h1>This is Form 1</h1>
  <form action="/form" method="POST">
    <label for="action">Action</label>
    <select onchange="firstAction(this)" name="action" id="action">
      <option value = "item1">Item 1</option>
      <option value = "item2">Item 2</option>
      <option value = "item3">Item 3</option>
      <option value = "item4">Item 4</option>
      <option value = "item5">Item 5</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</div>

</body>
</html>
</code>```

form2.ejs

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
  </head>
<body>
<div>
  <h1>This is Form 2 and it only displays if the POST request is submitted via the button
    from within the form. The POST request made via javascript does not accomplish the
    same even though the /form2 "GET" route appears to have been activated as evidenced
    by the console.log messages that are triggered whilst in route /form2"</h1>
</div>
</body>
</html>
</code>```

Any thoughts anyone?
Thanks.
Tim.

Body:
The "/" route renders "form1.ejs", this file contains an HTML dropdown box. When a change is detected within the dropdown, it triggers the execution of a function which perform a POST to route "/form", which then redirects to GET route "/form2" which is then supposed to render "form2.ejs". It appears that the POST worked because a console.log seems to confirm it, with "About to redirect to "/form2"", which seems to occur, because inside this GET route, two more console.logs are triggered, except that the browser does not show the GET route as "/form2" it still says "/form1" and the "form2.ejs" is not rendered.

If I were to manually enter the "/form2" route by typing it into the browser URL, the browser  then displays "form2.ejs", as expected (along with the "/form2" route. Also, to test the routing, I added a submit button to the form in "form1.ejs", and when I click on submit, the POST occurs fine, it redirects to the GET and "form2.ejs" is rendered.

So in summary, I can make a POST request via the button and receive the expected chain of events, but not so, when executing a POST via JavaScript ... even though the console.log(s) appear to indicate that all routes along the chain were triggered.

For those curious enough to want to reproduce:
https://github.com/timholmez/POST-using-JavaScript

app.js

let http = require('http');
const path = require('path');
const bodyParser = require('body-parser')
const session = require('express-session');

let express = require('express');
var jsonParser = bodyParser.json();
let app = express();
let http_port = 8080;
let httpServer = http.createServer(app);

httpServer.listen(http_port, () => {
    console.log(`Listenting on Port:${http_port}`);
});

app.use(express.static(`public`));
app.use(express.urlencoded({ extended: true}));

const sessionConfig = {
    secret: `notagoodsecret`,
    resave:false,
    saveUninitialized: false,
    cookie: {
        httpOnly: true,
        expires: Date.now() + 1000 * 60 * 60 * 24, // 24 hours
        maxAge: 1000 * 60 * 60 * 24
    }
}
app.use(session(sessionConfig));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/', function (req, res) {
    res.render('form1');
});

app.post('/form', jsonParser, (req, res) => {
    req.session.action = JSON.stringify(req.body.action);
    console.log(`About to redirect to "/form2"`);
    res.redirect(`/form2`);
});

app.get(`/form2`, (req, res) => {
    console.log(`Inside The "/form2" Route`);
    const action = req.session.action
    console.log(`Action:${req.session.action}`);
    res.render(`form2`, {action})
});

form1.ejs

<!DOCTYPE html>

    <meta charset="UTF-8">

This is Form 1

  <form action="/form" method="POST">
    Action
    <select onchange="firstAction(this)" name="action" id="action">
      <option value = "item1">Item 1</option>
      <option value = "item2">Item 2</option>
      <option value = "item3">Item 3</option>
      <option value = "item4">Item 4</option>
      <option value = "item5">Item 5</option>
    </select>
    <button type="submit">Submit</button>
  </form>

form2.ejs

<!DOCTYPE html>

    <meta charset="UTF-8">

This is Form 2 and it only displays if the POST request is submitted via the button
    from within the form. The POST request made via javascript does not accomplish the
    same even though the /form2 "GET" route appears to have been activated as evidenced
    by the console.log messages that are triggered whilst in route /form2"

Any thoughts anyone?
Thanks.
Tim.


问:
How to paginate +50000 records five9 report fetched over api
I'm fetching data from five9 using the SOAP api however some reports have more than 50000 records per day which is the limit that the method getReportResultCsv have.

Five9 Api method used

Right now im sending requests per hour but for some intervals the amount received is to small, so in order to make an optimization and reduce the number of requests send I'd like to know if there's a way to get a pagination when fetching results.

This is the documentation that's being used: https://webapps.five9.com/assets/files/for_customers/documentation/apis/config-webservices-api-reference-guide.pdf


问:
Is there a way to use survSplit to cut each observation at a different time?
I'm working on the following dataset: https://www.kaggle.com/datasets/pavansubhasht/ibm-hr-analytics-attrition-dataset

I'm trying to conduct a survival analysis on this dataset, but with so many measurements that depend on time after the start of the study, we need to do something about that. So I want to incorporate a recurring events model. I'm wondering if it's possible to set the 'cut' in the survSplit function at variable times, so that I can set something like YearsWithCurrManager as an intermediate event.

Obviously, people aren't going to be with their current manager for the same time as other people, so I wanted to cut by row based on how much time they've been with their current manager.

So, is it possible to cut at different times for each row? If my understanding of this data is also incorrect I'd be open to suggestions there too.

If I do cut= YearsAtCompany - YearsWithCurrManager (or something along those lines) that's just going to create a vector of all of those differences in time, which isn't what I want.


问:
Websocket Token Design
When we use http, we normally place our token in header, since HTTP is stateless. This makes sense.

However when it comes to WebSocket, I notice it is stateful. Should we still send it in every request, or just send it once, until some times has reached or server response expire, then we refresh the token and send it to server again?

I have found that public API expects us to send every request through WebSocket to include token, For example, in Deribit API

I do not understand the reason why token is needed for every request sent inside WebSocket. and Why such a design is made.

Can anyone explain to me, thanks.

Title: Websocket Token Design


问:
Speeding up batch prediction in Vertex AI on Tabular data to generate explanations
I am trying to run a batch prediction while generating explanations for tabular data with 100 features and 1.7 million rows with storage size 1.4GB

I am finding that my batch prediction is taking 20 minutes to run when the generate_explanation flag set to False or I run on 50 rows of data. But can take 15+ hours when set to generate_explanation=True on a full dataset

I am using this method here
https://cloud.google.com/python/docs/reference/aiplatform/latest/google.cloud.aiplatform.Model#google_cloud_aiplatform_Model_batch_predict

I have tried increasing these parameters from this

```<code>starting_replica_count=20,
max_replica_count=20,
batch_size=64
</code>```

To this. The job is currently running

```<code>starting_replica_count=40,
max_replica_count=40,
batch_size=128
</code>```

Are there any suggestions on how to improve the speed?

Body:
I am trying to run a batch prediction while generating explanations for tabular data with 100 features and 1.7 million rows with storage size 1.4GB

I am finding that my batch prediction is taking 20 minutes to run when the generate_explanation flag set to False or I run on 50 rows of data. But can take 15+ hours when set to generate_explanation=True on a full dataset

I am using this method here
https://cloud.google.com/python/docs/reference/aiplatform/latest/google.cloud.aiplatform.Model#google_cloud_aiplatform_Model_batch_predict

I have tried increasing these parameters from this

starting_replica_count=20,
max_replica_count=20,
batch_size=64

To this. The job is currently running

starting_replica_count=40,
max_replica_count=40,
batch_size=128

Are there any suggestions on how to improve the speed?


问:
How can I get rid of the VS Code warning of "Seriver[x] disconnected unexpectedly"
I ran into this warning (see pictures as I run Python multiprocessing to fire up multiple cores (almost all the core available). After I clicked cancel. I will see the second error message which says failed to launch debugger fora child processes.

The code will finish running and produce correct results. But VS code will generate multiple warning and laying on top of the entire VS code, which need to be manually click off.

Do we know the proper way to prevent this from happening?

Some relevent post I found. As I am investigating, I will keep updating this post.

https://github.com/microsoft/debugpy/issues/712

)


问:
How To find Distance between Npcs humanoids so they can chase eachother?
I have a testing studio place where I created Npcs to chase each other and they do that by looping through workspace to find other humanoids besides their own and chasing them. The problem is I use this if statement (fighter.HumanoidRootPart.Position.X. - closestEnemy.HumanoidRootPart.Position.X). Magnitude < 3 that when they are close and less than 3 studs away from each other they will damage one another, but when they are even touching each other, no Damage is happening and when I print that equation into output, I get a negative number when they approach from a certain direction. Someone please help! Thank you. Ps. It would be helpful If someone could tell me a good way to find distances between Npcs that work.
`


问:
How can I loop this script every 30 seconds?
I want to loop this script every 30 seconds.

tweets = tweepy.Cursor(api.search_tweets, q='safe dev', lang='en', tweet_mode='extended').items(100)
print(tweet.full_text, tweet.created_at)
```

I tried while true but it's not showing results.

Body:
I want to loop this script every 30 seconds.

tweets = tweepy.Cursor(api.search_tweets, q='safe dev', lang='en', tweet_mode='extended').items(100)
print(tweet.full_text, tweet.created_at)

I tried while true but it's not showing results.


问:
TypeScript Date type is not JS Date type?
I have a model:

```<code>export class SendModel{
periodFrom: Date,
periodTo: Date
}
</code>```

I have a service:

```<code>public async Calculate(periodFrom: Date,  periodTo: Date):Promise<SendModel>
{
let resObj = this.http.get(url, params:{periodFrom: `${periodFrom}`, periodTo: `${periodTo}`}).toPromise();
//...another code...//
}
</code>```

I receive a SendModel object from api.

```<code>{
periodFrom: '2022-11-24T00-00-00Z',
periodTo: '2026-01-01T00-00-00Z'
}
</code>```

Ok, I need add 3 month to periodFrom var.

```<code>let startPayday = receiveObj.periodFrom.setMonth(receiveObj.periodFrom.getMonth()+3); //not working, despite receiveObj.periodFrom has type is Date (what?)
let startPayday2 = new Date(new Date(receiveObj.periodFrom).setMonth(new Date(receiveObj.periodFrom).getMonth()+3)); //worsk! ok
</code>```

Ok, let`s send it to api.

```<code>this.service.Calculate(startPayday2, receiveObj.periodTo); //error!
</code>```

Wrong api call, status 400, One or more validation errors.
Look at the request: api/calculate?periodFrom=Fri Feb 24 2023 03:00:00 GMT 0300 (blablabla)&periodTo=2026-01-01T00-00-00Z

Maybe like this?

```<code>this.service.Calculate(startPayday2.toISOString(), receiveObj.periodTo); //nope, argument is type 'string' bla-bal-bla...
</code>```

startPayday2 has type Date, API expects type Date, but these are different types that are serialized differently?

Body:
I have a model:

export class SendModel{
periodFrom: Date,
periodTo: Date
}

I have a service:

public async Calculate(periodFrom: Date,  periodTo: Date):Promise<SendModel>
{
let resObj = this.http.get(url, params:{periodFrom: `${periodFrom}`, periodTo: `${periodTo}`}).toPromise();
//...another code...//
}

I receive a SendModel object from api.

{
periodFrom: '2022-11-24T00-00-00Z',
periodTo: '2026-01-01T00-00-00Z'
}

Ok, I need add 3 month to periodFrom var.

let startPayday = receiveObj.periodFrom.setMonth(receiveObj.periodFrom.getMonth()+3); //not working, despite receiveObj.periodFrom has type is Date (what?)
let startPayday2 = new Date(new Date(receiveObj.periodFrom).setMonth(new Date(receiveObj.periodFrom).getMonth()+3)); //worsk! ok

Ok, let`s send it to api.

this.service.Calculate(startPayday2, receiveObj.periodTo); //error!

Wrong api call, status 400, One or more validation errors.
Look at the request: api/calculate?periodFrom=Fri Feb 24 2023 03:00:00 GMT 0300 (blablabla)&periodTo=2026-01-01T00-00-00Z

Maybe like this?

this.service.Calculate(startPayday2.toISOString(), receiveObj.periodTo); //nope, argument is type 'string' bla-bal-bla...

startPayday2 has type Date, API expects type Date, but these are different types that are serialized differently?


问:
Debugging a nuget package built by Azure Devops doesn't work
Let me start by saying if I build the package locally and publish it to a local drive, everything works as expected. If the same steps are done in Azure DevOps and the package is published to our private/company feed, debugging does not work (the code steps through the package code without going in). Also, this is .Net 4.8 application, not net core.
Here's what I've done to enable debugging.

In the class library being packaged, installed Microsoft.SourceLink.GitHub packages to generate source link for GitHub repository (our code is there).

In VS, in Options->Debugging unchecked "Enable Just My Code".

I build a release configuration of the package either using VS build or msbuild (makes no differencce). Then I use Package Manager Console to build the package (i.e., nuget pack [path to project file] -properties configuration=Release). When I add this locally build package, debugging works just fine. My assumption is the above source link package points to the location in the repository. There's no pdb anywhere so, since everything works fine, I'm assuming it's not needed.

If the same steps are done on Azure Devops server, the package is published to the company's private feed and added to the consuming project from there, debugging does not work. You'd think with the project file being the same, debugging should work regardless where you built it.

I've tried to add "Index sources and publish symbols" step per these instructions  but it makes no difference. I also tried making the below change to the project file setting DebuggingSymbols=true and DebugType=Full. This didn't make any difference either.

```<code> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>full</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <Prefer32Bit>false</Prefer32Bit>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>
</code>```

Please share your ideas!

The pipeline is below:

# Variable 'BuildVerbosity' was defined in the Variables tab
# Variable 'ProjectName' was defined in the Variables tab
trigger:
  branches:
    include:
    - refs/heads/main
resources:
  repositories:
  - repository: self
    type: git
    ref: refs/heads/main
jobs:
- job: Job_1
  displayName: Agent job 1
  pool:
    vmImage: windows-latest
  steps:
  - checkout: self
    clean: true
    fetchTags: false
  - task: Assembly-Info-NetFramework@3
    name: SetVersion
    displayName: Set Assembly Version
    inputs:
      FileNames: >-
        **\AssemblyInfo.cs

        **\AssemblyInfo.vb
      VersionNumber: '#.#.#.$(Build.BuildId)'
      FileVersionNumber: '#.#.#.$(Build.BuildId)'
      FailOnWarning: true
  - task: Cache@2
    displayName: Cache NuGet Packages
    inputs:
      key: 926bec2e-d618-425e-b160-a368ecdcafc0
      path: packages
  - task: NuGetToolInstaller@1
    displayName: Get the latest NuGet.exe
  - task: NuGetCommand@2
    displayName: NuGet restore
    inputs:
      feedRestore: 697f4f9f-e201-40a9-9f9b-611dc64afec3
  - task: MSBuild@1
    displayName: Build solution **/*.sln
    inputs:
      msbuildArchitecture: x64
      configuration: $(BuildConfiguration)
  - task: CmdLine@2
    displayName: Display Directories - Delete this later
    enabled: False
    inputs:
      script: >
        echo "Here is the artifact directory: =====>>>   $(Build.ArtifactStagingDirectory)"

        echo "current directory"

        dir

        echo " "

        echo "*******************************************"

        echo "Build.SourcesDirectory\Projectname -> "  $(Build.SourcesDirectory)\$(ProjectName)\*

        dir $(Build.SourcesDirectory)\$(ProjectName)\*

        echo " "

        echo "*******************************************"

        echo "Build.SourcesDirectory\Projectname\bin\release\* -> "  $(Build.SourcesDirectory)\$(ProjectName)\bin\release\*

        dir $(Build.SourcesDirectory)\$(ProjectName)\bin\release\*

        echo " "

        echo "*******************************************"

        echo "Build.ArtifactStagingDirectory directory"

        dir $(Build.ArtifactStagingDirectory)
  - task: SimpleNuspecVersionSetter@1
    displayName: Set Nuspec Version to Beta
    inputs:
      RootDirectory: $(Build.SourcesDirectory)\$(ProjectName)
      NewVersion: $(SetVersion.AssemblyInfo.Version)-beta
  - task: NuGetCommand@2
    displayName: Create Package - Beta Version
    inputs:
      command: pack
      outputDir: $(Build.ArtifactStagingDirectory)/@BetaPackage
  - task: SimpleNuspecVersionSetter@1
    displayName: Set Nuspec Version to Release
    inputs:
      RootDirectory: $(Build.SourcesDirectory)\$(ProjectName)
      NewVersion: $(SetVersion.AssemblyInfo.Version)
  - task: NuGetCommand@2
    displayName: Create Package - Release Version
    inputs:
      command: pack
      outputDir: $(Build.ArtifactStagingDirectory)/@ReleasePackage
  - task: PublishSymbols@2
    displayName: Publish symbols path
    inputs:
      IndexSources: false
      SymbolServerType: TeamServices
  - task: PublishBuildArtifacts@1
    displayName: 'Publish Artifact: drop'
...```

Body:
Let me start by saying if I build the package locally and publish it to a local drive, everything works as expected. If the same steps are done in Azure DevOps and the package is published to our private/company feed, debugging does not work (the code steps through the package code without going in). Also, this is .Net 4.8 application, not net core.
Here's what I've done to enable debugging.

In the class library being packaged, installed Microsoft.SourceLink.GitHub packages to generate source link for GitHub repository (our code is there).

In VS, in Options->Debugging unchecked "Enable Just My Code".

I build a release configuration of the package either using VS build or msbuild (makes no differencce). Then I use Package Manager Console to build the package (i.e., nuget pack [path to project file] -properties configuration=Release). When I add this locally build package, debugging works just fine. My assumption is the above source link package points to the location in the repository. There's no pdb anywhere so, since everything works fine, I'm assuming it's not needed.

If the same steps are done on Azure Devops server, the package is published to the company's private feed and added to the consuming project from there, debugging does not work. You'd think with the project file being the same, debugging should work regardless where you built it.

I've tried to add "Index sources and publish symbols" step per these instructions  but it makes no difference. I also tried making the below change to the project file setting DebuggingSymbols=true and DebugType=Full. This didn't make any difference either.

 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>full</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <Prefer32Bit>false</Prefer32Bit>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

Please share your ideas!

The pipeline is below:

# Variable 'BuildVerbosity' was defined in the Variables tab
# Variable 'ProjectName' was defined in the Variables tab
trigger:
  branches:
    include:
    - refs/heads/main
resources:
  repositories:
  - repository: self
    type: git
    ref: refs/heads/main
jobs:
- job: Job_1
  displayName: Agent job 1
  pool:
    vmImage: windows-latest
  steps:
  - checkout: self
    clean: true
    fetchTags: false
  - task: Assembly-Info-NetFramework@3
    name: SetVersion
    displayName: Set Assembly Version
    inputs:
      FileNames: >-
        **\AssemblyInfo.cs

        **\AssemblyInfo.vb
      VersionNumber: '#.#.#.$(Build.BuildId)'
      FileVersionNumber: '#.#.#.$(Build.BuildId)'
      FailOnWarning: true
  - task: Cache@2
    displayName: Cache NuGet Packages
    inputs:
      key: 926bec2e-d618-425e-b160-a368ecdcafc0
      path: packages
  - task: NuGetToolInstaller@1
    displayName: Get the latest NuGet.exe
  - task: NuGetCommand@2
    displayName: NuGet restore
    inputs:
      feedRestore: 697f4f9f-e201-40a9-9f9b-611dc64afec3
  - task: MSBuild@1
    displayName: Build solution **/*.sln
    inputs:
      msbuildArchitecture: x64
      configuration: $(BuildConfiguration)
  - task: CmdLine@2
    displayName: Display Directories - Delete this later
    enabled: False
    inputs:
      script: >
        echo "Here is the artifact directory: =====>>>   $(Build.ArtifactStagingDirectory)"

        echo "current directory"

        dir

        echo " "

        echo "*******************************************"

        echo "Build.SourcesDirectory\Projectname -> "  $(Build.SourcesDirectory)\$(ProjectName)\*

        dir $(Build.SourcesDirectory)\$(ProjectName)\*

        echo " "

        echo "*******************************************"

        echo "Build.SourcesDirectory\Projectname\bin\release\* -> "  $(Build.SourcesDirectory)\$(ProjectName)\bin\release\*

        dir $(Build.SourcesDirectory)\$(ProjectName)\bin\release\*

        echo " "

        echo "*******************************************"

        echo "Build.ArtifactStagingDirectory directory"

        dir $(Build.ArtifactStagingDirectory)
  - task: SimpleNuspecVersionSetter@1
    displayName: Set Nuspec Version to Beta
    inputs:
      RootDirectory: $(Build.SourcesDirectory)\$(ProjectName)
      NewVersion: $(SetVersion.AssemblyInfo.Version)-beta
  - task: NuGetCommand@2
    displayName: Create Package - Beta Version
    inputs:
      command: pack
      outputDir: $(Build.ArtifactStagingDirectory)/@BetaPackage
  - task: SimpleNuspecVersionSetter@1
    displayName: Set Nuspec Version to Release
    inputs:
      RootDirectory: $(Build.SourcesDirectory)\$(ProjectName)
      NewVersion: $(SetVersion.AssemblyInfo.Version)
  - task: NuGetCommand@2
    displayName: Create Package - Release Version
    inputs:
      command: pack
      outputDir: $(Build.ArtifactStagingDirectory)/@ReleasePackage
  - task: PublishSymbols@2
    displayName: Publish symbols path
    inputs:
      IndexSources: false
      SymbolServerType: TeamServices
  - task: PublishBuildArtifacts@1
    displayName: 'Publish Artifact: drop'
...


问:
Not able to install Pgadmin4 in Oracle cloud with Ubuntu 22.04
While trying to install the pgadmin4 in Oracle cloud Ubuntu 22.04 am getting below error.

The following packages have unmet dependencies:

```<code>Depends: pgadmin4-server (= 6.17) but it is not installable
Depends: pgadmin4-desktop (= 6.17) but it is not installable
Depends: pgadmin4-web (= 6.17) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

I have installed postgresql successfully and verified the status as well. Used below below link to install Pgadmin4 https://www.pgadmin.org/download/pgadmin-4-apt/

Any help much appreciated, thanks

Body:
While trying to install the pgadmin4 in Oracle cloud Ubuntu 22.04 am getting below error.

The following packages have unmet dependencies:

Depends: pgadmin4-server (= 6.17) but it is not installable
Depends: pgadmin4-desktop (= 6.17) but it is not installable
Depends: pgadmin4-web (= 6.17) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I have installed postgresql successfully and verified the status as well. Used below below link to install Pgadmin4 https://www.pgadmin.org/download/pgadmin-4-apt/

Any help much appreciated, thanks


问:
Error "Unexpected end of multipart form" in busboy file upload
I am using busboy to upload file in node/express app. I get error Unexpected end of multipart form and the application crash. Whenever I try the route on insomnia, nothing works. Before it was showing that Busboy is not a constructor, so I changed let to const and deleted new, leaving it as it is in the code.

What could be the cause of this error?

this is my code:

```<code>router.post('/', async (req, res) => {
    const busboy = Busboy({ headers: req.headers });
    busboy.on('finish', async () => {
        try {
            const { salaoId, servicos } = req.body;
            let error = [];
            let arquivos = [];

            console.log(req.files)

            if (req.files && Object.keys(req.files) > 0) {
                for (let key of Object.keys(req.files)) {
                    const file = req.files[key];

                    const nameParts = file.name.split('.');
                    const fileName = `${new Date().getTime()}.${nameParts[nameParts.length - 1]
                        }`;
                    const path = `servicos/${salaoId}/${fileName}`;

                    const response = await aws.uploadToS3(file, path);

                    if (response.error) {
                        error.push({ error: true, message: response.message })
                    } else {
                        arquivos.push(path)
                    }
                }
            }

            if (error.length > 0) {
                res.json(error[0]);
                return false;
            }

            //CRIAR SERVIÇO
            let jsonServico = JSON.parse(servicos);
            const servicoCadastrado = await Servicos(jsonServico).save();

            //CRIAR ARQUIVO
            arquivos = arquivos.map(arquivo => ({
                referenciaId: servicoCadastrado._id,
                model: 'Servicos',
                caminho: arquivo,
            }));

            await Arquivo.insertMany(arquivos);
            res.json({ servicos: servicoCadastrado, arquivos });

        } catch (error) {
            res.json({ error: true, message: error.message })
        }
    });
    req.pipe(req.busboy)
});

module.exports = router;
</code>```

this is error:

```<code>throw er; // Unhandled 'error' event
      ^

Error: Unexpected end of form
    at Multipart._final (C:\Users\Lenovo\Desktop\projetos\meus-projetos\app-claudiagomes\ws\node_modules\busboy\lib\types\multipart.js:588:17)
</code>```

Body:
I am using busboy to upload file in node/express app. I get error Unexpected end of multipart form and the application crash. Whenever I try the route on insomnia, nothing works. Before it was showing that Busboy is not a constructor, so I changed let to const and deleted new, leaving it as it is in the code.

What could be the cause of this error?

this is my code:

router.post('/', async (req, res) => {
    const busboy = Busboy({ headers: req.headers });
    busboy.on('finish', async () => {
        try {
            const { salaoId, servicos } = req.body;
            let error = [];
            let arquivos = [];

            console.log(req.files)

            if (req.files && Object.keys(req.files) > 0) {
                for (let key of Object.keys(req.files)) {
                    const file = req.files[key];

                    const nameParts = file.name.split('.');
                    const fileName = `${new Date().getTime()}.${nameParts[nameParts.length - 1]
                        }`;
                    const path = `servicos/${salaoId}/${fileName}`;

                    const response = await aws.uploadToS3(file, path);

                    if (response.error) {
                        error.push({ error: true, message: response.message })
                    } else {
                        arquivos.push(path)
                    }
                }
            }

            if (error.length > 0) {
                res.json(error[0]);
                return false;
            }

            //CRIAR SERVIÇO
            let jsonServico = JSON.parse(servicos);
            const servicoCadastrado = await Servicos(jsonServico).save();

            //CRIAR ARQUIVO
            arquivos = arquivos.map(arquivo => ({
                referenciaId: servicoCadastrado._id,
                model: 'Servicos',
                caminho: arquivo,
            }));

            await Arquivo.insertMany(arquivos);
            res.json({ servicos: servicoCadastrado, arquivos });

        } catch (error) {
            res.json({ error: true, message: error.message })
        }
    });
    req.pipe(req.busboy)
});

module.exports = router;

this is error:

throw er; // Unhandled 'error' event
      ^

Error: Unexpected end of form
    at Multipart._final (C:\Users\Lenovo\Desktop\projetos\meus-projetos\app-claudiagomes\ws\node_modules\busboy\lib\types\multipart.js:588:17)


问:
ffmpeg on google app engine or other alternatives
This isn’t really a problem with any specific bit of code more just a general question about how I would host a ffmpeg function within a severless function like google app engine. Basically I have a block of code that takes every n frame a video and uploads it to google cloud storage. I have tried implementing such a solution with Firebase functions but to no avail. I think the primary problem is really to do with file storage, from my undetnsdjng data should be written to the tmp folder.

So if anyone can outline exactly how I could host this on app engine that would be great, please be very specific and don’t assumeI know anything because I’ve only really worked with functions :)

Thanks so much

```<code>
//Essentially this but on app engine or any other severless environment

try {
        const process = new ffmpeg('star_wars_film_scene.mp4');
        process.then(function(video) {
            // Callback mode
            video.fnExtractFrameToJPG('helpers/frames/', {
                every_n_frames: 500

            }, function(error, files) {
                if (error) {
                    console.log(error);
                    return;
                }
                ProcessFrames(files);
            });
        }, function(err) {
            console.log(err);
        });
    } catch (e) {
        console.log('Houston, we have a problem')
        console.log(e.code);
        console.log(e.msg);
    }

</code>```

Body:
This isn’t really a problem with any specific bit of code more just a general question about how I would host a ffmpeg function within a severless function like google app engine. Basically I have a block of code that takes every n frame a video and uploads it to google cloud storage. I have tried implementing such a solution with Firebase functions but to no avail. I think the primary problem is really to do with file storage, from my undetnsdjng data should be written to the tmp folder.

So if anyone can outline exactly how I could host this on app engine that would be great, please be very specific and don’t assumeI know anything because I’ve only really worked with functions :)

Thanks so much

//Essentially this but on app engine or any other severless environment

try {
        const process = new ffmpeg('star_wars_film_scene.mp4');
        process.then(function(video) {
            // Callback mode
            video.fnExtractFrameToJPG('helpers/frames/', {
                every_n_frames: 500

            }, function(error, files) {
                if (error) {
                    console.log(error);
                    return;
                }
                ProcessFrames(files);
            });
        }, function(err) {
            console.log(err);
        });
    } catch (e) {
        console.log('Houston, we have a problem')
        console.log(e.code);
        console.log(e.msg);
    }


问:
Unable to install libraries for google drive api? (in pycharm)
I've been following the instructions on the quickstart page for google drive api v3 (I'm learning python and I want to try create a program that involves downloading images from google drive) but I'm unable to install the required packages

it tells me to run this program in terminal to install the libraries

```<code>
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

</code>```

and I'm told that it succeeded (trying to do so again tells me that requirements have already been satisfied) but the red error lines still exist and i'm told that its a "unresolved reference"

Body:
I've been following the instructions on the quickstart page for google drive api v3 (I'm learning python and I want to try create a program that involves downloading images from google drive) but I'm unable to install the required packages

it tells me to run this program in terminal to install the libraries

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

and I'm told that it succeeded (trying to do so again tells me that requirements have already been satisfied) but the red error lines still exist and i'm told that its a "unresolved reference"


问:
Put KotlinLogging Logger call in another file and retain name
With KotlinLogger and SLF4J, I want to do something like

```<code>// In Log.kt
val logger = KotlinLogging.logger {}

// In Main.kt after importing logger
fun main() {
  val loggerMain = KotlinLogging.logger {}
  loggerMain.info("Hello world") // Main: Hello world

  // I want logger to have the same name as loggerMain instead.
  logger.info("Hello world") // Log: Hello world

}
</code>```

I want to reduce the amount of unnecessary boiler plate if possible, and having to create a variable containing the logger for every scope that needs it is something I want to avoid.

I.e. inside of Log.kt, I want to give the logger the name of whatever file accessed it as if it were declared in that file.

Body:
With KotlinLogger and SLF4J, I want to do something like

// In Log.kt
val logger = KotlinLogging.logger {}

// In Main.kt after importing logger
fun main() {
  val loggerMain = KotlinLogging.logger {}
  loggerMain.info("Hello world") // Main: Hello world

  // I want logger to have the same name as loggerMain instead.
  logger.info("Hello world") // Log: Hello world

}

I want to reduce the amount of unnecessary boiler plate if possible, and having to create a variable containing the logger for every scope that needs it is something I want to avoid.

I.e. inside of Log.kt, I want to give the logger the name of whatever file accessed it as if it were declared in that file.


问:
Is it possible to use quarkiverse.azureservices HTTP/Web client as I would use the CosmosAsyncClient/CosmosAsyncContainer/CosmosAsyncDatabase?
I'm still new at dev with CosmosDB, Quarkus, and Vertx and am seeking some clarification - originally I ran into errors with the Quarkus native build as specified in this GitHub issue and according to the reply, I assumed it referred to the CosmosAsyncClient that we use as the culprit of issues when trying to build the native image. Per the reply, I found this project and used mvn clean install to build locally (couldn't be found in the remote repository?) and added the following dependency for what I think is the extension that was being referred to in my project's pom:

```<code><dependency>
    <groupId>io.quarkiverse.azureservices</groupId>
    <artifactId>quarkus-azure-http-client-vertx</artifactId>
    <version>999-SNAPSHOT</version>
</dependency>
</code>```

But I am currently unsure of how to go from here in order to use the HTTP/Web client to communicate with CosmosDB (e.g. CosmosAsyncClientBuilder uses endpoint() and key() - are there equivalents/how can I use this in the HTTPClient context?) and the specific containers I need to query.

So far I've created a Vertx from the QuarkusVertxProvider and then a WebClient from that Vertx but I'm currently stuck with how I would go about sending queries to the database and the specific containers I want to use in CosmosDB without relying on classes from com.azure.cosmos, as later I want to be able to run the native build. Has anyone had success in using Web/HTTPClient instead of CosmosAsyncClient, or is this not possible?

If there are different suggestions for any Quarkus extensions I may have missed that is better suited for what I'm trying to do, please let me know. I have briefly worked with the reactive postgreSQL and mongoDB and the tutorials were easy to understand and showed how we could specify the database connection e.g. in our properties file, but I don't know what is the equivalent for this with Cosmos.

Body:
I'm still new at dev with CosmosDB, Quarkus, and Vertx and am seeking some clarification - originally I ran into errors with the Quarkus native build as specified in this GitHub issue and according to the reply, I assumed it referred to the CosmosAsyncClient that we use as the culprit of issues when trying to build the native image. Per the reply, I found this project and used mvn clean install to build locally (couldn't be found in the remote repository?) and added the following dependency for what I think is the extension that was being referred to in my project's pom:

<dependency>
    <groupId>io.quarkiverse.azureservices</groupId>
    <artifactId>quarkus-azure-http-client-vertx</artifactId>
    <version>999-SNAPSHOT</version>
</dependency>

But I am currently unsure of how to go from here in order to use the HTTP/Web client to communicate with CosmosDB (e.g. CosmosAsyncClientBuilder uses endpoint() and key() - are there equivalents/how can I use this in the HTTPClient context?) and the specific containers I need to query.

So far I've created a Vertx from the QuarkusVertxProvider and then a WebClient from that Vertx but I'm currently stuck with how I would go about sending queries to the database and the specific containers I want to use in CosmosDB without relying on classes from com.azure.cosmos, as later I want to be able to run the native build. Has anyone had success in using Web/HTTPClient instead of CosmosAsyncClient, or is this not possible?

If there are different suggestions for any Quarkus extensions I may have missed that is better suited for what I'm trying to do, please let me know. I have briefly worked with the reactive postgreSQL and mongoDB and the tutorials were easy to understand and showed how we could specify the database connection e.g. in our properties file, but I don't know what is the equivalent for this with Cosmos.


问:
How to get auto increment identity column working
We are using EF Core, but we also upgrade pre-ef core databases to the latest version. On Postegres there is a table:

CREATE TABLE "DatabaseVersion"
(
    "DatabaseVersionId" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ) PRIMARY KEY,
    "Version"     varchar(20) NOT NULL,
    "VersionDate" timestamptz NULL DEFAULT Now(),
    "Description" varchar(2000) NULL,
    "AppliedDate" timestamptz NULL DEFAULT Now()
);
```
<p>In PgAdmin, I create a database and this table, then I insert into the table for a test using:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO "DatabaseVersion" ("Version")
VALUES ('1.0.0.0');
</code>```

and I get the first row entered then I can change the version in the insert statement and insert more rows. Each row has a unique DatabaseVersionId.

However, when I run the upgrade and attempt to insert a value using EF Core, I get an exception

duplicate key value violates unique constraint

I created a new database to see how EF Core defined the key and it is:

GENERATED BY DEFAULT AS IDENTITY (INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1).
```
<p>I added primary key to that to avoid adding a lot of primary key constraints to our older scripts.</p>
<p>Our update code is shown here (<code>T</code> would be <code>DatabaseVersion</code>):</p>
<pre class="lang-cs prettyprint-override"><code>var dbSet = context.Set<T> ();

var id = GetKey (context, item);

if (id == 0)
{
    dbSet.Add (item);
}
else
{
    var p = dbSet.Find (id);
    dbSet.Attach (p);

    var a = context.Entry (p);

    if (a != null)
        a.CurrentValues.SetValues (item);
}

context.SaveChanges ();
</code>```

What needs to be done to older scripts to make the identity primary key work?

Or is that even the problem? I am not a postgres expert.

Our database upgrade uses scripts until it gets to a certain version, then we run each migration individually. EF Core figures out not to run the initial create migration on its own, but it still adds an entry in the __EFMigrationsHistory table, which is great.

Update

In my searches I found this question. During our update and create of a new database we insert data that has the primary key already set, so with postgresql the sequence is not updated and on your first insert your get a duplicate key exception. To get around this after a create or upgrade of a databse you can use the following script:

```<code>                @"SELECT setval(
                  (SELECT pg_get_serial_sequence( '""<%SchemaName%>"".""<%TableName%>""', '<%KeyName%>')),
                  (SELECT MAX(""<%KeyName%>"") from ""<%SchemaName%>"".""<%TableName%>""),
                  true );";

</code>```

Using this in a loop with table and primary key name all sequences can be set to their proper value.

Body:
We are using EF Core, but we also upgrade pre-ef core databases to the latest version. On Postegres there is a table:

CREATE TABLE "DatabaseVersion"
(
    "DatabaseVersionId" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ) PRIMARY KEY,
    "Version"     varchar(20) NOT NULL,
    "VersionDate" timestamptz NULL DEFAULT Now(),
    "Description" varchar(2000) NULL,
    "AppliedDate" timestamptz NULL DEFAULT Now()
);

In PgAdmin, I create a database and this table, then I insert into the table for a test using:

INSERT INTO "DatabaseVersion" ("Version")
VALUES ('1.0.0.0');

and I get the first row entered then I can change the version in the insert statement and insert more rows. Each row has a unique DatabaseVersionId.

However, when I run the upgrade and attempt to insert a value using EF Core, I get an exception

duplicate key value violates unique constraint

I created a new database to see how EF Core defined the key and it is:

GENERATED BY DEFAULT AS IDENTITY (INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1).

I added primary key to that to avoid adding a lot of primary key constraints to our older scripts.

Our update code is shown here (T would be DatabaseVersion):

var dbSet = context.Set<T> ();

var id = GetKey (context, item);

if (id == 0)
{
    dbSet.Add (item);
}
else
{
    var p = dbSet.Find (id);
    dbSet.Attach (p);

    var a = context.Entry (p);

    if (a != null)
        a.CurrentValues.SetValues (item);
}

context.SaveChanges ();

What needs to be done to older scripts to make the identity primary key work?

Or is that even the problem? I am not a postgres expert.

Our database upgrade uses scripts until it gets to a certain version, then we run each migration individually. EF Core figures out not to run the initial create migration on its own, but it still adds an entry in the __EFMigrationsHistory table, which is great.

Update

In my searches I found this question. During our update and create of a new database we insert data that has the primary key already set, so with postgresql the sequence is not updated and on your first insert your get a duplicate key exception. To get around this after a create or upgrade of a databse you can use the following script:

                @"SELECT setval(
                  (SELECT pg_get_serial_sequence( '""<%SchemaName%>"".""<%TableName%>""', '<%KeyName%>')),
                  (SELECT MAX(""<%KeyName%>"") from ""<%SchemaName%>"".""<%TableName%>""),
                  true );";

Using this in a loop with table and primary key name all sequences can be set to their proper value.


问:
Compiling C++ with `.hpp` in includes folder and `.cpp` in sources folder in VS Code using Code Runner
So I'm using Code Runner extension by Jun Han to compile and run my C++ Code in VS Code (in Windows), My workspace folder looks like this

I really want to separate my .hpp files inside subfolder named incldues and also separate my .cpp class files to subfolder named sources to organize my files.

My Code Runner executor map - settings.json looks like this and it works fine but only if my .hpp's and .cpp's are also in the workspace main folder.

I can use CMake but we have no CMake in our University Computer Lab and our professor is the only one with access to download and install some application in it.

I have tried editing my Code Runner executor map - settings.json like this and #include "../includes/ConsoleInterface.hpp" in main.cpp and it don't work.


问:
C# Process Start: Programmatically open .cs file and navigate to line number
I'm curious if there is a way for a .cs file to programmatically open and navigate to a c# line of code (similar to ctrl + g)
via

```<code>public static System.Diagnostics.Process Start (string fileName, **string arguments**);
</code>```

Is it possible to use the overload string arguments to accomplish this?

I am currently using the single argument Process.Start() to open the .cs file and am copying the line# to clipboard, but the user still need to press ctrl+g && ctrl+v which is what I am trying to eliminate.

```<code>Clipboard.SetText(dr["Line"].ToString());
System.Diagnostics.Process.Start(Path.Combine(dr["Folder"].ToString(), dr["Filename"].ToString()));
</code>```

Body:
I'm curious if there is a way for a .cs file to programmatically open and navigate to a c# line of code (similar to ctrl + g)
via

public static System.Diagnostics.Process Start (string fileName, **string arguments**);

Is it possible to use the overload string arguments to accomplish this?

I am currently using the single argument Process.Start() to open the .cs file and am copying the line# to clipboard, but the user still need to press ctrl+g && ctrl+v which is what I am trying to eliminate.

Clipboard.SetText(dr["Line"].ToString());
System.Diagnostics.Process.Start(Path.Combine(dr["Folder"].ToString(), dr["Filename"].ToString()));


问:
How to use private OSLogMessage in iOS Swift Logger library?
I was working on Logging on to iOS and decided to learn more about Logger structure in iOS, started with Apple Official Documentation which is quite well, and after watched WWDC 2020 video about Logging, the problem is that I could not achieve to simulate the private logging as the documentation dictate or even in WWDC video did, somehow my application couldn't achieve it. I already examine the logs from the XCode terminal and the Console app with Simulator + Real Device, let me share my piece of code on logging.

let logger = Logger(subsystem: "com.myname.LogExample", category: "ViewController")
let appName = "LogExample"
let numberToBePrivate = 35
logger.notice("Hello, this is default message")
logger.notice("Hello again, this is default message with private integer of \(numberToBePrivate, privacy: .private)")
logger.log("Hello, my name is \(appName, privacy: .private)")
```
<p>And my logs, the outputs of the XCode terminal</p>
```2022-12-07 01:30:14.372319+0200 LogExample[62053:2356742] [ViewController] Hello, this is default message
2022-12-07 01:30:14.372816+0200 LogExample[62053:2356742] [ViewController] Hello again, this is default message with private integer of 35
2022-12-07 01:30:14.372921+0200 LogExample[62053:2356742] [ViewController] Hello, my name is LogExample
```
<p>And in the Console app</p>
<p><img src="https://i.stack.imgur.com/Df0gM.png" alt="enter image description here" /></p>
<p>What I expect is a total <code><private></code> mark on the message of set private privacy sections, which is the expected one.</p>
<p>As I know, the output in the Console.app for the second log should be exact like this:</p>
```Hello again, this is default message with private integer of <private>
```

As I said before, I tried both the simulator + real device and the behavior of the Logger is totally the same. If I am doing anything wrong, I would like to learn it or any idea which useful would be super cool.

PS: notice and log function is the same level, notice basically is the default log level, and when you don't describe the level in the log function, it is described as default, so they are basically the same. And they are supposed be persisted.

Thanks

Body:
I was working on Logging on to iOS and decided to learn more about Logger structure in iOS, started with Apple Official Documentation which is quite well, and after watched WWDC 2020 video about Logging, the problem is that I could not achieve to simulate the private logging as the documentation dictate or even in WWDC video did, somehow my application couldn't achieve it. I already examine the logs from the XCode terminal and the Console app with Simulator + Real Device, let me share my piece of code on logging.

let logger = Logger(subsystem: "com.myname.LogExample", category: "ViewController")
let appName = "LogExample"
let numberToBePrivate = 35
logger.notice("Hello, this is default message")
logger.notice("Hello again, this is default message with private integer of \(numberToBePrivate, privacy: .private)")
logger.log("Hello, my name is \(appName, privacy: .private)")

And my logs, the outputs of the XCode terminal

2022-12-07 01:30:14.372319+0200 LogExample[62053:2356742] [ViewController] Hello, this is default message
2022-12-07 01:30:14.372816+0200 LogExample[62053:2356742] [ViewController] Hello again, this is default message with private integer of 35
2022-12-07 01:30:14.372921+0200 LogExample[62053:2356742] [ViewController] Hello, my name is LogExample

And in the Console app

What I expect is a total <private> mark on the message of set private privacy sections, which is the expected one.

As I know, the output in the Console.app for the second log should be exact like this:

Hello again, this is default message with private integer of <private>

As I said before, I tried both the simulator + real device and the behavior of the Logger is totally the same. If I am doing anything wrong, I would like to learn it or any idea which useful would be super cool.

PS: notice and log function is the same level, notice basically is the default log level, and when you don't describe the level in the log function, it is described as default, so they are basically the same. And they are supposed be persisted.

Thanks


问:
Export from Excel to Word with Header Image Issue
I'm attempting to create a VBA code in Excel that will export from Excel into Word, with header text and a header image.  The header image should go on the right side of the Word header, with other header text on the left side of the Word header.

I can get the code to create a Word document and to create the header table.  The problem is, the image is always pasted into the Word header in column 1, I need that header image in column 2.  You can see in the code I'm telling it to paste the image in column 2 however it always pastes in column 1.  Any help would be greatly appreciated!  Thank you!

```<code>    Sub Export()

    Dim obj As Object
    Dim newobj As Object

    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    Sheets("Sheet1").Cells.Copy
    newobj.Range.Paste

    Application.CutCopyMode = False
    obj.Activate

    With obj
        .Visible = True
        With newobj
            Set wdRng = .Sections(1).Headers(1).Range
            Set wdTbl = .Tables.Add(Range:=wdRng, NumRows:=4, NumColumns:=2)
            With wdTbl
            ThisWorkbook.Sheets("Header_Image").Shapes(1).CopyPicture xlScreen, xlBitmap
            .cell(1, 2).Range.PasteSpecial
            End With
        End With
    End With

    End Sub
</code>```

I've tried many code variations, modifying the image formats, searching the web, etc.

Body:
I'm attempting to create a VBA code in Excel that will export from Excel into Word, with header text and a header image.  The header image should go on the right side of the Word header, with other header text on the left side of the Word header.

I can get the code to create a Word document and to create the header table.  The problem is, the image is always pasted into the Word header in column 1, I need that header image in column 2.  You can see in the code I'm telling it to paste the image in column 2 however it always pastes in column 1.  Any help would be greatly appreciated!  Thank you!

    Sub Export()

    Dim obj As Object
    Dim newobj As Object

    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    Sheets("Sheet1").Cells.Copy
    newobj.Range.Paste

    Application.CutCopyMode = False
    obj.Activate

    With obj
        .Visible = True
        With newobj
            Set wdRng = .Sections(1).Headers(1).Range
            Set wdTbl = .Tables.Add(Range:=wdRng, NumRows:=4, NumColumns:=2)
            With wdTbl
            ThisWorkbook.Sheets("Header_Image").Shapes(1).CopyPicture xlScreen, xlBitmap
            .cell(1, 2).Range.PasteSpecial
            End With
        End With
    End With

    End Sub

I've tried many code variations, modifying the image formats, searching the web, etc.


问:
Auto run npm install after git pull
so I have my own VPS, and I installed CyberPanel to host my website. The problem is that there is no option to do a command after my git is being pulled to the server. So I have to include node_modules in the repository which is a pain. Is there a way to automate the npm i script using anything like pm2 or something else? I have the root access in the VPS so I can install anything.

Title: Auto run npm install after git pull


问:
GAS files: how to free global space from polution?
How do I clean up my global space without having to create +1000 lines .gs files

Here follows two photos of some of my files/folders. Mind how low the scroll bar can slide (30+ GAS files) ↓

In Apps Script, .gs files cannot be manually mixed like .js modules, which means I cannot import or export (right?), neither control what will be shown when you search for completions;

If I wrap it around an interface, I usually end up with +1000 lines of code, which made the whole project difficult to read;

```<code>function groupOfFunctions() {
    this.doThis = function() { /* hundreds of lines */ };
    this.doThat = function() { /* hundreds of lines */ };
    // ...
    this.subFunc_N = function() { /* hundreds of lines */ };
    return this; // <-- makes tired face after this
};
</code>```

To avoid that, the project's been organized in a way all Functions rest on the global space;

New problem: eventually, my global space has gotten heavily poluted with tons of Functions;

The scenario is: I usually forget what Functions do, or even that they exist (so many times I coded something that was ready, but lost a

I've found no Youtube videos, questions in forums or anything like it anywhere on the internet that talks about how to deal with it, so the question is:

How do I clean up my global space without having to create +1000 lines .gs files

Articles, blogs, videos etc. are welcome.

Body:
How do I clean up my global space without having to create +1000 lines .gs files

Here follows two photos of some of my files/folders. Mind how low the scroll bar can slide (30+ GAS files) ↓

In Apps Script, .gs files cannot be manually mixed like .js modules, which means I cannot import or export (right?), neither control what will be shown when you search for completions;

If I wrap it around an interface, I usually end up with +1000 lines of code, which made the whole project difficult to read;

function groupOfFunctions() {
    this.doThis = function() { /* hundreds of lines */ };
    this.doThat = function() { /* hundreds of lines */ };
    // ...
    this.subFunc_N = function() { /* hundreds of lines */ };
    return this; // <-- makes tired face after this
};

To avoid that, the project's been organized in a way all Functions rest on the global space;

New problem: eventually, my global space has gotten heavily poluted with tons of Functions;

The scenario is: I usually forget what Functions do, or even that they exist (so many times I coded something that was ready, but lost a

I've found no Youtube videos, questions in forums or anything like it anywhere on the internet that talks about how to deal with it, so the question is:

How do I clean up my global space without having to create +1000 lines .gs files

Articles, blogs, videos etc. are welcome.