问:
Ebay - 'error': 'invalid_grant', 'error_description': 'the provided authorization refresh token is invalid or was issued to another client'
Up until last month, my code was working perfectly. I was able to get a refresh token from eBay using AuthToken but for some reason, it just stopped. I have tried getting a new AuthToken with the same results and i have got the token manually from eBay and it works. I am at a loss as to what has happened and was wondering if someone could have a look at my code for me and see if I am doing something wrong.

Many Thanks

```<code>import datetime
import base64
import requests
import mysql.connector as mysql

class Access_Token:

    def __init__(self, User, Database,UserDetails):

        #print("Get/Check Token",User)
        self.Token = self.CheckUser(User,Database,UserDetails)

    def CheckUser(self, User,Database,UserDetails):
        AuthToken = ""
        CurrentTime = datetime.datetime.now()
        ExpireTime = CurrentTime + datetime.timedelta(minutes=4)  # Current time pluss 5 mins for expiry

        if User['token'] == None:  # If no Token then make one
            print("Make a new token as we have none for", Database['Database'], "-",Database['User'])
            AuthToken = self.GetOAuth(User,UserDetails)
            UserID = User['id']
            db_connection = mysql.connect(host=Database['Host'], database=Database['Database'], user=Database['User'], password=Database['Password'])  # Users
            cursor = db_connection.cursor()
            sql = "UPDATE Users SET AuthToken = %s, AuthTokenCreated = %s WHERE id=%s"
            val = (AuthToken, ExpireTime, UserID)
            cursor.execute(sql, val)
            db_connection.commit()
            cursor.close()
            return AuthToken

        elif User['AuthTokenCreated'] < str(CurrentTime):  # if token expires get a new one
            print("Token Expired for", Database['Database'], "-",Database['User'])
            AuthToken = self.GetOAuth(User,UserDetails)
            UserID = User['id']
            db_connection = mysql.connect(host=Database['Host'], database=Database['Database'], user=Database['User'], password=Database['Password'])  # Users
            cursor = db_connection.cursor()
            sql = "UPDATE Users SET AuthToken = %s, AuthTokenCreated = %s WHERE id=%s"
            val = (AuthToken, ExpireTime, UserID)
            cursor.execute(sql, val)
            db_connection.commit()
            cursor.close()
            return AuthToken

        else:
            print("Token Good for", Database['Database'], "-",Database['User'])
            AuthToken = User['AuthToken']
            return AuthToken

    def GetOAuth(self, User,UserDetails):
        encodedData = base64.b64encode(bytes(f"{UserDetails['client_id']}:{UserDetails['client_secret']}", "ISO-8859-1")).decode("ascii")
        authorization_header_string = f"Authorization: Basic {encodedData}"

        headers = {"Authorization": "Basic " + encodedData, "Content-Type": "application/x-www-form-urlencoded"}

        data = {
            'grant_type': 'refresh_token',
            'refresh_token': User['token'],
            'redirect_uri': User['redirect_uri'],
        }

        response = requests.post('https://api.ebay.com/identity/v1/oauth2/token', headers=headers, data=data)
        data = response.json()
        print("UserDetails", UserDetails)
        print("===================")
        print("User", User)
        print("===================")
        print("Headers", headers)
        print("===================")
        print("Response", response)
        print("===================")
        print("data", data)
        print("===================")
        print("Getting New Token",response,data['access_token'])
        print("===================")
        print(data)
        return data['access_token']
</code>```

I have tried revoking the keys and readding them all with no luck. EBay have told me there is nothing wrong on their end. I have manually inputted the Authtoken and my script works

Body:
Up until last month, my code was working perfectly. I was able to get a refresh token from eBay using AuthToken but for some reason, it just stopped. I have tried getting a new AuthToken with the same results and i have got the token manually from eBay and it works. I am at a loss as to what has happened and was wondering if someone could have a look at my code for me and see if I am doing something wrong.

Many Thanks

import datetime
import base64
import requests
import mysql.connector as mysql

class Access_Token:

    def __init__(self, User, Database,UserDetails):

        #print("Get/Check Token",User)
        self.Token = self.CheckUser(User,Database,UserDetails)

    def CheckUser(self, User,Database,UserDetails):
        AuthToken = ""
        CurrentTime = datetime.datetime.now()
        ExpireTime = CurrentTime + datetime.timedelta(minutes=4)  # Current time pluss 5 mins for expiry

        if User['token'] == None:  # If no Token then make one
            print("Make a new token as we have none for", Database['Database'], "-",Database['User'])
            AuthToken = self.GetOAuth(User,UserDetails)
            UserID = User['id']
            db_connection = mysql.connect(host=Database['Host'], database=Database['Database'], user=Database['User'], password=Database['Password'])  # Users
            cursor = db_connection.cursor()
            sql = "UPDATE Users SET AuthToken = %s, AuthTokenCreated = %s WHERE id=%s"
            val = (AuthToken, ExpireTime, UserID)
            cursor.execute(sql, val)
            db_connection.commit()
            cursor.close()
            return AuthToken

        elif User['AuthTokenCreated'] < str(CurrentTime):  # if token expires get a new one
            print("Token Expired for", Database['Database'], "-",Database['User'])
            AuthToken = self.GetOAuth(User,UserDetails)
            UserID = User['id']
            db_connection = mysql.connect(host=Database['Host'], database=Database['Database'], user=Database['User'], password=Database['Password'])  # Users
            cursor = db_connection.cursor()
            sql = "UPDATE Users SET AuthToken = %s, AuthTokenCreated = %s WHERE id=%s"
            val = (AuthToken, ExpireTime, UserID)
            cursor.execute(sql, val)
            db_connection.commit()
            cursor.close()
            return AuthToken

        else:
            print("Token Good for", Database['Database'], "-",Database['User'])
            AuthToken = User['AuthToken']
            return AuthToken

    def GetOAuth(self, User,UserDetails):
        encodedData = base64.b64encode(bytes(f"{UserDetails['client_id']}:{UserDetails['client_secret']}", "ISO-8859-1")).decode("ascii")
        authorization_header_string = f"Authorization: Basic {encodedData}"

        headers = {"Authorization": "Basic " + encodedData, "Content-Type": "application/x-www-form-urlencoded"}

        data = {
            'grant_type': 'refresh_token',
            'refresh_token': User['token'],
            'redirect_uri': User['redirect_uri'],
        }

        response = requests.post('https://api.ebay.com/identity/v1/oauth2/token', headers=headers, data=data)
        data = response.json()
        print("UserDetails", UserDetails)
        print("===================")
        print("User", User)
        print("===================")
        print("Headers", headers)
        print("===================")
        print("Response", response)
        print("===================")
        print("data", data)
        print("===================")
        print("Getting New Token",response,data['access_token'])
        print("===================")
        print(data)
        return data['access_token']

I have tried revoking the keys and readding them all with no luck. EBay have told me there is nothing wrong on their end. I have manually inputted the Authtoken and my script works


来源: stackexchange

问:
Creating a Scraping function in R, using a variable dependent on a Weblink
I am trying to create a function that would automatically scrape the table for moves learned by level up of any given pokemon based on the pokemon name from the pokemondb website, the issue comes in my usage of paste0 in relation to the pokemon database link.

```<code>
move_list <- function(pokemon){
  url <- paste0("https://pokemondb.net/pokedex/", pokemon)
  list_table <-
    read_html(url) %>%
    html_nodes(xpath = '//table[@class = "data-table"]') %>%
    html_table()
  level_up <- list_table[[1]]
  return(print(level_up))
}

move_list(donphan)
</code>```

Error in paste0("https://pokemondb.net/pokedex/", pokemon) :
object 'donphan' not found

With the goal to vary the pokemon the table is scraped from based on their name, I used paste0 to put together the input of the function with the link to generate the proper website to scrape, but for some reason this does not work. I wondered if it had to do with the name of the input being "pokemon" so I tried different things like "string" "x" etc. I also tried putting "pokemon" in place of pokemon, but then the link would go to "https://pokemondb.net/pokedex/pokemon" every time which of course does not exist. How can I make the input correspond to the respective link of pokemon within this function?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a function that would automatically scrape the table for moves learned by level up of any given pokemon based on the pokemon name from the pokemondb website, the issue comes in my usage of paste0 in relation to the pokemon database link.

move_list <- function(pokemon){
  url <- paste0("https://pokemondb.net/pokedex/", pokemon)
  list_table <-
    read_html(url) %>%
    html_nodes(xpath = '//table[@class = "data-table"]') %>%
    html_table()
  level_up <- list_table[[1]]
  return(print(level_up))
}

move_list(donphan)

Error in paste0("https://pokemondb.net/pokedex/", pokemon) :
object 'donphan' not found

With the goal to vary the pokemon the table is scraped from based on their name, I used paste0 to put together the input of the function with the link to generate the proper website to scrape, but for some reason this does not work. I wondered if it had to do with the name of the input being "pokemon" so I tried different things like "string" "x" etc. I also tried putting "pokemon" in place of pokemon, but then the link would go to "https://pokemondb.net/pokedex/pokemon" every time which of course does not exist. How can I make the input correspond to the respective link of pokemon within this function?


问:
VS code method documentation tooltip keyboard shortcut
When i write javascript code in VS code and start using a method, the editor shows the method documentation tooltip. Is there a keyboard shortcut to later be able to see that tooltip again?

For example in screenshot i have started writing a callbackFunction in array reduce method and now would prefer to see the reduce method documentation tooltip (marked with red on screenshot) to know where to specify the initialValue parameter. Is there a keyboard shortcut, to trigger this tooltip for reduce later when needed?

Screenshot


问:
Problem with using multiple inputs with embedding layers in a Keras Model
I am trying to build a basic NN using Keras using multiple input layers, some of which are connected to Embedding layers.  I am using the data for Kaggle's Housing Prices competition.

Here is the structure of the model I am using:

I use a scikit-learn Pipeline to transform the data. For the embedding layers, I transform the data using label encoding. The rest of the code I am using to build the model:

#####################  CREATE INPUT AND EMBEDDING LAYERS FOR CATEGORICAL FEATURES  #####################
# Input and embedding layer for MSSubClass feature
no_of_unique_categories = X_train['MSSubClass'].nunique() + 1
embedding_size = int(max(min(np.ceil((no_of_unique_categories)/2), 50),2))

input_cat_layer_1 = Input(shape=(1,))
embedding_layer_1 = Embedding(
    input_dim=no_of_unique_categories,
    output_dim=embedding_size,
    input_length=1)(input_cat_layer_1)
flattened_layer_1 = Flatten()(embedding_layer_1)

no_of_unique_categories = X_train['MSZoning'].nunique() + 1
embedding_size = int(max(min(np.ceil((no_of_unique_categories)/2), 50),2))

# Input and embedding layer for MSZoning feature
input_cat_layer_2 = Input(shape=(1,))
embedding_layer_2 = Embedding(
    input_dim=no_of_unique_categories,
    output_dim=embedding_size,
    input_length=1)(input_cat_layer_2)
flattened_layer_2 = Flatten()(embedding_layer_2)

# Input layer for all the numerical features
no_of_numeric_features = len(numeric_columns)
numeric_input = Input(shape=(no_of_numeric_features,))

#####################  BUILD THE MODEL  #####################
concatenate = Concatenate()([numeric_input, flattened_layer_1, flattened_layer_2])
hidden = Dense(110, activation='relu')(concatenate)
output = Dense(1)(hidden)

model = Model(inputs=[numeric_input, input_cat_layer_1, input_cat_layer_2], outputs=output, name='final_model')
print(model.summary())
plot_model(model, show_shapes=True, show_layer_names=True, to_file='model_structure.png')
optimizer = Adam(learning_rate=0.001)
model.compile(loss='mse', optimizer=optimizer, metrics=['RootMeanSquaredError'])

#####################  TRANSFORM DATA TO USE IN MODEL  #####################
X_train_transformed = preprocessor.fit_transform(X_train)
X_test_transformed = preprocessor.transform(X_test)

model.fit(X_train_transformed, y_train, epochs=200, validation_data=(X_test_transformed, y_test))
mse_test = model.evaluate(X_test_transformed, y_test)
predictions = model.predict(X_test_transformed)

mse = mean_squared_error(y_test, predictions)
rmse = np.sqrt(mse)```

The problem I am running into is when I try and fit the model to the training data, I receive the following error:

ValueError: Layer "final_model" expects 3 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 37) dtype=float32>]

I cannot figure out why this is happening and what I can do to fix it.

Body:
I am trying to build a basic NN using Keras using multiple input layers, some of which are connected to Embedding layers.  I am using the data for Kaggle's Housing Prices competition.

Here is the structure of the model I am using:

I use a scikit-learn Pipeline to transform the data. For the embedding layers, I transform the data using label encoding. The rest of the code I am using to build the model:

#####################  CREATE INPUT AND EMBEDDING LAYERS FOR CATEGORICAL FEATURES  #####################
# Input and embedding layer for MSSubClass feature
no_of_unique_categories = X_train['MSSubClass'].nunique() + 1
embedding_size = int(max(min(np.ceil((no_of_unique_categories)/2), 50),2))

input_cat_layer_1 = Input(shape=(1,))
embedding_layer_1 = Embedding(
    input_dim=no_of_unique_categories,
    output_dim=embedding_size,
    input_length=1)(input_cat_layer_1)
flattened_layer_1 = Flatten()(embedding_layer_1)

no_of_unique_categories = X_train['MSZoning'].nunique() + 1
embedding_size = int(max(min(np.ceil((no_of_unique_categories)/2), 50),2))

# Input and embedding layer for MSZoning feature
input_cat_layer_2 = Input(shape=(1,))
embedding_layer_2 = Embedding(
    input_dim=no_of_unique_categories,
    output_dim=embedding_size,
    input_length=1)(input_cat_layer_2)
flattened_layer_2 = Flatten()(embedding_layer_2)

# Input layer for all the numerical features
no_of_numeric_features = len(numeric_columns)
numeric_input = Input(shape=(no_of_numeric_features,))

#####################  BUILD THE MODEL  #####################
concatenate = Concatenate()([numeric_input, flattened_layer_1, flattened_layer_2])
hidden = Dense(110, activation='relu')(concatenate)
output = Dense(1)(hidden)

model = Model(inputs=[numeric_input, input_cat_layer_1, input_cat_layer_2], outputs=output, name='final_model')
print(model.summary())
plot_model(model, show_shapes=True, show_layer_names=True, to_file='model_structure.png')
optimizer = Adam(learning_rate=0.001)
model.compile(loss='mse', optimizer=optimizer, metrics=['RootMeanSquaredError'])

#####################  TRANSFORM DATA TO USE IN MODEL  #####################
X_train_transformed = preprocessor.fit_transform(X_train)
X_test_transformed = preprocessor.transform(X_test)

model.fit(X_train_transformed, y_train, epochs=200, validation_data=(X_test_transformed, y_test))
mse_test = model.evaluate(X_test_transformed, y_test)
predictions = model.predict(X_test_transformed)

mse = mean_squared_error(y_test, predictions)
rmse = np.sqrt(mse)

The problem I am running into is when I try and fit the model to the training data, I receive the following error:

ValueError: Layer "final_model" expects 3 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 37) dtype=float32>]

I cannot figure out why this is happening and what I can do to fix it.


问:
react-leaflet map.locate() overrides state when updated through <select> in a different component
I am trying to build an app with a map that takes the user to their location when loaded , but once that is done it should move to any country through a select box. I am using a geoJSON file to update the state both in the  and the  component.
This works when on load, but when I try to change the country borders through the select box the state immediately re-updates to the current location country .

ex. current location is Ireland so when the map is loaded console.log(countryIso_a3) is IRL . When selecting Albania, console.log(countryIso_a3) is ALB but immediately updates to IRL.

Here is my code :

App.js :

```<code>import "./App.css";
import { Fragment, useEffect, useState } from "react";
import NavBar from "./components/navbar/Navbar";
import BasicMap from "./components/leaflet/BasicMap";

function App() {
  const [countryIso_a3, setCountryIso_a3] = useState("");
  const [countryBorders, setCountryBorders] = useState({});

  return (
    <Fragment>
      <NavBar
        setCountryIso_a3={setCountryIso_a3}
        setCountryBorders={setCountryBorders}
      />
      <BasicMap
        setCountryIso_a3={setCountryIso_a3}
        setCountryBorders={setCountryBorders}
        countryBorders={countryBorders}
      />
    </Fragment>
  );
}

export default App;

</code>```

BasicMap.js

```<code>import React, { useEffect, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";
import osm from "./osm_providers";
import "leaflet/dist/leaflet.css";
import icon from "./icons";
import L from "leaflet";
import countryData from "../../countryData.json";

function BasicMap({ countryBorders,setCountryIso_a3, setCountryBorders }) {
  function LocationMarker() {
    const [center, setCenter] = useState(null);
    const [bbox, setBbox] = useState([]);

    const map = useMap();

    useEffect(() => {
      map.locate().on("locationfound", function (e) {
        setCenter(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
        const radius = e.accuracy;
        const circle = L.circle(e.latlng, radius);
        circle.addTo(map);
        setBbox(e.bounds.toBBoxString().split(","));
        map.fitBounds(L.geoJson(countryBorders).addTo(map).getBounds());

        for (let details of countryData) {
          for (let coordinateSet of details.geometry.coordinates) {
            for (let coordinates of coordinateSet) {
              if (
                e.latlng.lat < coordinates[1] &&
                e.latlng.lng > coordinates[0]
              ) {
                setCountryIso_a3(details.properties.iso_a3);
                setCountryBorders(details.geometry);
              }
            }
          }
        }
      })
      return function cleanup() {
        map.stopLocate();
      };
    }, [map]);

    return center === null ? null : (
      <Marker position={center} icon={icon}>
        <Popup>
          You are here. <br />
          Map bbox: <br />
          <b>Southwest lng</b>: {bbox[0]} <br />
          <b>Southwest lat</b>: {bbox[1]} <br />
          <b>Northeast lng</b>: {bbox[2]} <br />
          <b>Northeast lat</b>: {bbox[3]}
        </Popup>
      </Marker>
    );
  }

  return (
    <MapContainer
      center={[49.1951, 16.6068]}
      zoom={13}
      scrollWheelZoom
      style={{ height: "100vh" }}
    >
      <TileLayer
        url={osm.maptiler.url}
        attribution={osm.maptiler.attribution}
      />
      <LocationMarker />
    </MapContainer>
  );
}

export default BasicMap;

</code>```

I have tried  wrapping BasicMap in React.memo (React.memo(BasicMap)) and it works but I am not sure this is the right solution.

Body:
I am trying to build an app with a map that takes the user to their location when loaded , but once that is done it should move to any country through a select box. I am using a geoJSON file to update the state both in the  and the  component.
This works when on load, but when I try to change the country borders through the select box the state immediately re-updates to the current location country .

ex. current location is Ireland so when the map is loaded console.log(countryIso_a3) is IRL . When selecting Albania, console.log(countryIso_a3) is ALB but immediately updates to IRL.

Here is my code :

App.js :

import "./App.css";
import { Fragment, useEffect, useState } from "react";
import NavBar from "./components/navbar/Navbar";
import BasicMap from "./components/leaflet/BasicMap";

function App() {
  const [countryIso_a3, setCountryIso_a3] = useState("");
  const [countryBorders, setCountryBorders] = useState({});

  return (
    <Fragment>
      <NavBar
        setCountryIso_a3={setCountryIso_a3}
        setCountryBorders={setCountryBorders}
      />
      <BasicMap
        setCountryIso_a3={setCountryIso_a3}
        setCountryBorders={setCountryBorders}
        countryBorders={countryBorders}
      />
    </Fragment>
  );
}

export default App;

BasicMap.js

import React, { useEffect, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";
import osm from "./osm_providers";
import "leaflet/dist/leaflet.css";
import icon from "./icons";
import L from "leaflet";
import countryData from "../../countryData.json";

function BasicMap({ countryBorders,setCountryIso_a3, setCountryBorders }) {
  function LocationMarker() {
    const [center, setCenter] = useState(null);
    const [bbox, setBbox] = useState([]);

    const map = useMap();

    useEffect(() => {
      map.locate().on("locationfound", function (e) {
        setCenter(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
        const radius = e.accuracy;
        const circle = L.circle(e.latlng, radius);
        circle.addTo(map);
        setBbox(e.bounds.toBBoxString().split(","));
        map.fitBounds(L.geoJson(countryBorders).addTo(map).getBounds());

        for (let details of countryData) {
          for (let coordinateSet of details.geometry.coordinates) {
            for (let coordinates of coordinateSet) {
              if (
                e.latlng.lat < coordinates[1] &&
                e.latlng.lng > coordinates[0]
              ) {
                setCountryIso_a3(details.properties.iso_a3);
                setCountryBorders(details.geometry);
              }
            }
          }
        }
      })
      return function cleanup() {
        map.stopLocate();
      };
    }, [map]);

    return center === null ? null : (
      <Marker position={center} icon={icon}>
        <Popup>
          You are here.

          Map bbox:

          Southwest lng: {bbox[0]}

          Southwest lat: {bbox[1]}

          Northeast lng: {bbox[2]}

          Northeast lat: {bbox[3]}
        </Popup>
      </Marker>
    );
  }

  return (
    <MapContainer
      center={[49.1951, 16.6068]}
      zoom={13}
      scrollWheelZoom
      style={{ height: "100vh" }}
    >
      <TileLayer
        url={osm.maptiler.url}
        attribution={osm.maptiler.attribution}
      />
      <LocationMarker />
    </MapContainer>
  );
}

export default BasicMap;

I have tried  wrapping BasicMap in React.memo (React.memo(BasicMap)) and it works but I am not sure this is the right solution.


问:
node.js mongo queries are not the same as mongosh queries? How do you troubleshoot mongo queries written in node.js?
I come from a mysql background.

Currently experimenting with node.js and mongo.

When learning mysql:

you start with the command-line client and you learn how to write queries.

you move up to the application layer, and you write those EXACT same queries.

When learning mongo, I followed the same pattern:

I started with mongosh and learned how to write queries.

I move up to the node.js layer.

Now this is where it get's strange:  I haven't found a library that allows me to write mongo queries EXACTLY as I would write them in mongosh.

mongoose and the mongodb library both let me write queries that "accomplish the same thing", but I have to write something slightly different.

This is concerning.  With mysql, when I get unexpected results, I can cut and paste each application layer query into the command-line client to double check what is happening.

But what do node.js developers do? You've written node.js code that "accomplishes the same thing", but not something that you can paste into the command-line client.

Bugs often come down to tiny typos.  How do you check what node.js is sending to mongo?


问:
Raw image to Datapoint Conversion
I am working with a dataset that has images in shape (105,105,3). Since this raw image gives us a range of (0 to 105) on the x axis and (105 to 0) on the y axis, I am converting the image into (x,y) datapoints by using the code below where example is the raw image:

```<code>example = x_train[21]
x = []
y = []

i1 = np.argwhere(example < 1)
H = i1.shape[1]
i1[:1] = [H-1]-i1[:1]

for i in i1:
  x.append(i[0])
  y.append(i[1])

plt.scatter(x,y)
xy = np.column_stack((x,y))
</code>```

This code changes

to this:

Obviously i am doing something wrong and there is some random fricken dot in the bottom left corner that is driving me crazy. Is there a better less stupid way to do this? Ideally a nice mapping with the proper orientation and size would be great.

Title: Raw image to Datapoint Conversion

Body:
I am working with a dataset that has images in shape (105,105,3). Since this raw image gives us a range of (0 to 105) on the x axis and (105 to 0) on the y axis, I am converting the image into (x,y) datapoints by using the code below where example is the raw image:

example = x_train[21]
x = []
y = []

i1 = np.argwhere(example < 1)
H = i1.shape[1]
i1[:1] = [H-1]-i1[:1]

for i in i1:
  x.append(i[0])
  y.append(i[1])

plt.scatter(x,y)
xy = np.column_stack((x,y))

This code changes

to this:

Obviously i am doing something wrong and there is some random fricken dot in the bottom left corner that is driving me crazy. Is there a better less stupid way to do this? Ideally a nice mapping with the proper orientation and size would be great.


问:
WPF datagrid image binding situation
i try to show images from database in datagrid that i saved them as binary. pictures are showed but im getting binding errors.
my datagrid xaml codes are:

```<code><DataGridTemplateColumn Header=" Image" Width=" 95">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate >
                        <Image  Source="{Binding ProductImage ,TargetNullValue={x:Null}}" Width=" 80" Height=" 80"></Image>
                    </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.HeaderStyle >
                        <Style TargetType="{x:Type DataGridColumnHeader }">
                            <Setter Property="FontFamily" Value="Arial Black"/>
                            <Setter Property="HorizontalContentAlignment"  Value="Center"/>
                            <Setter Property="Foreground"  Value="#FF3211B8" />
                            <Setter Property="FontSize"  Value="12"/>
                        </Style>
                    </DataGridTemplateColumn.HeaderStyle>
            </DataGridTemplateColumn>
</code>```

and the c# code that im using to convert images to binary and save them to database

```<code>FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
                    byte[] ImgByteArr = new byte[fileStream.Length];
                    fileStream.Read(ImgByteArr, 0, ImgByteArr.Length);
                    fileStream.Close();
</code>```

and i send (ImgByteArr) to database

and this is binding errors:

when i scroll up and down, number of binding errors are increasing.
also image can be null.

Title: WPF datagrid image binding situation

Body:
i try to show images from database in datagrid that i saved them as binary. pictures are showed but im getting binding errors.
my datagrid xaml codes are:

<DataGridTemplateColumn Header=" Image" Width=" 95">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate >
                        <Image  Source="{Binding ProductImage ,TargetNullValue={x:Null}}" Width=" 80" Height=" 80"></Image>
                    </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.HeaderStyle >

                    </DataGridTemplateColumn.HeaderStyle>
            </DataGridTemplateColumn>

and the c# code that im using to convert images to binary and save them to database

FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
                    byte[] ImgByteArr = new byte[fileStream.Length];
                    fileStream.Read(ImgByteArr, 0, ImgByteArr.Length);
                    fileStream.Close();

and i send (ImgByteArr) to database

and this is binding errors:

when i scroll up and down, number of binding errors are increasing.
also image can be null.


问:
Unable to access and edit "Footer Section" in Word using docx, python
Let me make it clear that I am able to access and edit(color highlight) the footers ("Footer Section xx") but not some footers, which are named as "First Page Footer - Section xx" (The Footer Section vs First Page Footer - Section are distinguish in the screenshot below).

The examples of footers that I am able to highlight:

The example of footers that I am unable to highlight. And these footers are not only on page 1 but throughout the document:

I believe these "First Page Footer Section" are the isolated footers when the option "Different 1st page footer" is selected in the Word Footer option. The question is how do I access and then ultimately highlight these "First Page Footer Section"?

The python code that I used which did highlight "Footer Section" (but couldn't highlight "First Page Footer Section") is:

```<code>filepath = r'c:\temp\doc_input_file.docx'
doc1 = docx.Document( filepath )
for section in doc1.sections:
    for p in section.footer.paragraphs:
        for e_run in p.runs:
            e_run.font.highlight_color = WD_COLOR_INDEX.YELLOW
doc1.save( r'c:\temp\doc_output_file.docx'' )
</code>```

Thank you in advance!

Body:
Let me make it clear that I am able to access and edit(color highlight) the footers ("Footer Section xx") but not some footers, which are named as "First Page Footer - Section xx" (The Footer Section vs First Page Footer - Section are distinguish in the screenshot below).

The examples of footers that I am able to highlight:

The example of footers that I am unable to highlight. And these footers are not only on page 1 but throughout the document:

I believe these "First Page Footer Section" are the isolated footers when the option "Different 1st page footer" is selected in the Word Footer option. The question is how do I access and then ultimately highlight these "First Page Footer Section"?

The python code that I used which did highlight "Footer Section" (but couldn't highlight "First Page Footer Section") is:

filepath = r'c:\temp\doc_input_file.docx'
doc1 = docx.Document( filepath )
for section in doc1.sections:
    for p in section.footer.paragraphs:
        for e_run in p.runs:
            e_run.font.highlight_color = WD_COLOR_INDEX.YELLOW
doc1.save( r'c:\temp\doc_output_file.docx'' )

Thank you in advance!


问:
git apply stylegan2_upgrade.patch not working (windows 11)
I am trying to launch https://github.com/google-research/google-research/tree/master/infinite_nature_zero locally and when i use: git apply stylegan2_upgrade.patch. I am using Anaconda and Python 3.9.13

I get:

```<code>Checking patch model.py...
warning: model.py has type 100644, expected 100755
error: while searching for:
from torch.nn import functional as F
from torch.autograd import Function

from op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d, conv2d_gradfix

class PixelNorm(nn.Module):

error: patch failed: model.py:8
error: while searching for:
        return out

class ToRGB(nn.Module):
    def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]):
        super().__init__()

        if upsample:
            self.upsample = Upsample(blur_kernel)

        self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False)
        self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))

    def forward(self, input, style, skip=None):
        out = self.conv(input, style)
        out = out + self.bias

        if skip is not None:
            skip = self.upsample(skip)

            out = out + skip

        return out

class Generator(nn.Module):
    def __init__(

error: patch failed: model.py:366
Applying patch model.py with 2 rejects...
Rejected hunk #1.
Rejected hunk #2.
</code>```

and model.py is empty enter image description here

and i gott unfinished another file model.py.rej

I tried to create my own model.py, tried to do it inmodels folder, tried on wsl2 but nothing worked :/

Body:
I am trying to launch https://github.com/google-research/google-research/tree/master/infinite_nature_zero locally and when i use: git apply stylegan2_upgrade.patch. I am using Anaconda and Python 3.9.13

I get:

Checking patch model.py...
warning: model.py has type 100644, expected 100755
error: while searching for:
from torch.nn import functional as F
from torch.autograd import Function

from op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d, conv2d_gradfix

class PixelNorm(nn.Module):

error: patch failed: model.py:8
error: while searching for:
        return out

class ToRGB(nn.Module):
    def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]):
        super().__init__()

        if upsample:
            self.upsample = Upsample(blur_kernel)

        self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False)
        self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))

    def forward(self, input, style, skip=None):
        out = self.conv(input, style)
        out = out + self.bias

        if skip is not None:
            skip = self.upsample(skip)

            out = out + skip

        return out

class Generator(nn.Module):
    def __init__(

error: patch failed: model.py:366
Applying patch model.py with 2 rejects...
Rejected hunk #1.
Rejected hunk #2.

and model.py is empty enter image description here

and i gott unfinished another file model.py.rej

I tried to create my own model.py, tried to do it inmodels folder, tried on wsl2 but nothing worked :/


问:
Image Hover Border Radius Safari Issue
I am creating a card that contains an image and text. When the card is hovered, the image scales to 1.5. When you hover, the image will scale but then it will have this flicker where the corners will be sharp and then round out again.

.box {
  width: 100%;
  max-width: 19.375em;
  background-color: green;
  border-radius: 1em;
  overflow: hidden;
}
.box:hover .box__image img {
  transform: scale(1.5);
}
.box__image {
  overflow: hidden;
}
.box__image img {
  display: block;
  height: 12.5em;
  width: 100%;
  object-fit: cover;
  transform: scale(1);
  transition: transform 500ms ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="box__image"><img src="https://via.placeholder.com/576x200"/></div>
  <div class="box__desc">
    <p>hello</p>
  </div>
</div></code>```

Works perfectly fine on Chrome and Firefox

Title: Image Hover Border Radius Safari Issue

Body:
I am creating a card that contains an image and text. When the card is hovered, the image scales to 1.5. When you hover, the image will scale but then it will have this flicker where the corners will be sharp and then round out again.

.box {
  width: 100%;
  max-width: 19.375em;
  background-color: green;
  border-radius: 1em;
  overflow: hidden;
}
.box:hover .box__image img {
  transform: scale(1.5);
}
.box__image {
  overflow: hidden;
}
.box__image img {
  display: block;
  height: 12.5em;
  width: 100%;
  object-fit: cover;
  transform: scale(1);
  transition: transform 500ms ease;
}

hello

Works perfectly fine on Chrome and Firefox


问:
Validation Rules Salesforce
I need to make validation rules like this:

Create a validation rule that displays an error message and prevents the user from creating or updating a contact if both conditions are true.

Create a validation rule:
Rule name: Contact_must_be_in_Account_ZIP_Code
Operator: AND (returns true if both conditions are true)
Define two error conditions:
The contact is associated with an account ID
Hint: use the ISBLANK and NOT functions.
The zip code for the contact's address is different than the zip code for account submissions.
Tip: Use the API names (MailingPostalCode and ShippingPostalCode) and the <> operator (Not equal to).
Enter an error message for the validation rule
?

I'm in training and I've tried everything to solve it but nothing worked

Title: Validation Rules Salesforce


问:
How to test custom yup validation by jest?
I am trying to create unit tests for the custom yup validation method by jest with correct and incorrect data.

```<code>function nextValueBigger(message = 'Some error') {
  return this.test('nextValueBigger', (value, { path }) => {
    const errors = value.map((item, index) => {
      if (item?.from < item?.to) { return null; } // Successful validation, no error

      return new ValidationError(
        message,
        null,
        `${path}[${index}].to`,
      );
    }).filter(Boolean);

    if (errors.length === 0) { return true; }

    return new ValidationError(errors);
  });
}
</code>```

I tried with creating simulation of validation like this:

```<code>const data = [
  { from: 1, to: 2 },
  { from: 3, to: 4 },
  { from: 5, to: 6 },
];
</code>```
```<code>const schema = Yup.object().shape({
  item: Yup.array().of(Yup.object().shape({
    from: Yup.number(),
    to: Yup.number(),
  }))
    .nextValueBigger(),
});
</code>```
```<code>it('should not found any errors', async () => {
  const result = await schema.validateAt('items', { items: data }
  expect(result).toEqual(true)
}
</code>```

Body:
I am trying to create unit tests for the custom yup validation method by jest with correct and incorrect data.

function nextValueBigger(message = 'Some error') {
  return this.test('nextValueBigger', (value, { path }) => {
    const errors = value.map((item, index) => {
      if (item?.from < item?.to) { return null; } // Successful validation, no error

      return new ValidationError(
        message,
        null,
        `${path}[${index}].to`,
      );
    }).filter(Boolean);

    if (errors.length === 0) { return true; }

    return new ValidationError(errors);
  });
}

I tried with creating simulation of validation like this:

const data = [
  { from: 1, to: 2 },
  { from: 3, to: 4 },
  { from: 5, to: 6 },
];

const schema = Yup.object().shape({
  item: Yup.array().of(Yup.object().shape({
    from: Yup.number(),
    to: Yup.number(),
  }))
    .nextValueBigger(),
});

it('should not found any errors', async () => {
  const result = await schema.validateAt('items', { items: data }
  expect(result).toEqual(true)
}


问:
How to edit this code to vie power consumption in google firebase?
```<code>#include <ESP8266WiFi.h>;

#include <WiFiClient.h>;

#include <ThingSpeak.h>;

const char* ssid = "Wifi_Project"; //Your Network SSID

const char* password = "1111aaaa"; //Your Network Password

WiFiClient client;

unsigned long myChannelNumber =   1947152; //Your Channel Number (Without Brackets)

const char * myWriteAPIKey = "QA02MFMGFJVIDBZR"; //Your Write API Key

#include <SoftwareSerial.h>
SoftwareSerial SMESerial (D6, D7);
int xVal, yVal, zVal;
float xtotal,ytotal,ztotal,xprice,yprice,zprice;

void setup() {
   Serial.begin(9600);
  SMESerial.begin(9600);
    WiFi.begin(ssid, password);
  ThingSpeak.begin(client);

}

void loop() {

  if (SMESerial.available()<1)  return;
  char R=SMESerial.read();
  int data=SMESerial.parseInt();

  if (R == 'x')
  xVal = data;
  xtotal = xVal + xtotal;
  xprice = xtotal*0.1;

  Serial.print("X = ");
  Serial.println(xtotal);

  ThingSpeak.setField(1, xtotal);
  ThingSpeak.setField(2, xprice);

  if (R == 'y')
  yVal = data;
  ytotal = yVal + ytotal;
  yprice = ytotal*0.1;

  Serial.print("Y = ");
  Serial.println(ytotal);

  ThingSpeak.setField(3, ytotal);
  ThingSpeak.setField(4, yprice);

    if (R == 'z')
  zVal = data;
  ztotal = zVal + ztotal;
  zprice = ztotal*0.1;

  Serial.print("Z = ");
  Serial.println(ztotal);

  ThingSpeak.setField(5, ztotal);
  ThingSpeak.setField(6, zprice);

  ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

}
</code>```

I've made a wireless sensor networks project by using 3 slave nodemcu esp8266 to collect current reading using ACS712 and send it to master nodemcu esp8266. The master nodemcu should send data to phone to view the data through a mobile application. I used Thingspeak at first to view data of the power consumption but i want to use google firebase to view the power consumption easier for my application view. Need help please.

Body:
#include <ESP8266WiFi.h>;

#include <WiFiClient.h>;

#include <ThingSpeak.h>;

const char* ssid = "Wifi_Project"; //Your Network SSID

const char* password = "1111aaaa"; //Your Network Password

WiFiClient client;

unsigned long myChannelNumber =   1947152; //Your Channel Number (Without Brackets)

const char * myWriteAPIKey = "QA02MFMGFJVIDBZR"; //Your Write API Key

#include <SoftwareSerial.h>
SoftwareSerial SMESerial (D6, D7);
int xVal, yVal, zVal;
float xtotal,ytotal,ztotal,xprice,yprice,zprice;

void setup() {
   Serial.begin(9600);
  SMESerial.begin(9600);
    WiFi.begin(ssid, password);
  ThingSpeak.begin(client);

}

void loop() {

  if (SMESerial.available()<1)  return;
  char R=SMESerial.read();
  int data=SMESerial.parseInt();

  if (R == 'x')
  xVal = data;
  xtotal = xVal + xtotal;
  xprice = xtotal*0.1;

  Serial.print("X = ");
  Serial.println(xtotal);

  ThingSpeak.setField(1, xtotal);
  ThingSpeak.setField(2, xprice);

  if (R == 'y')
  yVal = data;
  ytotal = yVal + ytotal;
  yprice = ytotal*0.1;

  Serial.print("Y = ");
  Serial.println(ytotal);

  ThingSpeak.setField(3, ytotal);
  ThingSpeak.setField(4, yprice);

    if (R == 'z')
  zVal = data;
  ztotal = zVal + ztotal;
  zprice = ztotal*0.1;

  Serial.print("Z = ");
  Serial.println(ztotal);

  ThingSpeak.setField(5, ztotal);
  ThingSpeak.setField(6, zprice);

  ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

}

I've made a wireless sensor networks project by using 3 slave nodemcu esp8266 to collect current reading using ACS712 and send it to master nodemcu esp8266. The master nodemcu should send data to phone to view the data through a mobile application. I used Thingspeak at first to view data of the power consumption but i want to use google firebase to view the power consumption easier for my application view. Need help please.


问:
.Net 6 with Ocelot 18 returns error 404 when navigating to an URL of the gateway after publish in IIS
I created a gateway with Ocelot and Net6, I configured the .json file and tested locally and everything works fine, but when I publish it to IIS it gives me a 404. When I go to the error it is setting the port to the route, or rather in the sub route.

I have a player microservice that is published in IIS and was also built with Net6 which I call without problem and it returns the data. When I try to call it from the gateway it doesn't work.

This is my .json file configuration

As can be seen in the image, the requested url is armed with the ports and I don't understand the reason.

Does anyone know the reason and can give me a hand to solve this issue.

I tried removing the ports and removing the BaseUrl but it always gives me the same error


问:
Unable to upload a file with RSelenium
Using this code snippet, I have been able to get RSelenium to bring up a dialog box that allows me to select the file I would like to upload. However, my goal is to pass the file itself to the upload button; what am I missing? I am attempting to upload to a list of climate stations to https://prism.oregonstate.edu/explorer/bulk.php.</p>
```<code># Set up RSelenium -------------------------------------------------------
## load packages ----
library(RSelenium)
library(rvest)
library(tidyverse)
library(netstat)
library(here)
library(dplyr)
library(readr)

##Set Default download folder ----
eCaps <- list(
  chromeOptions =
    list(prefs = list(
      "profile.default_content_settings.popups" = 0L,
      "download.prompt_for_download" = FALSE,
      "download.default_directory" = gsub(pattern = '/', replacement = '\\\\', x = here("WebData")) # download.dir
    )
    )
)
default_folder = here("WebData")
## Open a chrome browser session with RSelenium ----
rs_driver_object <-rsDriver(
  browser = 'chrome',
  chromever ='108.0.5359.71',
  port = free_port(),
)

remDr <- rs_driver_object$client

##Input Locations File
LocationFile <- gsub(pattern = "/", replacement = "\\\\", x = here("InputData/prism_rr_precip_stations.csv"))

#Navigate to PRISM Explorer webpage----
remDr <- rs_driver_object$client
URL <- "https://prism.oregonstate.edu/explorer/bulk.php"
remDr$navigate(URL)

#Select Open Locations File
UploadBtn <- remDr$findElement(using = "id", value = "upload_locations")
UploadBtn$sendKeysToElement(list(LocationFile))
UploadBtn$clickElement()
</code>```

Title: Unable to upload a file with RSelenium

Body:
Using this code snippet, I have been able to get RSelenium to bring up a dialog box that allows me to select the file I would like to upload. However, my goal is to pass the file itself to the upload button; what am I missing? I am attempting to upload to a list of climate stations to https://prism.oregonstate.edu/explorer/bulk.php.

# Set up RSelenium -------------------------------------------------------
## load packages ----
library(RSelenium)
library(rvest)
library(tidyverse)
library(netstat)
library(here)
library(dplyr)
library(readr)

##Set Default download folder ----
eCaps <- list(
  chromeOptions =
    list(prefs = list(
      "profile.default_content_settings.popups" = 0L,
      "download.prompt_for_download" = FALSE,
      "download.default_directory" = gsub(pattern = '/', replacement = '\\\\', x = here("WebData")) # download.dir
    )
    )
)
default_folder = here("WebData")
## Open a chrome browser session with RSelenium ----
rs_driver_object <-rsDriver(
  browser = 'chrome',
  chromever ='108.0.5359.71',
  port = free_port(),
)

remDr <- rs_driver_object$client

##Input Locations File
LocationFile <- gsub(pattern = "/", replacement = "\\\\", x = here("InputData/prism_rr_precip_stations.csv"))

#Navigate to PRISM Explorer webpage----
remDr <- rs_driver_object$client
URL <- "https://prism.oregonstate.edu/explorer/bulk.php"
remDr$navigate(URL)

#Select Open Locations File
UploadBtn <- remDr$findElement(using = "id", value = "upload_locations")
UploadBtn$sendKeysToElement(list(LocationFile))
UploadBtn$clickElement()


问:
Unity 3D fps view - objects placing at center point
I've searched around and can't seem to find a write up on the calculations I might need for placing an object onto another one without them placing halfway inside of eachother.

```<code>private void MovePlaceableObject()
    {
        Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);

        Debug.DrawRay(ray.origin, ray.direction * 20f);

        RaycastHit hit;

        if(Physics.Raycast(ray, out hit, 15f))
        {
            Vector3 newPosition = hit.point;

            currentPlaceableObject.transform.position = newPosition; //move object to where we have the mouse

            currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal); //rotation equal to the current rotation of our hitinfo, then up
        }
    }

private void HandeNewObjectHotkey()
    {
        if (Input.GetKeyDown(newObjectHotkey))
        {
            if(currentPlaceableObject == null)
            {
                currentPlaceableObject = Instantiate(placeableObjectPrefab);
                //currentPlaceableObject.GetComponent<BoxCollider>().enabled = false;
            }
            else
            {
                Destroy(currentPlaceableObject); //pressing the button again will destroy current object
            }
        }
    }
</code>```

I've tried storing the object I'm looking at's size to floats for x,y,z and a vector3 for it's position, and tried fiddling around with adding those to the newPosition with the hit.point to no avail.

I've wracked my brains for about a day now, i'm terrible at math, however I know that you must need to get the current object your looking ats position or size, then factor that into your placement right?

Body:
I've searched around and can't seem to find a write up on the calculations I might need for placing an object onto another one without them placing halfway inside of eachother.

private void MovePlaceableObject()
    {
        Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);

        Debug.DrawRay(ray.origin, ray.direction * 20f);

        RaycastHit hit;

        if(Physics.Raycast(ray, out hit, 15f))
        {
            Vector3 newPosition = hit.point;

            currentPlaceableObject.transform.position = newPosition; //move object to where we have the mouse

            currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal); //rotation equal to the current rotation of our hitinfo, then up
        }
    }

private void HandeNewObjectHotkey()
    {
        if (Input.GetKeyDown(newObjectHotkey))
        {
            if(currentPlaceableObject == null)
            {
                currentPlaceableObject = Instantiate(placeableObjectPrefab);
                //currentPlaceableObject.GetComponent<BoxCollider>().enabled = false;
            }
            else
            {
                Destroy(currentPlaceableObject); //pressing the button again will destroy current object
            }
        }
    }

I've tried storing the object I'm looking at's size to floats for x,y,z and a vector3 for it's position, and tried fiddling around with adding those to the newPosition with the hit.point to no avail.

I've wracked my brains for about a day now, i'm terrible at math, however I know that you must need to get the current object your looking ats position or size, then factor that into your placement right?


问:
create lua autocommand to make mason window transparent
I want to make the Mason window transparent, in neovim, using lua.

Here was suggested to set winbled locally as autocommand but its not using the newer lua api: https://github.com/williamboman/mason.nvim/discussions/355.

```<code>autocmd FileType mason setlocal winblend=10
</code>```

I am trying to do the same with lua:

vim.api.nvim_create_autocmd("FileType", {
  pattern = "mason",
  callback = function() vim.opt_local.winblend = 10 end,
})
```

Nothing is happening after sourcing this. No error and no transparent window.

Body:
I want to make the Mason window transparent, in neovim, using lua.

Here was suggested to set winbled locally as autocommand but its not using the newer lua api: https://github.com/williamboman/mason.nvim/discussions/355.

autocmd FileType mason setlocal winblend=10

I am trying to do the same with lua:

vim.api.nvim_create_autocmd("FileType", {
  pattern = "mason",
  callback = function() vim.opt_local.winblend = 10 end,
})

Nothing is happening after sourcing this. No error and no transparent window.


问:
Return several mutable references from `self`
I have the following struct Grid where I would like to have a mutable get function which returns mutable references to the underlying Cells:
MWE here

struct Cell {
    c: i64,
}

struct Grid {
    a: [Cell; 3],
}

impl Grid {
    fn cell_i(&mut self, i: usize) -> &mut Cell {
        return &mut self.a[i];
    }

    fn neighbors(&mut self, _i: usize) -> (&mut Cell, &mut Cell) {
        return (self.cell_i(0), self.cell_i(2));
    }
}

fn main() {
    let a = &mut Grid {
            a: [Cell { c: 3 }, Cell { c: 4 }, Cell { c: 5 }],
        };

    let _bs = a.neighbors(1);
}
```

I am just puzzeled as a beginner, how to solve this?
I need both neighbor cells mutable returned from neighbors, to make computations on them.
I could return immutable but then I cannot turn them into &mut Cells because that does not exist (undefined behavior). Whats the common idiom here?

Body:
I have the following struct Grid where I would like to have a mutable get function which returns mutable references to the underlying Cells:
MWE here

struct Cell {
    c: i64,
}

struct Grid {
    a: [Cell; 3],
}

impl Grid {
    fn cell_i(&mut self, i: usize) -> &mut Cell {
        return &mut self.a[i];
    }

    fn neighbors(&mut self, _i: usize) -> (&mut Cell, &mut Cell) {
        return (self.cell_i(0), self.cell_i(2));
    }
}

fn main() {
    let a = &mut Grid {
            a: [Cell { c: 3 }, Cell { c: 4 }, Cell { c: 5 }],
        };

    let _bs = a.neighbors(1);
}

I am just puzzeled as a beginner, how to solve this?
I need both neighbor cells mutable returned from neighbors, to make computations on them.
I could return immutable but then I cannot turn them into &mut Cells because that does not exist (undefined behavior). Whats the common idiom here?


问:
Why do I fail in exposing a collection on MongoDB Compass to a REST API using Java?
So I've got this school assignment where I'm creating my own web based REST API using Java. I've got a database in MongoDB Compass called "mflix" which contains the collection I'm trtying to expose to my REST API. I've created a Java application identical to that of my fellow students and my teacher in order to create the connection but everytime I use Postman to check my url i get this return message:
Return Message in Postman
"It looks like you are trying to access MongoDB over HTTP on the native driver port."

I've done some googling on this matter any I see many that claims that this is because port 27017 cant be used for this since the default port cant speak with the http protocol. Then how come port 27017 work for all my course mates and my teacher?

This is my connection properties:
Connection Properties file in Eclipse

This is the url I use in Postman:
Postman url and return message

And here is my Java code:

```<code>import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.delete;
import static spark.Spark.put;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.text.WordUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class RestClient {

    private void runDatabase() {
        String propertyString;
        Logger logger = LoggerFactory.getLogger( RestClient.class );
        try (InputStream input = new FileInputStream( "connection.properties" ) ) {

            Properties properties = new Properties();
            properties.load( input );
            propertyString = properties.getProperty( "db.connection_string" );
            logger.info( propertyString );

            ConnectionString connectionString = new ConnectionString( propertyString );
            MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString( connectionString ).build();
            MongoClient mongoClient = MongoClients.create( settings );
            MongoDatabase database = mongoClient.getDatabase( properties.getProperty( "db.name" ) );
            System.out.println("hello");

            get( "/title/:title", ( request, response ) -> {
                System.out.println("hello igen");
                MongoCollection<Document> collection = database.getCollection( "movies" );
                String filter = request.params( "title" ).toLowerCase();
                filter = WordUtils.capitalizeFully( filter );
                logger.info( "Filtering movies for the title: " + filter );
                Document myDocument = collection.findOneAndDelete( Filters.eq( "title", filter ) );

                if( myDocument != null ) {
                    myDocument.remove( "_id" );
                } else {
                    response.status(404);
                    return ( "<html><body><h1>Movie not found.</h1></body></html>" );
                }

                return myDocument.toJson();
            } );

        } catch ( FileNotFoundException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch ( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main( String[] args ) {
        RestClient restClient = new RestClient();
        restClient.runDatabase();
    }

}
</code>```

When I run this in Eclipse this is my console/logger:
Eclipse console message

As I said I use Compass to connect with my database, Java to create the connection, and Postman to test the url.

I've tried to change my port to 28017 in Compass but then I just get this error message : "connect ECONNREFUSED 127.0.0.1:28017".

Body:
So I've got this school assignment where I'm creating my own web based REST API using Java. I've got a database in MongoDB Compass called "mflix" which contains the collection I'm trtying to expose to my REST API. I've created a Java application identical to that of my fellow students and my teacher in order to create the connection but everytime I use Postman to check my url i get this return message:
Return Message in Postman
"It looks like you are trying to access MongoDB over HTTP on the native driver port."

I've done some googling on this matter any I see many that claims that this is because port 27017 cant be used for this since the default port cant speak with the http protocol. Then how come port 27017 work for all my course mates and my teacher?

This is my connection properties:
Connection Properties file in Eclipse

This is the url I use in Postman:
Postman url and return message

And here is my Java code:

import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.delete;
import static spark.Spark.put;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.text.WordUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class RestClient {

    private void runDatabase() {
        String propertyString;
        Logger logger = LoggerFactory.getLogger( RestClient.class );
        try (InputStream input = new FileInputStream( "connection.properties" ) ) {

            Properties properties = new Properties();
            properties.load( input );
            propertyString = properties.getProperty( "db.connection_string" );
            logger.info( propertyString );

            ConnectionString connectionString = new ConnectionString( propertyString );
            MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString( connectionString ).build();
            MongoClient mongoClient = MongoClients.create( settings );
            MongoDatabase database = mongoClient.getDatabase( properties.getProperty( "db.name" ) );
            System.out.println("hello");

            get( "/title/:title", ( request, response ) -> {
                System.out.println("hello igen");
                MongoCollection<Document> collection = database.getCollection( "movies" );
                String filter = request.params( "title" ).toLowerCase();
                filter = WordUtils.capitalizeFully( filter );
                logger.info( "Filtering movies for the title: " + filter );
                Document myDocument = collection.findOneAndDelete( Filters.eq( "title", filter ) );

                if( myDocument != null ) {
                    myDocument.remove( "_id" );
                } else {
                    response.status(404);
                    return ( "
Movie not found.
" );
                }

                return myDocument.toJson();
            } );

        } catch ( FileNotFoundException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch ( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main( String[] args ) {
        RestClient restClient = new RestClient();
        restClient.runDatabase();
    }

}

When I run this in Eclipse this is my console/logger:
Eclipse console message

As I said I use Compass to connect with my database, Java to create the connection, and Postman to test the url.

I've tried to change my port to 28017 in Compass but then I just get this error message : "connect ECONNREFUSED 127.0.0.1:28017".


问:
How to insert the correct parameter in order to visualize wms maps in leaflet (proj4)
I'm struggling to visualize WMS-layers from a Rest-service using Leaflet. All i see currently is a gray map, not changing anything when moved.

The layers i want to visualize are located in Faroe Island, and are therefore using the CS (coordinatesystem) EPSG:5316. Because EPSG:5316 is not one of the standard CS in Leaflet, i have to use Proj4Leaflet. In Proj4Leaflets github site, there are some instructions on how to set the crs and layers, and i've tried to follow the instructions with no success.

The two maps are:

A normal image map

A contour line map

The code:

```<code>   // Imports:
   import { onMount } from 'svelte';
   import L from 'leaflet';
   import 'proj4leaflet'

   const kortalUrlHaedd = 'https://gis.us.fo/arcgis/services/haeddarkurvar/us_haeddarkurvar_2009_2m/MapServer/WMSServer';
   const kortalUrlMynd = 'https://gis.us.fo/arcgis/services/myndakort/us_myndakort_fotm/MapServer/WMSServer'
   const EPSG5136value = '+proj=tmerc +lat_0=0 +lon_0=-7 +k=0.999997 +x_0=200000 +y_0=-6000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs +type=crs'

   // Define the global variable L to new variable:
   $data.leaf = L;

   // Center of map.
   var center = [62, -7];

   onMount(() => {

     var crs = new L.Proj.CRS('EPSG:5316', EPSG5136value, {
       origin: [-5423100, 4002100],
       resolutions: [
         1083.735500804335,
         541.8677504021675,
         270.93387520108377,
         135.46693760054188,
         67.73346880027094,
         33.86673440013547,
         16.933367200067735,
         8.466683600033868,
         4.233341800016934,
         2.116670900008467,
         1.0583354500042335,
         0.5291677250021167,
         0.26458386250105836,
         0.13229193125052918,
         0.06614596562526459,
       ],
     })

     $data.map = $data.leaf.map('map', {
       crs: crs,
     });

     var wmsLayerHaedd = $data.leaf.tileLayer.wms(kortalUrlHaedd, {
       maxZoom: 20,
       minZoom: 8,
     }).addTo($data.map);

     var wmsLayerMynd = $data.leaf.tileLayer.wms(kortalUrlMynd, {
       maxZoom: 20,
       minZoom: 8,
     }).addTo($data.map);

     $data.map.setView(center, 8);

   })
</code>```

Some remarks:

All interactive code related to leaflet works (i get coordinates by pressing on a point on the map, code is not shown here), and i get no errors when opening the project.

The maps seems to be loaded from the Rest-API, but i'm not sure if it's visible on the map, or something is wrong with the settings, making the map appear somewhere completely off the view, impossible to find.

I have QGIS installed, and i can successfully add the layers into a QGIS project and visualize them by doing "Layer -> Add layer -> Add WMS/WMTS layer..." and use the links defined in the code by the variables kortalUrlHaedd and kortalUrlMynd.

These instructions on the Leaflet site are mentioning; "An instance of L.TileLayer.WMS needs at least one option: layers." When adding the layers into QGIS, i see that they do not have any layer name that is inserted into the layers-option as mentioned on this site. Is this a problem?

If some information around the code is missing, please let me know. Also i could mention, i'm completely new to the whole "GIS world", so there may be concepts i'm unaware of.

Body:
I'm struggling to visualize WMS-layers from a Rest-service using Leaflet. All i see currently is a gray map, not changing anything when moved.

The layers i want to visualize are located in Faroe Island, and are therefore using the CS (coordinatesystem) EPSG:5316. Because EPSG:5316 is not one of the standard CS in Leaflet, i have to use Proj4Leaflet. In Proj4Leaflets github site, there are some instructions on how to set the crs and layers, and i've tried to follow the instructions with no success.

The two maps are:

A normal image map

A contour line map

The code:

   // Imports:
   import { onMount } from 'svelte';
   import L from 'leaflet';
   import 'proj4leaflet'

   const kortalUrlHaedd = 'https://gis.us.fo/arcgis/services/haeddarkurvar/us_haeddarkurvar_2009_2m/MapServer/WMSServer';
   const kortalUrlMynd = 'https://gis.us.fo/arcgis/services/myndakort/us_myndakort_fotm/MapServer/WMSServer'
   const EPSG5136value = '+proj=tmerc +lat_0=0 +lon_0=-7 +k=0.999997 +x_0=200000 +y_0=-6000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs +type=crs'

   // Define the global variable L to new variable:
   $data.leaf = L;

   // Center of map.
   var center = [62, -7];

   onMount(() => {

     var crs = new L.Proj.CRS('EPSG:5316', EPSG5136value, {
       origin: [-5423100, 4002100],
       resolutions: [
         1083.735500804335,
         541.8677504021675,
         270.93387520108377,
         135.46693760054188,
         67.73346880027094,
         33.86673440013547,
         16.933367200067735,
         8.466683600033868,
         4.233341800016934,
         2.116670900008467,
         1.0583354500042335,
         0.5291677250021167,
         0.26458386250105836,
         0.13229193125052918,
         0.06614596562526459,
       ],
     })

     $data.map = $data.leaf.map('map', {
       crs: crs,
     });

     var wmsLayerHaedd = $data.leaf.tileLayer.wms(kortalUrlHaedd, {
       maxZoom: 20,
       minZoom: 8,
     }).addTo($data.map);

     var wmsLayerMynd = $data.leaf.tileLayer.wms(kortalUrlMynd, {
       maxZoom: 20,
       minZoom: 8,
     }).addTo($data.map);

     $data.map.setView(center, 8);

   })

Some remarks:

All interactive code related to leaflet works (i get coordinates by pressing on a point on the map, code is not shown here), and i get no errors when opening the project.

The maps seems to be loaded from the Rest-API, but i'm not sure if it's visible on the map, or something is wrong with the settings, making the map appear somewhere completely off the view, impossible to find.

I have QGIS installed, and i can successfully add the layers into a QGIS project and visualize them by doing "Layer -> Add layer -> Add WMS/WMTS layer..." and use the links defined in the code by the variables kortalUrlHaedd and kortalUrlMynd.

These instructions on the Leaflet site are mentioning; "An instance of L.TileLayer.WMS needs at least one option: layers." When adding the layers into QGIS, i see that they do not have any layer name that is inserted into the layers-option as mentioned on this site. Is this a problem?

If some information around the code is missing, please let me know. Also i could mention, i'm completely new to the whole "GIS world", so there may be concepts i'm unaware of.


问:
Export button is not showing on Bootstrap table
I'm using this website as a reference - https://bootstrap-table.com/docs/extensions/export/#showexport. The problem here is that the export button is not showing, I've already re-arranged the scripts and nothing is happening. I settled the data-show-export as true - nothing happened. I added the Jquery script first, Popper second and finally Bootstrap, and nothing. Now, I don't know what to do, may anyone help to see if I'm doing anything wrong? Thank you!

HTML

```<code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>TSS BRA Automation For Unbilled</title>

      <!-- Fonts -->
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" crossorigin="anonymous"></script>
      <!-- Table loading -->
      <link rel="stylesheet" href="https://unpkg.com/placeholder-loading/dist/css/placeholder-loading.min.css">
      <!-- Bootstrap -->
      <link rel="stylesheet" href="static/styles/css/bootstrap/bootstrap.min.css">
      <link rel="stylesheet" href="static/styles/css/bootstrap/bootstrap-table.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
      <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.21.2/dist/bootstrap-table.min.css" rel="stylesheet">
      <!-- Style CSS -->
      <link rel="stylesheet" href="static/styles/css/main-styles.css">
      <!-- Style SCSS -->
      <link rel="stylesheet" href="static/styles/scss/style.css">
      <!-- Resizable property -->
      <link rel="stylesheet" href="https://unpkg.com/jquery-resizable-columns@0.2.3/dist/jquery.resizableColumns.css">
      <!-- Export property -->
      <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table.min.css">
   </head>

   <body class="main-layout">
      <!-- <div class="loader_bg">
         <div class="loader"><img src="static/styles/static/images/loading.gif" alt="#" /></div>
      </div> -->
      <header>
         <div class="header_bg">
            <div class="header">
               <a href="index.html"><img class="logo"
                     src="https://i.postimg.cc/bwWpnryh/images-removebg-preview.png"
                     alt="#" />
               </a>
            </div>

            <section class="banner_main">
               <div class="container-fluid">
                  <div class="row d_flex">
                     <div class="text-bg">
                        <h1><strong>Welcome to<br/></strong> TSS BRA Automation
                              for Unbilled</h1>
                        </div>
                     </div>
                  </section>
               </div>
            </header>

            <main>
               <div class="container">
                  <div class="row">
                     <div class="col-lg-12">
                        <div class="card">
                           <div class="card-header">
                              <div class="center">
                                 <i class="fa-solid fa-upload"></i>
                                 <strong>Upload your files</strong>
                              </div>
                           </div>
                           <div class="cardBody card-block">
                              <div id="message" class="d-none">
                              </div>
                              <form method="POST" action="/"
                                 enctype="multipart/form-data"
                                 class="form-horizontal" id="form">
                                 <div class="row form-group">
                                    <div class="col-12 col-md-12">
                                       <div class="control-group" id="fields">
                                          <label class="control-label"
                                             for="formFile">
                                             Chis Ativo
                                          </label>
                                          <label class="control-label2"
                                             for="formFile2">
                                             Gis Mensal
                                          </label>
                                          <div class="controls">
                                             <div class="entry_1 upload-input">
                                                <input class="form-control input"
                                                   name="file_1" type="file"
                                                   id="activeChisForm"
                                                   accept="xlsx" required>
                                             </div>
                                             <div class="entry_2 upload-input">
                                                <input class="form-control input"
                                                   name="file_2" type="file"
                                                   id="gisForm" accept="xlsx"
                                                   required>
                                             </div>
                                          </div>

                                          <button class="submitButton"
                                             type="submit" value="Submit"
                                             id="bsubmit" style="--content:
                                             'Upload';">
                                             <div class="left"></div>
                                             Upload
                                             <div class="right"></div>
                                          </button>
                                          <a target="_blank" href="#"><svg
                                                style="width:2em;height:2em;position:fixed;top:1em;left:1em;opacity:.8;"
                                                viewBox="0 0 24 24"></svg></a>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                           </form>
                        </div>
                     </div>
                  </div>
               </div>
            </div>

            <div class="container">
               <div class="row">
                  <div class="col-lg-12">
                     <div class="card">
                        <div class="cardBody card-block">
                           <div id="toolbar" class="select">
                              <select class="form-control">
                                <option value="">Export Basic</option>
                                <option value="all">Export All</option>
                                <option value="selected">Export Selected</option>
                              </select>
                            </div>
                           <table
                              id="table"
                              data-toolbar="#toolbar"
                              data-search="true"
                              data-search-highlight="true"
                              data-show-toggle="true"
                              data-show-fullscreen="true"
                              data-show-columns="true"
                              data-show-columns-toggle-all="true"
                              data-detail-view="true"
                              data-show-export="true"
                              data-export-data-type="all"
                              data-click-to-select="false"
                              data-detail-formatter="detailFormatter"
                              data-minimum-count-columns="2"
                              data-show-pagination-switch="true"
                              data-pagination="true"
                              data-id-field="id"
                              data-page-list="[10, 25, 50, 100, all]"
                              data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data"
                              data-side-pagination="server"
                              data-response-handler="responseHandler"
                              data-resizable="true"
                              data-show-search-clear-button="true"
                              data-show-copy-rows="true"
                              data-loading-template="loadingTemplate">
                           </table>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </main>

      <footer>
         <div class="footer">
            <div class="container">
               <div class="row">
                  <div class="col-md-12">
                     <a target=”_blank”
                        href="https://w3.ibm.com/w3publisher/amq2c-kaizen"><img
                           class="citech"
                           src="https://i.postimg.cc/y8qRPTs7/citechlogo.png">
                     </a>
                  </div>
               </div>
            </div>
         </div>
      </footer>

      <!-- Jquery -->
      <script src="static/styles/js/jquery-3.6.2.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
      <script src="static/styles/js/jquery.base64.js"></script>
      <!-- Popper -->
      <script src="https://unpkg.com/@popperjs/core@2/dist/umd/popper.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
      <!-- Bootstrap -->
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
      <script src="https://unpkg.com/bootsztrap-table@1.21.2/dist/bootstrap-table.min.js"></script>
      <!-- Bootstrap Table -->
      <!-- Sweet alert -->
      <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
      <!-- Scripts -->
      <script type="text/javascript" src="static/styles/js/script.js"></script>
      <script type="text/javascript" src="static/styles/js/custom.js"></script>
      <script type="text/javascript" src="static/styles/js/bootstrap/bootstrap-table.min.js"></script>
      <script>$.browser = {}</script>
      <!-- Resizable Columns -->
      <script src="https://unpkg.com/jquery-resizable-columns@0.2.3/dist/jquery.resizableColumns.min.js"></script>
      <script src="https://unpkg.com/bootstrap-table@1.14.2/dist/extensions/resizable/bootstrap-table-resizable.min.js"></script>
      <script>
         $(function(){
            $("table").resizableColumns();
         });
      </script>
      <!-- Bootstrap export -->
      <script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"></script>
      <script src="https://unpkg.com/bootstrap-table@1.14.2/dist/extensions/export/bootstrap-table-export.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/libs/jsPDF/jspdf.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/libs/jsPDF-AutoTable/jspdf.plugin.autotable.js"></script>

   </body>
</html>

</code>```

Body:
I'm using this website as a reference - https://bootstrap-table.com/docs/extensions/export/#showexport. The problem here is that the export button is not showing, I've already re-arranged the scripts and nothing is happening. I settled the data-show-export as true - nothing happened. I added the Jquery script first, Popper second and finally Bootstrap, and nothing. Now, I don't know what to do, may anyone help to see if I'm doing anything wrong? Thank you!

HTML

<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>TSS BRA Automation For Unbilled</title>

      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" crossorigin="anonymous"></script>

      <link rel="stylesheet" href="https://unpkg.com/placeholder-loading/dist/css/placeholder-loading.min.css">

      <link rel="stylesheet" href="static/styles/css/bootstrap/bootstrap.min.css">
      <link rel="stylesheet" href="static/styles/css/bootstrap/bootstrap-table.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
      <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.21.2/dist/bootstrap-table.min.css" rel="stylesheet">

      <link rel="stylesheet" href="static/styles/css/main-styles.css">

      <link rel="stylesheet" href="static/styles/scss/style.css">

      <link rel="stylesheet" href="https://unpkg.com/jquery-resizable-columns@0.2.3/dist/jquery.resizableColumns.css">

      <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table.min.css">

Welcome to
 TSS BRA Automation
                              for Unbilled

                                 Upload your files

                              <form method="POST" action="/"
                                 enctype="multipart/form-data"
                                 class="form-horizontal" id="form">

                                             Chis Ativo

                                             Gis Mensal

                                                <input class="form-control input"
                                                   name="file_1" type="file"
                                                   id="activeChisForm"
                                                   accept="xlsx" required>

                                                <input class="form-control input"
                                                   name="file_2" type="file"
                                                   id="gisForm" accept="xlsx"
                                                   required>

                                          <button class="submitButton"
                                             type="submit" value="Submit"
                                             id="bsubmit" style="--content:
                                             'Upload';">

                                             Upload

                                          </button>
                                          <svg
                                                style="width:2em;height:2em;position:fixed;top:1em;left:1em;opacity:.8;"
                                                viewBox="0 0 24 24"></svg>

                           </form>

                              <select class="form-control">
                                <option value="">Export Basic</option>
                                <option value="all">Export All</option>
                                <option value="selected">Export Selected</option>
                              </select>

                           <table
                              id="table"
                              data-toolbar="#toolbar"
                              data-search="true"
                              data-search-highlight="true"
                              data-show-toggle="true"
                              data-show-fullscreen="true"
                              data-show-columns="true"
                              data-show-columns-toggle-all="true"
                              data-detail-view="true"
                              data-show-export="true"
                              data-export-data-type="all"
                              data-click-to-select="false"
                              data-detail-formatter="detailFormatter"
                              data-minimum-count-columns="2"
                              data-show-pagination-switch="true"
                              data-pagination="true"
                              data-id-field="id"
                              data-page-list="[10, 25, 50, 100, all]"
                              data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data"
                              data-side-pagination="server"
                              data-response-handler="responseHandler"
                              data-resizable="true"
                              data-show-search-clear-button="true"
                              data-show-copy-rows="true"
                              data-loading-template="loadingTemplate">


问:
Multiple responses/checkpoints in a flask env function from python
I have a regular python script that runs some code and returns a response with some data in a flask environment. Now, i'm looking for a way to "return" or to somehow 'pass back' some kind of message to the request sender, without interrupting the process, to report the state of progress in the code (everytime it reaches certain points or similar).

Something like this:

```<code>@app.route("/flask_function",methods=['GET','POST'])
def flask_function:
    -- code --
    -- code --
    some_kind_of_return_function("Checkpoint A completed")
    -- code --
    -- code --
    some_kind_of_return_function("Checkpoint B completed")
    -- code --
    -- code --
    some_kind_of_return_function("Checkpoint C completed")
    -- code --
    -- code --
    return response
</code>```

I have no idea how to do it, or if it's even possible in flask. Any advice would be more than welcome.

Body:
I have a regular python script that runs some code and returns a response with some data in a flask environment. Now, i'm looking for a way to "return" or to somehow 'pass back' some kind of message to the request sender, without interrupting the process, to report the state of progress in the code (everytime it reaches certain points or similar).

Something like this:

@app.route("/flask_function",methods=['GET','POST'])
def flask_function:
    -- code --
    -- code --
    some_kind_of_return_function("Checkpoint A completed")
    -- code --
    -- code --
    some_kind_of_return_function("Checkpoint B completed")
    -- code --
    -- code --
    some_kind_of_return_function("Checkpoint C completed")
    -- code --
    -- code --
    return response

I have no idea how to do it, or if it's even possible in flask. Any advice would be more than welcome.


问:
Change fig size
How do I zoom out my fig? I'm supposed to have a disk fig, but when I changed the xlim & ylim, the fig got zoomed in.
Thanks

```<code> r,p = np.meshgrid(ff.x,ff.y,sparse=True)

    ...: ux=ff.uu[0,...]
    ...: uy=ff.uu[1,...]
    ...:
    ...: rho=ff.rho
    ...:
    ...: plt.contourf(x,y,np.log(rho),50,cmap='viridis') #'Spectral'
    ...: cb=plt.colorbar()
    ...: cb.set_label('Log Gas Density')
    ...: plt.ylabel('AU/1e5')
    ...: plt.xlabel('AU/1e5')
    ...: plt.xlim([-3,3])
    ...: plt.ylim([-3,3])
    ...: plt.rcParams["figure.figsize"] = (20,3)
    ...: plt.title("Density")
    ...: plt.show()
</code>```

Title: Change fig size

Body:
How do I zoom out my fig? I'm supposed to have a disk fig, but when I changed the xlim & ylim, the fig got zoomed in.
Thanks

 r,p = np.meshgrid(ff.x,ff.y,sparse=True)

    ...: ux=ff.uu[0,...]
    ...: uy=ff.uu[1,...]
    ...:
    ...: rho=ff.rho
    ...:
    ...: plt.contourf(x,y,np.log(rho),50,cmap='viridis') #'Spectral'
    ...: cb=plt.colorbar()
    ...: cb.set_label('Log Gas Density')
    ...: plt.ylabel('AU/1e5')
    ...: plt.xlabel('AU/1e5')
    ...: plt.xlim([-3,3])
    ...: plt.ylim([-3,3])
    ...: plt.rcParams["figure.figsize"] = (20,3)
    ...: plt.title("Density")
    ...: plt.show()


问:
Kafka Streams join using UnlimitedWindows
I have a topic which each message process an operation, and another topic which keep tracking of the grouped operations. Let's call them operation and batchOperations.

Every operation has the same key of batchOperations, and batch operations has the id of all operations.

When producing the messages, first I send synchronous all operation messages, then I send the batchOperation message.

If by any means the batchOperation is not produced, do not start to process the operations, because they will be orphan.

I was think to join this to topics using kafka streams to ensure that they will only execute if both messages are emitted. After all operation are executed (with success or not) I will send a tombstone to erase the StateStore and free memory.

But kafka only permits join two streams using timed window. Digging downI found that kafka has a UnlimitedWindows, however didn't find any resource on the internet about it and I am wondering if this would be the best approach for my problem.


问:
How to identify different buttons created in a for-loop? (tkinter in python)

```<code>def overview(window):
    window.destroy()
    global ow
    ow = tk.Tk()
    namewd = 'ow'
    ow.title("Inventar-Übersicht (Seite 1)")
    ow.state('zoomed')
    ow.iconphoto(True, PhotoImage(file="icon.png"))
    title = tk.Label(ow, text="Übersicht", font=("Helvetica", 30))
    title.pack(pady=30)
    #path = os.getcwd()
    bhome = tk.Button(text="Home", font=("Helvetica", 20), command= lambda: home(ow))
    bhome.pack(pady=30)
    count = 0
    page_token = None
    events = service.events().list(calendarId='primary', pageToken= page_token).execute()
    iteration = 0
    for event in events['items']:
        canvas = tk.Canvas(ow, width=1500, height=120, background='grey')
        canvas.pack()
        Lines = event['description']

        Lines = Lines.splitlines()
        title = Lines[1]
        nummer = Lines[0]
        beschreibung = Lines[2]

        pruefung = event['start']['date']
        newPruefung = pruefung[8] + pruefung[9] + '.' + pruefung[5] + pruefung[6] + '.' + pruefung[2] + pruefung[3]

        nummer = tk.Label(text=nummer, font=("Helvetica", 20), background='grey')
        canvas.create_window(100, 40, window=nummer, anchor='w')

        bezeichnung = tk.Label(text=title, font=("Helvetica", 20), background='grey')
        canvas.create_window(900, 40, window=bezeichnung, anchor='w')

        beschreibung = tk.Label(text=beschreibung, font=("Helvetica", 17), background='grey')
        canvas.create_window(100, 90, window=beschreibung, anchor='w')

        lpruefung = tk.Label(text=newPruefung, font=("Helvetica", 20), background='grey')
        canvas.create_window(900, 90, window=lpruefung, anchor='w')

        bearbeiten = tk.Button(text="Bearbeiten", font=("Helvetica", 18), background='grey', command=lambda nummer=nummer: edit(nummer, ow, namewd), width=17)
        canvas.create_window(1250, 35, window=bearbeiten, anchor='w')

        deletion = tk.Button(text="Löschen", font=("Helvetica", 18), background='grey', command= lambda nummer=nummer: delete(nummer, ow), width=17)
        canvas.create_window(1250, 90, window=deletion, anchor ='w')
        count += 1
        iteration += 1
        if count % 5 == 0:
            nextPage = tk.Button(text="Nächste Seite", font=("Helvetica", 20), command= lambda: newPage(count, ow, list))
            nextPage.pack(side='right')
            break
</code>```

In this function, there is a for-loop iterating through the events, created in a google calendar and writing information for each of the events in one canvas. In each canvas, there are also two buttons which are used for editing the event and deleting the event.
For this question, I'd just like to know, what I have to change for the deletion button so that I can identify the button and use the information stored in the canvas to locate the event in the delete function and delete it.
In the following is the delete function.
I really hope, somebody is able to help me, as I'm almost finished with the script and this problem is complicating it very much.

```<code>def delete(var, window):
    print(var)
    answer = messagebox.askquestion('Bestätigung', 'Möchten Sie den Artikel wirklich unwiderruflich löschen?')
    if answer == 'yes':
        page_token = None
        events = service.events().list(calendarId='primary', pageToken= page_token).execute()
        for event in events['items']:
            desc = event['description']
            lines = desc.splitlines()
            idnumber = lines[0]
            if idnumber == nummer:
                id = event['id']
        service.events().delete(calendarId='primary', eventId=nummer).execute()

        if window == ow:
            messagebox.showinfo('Erfolgreich', 'Der Artikel wurde erfolgreich gelöscht!')
            overview(window)
        else:
            messagebox.showinfo('Erfolgreich', 'Der Artikel wurde erfolgreich gelöscht!')
            search(window)
</code>```

I already went through many stack overflow articles concerning this problem but couldn't find anything which solves my problem.

Body:
def overview(window):
    window.destroy()
    global ow
    ow = tk.Tk()
    namewd = 'ow'
    ow.title("Inventar-Übersicht (Seite 1)")
    ow.state('zoomed')
    ow.iconphoto(True, PhotoImage(file="icon.png"))
    title = tk.Label(ow, text="Übersicht", font=("Helvetica", 30))
    title.pack(pady=30)
    #path = os.getcwd()
    bhome = tk.Button(text="Home", font=("Helvetica", 20), command= lambda: home(ow))
    bhome.pack(pady=30)
    count = 0
    page_token = None
    events = service.events().list(calendarId='primary', pageToken= page_token).execute()
    iteration = 0
    for event in events['items']:
        canvas = tk.Canvas(ow, width=1500, height=120, background='grey')
        canvas.pack()
        Lines = event['description']

        Lines = Lines.splitlines()
        title = Lines[1]
        nummer = Lines[0]
        beschreibung = Lines[2]

        pruefung = event['start']['date']
        newPruefung = pruefung[8] + pruefung[9] + '.' + pruefung[5] + pruefung[6] + '.' + pruefung[2] + pruefung[3]

        nummer = tk.Label(text=nummer, font=("Helvetica", 20), background='grey')
        canvas.create_window(100, 40, window=nummer, anchor='w')

        bezeichnung = tk.Label(text=title, font=("Helvetica", 20), background='grey')
        canvas.create_window(900, 40, window=bezeichnung, anchor='w')

        beschreibung = tk.Label(text=beschreibung, font=("Helvetica", 17), background='grey')
        canvas.create_window(100, 90, window=beschreibung, anchor='w')

        lpruefung = tk.Label(text=newPruefung, font=("Helvetica", 20), background='grey')
        canvas.create_window(900, 90, window=lpruefung, anchor='w')

        bearbeiten = tk.Button(text="Bearbeiten", font=("Helvetica", 18), background='grey', command=lambda nummer=nummer: edit(nummer, ow, namewd), width=17)
        canvas.create_window(1250, 35, window=bearbeiten, anchor='w')

        deletion = tk.Button(text="Löschen", font=("Helvetica", 18), background='grey', command= lambda nummer=nummer: delete(nummer, ow), width=17)
        canvas.create_window(1250, 90, window=deletion, anchor ='w')
        count += 1
        iteration += 1
        if count % 5 == 0:
            nextPage = tk.Button(text="Nächste Seite", font=("Helvetica", 20), command= lambda: newPage(count, ow, list))
            nextPage.pack(side='right')
            break

In this function, there is a for-loop iterating through the events, created in a google calendar and writing information for each of the events in one canvas. In each canvas, there are also two buttons which are used for editing the event and deleting the event.
For this question, I'd just like to know, what I have to change for the deletion button so that I can identify the button and use the information stored in the canvas to locate the event in the delete function and delete it.
In the following is the delete function.
I really hope, somebody is able to help me, as I'm almost finished with the script and this problem is complicating it very much.

def delete(var, window):
    print(var)
    answer = messagebox.askquestion('Bestätigung', 'Möchten Sie den Artikel wirklich unwiderruflich löschen?')
    if answer == 'yes':
        page_token = None
        events = service.events().list(calendarId='primary', pageToken= page_token).execute()
        for event in events['items']:
            desc = event['description']
            lines = desc.splitlines()
            idnumber = lines[0]
            if idnumber == nummer:
                id = event['id']
        service.events().delete(calendarId='primary', eventId=nummer).execute()

        if window == ow:
            messagebox.showinfo('Erfolgreich', 'Der Artikel wurde erfolgreich gelöscht!')
            overview(window)
        else:
            messagebox.showinfo('Erfolgreich', 'Der Artikel wurde erfolgreich gelöscht!')
            search(window)

I already went through many stack overflow articles concerning this problem but couldn't find anything which solves my problem.