问:
How to add a class based on the horizontal cursor position in jQuery?
I have a nav bar that has an overflow, meaning, some LI elements are not visible and the user needs to scroll to see them. I want to add a few classes for these scenarios:

Case 1: a "solid to transparent" background when the user has reached the far left end of the nav bar

Case 2: a "transparent to transparent" background when the user is scrolling and there are elements either in the left or right to scroll

Case 3: a "transparent to solid" background when the user has reached the far right end of the nav bar

HTML:

```<code><ul class="navigator">
        <li class="active"><a href="">Ipsum</a></li>
        <li><a href="">Lorem</a></li>
        ...
      </ul>
</code>```

CSS:

```<code>.navigator {
  background: rgb(238,242,245);
  overflow: auto;
  white-space: nowrap;
}

// class to add when Case 1

.navigator.far-left {
}

// class to add when Case 2

.navigator.scrolling {
}

// class to add when Case 3

.navigator.far-right {
}
</code>```

I tried to do an exploration with jQuery "scrollLeft", but can't make it work. Any ideas? Thank you

Body:
I have a nav bar that has an overflow, meaning, some LI elements are not visible and the user needs to scroll to see them. I want to add a few classes for these scenarios:

Case 1: a "solid to transparent" background when the user has reached the far left end of the nav bar

Case 2: a "transparent to transparent" background when the user is scrolling and there are elements either in the left or right to scroll

Case 3: a "transparent to solid" background when the user has reached the far right end of the nav bar

HTML:

Ipsum

Lorem

        ...

CSS:

.navigator {
  background: rgb(238,242,245);
  overflow: auto;
  white-space: nowrap;
}

// class to add when Case 1

.navigator.far-left {
}

// class to add when Case 2

.navigator.scrolling {
}

// class to add when Case 3

.navigator.far-right {
}

I tried to do an exploration with jQuery "scrollLeft", but can't make it work. Any ideas? Thank you


来源: stackexchange

问:
How do I check that my npm package is installable on all the Node versions and platforms I want to support?
I publish an npm package that uses C++ code using nan. How can I double check that my package can be installed/imported on Linux, macOS and Windows with Node 14+ after I run npm publish?

ContentLicense: CC BY-SA 4.0


问:
Convert uiwebview to pdf and emailing
I have a Uiwebview which shows local htmls.I've done to convert html to pdf and can read on desktop.But when I attached pdf file to mail,It sent successfully but sometimes those pdfs can not be read in ipad or iphone?who has any suggestions to help me?
Thanks in advance,</p>

ContentLicense: CC BY-SA 3.0

Title: Convert uiwebview to pdf and emailing


问:
Used a script from another site to add a search function to a large excel file. Assistance to amend the script and to optimize
I am a beginner. Need to amend script, to, when search not to stop at the first empty cell in the selected column, but to keep searching until last row. I only have two worksheets i.e. 'Dashboard' and 'OMVL_Data' and the script is for many worksheets, perhaps it will run faster if amended.

Copied script from other site, googled for hours to find solution. Requested: Optimized script that will search and pass over empty cells in a column to last row of column. Also to add a field of search which will search all data on sheet.

Sub Data_Search()
    Dim ws As Worksheet
    Dim dashboard As Worksheet
    Dim dataArray As Variant
    Dim datatoShowArray As Variant
    Application.ScreenUpdating = False 'Turning off for the macro can speed things up - not so much here though.

    'Dashboard sheet
    Set dashboard = Sheets("Dashboard")

    'Data table information
    dataColumnStart = 1
    dataColumnEnd = 39
    dataColumnWidth = dataColumnEnd - dataColumnStart ' Number of columns for the raw data (+1 not included because it makes lower calculations more confusing)
    dataRowStart = 2
    dashboardDataColumnStart = 2 ' Column for the data on the dashboard

    'Get user input
    searchValue = dashboard.Range("K3").Value
    FieldValue = dashboard.Range("D6").Value

    'Clear Dashboard
    Call Clear_Data

    'Figure out by which field we will search.
    If (FieldValue = "ONLPAYSEQ") Then
    searchField = 1
    ElseIf (FieldValue = "RECEIPTN") Then
    searchField = 2
    ElseIf (FieldValue = "MVREGN") Then
    searchField = 3
    ElseIf (FieldValue = "REGTN") Then
    searchField = 4
    ElseIf (FieldValue = "MVCERTN") Then
    searchField = 6
    ElseIf (FieldValue = "CLIENT") Then
    searchField = 14
    ElseIf (FieldValue = "IDDOCN") Then
    searchField = 15
    ElseIf (FieldValue = "PERIDN") Then
    searchField = 16
    ElseIf (FieldValue = "MOBILE") Then
    searchField = 17
    ElseIf (FieldValue = "EMAIL") Then
    searchField = 18

End If

'Loop through the worksheets
    For Each ws In Worksheets

    'Ignore the Dashboard worksheet
    If (ws.Name <> "Dashboard") Then

        'Get the range values into a variable that can be looped through.
        'Example usage: dataArray(1,1) [row,column]
        'Simple version: ws.Range(Cells(1,1),Cells(2,2)).Value
        dataArray = ws.Range(ws.Cells(dataRowStart, dataColumnStart), ws.Cells(ws.Cells(Rows.Count, dataColumnStart).End(xlUp).Row, dataColumnEnd)).Value

        'Increase size of array that will hold the data to display to its max possible size for the current worksheet.
        ReDim datatoShowArray(1 To UBound(dataArray, 1), 1 To UBound(dataArray, 2))

        'Row increment for the final data array (datatoShowArray).
        j = 1

        'Loop through the rows in the data range.
        For i = 1 To UBound(dataArray, 1)

            'Check if the value in the row equals our search value
            If (dataArray(i, searchField) = searchValue) Then

                'MATCH FOUND! Now do something!

                'Loop through the columns in the data range so can get their values.
                For k = 1 To UBound(dataArray, 2)

                    'Add values to the array that will be used to put data into the Dashboard.
                    datatoShowArray(j, k) = dataArray(i, k)

                Next k

                'Increment the counter for the datatoShowArray
                j = j + 1

            End If

        Next i

        'Find next empty row in the dashboard.
        nextRow = dashboard.Cells(Rows.Count, dashboardDataColumnStart).End(xlUp).Row + 1

        'Put data into the dashboard.
        'Format = Range(Cells(1,1),Cells(2,2)).Value = datatoShowArray
        dashboard.Range(Cells(nextRow, dashboardDataColumnStart), Cells(nextRow + UBound(datatoShowArray, 1) - 1, dashboardDataColumnStart + dataColumnWidth)).Value = datatoShowArray

    End If

    'Go to the next worksheet.
    Next ws

    Application.ScreenUpdating = True 'Turn it back on at the end of the macro!

End Sub
```


问:
Customising color of top 5 bars differently in plotly R bar charts
I am trying to customise my horizontal bar chart, in plotly R, in such a way that the top 5 bars (which represent highest 5 values out of the total 20) are colored differently, say Green, and the rest 15 having default blue colors. How do I go about achieving that? I appreciate any help. For the sake of reproducing an example, assume that my data frame is as follows:

```<code>categories<- letters[1:20]
values <- sort(runif(20, 1, 40), decreasing = TRUE)
df <- data.frame(categories, values)
</code>```

And the standard plotly horizontal bar chart (which I am looking to customise its colours) was created using the following code:

```<code># To make horizontal bars appear in decreasing order, set factor level order to ascending

  df$categories <- factor(df$categories, levels = unique(
                              df$categories)[order(df$values,
                                                     decreasing = FALSE)]

# Plot the poorly bar chart using poorly
                            )
  fig <- plot_ly(df, x = ~values, y = ~categories,
          type = 'bar', orientation = 'h')
</code>```

A screenshot of the standard bar chart the above codes produced is given below:

Now, the question is how do I convert the colors of the first 5 bars (for bars a, b, c, d, and e) to green, leaving the rest as they are in blue color.

Body:
I am trying to customise my horizontal bar chart, in plotly R, in such a way that the top 5 bars (which represent highest 5 values out of the total 20) are colored differently, say Green, and the rest 15 having default blue colors. How do I go about achieving that? I appreciate any help. For the sake of reproducing an example, assume that my data frame is as follows:

categories<- letters[1:20]
values <- sort(runif(20, 1, 40), decreasing = TRUE)
df <- data.frame(categories, values)

And the standard plotly horizontal bar chart (which I am looking to customise its colours) was created using the following code:

# To make horizontal bars appear in decreasing order, set factor level order to ascending

  df$categories <- factor(df$categories, levels = unique(
                              df$categories)[order(df$values,
                                                     decreasing = FALSE)]

# Plot the poorly bar chart using poorly
                            )
  fig <- plot_ly(df, x = ~values, y = ~categories,
          type = 'bar', orientation = 'h')

A screenshot of the standard bar chart the above codes produced is given below:

Now, the question is how do I convert the colors of the first 5 bars (for bars a, b, c, d, and e) to green, leaving the rest as they are in blue color.


问:
Google Cloud Run - Stockfish causes deploy failure
recently been trying to get Stockfish to run and receive HTTP requests on a web server and ran into an issue. importing and initilizing stockfish causes the deploy to fail, when locally ran it runs perfectictly fine but as soon as I go to deploy it I get

```<code>Invalid filter resource.type="cloud_run_revision"resource.labels.service_name="main"resource.labels.revision_name="main-00003-cuf"
</code>```

To get stockfish into the project I compiled it like normal and the code used to initalize it is

```<code>From stockfish import Stockfish

stockfish = Stockfish(path="PATH")
</code>```

These 2 lines cause the deploy to fail, I know this becasue as soon as I remove these 2 lines the deploy works.

Here is the link to the Stockfish doc https://pypi.org/project/stockfish/

Any help would be much appreciated!

I haven't been able to find anyone else who has ran into an issue like this but im sure there has been or it's a simple fix and im just dumb.

Body:
recently been trying to get Stockfish to run and receive HTTP requests on a web server and ran into an issue. importing and initilizing stockfish causes the deploy to fail, when locally ran it runs perfectictly fine but as soon as I go to deploy it I get

Invalid filter resource.type="cloud_run_revision"resource.labels.service_name="main"resource.labels.revision_name="main-00003-cuf"

To get stockfish into the project I compiled it like normal and the code used to initalize it is

From stockfish import Stockfish

stockfish = Stockfish(path="PATH")

These 2 lines cause the deploy to fail, I know this becasue as soon as I remove these 2 lines the deploy works.

Here is the link to the Stockfish doc https://pypi.org/project/stockfish/

Any help would be much appreciated!

I haven't been able to find anyone else who has ran into an issue like this but im sure there has been or it's a simple fix and im just dumb.


问:
In Electron (Forge) when nodeIntegrationInWorker: true, embedding gmail shows a blank screen
In Electron Forge when I embed gmail and set nodeIntegrationInWorker: true I get a blank screen for Gmail. How do I fix this?

```<code>const createWindow = () => {
  const mainWindow = new BrowserWindow({

    webPreferences: {
       preload: path.join(__dirname, 'preload.js'),
       nodeIntegrationInWorker: true,
      contextIsolation: true
    },
  });

  mainWindow.loadURL("https://gmail.com")

};
</code>```

I am using nodeIntegrationInWorker: true to manipulate the CSS of a site that requires gmail authentication. Without it, I can execute preload.js

EDIT

Reading about preload, it looks like I am using it incorrectly.

My goal is to create an app that manipulates the CSS of a website that uses gmail for authentication and to have the app persist those changes. I am writing dom manipulating JS in the preload.js file.

Body:
In Electron Forge when I embed gmail and set nodeIntegrationInWorker: true I get a blank screen for Gmail. How do I fix this?

const createWindow = () => {
  const mainWindow = new BrowserWindow({

    webPreferences: {
       preload: path.join(__dirname, 'preload.js'),
       nodeIntegrationInWorker: true,
      contextIsolation: true
    },
  });

  mainWindow.loadURL("https://gmail.com")

};

I am using nodeIntegrationInWorker: true to manipulate the CSS of a site that requires gmail authentication. Without it, I can execute preload.js

EDIT

Reading about preload, it looks like I am using it incorrectly.

My goal is to create an app that manipulates the CSS of a website that uses gmail for authentication and to have the app persist those changes. I am writing dom manipulating JS in the preload.js file.


问:
A personal class object for each user
in the process of creating telegram bot created a separate class with functionality.
I created a class object in the main file, but unfortunately all users work with one object, and the actions of one affect the result of the others.
How to make it so that when interacting with a bot, each user works with his own class object

I tried to dynamically create variables using the vars() function['message.from_user.id '], but access to the idi is only inside the command processing function, and it does not work to make it global, besides, I do not know how to access this individual variable in the program

Title: A personal class object for each user


问:
Creating script to search webpage
I am trying to create a script to go to this specific website and search for a name, any name really.

It will pull up the website but it won't type anything into the search bar and click search. Can anyone shed some light on what might be missing?

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By

# Replace "search term" with the search term you want to use
search_term = "John"

# Create an instance of the WebDriver class
driver = webdriver.Chrome()

# Open the web browser and go to the website
driver.get("https://probaterecords.shelbyal.com/shelby/search.do?indexName=opr")

# Find the search bar element and enter the search term
search_bar = driver.find_element_by_xpath('//*[@id="q"]')
search_bar.send_keys(search_term)

# Find the search button element and click it
search_button = driver.find_element_by_xpath('//*[@id="search-icon-legacy"]')
search_button.click()

# Close the web browser
driver.quit()
</code>```

Expecting it to open the webbrower. Click in the search bar, enter a name and click search. I then need it to search for specific documents but that's another issue I will have to tackle.

Title: Creating script to search webpage

Body:
I am trying to create a script to go to this specific website and search for a name, any name really.

It will pull up the website but it won't type anything into the search bar and click search. Can anyone shed some light on what might be missing?

from selenium import webdriver
from selenium.webdriver.common.by import By

# Replace "search term" with the search term you want to use
search_term = "John"

# Create an instance of the WebDriver class
driver = webdriver.Chrome()

# Open the web browser and go to the website
driver.get("https://probaterecords.shelbyal.com/shelby/search.do?indexName=opr")

# Find the search bar element and enter the search term
search_bar = driver.find_element_by_xpath('//*[@id="q"]')
search_bar.send_keys(search_term)

# Find the search button element and click it
search_button = driver.find_element_by_xpath('//*[@id="search-icon-legacy"]')
search_button.click()

# Close the web browser
driver.quit()

Expecting it to open the webbrower. Click in the search bar, enter a name and click search. I then need it to search for specific documents but that's another issue I will have to tackle.


问:
R is completely messed up after trying to download caret package
I tried to download the caret package in R and it started removing some packages I had and now I get these messages on R startup:

```<code>Warning: namespace ‘ggplot2’ is not available and has been replaced
by .GlobalEnv when processing object ‘belPlotTest’
Warning: namespace ‘scales’ is not available and has been replaced
by .GlobalEnv when processing object ‘belPlotTest’
Warning: namespace ‘cowplot’ is not available and has been replaced
by .GlobalEnv when processing object ‘g’
Warning: namespace ‘forecast’ is not available and has been replaced
by .GlobalEnv when processing object ‘mtgomeryPlot’
</code>```

I tried rm(belPlotTest), rm(g) and rm(mtgomeryPlot) and restarted R as recommended but I keep getting these messages. I have no idea what these messages mean. I have the latest R version from 2022, 4.1.2. please help :(

Body:
I tried to download the caret package in R and it started removing some packages I had and now I get these messages on R startup:

Warning: namespace ‘ggplot2’ is not available and has been replaced
by .GlobalEnv when processing object ‘belPlotTest’
Warning: namespace ‘scales’ is not available and has been replaced
by .GlobalEnv when processing object ‘belPlotTest’
Warning: namespace ‘cowplot’ is not available and has been replaced
by .GlobalEnv when processing object ‘g’
Warning: namespace ‘forecast’ is not available and has been replaced
by .GlobalEnv when processing object ‘mtgomeryPlot’

I tried rm(belPlotTest), rm(g) and rm(mtgomeryPlot) and restarted R as recommended but I keep getting these messages. I have no idea what these messages mean. I have the latest R version from 2022, 4.1.2. please help :(


问:
How to work around needing to access context state within the entry point of my App before the Provider has been defined
I have a react native app. I have a hook useAppIsReady that contains a check for whether images have been loaded yet located in my App.tsx.

The way it works is I have state in my context numberOfImagesLoaded. I have multiple images loaded within Home. When an image loads, numberOfImagesLoaded gets incremented by 1, and once it reaches a specified number, appIsReady gets set to true.

The problem is that I can't use useAppIsReady within my App.tsx since numberOfImagesLoaded is located within my context, and useAppIsReady is used within App.tsx, the entry point to my application, so the return statement that contains my whole app wrapped in context is defined after useAppIsReady gets called. So I'm forced to place useAppIsReady inside a child component Home instead, which is suboptimal. How can I make useAppIsReady work in my app's entry point, App.tsx?

(btw I don't want to define the numberOfImagesLoaded state in my App.tsx because it will be a pain to pass down through props)

useAppIsReady

const useAppIsReady = () => {
  const [appIsReady, setAppIsReady] = useState(false);
  const context = useContext(AppContext);

  // If all images are loaded

  const imagesAreLoaded = context.numberOfImagesLoaded > 5;

  if (imagesAreLoaded && !appIsReady) {
    setAppIsReady(true);
  }

  return appIsReady;
};
```
<p>App.tsx</p>
<pre class="lang-js prettyprint-override"><code>SplashScreen.preventAutoHideAsync();

export default function App() {

  // useAppIsReady() won't work since context has not yet been defined

  const appIsReady = useAppIsReady();

  const Tab = createBottomTabNavigator<AppParamList>();

   useEffect(() => {
    const prepare = async () => {
      if (appIsReady) {
        await SplashScreen.hideAsync();
      }
    };

    prepare();
  }, [appIsReady]);

  if (!appIsReady) {
    return null;
  }

  return (
      <AppProvider>
        <NavigationContainer>
          <Tab.Navigator
          >
            <Tab.Screen name="Home" component={Home} />
            <Tab.Screen
              name="MyQueues"
              component={MyQueuesScreen}
            />
            <Tab.Screen name="Profile" component={Profile} />
          </Tab.Navigator>
        </NavigationContainer>
      </AppProvider>
  );
}
</code>```

Body:
I have a react native app. I have a hook useAppIsReady that contains a check for whether images have been loaded yet located in my App.tsx.

The way it works is I have state in my context numberOfImagesLoaded. I have multiple images loaded within Home. When an image loads, numberOfImagesLoaded gets incremented by 1, and once it reaches a specified number, appIsReady gets set to true.

The problem is that I can't use useAppIsReady within my App.tsx since numberOfImagesLoaded is located within my context, and useAppIsReady is used within App.tsx, the entry point to my application, so the return statement that contains my whole app wrapped in context is defined after useAppIsReady gets called. So I'm forced to place useAppIsReady inside a child component Home instead, which is suboptimal. How can I make useAppIsReady work in my app's entry point, App.tsx?

(btw I don't want to define the numberOfImagesLoaded state in my App.tsx because it will be a pain to pass down through props)

useAppIsReady

const useAppIsReady = () => {
  const [appIsReady, setAppIsReady] = useState(false);
  const context = useContext(AppContext);

  // If all images are loaded

  const imagesAreLoaded = context.numberOfImagesLoaded > 5;

  if (imagesAreLoaded && !appIsReady) {
    setAppIsReady(true);
  }

  return appIsReady;
};

App.tsx

SplashScreen.preventAutoHideAsync();

export default function App() {

  // useAppIsReady() won't work since context has not yet been defined

  const appIsReady = useAppIsReady();

  const Tab = createBottomTabNavigator<AppParamList>();

   useEffect(() => {
    const prepare = async () => {
      if (appIsReady) {
        await SplashScreen.hideAsync();
      }
    };

    prepare();
  }, [appIsReady]);

  if (!appIsReady) {
    return null;
  }

  return (
      <AppProvider>
        <NavigationContainer>
          <Tab.Navigator
          >
            <Tab.Screen name="Home" component={Home} />
            <Tab.Screen
              name="MyQueues"
              component={MyQueuesScreen}
            />
            <Tab.Screen name="Profile" component={Profile} />
          </Tab.Navigator>
        </NavigationContainer>
      </AppProvider>
  );
}


问:
Setup ODBC for SQL Server in PHP 8 native Windows 11

Fatal error: Uncaught Error: Call to undefined function odbc_connect() in C:\xampp\htdocs\simrs\tes.php:8 Stack trace: #0 {main} thrown in C:\xampp\htdocs\simrs\tes.php on line 8

I tried to write this

```<code>$server="myservername";
$username="myusername";
$password="mypassword";
$db="mydb";
$connection_string = "DRIVER={ODBC DRIVER 17 for SQL Server};SERVER=$server;PORT:myPort;DATABASE=$db";
$odbcConn = odbc_connect($connection_string,$username,$password); `
</code>```

But that always fatal error.

I already installed ODBC driver. I don't actually know what caused this.

Body:
Fatal error: Uncaught Error: Call to undefined function odbc_connect() in C:\xampp\htdocs\simrs\tes.php:8 Stack trace: #0 {main} thrown in C:\xampp\htdocs\simrs\tes.php on line 8

I tried to write this

$server="myservername";
$username="myusername";
$password="mypassword";
$db="mydb";
$connection_string = "DRIVER={ODBC DRIVER 17 for SQL Server};SERVER=$server;PORT:myPort;DATABASE=$db";
$odbcConn = odbc_connect($connection_string,$username,$password); `

But that always fatal error.

I already installed ODBC driver. I don't actually know what caused this.


问:
Transport Optimization (PuLP) with Shipping Volume Discount
In the transport optimization problem of PuLP, i am want to optimize the final cost after taking into consideration volume based cost discount. Hence in the problem below we have 3 warehouses and  3 projects with each projects having a demand and warehouse having supply with cost of transport defined.

```<code># Creates a list of all the supply nodes
warehouses = ["A", "B", "C"]

# Creates a dictionary for the number of units of supply for each supply node
supply = {"A": 150, "B": 600, "C":1000}

# Creates a list of all demand nodes
projects = ["1", "2", "3"]

# Creates a dictionary for the number of units of demand for each demand node
demand = {
    "1": 150,
    "2": 450,
    "3": 900,
}

# Creates a list of costs of each transportation path
costs = [  # Projects
    [5,1,9],  # A   warehouses
    [4,2,8],  # B
    [8,7,2]   # C
]

# The cost data is made into a dictionary
costs = makeDict([warehouses, projects], costs, 0)

# Import PuLP modeler functions
from pulp import *

# Creates the 'prob' variable to contain the problem data
prob = LpProblem("Material Supply Problem", LpMinimize)

# Creates a list of tuples containing all the possible routes for transport
Routes = [(w, b) for w in warehouses for b in projects]

# A dictionary called 'Vars' is created to contain the referenced variables(the routes)
vars = LpVariable.dicts("Route", (warehouses, projects), 0, None, LpInteger)
</code>```

At this stage usually the objective function is created as below

```<code># The objective function is added to 'prob' first
prob += (
    lpSum([vars[w][j] * costs[w][j] for (w, j) in assign]),
    "Sum_of_Assignment_Costs",
)
</code>```

Instead of this I am trying to figure out how to incorporate volume based discount into objective function such as if Warehouse C fulfills >= 600 units then transport cost will be 10% discounted per unit, if Warehouse B fulfills >= 200 units then transport cost will be 5% discounted per unit

Body:
In the transport optimization problem of PuLP, i am want to optimize the final cost after taking into consideration volume based cost discount. Hence in the problem below we have 3 warehouses and  3 projects with each projects having a demand and warehouse having supply with cost of transport defined.

# Creates a list of all the supply nodes
warehouses = ["A", "B", "C"]

# Creates a dictionary for the number of units of supply for each supply node
supply = {"A": 150, "B": 600, "C":1000}

# Creates a list of all demand nodes
projects = ["1", "2", "3"]

# Creates a dictionary for the number of units of demand for each demand node
demand = {
    "1": 150,
    "2": 450,
    "3": 900,
}

# Creates a list of costs of each transportation path
costs = [  # Projects
    [5,1,9],  # A   warehouses
    [4,2,8],  # B
    [8,7,2]   # C
]

# The cost data is made into a dictionary
costs = makeDict([warehouses, projects], costs, 0)

# Import PuLP modeler functions
from pulp import *

# Creates the 'prob' variable to contain the problem data
prob = LpProblem("Material Supply Problem", LpMinimize)

# Creates a list of tuples containing all the possible routes for transport
Routes = [(w, b) for w in warehouses for b in projects]

# A dictionary called 'Vars' is created to contain the referenced variables(the routes)
vars = LpVariable.dicts("Route", (warehouses, projects), 0, None, LpInteger)

At this stage usually the objective function is created as below

# The objective function is added to 'prob' first
prob += (
    lpSum([vars[w][j] * costs[w][j] for (w, j) in assign]),
    "Sum_of_Assignment_Costs",
)

Instead of this I am trying to figure out how to incorporate volume based discount into objective function such as if Warehouse C fulfills >= 600 units then transport cost will be 10% discounted per unit, if Warehouse B fulfills >= 200 units then transport cost will be 5% discounted per unit


问:
rnn and input shape on a 1d toy dataset with keras
i was trying to implement a simple RNN on a 1 dimensional toy dataset (just one x and one target variable y) to learn but I am having issue with the input shape.

X_train has input shape equal to (848,)
y_train the same

my model is very simple

```<code>from keras.layers import Input, SimpleRNN, Dense
def create_rnn_model(train_size):
  inputs = Input(shape=( 1,))
  rnn = SimpleRNN(units=32, input_shape=( 1,))(inputs)
  dense1 = Dense(units=64, activation='relu')(rnn)
  dense2 = Dense(units=64, activation='relu')(dense1)
  modello = Model(inputs=inputs, outputs=dense2)
  return modello

optimizer = tf.optimizers.SGD(learning_rate=0.0001,momentum=0.9)
rnn_model = create_rnn_model(train_size=train_size)
 rnn_model.compile(optimizer=optimizer,
                  loss="mse" , jit_compile=True ]
                 )
</code>```

but whenever i try to fit it i get this input shape that doesn't allow me to go further

ValueError: Input 0 of layer "simple_rnn_5" is incompatible with the
layer: expected ndim=3, found ndim=2. Full shape received: (None, 1)

i know it depends on the format that the rnn want  but i don't understand how to organize the data correctly.
i was trying without any windows size but i would really like to understand how to set a windows size of 10 for example.

Body:
i was trying to implement a simple RNN on a 1 dimensional toy dataset (just one x and one target variable y) to learn but I am having issue with the input shape.

X_train has input shape equal to (848,)
y_train the same

my model is very simple

from keras.layers import Input, SimpleRNN, Dense
def create_rnn_model(train_size):
  inputs = Input(shape=( 1,))
  rnn = SimpleRNN(units=32, input_shape=( 1,))(inputs)
  dense1 = Dense(units=64, activation='relu')(rnn)
  dense2 = Dense(units=64, activation='relu')(dense1)
  modello = Model(inputs=inputs, outputs=dense2)
  return modello

optimizer = tf.optimizers.SGD(learning_rate=0.0001,momentum=0.9)
rnn_model = create_rnn_model(train_size=train_size)
 rnn_model.compile(optimizer=optimizer,
                  loss="mse" , jit_compile=True ]
                 )

but whenever i try to fit it i get this input shape that doesn't allow me to go further

ValueError: Input 0 of layer "simple_rnn_5" is incompatible with the
layer: expected ndim=3, found ndim=2. Full shape received: (None, 1)

i know it depends on the format that the rnn want  but i don't understand how to organize the data correctly.
i was trying without any windows size but i would really like to understand how to set a windows size of 10 for example.


问:
In MongoDB, how to roll back update to one collection if update fails on another collection?
For example, a user is deleted in the members collection. Thus, all of its documents must also be deleted in all other collections.

After successfully deleting the user from the members collection, how do I ensure that the cascading deletes will succeed in other collections? What if they don't succeed? How do I know of this inconsistency that is now in my database?


问:
"Origin Not Allowed" error when asking Grafana form Azure Front Door with Fronted Domain
When I access Grafana from browser with Azure Front Door Domain, I can login successfully but after sometime i can see "Origin not Allowed" Error,

Grafana installed on Kubernetes 1.24v
we have Nginx Ingress Controller setup in K8s with public domain mapped with GoDaddy(example.dev)

we have Configured Ingress rules for Grafana and added "example.dev" as a host in spec.rules.host, so it can accessible from "example.dev/grafana".

Everything is fine with "example.dev/grafana", can login successfully and could'nt find any issues.

Coming to Azure Front Door, We added "example.dev" domain as custom Domain as Backend Pool and Added Route rule to "/grafana.

When Accessed From  " *.azurefd.net " domain, it can hit login page of Grafana and login is happening well but after login I can see "Origin Not Allowed" issue prompted in Grafana UI.

version:

Grafana:  8.5.5, 8.3.5, 9.0.4, 9.3.1(stable) same issue with every version
Azure Kuberenetes Service: 1.24.x
Nginx Ingress: registry.k8s.io/ingress-nginx/controller:v1.5.1
others: Azure Front Door, Azure Kuberertes Service
Browser: Chrome, Microsoft Edge

I need to Access Grafana  from Azure front Domain " *.azurefd.net/grafana ", azure door will route it to Nginx Ingress and from to Grafana Service "ClusterIP".

*.azurefd.net/grafana  ----->  example.dev/grafana

Front Door to ingress is https
ingress to backed Grafana service is http


问:
Google Chrome is sending empty payload to endpoint in Reporting-Endpoints
I'm sending this header in the responses:

Reporting-Endpoints: default="https://example.com/error-reports"

Then, I tested doing the following on page loads:

document.domain = "example.com";

On the error-reports endpoint, I have the following code:

```<code>log_to_file(var_dump_return($_REQUEST));
log_to_file(var_dump_return(file_get_contents('php://input')));
</code>```

(log_to_file and var_dump_return are custom functions that are very well tested in the past. In the code above, I'm basically logging the $_REQUEST and php://input to a file)

And what's being logged is:

array(0) {

}

string(0) ""

Is there any way I can see the exact HTTP request that Google Chrome invokes to this endpoint?

I'm not understanding how to see the payload of these requests.

Body:
I'm sending this header in the responses:

Reporting-Endpoints: default="https://example.com/error-reports"

Then, I tested doing the following on page loads:

document.domain = "example.com";

On the error-reports endpoint, I have the following code:

log_to_file(var_dump_return($_REQUEST));
log_to_file(var_dump_return(file_get_contents('php://input')));

(log_to_file and var_dump_return are custom functions that are very well tested in the past. In the code above, I'm basically logging the $_REQUEST and php://input to a file)

And what's being logged is:

array(0) {

}

string(0) ""

Is there any way I can see the exact HTTP request that Google Chrome invokes to this endpoint?

I'm not understanding how to see the payload of these requests.


问:
Traefik non-regex specific Path replacements
Running traefik 2.8.4

I have, essentially, a map of paths that need to be redirected. For instance /asdf to /specific-word-1, /qwerty to /another-path, etc. They're not regex replacements, and there's no logical way to do the conversion. They're hardcoded, specific, redirections. All exact matches. Unfortunately none of this is something I have control over. I have ~70 of these.

What would be the nicest way to do this in Traefik? An IngressRoute with some Rules to match, each with a ReplacePath middleware? This wouldn't be too terrible to generate with some helm templating, but I was hoping for something that would be nicer and more obvious, without creating a huge number of kubernetes resources (literally 70 in this case). Is this the scenario ReplacePath was meant to be used it?

Efficiency isn't the greatest concern, but is Traefik's rule evaluation smart enough to notice the exact matches and not evaluate rules one-by-one in order of length like it normally does? (I'm actively looking through the source code, but thought I might as well ask in case someone had good knowledge about it)


问:
Adding 25+ textviews programmatically to 5 linearlayouts in numerical order
Here i have 25+ names and i have created 5 linearlayouts which have vertical orientation.

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical
        android:layout_weight="1"
        android:id="@+id/ll_one" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_two" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_three" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_four" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_five" />
</LinearLayout>
</code>```

and i have names data in arraylist i. e.

```<code>ArrayList<String> data = new ArrayList<>();
data.add("1. temp1");
data.add("2. temp2");
data.add("3. temp3");
...
data.add("25. temp25");
</code>```

now i want to set this arraylist strings into textviews and add those textviews in above linearlayouts like i want to add 1. temp1 textview into first linearlayout, 2. temp2 textview into second linearlayout, 3. temp3 textview into third linearlayout, 4. temp4 textview into fourth linearlayout , 5. temp5 textview into fifth linearlayout, 6. temp6 textview into first linearlayout, 7. temp7 textview into second linearlayout, and so on like this...

Body:
Here i have 25+ names and i have created 5 linearlayouts which have vertical orientation.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical
        android:layout_weight="1"
        android:id="@+id/ll_one" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_two" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_three" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_four" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:id="@+id/ll_five" />
</LinearLayout>

and i have names data in arraylist i. e.

ArrayList<String> data = new ArrayList<>();
data.add("1. temp1");
data.add("2. temp2");
data.add("3. temp3");
...
data.add("25. temp25");

now i want to set this arraylist strings into textviews and add those textviews in above linearlayouts like i want to add 1. temp1 textview into first linearlayout, 2. temp2 textview into second linearlayout, 3. temp3 textview into third linearlayout, 4. temp4 textview into fourth linearlayout , 5. temp5 textview into fifth linearlayout, 6. temp6 textview into first linearlayout, 7. temp7 textview into second linearlayout, and so on like this...


问:
Fetch() async/await method in a local NextJs 13 app getting object “undefined”when trying to build for prod but works in dev
I’m learning NextJS 13 and trying out fetch()/async/await in a simple demo app running on a local Docker container. I’m using fetch()/async/await hitting a GraphQL api on another local container. Everything works great when running “npm run dev” and I’m now wanting to try out the workflow of Next’s static output and pushing to production but when I try generating the app via “npm run build” none of the api calls work because my code which is trying to display for example “data.item.name” and can’t select “item.name” on object “undefined” and the build fails. I retry running “npm run dev” and all works perfectly fine again.

I’ve double checked that my api is responding with Postman and all seems to be good. I did notice that when running the NextJS 13 app within Docker it wanted me to use the container ID of the api container ie “http://nginx/api” vs “http://localhost:8888” when making the fetch() call which had me hung up for a few days. But once I got that working the app and the fetch() calls worked great.

I’m brand new to Next and React so this one has really had me stuck.


问:
npm ERR! PhantomJS not found on PATH in Railway
I have a node.js app in Railway.

When it is buliding,I get an error:

I install phantomjs package,but it still not work.
How can I do?


问:
scale background image in plot python matplotlib
I am using imshow to plot an image in the background of a subplot.
Is it possible to show only part of the image, scale it?
It seems extent does not do the job.</p>
```<code>fig, axs = plt.subplots(1,1)
im = plt.imread("GUN2.png")
axs[0,0].imshow(im, extent=[0,10,0, 10])
axs[0,0].plot((z_main,G, 'b.')
axs[0,0].grid()
</code>```

Body:
I am using imshow to plot an image in the background of a subplot.
Is it possible to show only part of the image, scale it?
It seems extent does not do the job.

fig, axs = plt.subplots(1,1)
im = plt.imread("GUN2.png")
axs[0,0].imshow(im, extent=[0,10,0, 10])
axs[0,0].plot((z_main,G, 'b.')
axs[0,0].grid()


问:
Completely Remove Python-Related Files Windows
Something was wrong with my Python installation so I tried to fix it by uninstalling and reinstalling Python. I've tried to do so several times, but whenever I type "python" into my terminal, I get this nasty error:

```<code>Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = 'C:\Users\jeffrey\AppData\Local\Programs\Python\Python39\'
  program name = 'python'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'C:\\msys64\\mingw64\\bin\\python.exe'
  sys.base_prefix = 'D:\\a\\msys64\\mingw64'
  sys.base_exec_prefix = 'D:\\a\\msys64\\mingw64'
  sys.platlibdir = 'lib'
  sys.executable = 'C:\\msys64\\mingw64\\bin\\python.exe'
  sys.prefix = 'D:\\a\\msys64\\mingw64'
  sys.exec_prefix = 'D:\\a\\msys64\\mingw64'
  sys.path = [
    'C:\\Users\\jeffrey\\AppData\\Local\\Programs\\Python\\Python39\\',
    'D:\\a\\msys64\\mingw64\\lib\\python310.zip',
    'D:\\a\\msys64\\mingw64\\lib\\python3.10',
    'D:\\a\\msys64\\mingw64\\lib\\lib-dynload',
    '',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00006b50 (most recent call first):
  <no Python frame>
</code>```

Is there a way to uninstall everything and get a fresh Python installation? I'm on Windows.

I've tried uninstalling Python using the control panel, manually deleting the files myself, and I've removed Python from the PATH each time.

Body:
Something was wrong with my Python installation so I tried to fix it by uninstalling and reinstalling Python. I've tried to do so several times, but whenever I type "python" into my terminal, I get this nasty error:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = 'C:\Users\jeffrey\AppData\Local\Programs\Python\Python39\'
  program name = 'python'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'C:\\msys64\\mingw64\\bin\\python.exe'
  sys.base_prefix = 'D:\\a\\msys64\\mingw64'
  sys.base_exec_prefix = 'D:\\a\\msys64\\mingw64'
  sys.platlibdir = 'lib'
  sys.executable = 'C:\\msys64\\mingw64\\bin\\python.exe'
  sys.prefix = 'D:\\a\\msys64\\mingw64'
  sys.exec_prefix = 'D:\\a\\msys64\\mingw64'
  sys.path = [
    'C:\\Users\\jeffrey\\AppData\\Local\\Programs\\Python\\Python39\\',
    'D:\\a\\msys64\\mingw64\\lib\\python310.zip',
    'D:\\a\\msys64\\mingw64\\lib\\python3.10',
    'D:\\a\\msys64\\mingw64\\lib\\lib-dynload',
    '',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00006b50 (most recent call first):
  <no Python frame>

Is there a way to uninstall everything and get a fresh Python installation? I'm on Windows.

I've tried uninstalling Python using the control panel, manually deleting the files myself, and I've removed Python from the PATH each time.


问:
Python3 Matplotlib to Show Solid of Revolution from Method of Disks, Method of Shells, and Method of Washers around x-axis and y-axis
I have created this topic before: How to Add another subplot to show Solid of Revolution toward x-axis?

I want to plot the solid from a curve 3 + 2x - x^2 that is revolved about:

a. the x-axis

b. the y-axis

c. the line y = -1

d. the line x = 4

this is my MWE (the problem is to find the inverse of 3 + 2x - x^2 is not something easy thus I have no idea how to make this code works):

```<code># Compare the plot at xy axis with the solid of revolution toward x and y axis
# For function x=(y)^(3/2)
import matplotlib.pyplot as plt
import numpy as np

n = 100

fig = plt.figure(figsize=(14, 7))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222, projection='3d')
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224, projection='3d')
y = np.linspace(0, 9, n)
x = (y) ** (3 / 2)
t = np.linspace(0, np.pi * 2, n)

xn = np.outer(x, np.cos(t))
yn = np.outer(x, np.sin(t))
zn = np.zeros_like(xn)
for i in range(len(x)):
    zn[i:i + 1, :] = np.full_like(zn[0, :], y[i])

ax1.plot(x, y)
ax1.set_title("$f(x)$")
ax2.plot_surface(xn, yn, zn)
ax2.set_title("$f(x)$: Revolution around $y$")

# find the inverse of the function
x_inverse = y
y_inverse = np.power(x_inverse, 3 / 2)
xn_inverse = np.outer(x_inverse, np.cos(t))
yn_inverse = np.outer(x_inverse, np.sin(t))
zn_inverse = np.zeros_like(xn_inverse)
for i in range(len(x_inverse)):
    zn_inverse[i:i + 1, :] = np.full_like(zn_inverse[0, :], y_inverse[i])

ax3.plot(x_inverse, y_inverse)
ax3.set_title("Inverse of $f(x)$")
ax4.plot_surface(xn_inverse, yn_inverse, zn_inverse)
ax4.set_title("$f(x)$: Revolution around $x$")

plt.tight_layout()
plt.show()
</code>```

Body:
I have created this topic before: How to Add another subplot to show Solid of Revolution toward x-axis?

I want to plot the solid from a curve 3 + 2x - x^2 that is revolved about:

a. the x-axis

b. the y-axis

c. the line y = -1

d. the line x = 4

this is my MWE (the problem is to find the inverse of 3 + 2x - x^2 is not something easy thus I have no idea how to make this code works):

# Compare the plot at xy axis with the solid of revolution toward x and y axis
# For function x=(y)^(3/2)
import matplotlib.pyplot as plt
import numpy as np

n = 100

fig = plt.figure(figsize=(14, 7))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222, projection='3d')
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224, projection='3d')
y = np.linspace(0, 9, n)
x = (y) ** (3 / 2)
t = np.linspace(0, np.pi * 2, n)

xn = np.outer(x, np.cos(t))
yn = np.outer(x, np.sin(t))
zn = np.zeros_like(xn)
for i in range(len(x)):
    zn[i:i + 1, :] = np.full_like(zn[0, :], y[i])

ax1.plot(x, y)
ax1.set_title("$f(x)$")
ax2.plot_surface(xn, yn, zn)
ax2.set_title("$f(x)$: Revolution around $y$")

# find the inverse of the function
x_inverse = y
y_inverse = np.power(x_inverse, 3 / 2)
xn_inverse = np.outer(x_inverse, np.cos(t))
yn_inverse = np.outer(x_inverse, np.sin(t))
zn_inverse = np.zeros_like(xn_inverse)
for i in range(len(x_inverse)):
    zn_inverse[i:i + 1, :] = np.full_like(zn_inverse[0, :], y_inverse[i])

ax3.plot(x_inverse, y_inverse)
ax3.set_title("Inverse of $f(x)$")
ax4.plot_surface(xn_inverse, yn_inverse, zn_inverse)
ax4.set_title("$f(x)$: Revolution around $x$")

plt.tight_layout()
plt.show()


问:
can't click on element on web page
I'm trying to use selenium to auto login twitter. But when it comes to decoding the captcha, I can't click the 'Authenticate' button (https://imgur.com/a/vPsBy4b). I have tried using element search methods like Class name, CSS Selector, Xpath but still not working.
Can someone help me?

Here's some code I used in trying to click that button

```<code>driver.find_element(By.XPATH, "/html/body/div/div/div[1]/button").click()

driver.find_element(By.CSS_SELECTOR, "#root > div > div.sc-99cwso-0.sc-11w6f91-0.fcBZbp.eWRcSj.home.box.screen > button").click()
</code>```

Title: can't click on element on web page

Body:
I'm trying to use selenium to auto login twitter. But when it comes to decoding the captcha, I can't click the 'Authenticate' button (https://imgur.com/a/vPsBy4b). I have tried using element search methods like Class name, CSS Selector, Xpath but still not working.
Can someone help me?

Here's some code I used in trying to click that button

driver.find_element(By.XPATH, "/html/body/div/div/div[1]/button").click()

driver.find_element(By.CSS_SELECTOR, "#root > div > div.sc-99cwso-0.sc-11w6f91-0.fcBZbp.eWRcSj.home.box.screen > button").click()


问:
How to fix videos not displaying on deployment using AWS
In localhost these videos work as expected using OnMouseHover and OnMouseOut, however when I deploy the site, the videos don't show up and I get an error saying : "Uncaught (in promise) DOMException: The element has no supported sources." The videos are uploaded to my github but I suspect that isn't the issue. Can anyone guide me as to how to fix this?

Here's my code:

```<code>interface ICanvasProps {
canvas: {
name: string;
src: any;
}
}

export function Canvas(props: ICanvasProps) {

const { canvas } = props

return (

        {
      canvas.map((canva) => {

              return (
        <div key={canva.name} className='card'>

         <video
                    preload={'auto'}
                    autoPlay
                    loop
                    onLoad={()=>{"I am loaded"}}
                    //@ts-ignore
                    onMouseOver = { (event) => event.target.play() }
                    //@ts-ignore
                    onMouseOut = { (event) => event.target.pause() }
        style={{
                            width: '100%',
                            borderRadius:"10px"
                        }}
            src={canva.src}></video>
         </div>
            )
        })
        }

    </div>
)

}
</code>```

I tried looking for issues using event.target and suspect it could be because the browser cannot load the videos before displaying them but I am unsure how to load the videos since I'm mapping through an array of sources. `

Body:
In localhost these videos work as expected using OnMouseHover and OnMouseOut, however when I deploy the site, the videos don't show up and I get an error saying : "Uncaught (in promise) DOMException: The element has no supported sources." The videos are uploaded to my github but I suspect that isn't the issue. Can anyone guide me as to how to fix this?

Here's my code:

interface ICanvasProps {
canvas: {
name: string;
src: any;
}
}

export function Canvas(props: ICanvasProps) {

const { canvas } = props

return (

        {
      canvas.map((canva) => {

              return (

         <video
                    preload={'auto'}
                    autoPlay
                    loop
                    onLoad={()=>{"I am loaded"}}
                    //@ts-ignore
                    onMouseOver = { (event) => event.target.play() }
                    //@ts-ignore
                    onMouseOut = { (event) => event.target.pause() }
        style={{
                            width: '100%',
                            borderRadius:"10px"
                        }}
            src={canva.src}></video>

            )
        })
        }

)

}

I tried looking for issues using event.target and suspect it could be because the browser cannot load the videos before displaying them but I am unsure how to load the videos since I'm mapping through an array of sources. `


问:
Creating new shopify article with the same content gives errors
Following is my code and struct for creating shopify articles. I never had a issue with them until recently where some of the pages get created and others send a 422 Unprocessable Entity response. can someone help me sorting this out as i dont see an issue here..!

```<code>pageArticle := &ArticleRequest{
                Article: Article{
                    Title:       FinalTitle,
                    Author:      "Hit Parader",
                    Tags:        Tags,
                    BodyHTML:    html,
                    PublishedAt: time.Now().UTC().Format("2006-01-02T15:04:05-0700"),
                    Image: ArticleImage{
                        Src: pageSRC,
                        Alt: title,
                    },
                    Metafields: []ArticleMeta{
                        {
                            Key:       "feature_image_page_number",
                            Value:     page,
                            Type:      "number_integer",
                            Namespace: "custom",
                        },
                    },
                },
            }

        spew.Dump(pageArticle)
        articleJSON2, err := json.Marshal(pageArticle)
        if err != nil {
            fmt.Println(err)
        }
        articleReq2, err := http.NewRequest("POST", newArticleQueryFinal, bytes.NewBuffer(articleJSON2))
        if err != nil {
            fmt.Println(err)
        }
        articleReq2.Header.Add("X-Shopify-Access-Token", token)
        articleReq2.Header.Add("Content-Type", "application/json")

        resp3, err := client.Do(articleReq2)
        if err != nil {
            fmt.Println(err)
        }
</code>```

Struct

```<code>type ArticleRequest struct {
    Article Article `json:"article"`
}
type Article struct {
    Title       string        `json:"title"`
    Author      string        `json:"author"`
    Tags        string        `json:"tags"`
    BodyHTML    string        `json:"body_html"`
    PublishedAt string        `json:"published_at"`
    Image       ArticleImage  `json:"image"`
    Metafields  []ArticleMeta `json:"metafields"`
}
type ArticleImage struct {
    Src string `json:"src,omitempty"`
    Alt string `json:"alt,omitempty"`
}
type ArticleMeta struct {
    Key       string `json:"key"`
    Value     int    `json:"value"`
    Type      string `json:"type"`
    Namespace string `json:"namespace"`
}
</code>```

same kind of content gives 2 response types. Im at a loss here.

Any help would be appreciated..!!!

Body:
Following is my code and struct for creating shopify articles. I never had a issue with them until recently where some of the pages get created and others send a 422 Unprocessable Entity response. can someone help me sorting this out as i dont see an issue here..!

pageArticle := &ArticleRequest{
                Article: Article{
                    Title:       FinalTitle,
                    Author:      "Hit Parader",
                    Tags:        Tags,
                    BodyHTML:    html,
                    PublishedAt: time.Now().UTC().Format("2006-01-02T15:04:05-0700"),
                    Image: ArticleImage{
                        Src: pageSRC,
                        Alt: title,
                    },
                    Metafields: []ArticleMeta{
                        {
                            Key:       "feature_image_page_number",
                            Value:     page,
                            Type:      "number_integer",
                            Namespace: "custom",
                        },
                    },
                },
            }

        spew.Dump(pageArticle)
        articleJSON2, err := json.Marshal(pageArticle)
        if err != nil {
            fmt.Println(err)
        }
        articleReq2, err := http.NewRequest("POST", newArticleQueryFinal, bytes.NewBuffer(articleJSON2))
        if err != nil {
            fmt.Println(err)
        }
        articleReq2.Header.Add("X-Shopify-Access-Token", token)
        articleReq2.Header.Add("Content-Type", "application/json")

        resp3, err := client.Do(articleReq2)
        if err != nil {
            fmt.Println(err)
        }

Struct

type ArticleRequest struct {
    Article Article `json:"article"`
}
type Article struct {
    Title       string        `json:"title"`
    Author      string        `json:"author"`
    Tags        string        `json:"tags"`
    BodyHTML    string        `json:"body_html"`
    PublishedAt string        `json:"published_at"`
    Image       ArticleImage  `json:"image"`
    Metafields  []ArticleMeta `json:"metafields"`
}
type ArticleImage struct {
    Src string `json:"src,omitempty"`
    Alt string `json:"alt,omitempty"`
}
type ArticleMeta struct {
    Key       string `json:"key"`
    Value     int    `json:"value"`
    Type      string `json:"type"`
    Namespace string `json:"namespace"`
}

same kind of content gives 2 response types. Im at a loss here.

Any help would be appreciated..!!!


问:
Deploy React Native Expo for Android: error Execution failed for task ':app:bundleReleaseJsAndAssets'
Trying to deploy my react native project, got as far as putting eas build --platform android in the terminal and got this error

```<code>[stderr] FAILURE: Build completed with 2 failures.
[stderr] 1: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] Execution failed for task ':app:bundleReleaseJsAndAssets'.
[stderr] > Process 'command 'node'' finished with non-zero exit value 1
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] 2: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] java.lang.StackOverflowError (no error message)
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.

</code>```

I tried killing the terminal and trying again, making sure android studio is closed, and having been searching the web but to no avail. Thanks in advance!

Body:
Trying to deploy my react native project, got as far as putting eas build --platform android in the terminal and got this error

[stderr] FAILURE: Build completed with 2 failures.
[stderr] 1: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] Execution failed for task ':app:bundleReleaseJsAndAssets'.
[stderr] > Process 'command 'node'' finished with non-zero exit value 1
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] 2: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] java.lang.StackOverflowError (no error message)
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.

I tried killing the terminal and trying again, making sure android studio is closed, and having been searching the web but to no avail. Thanks in advance!


问:
How to make a split window into 4 parts in flet?
I want to make split window into 4 parts in flet,similar to R GUI. Where Each part can run different codes altogether or showing graph etc.

Below is reference:
How do I make a split window?

I want to do the same thing in flet.

I have tried to sepearate 4 parts by columns and stacking it,but not able to do.please help


问:
Disable swipe navigation on Android Webview through CapacitorJS?
I've build an Android app using CapacitorJS and I want to disable the native webview's swipe navigation (swipe from edges to go forward/back). Is that possible?

Can this be done through Javascript or an HTML meta tag? As far as I can tell this is not possible.

Is there a Capacitor plugin or setting to do this? (Ionic, which uses Capacitor, has the swipeBackEnabled setting that sounds like it does what I'm looking for)

If not, can it be set on the Android WebView directly?


问:
Microphone based-input CLASH, using microphone to jump, whilst also using microphone to record and play-back audio
The first script (JumpFromMicrophone) I have created is a script where based on my MICROPHONE audio input, the game object (player) moves up on the Y axis. The game object also automatically moves forward using speed on the Z axis.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class JumpFromMicrophone : MonoBehaviour
{
    public AudioSource source;
    public AudioLoudnessDetection detector;
    public Vector3 minPosition;
    public Vector3 maxPosition;
    public float speed = 2;

    public float loudnessSensibility = 100;
    public float threshold = 0.1f;

    // The duration of the smooth transition
    public float smoothTime = 0.1f;
    private Vector3 velocity = Vector3.zero;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float loudness = detector.GetLoudnessFromMicrophone() * loudnessSensibility;

        if (loudness < threshold)
            loudness = 0;
        else
            loudness = (loudness - threshold) / (1 - threshold);

        // Calculate the target position, keeping the current X and Z values
        Vector3 targetPosition = Vector3.Lerp(minPosition, maxPosition, loudness);
        targetPosition.x = transform.localPosition.x;
        targetPosition.z = transform.localPosition.z;

        // Smoothly move the object towards the target position
        transform.localPosition = Vector3.SmoothDamp(transform.localPosition, targetPosition, ref velocity, smoothTime);

        transform.Translate(Vector3.forward * speed * Time.deltaTime);

    }

    // reloads the scene if obstacle hits player
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Obstacle")
        {
            SceneManager.LoadScene("Game");
        }
    }

}

</code>```

The second script (RNP) created records this audio picked up by the MICROPHONE and then plays it back to the player using a recording from a generated AudioSource. This is done using MaxRecordingTime, which I am fine using as I am going to relate it to timed game audio once this issue has been resolved.

```<code>public class RNP : MonoBehaviour
{
    // The AudioClip that will be recorded
    public AudioClip recordedClip;

    // The maximum recording time in seconds
    public int maxRecordingTime = 10;

    void Start()
    {

        // Start the recording and playback coroutine
        StartCoroutine(RecordAndPlayback());
    }

    IEnumerator RecordAndPlayback()
    {
        // Start recording from the default microphone
        recordedClip = Microphone.Start(null, true, maxRecordingTime, 44100);

        // Wait for the specified number of seconds
        yield return new WaitForSeconds(maxRecordingTime);

        // Stop the recording
        Microphone.End(null);

        // Create an AudioSource to play the recorded audio
        AudioSource audioSource = gameObject.AddComponent<AudioSource>();
        audioSource.clip = recordedClip;
        audioSource.loop = false;
        audioSource.Play();

        // Wait for the audio to finish playing
        yield return new WaitWhile(() => audioSource.isPlaying);

        // Destroy the AudioSource
        Destroy(audioSource);
    }
}
</code>```

However, the second script seems to clash with the first and implementing the second script does not allow for some aspects of the first script to work, I am beginning to think it might be something to do with the use of the Microphone for both scripts clashing, but I have no idea how to solve this issue so that both work together without disabling one another.

The JumpOnMicrophone script does not allow the player to move up the Y axis when the RNP script is added as a compenent onto the game object (player), but the player still moves along the Z axis.

Some fixes I have attemped that did not work:

Placing the 2nd script on another GameObject rather than the player

Combining both scripts

If anyone could help me figure this out, it would be greatly appreciated.

*** EDIT ***

AudioLoudnessDetection script

```<code>public class AudioLoudnessDetection : MonoBehaviour
{
    public int sampleWindow = 64;
    private AudioClip microphoneClip;

    // Start is called before the first frame update
    void Start()
    {
        MicrophoneToAudioClip();
    }

    // Update is called once per frame
    void FixedUpdate()
    {

    }

    public void MicrophoneToAudioClip()
    {
        string microphoneName = Microphone.devices[0];
        microphoneClip = Microphone.Start(microphoneName, true, 20, AudioSettings.outputSampleRate);
    }

    public float GetLoudnessFromMicrophone()
    {
        return GetLoudnessFromAudioClip(Microphone.GetPosition(Microphone.devices[0]), microphoneClip);
    }

    public float GetLoudnessFromAudioClip(int clipPosition,AudioClip clip)
    {
        int startPosition = clipPosition - sampleWindow;

        if (startPosition < 0)
            return 0;

        float[] waveData = new float[sampleWindow];
        clip.GetData(waveData, startPosition);

        // compute loudness
        float totalLoudness = 0;

        for (int i = 0; i < sampleWindow; i++)
        {
            totalLoudness += Mathf.Abs(waveData[i]);
        }

        return totalLoudness/ sampleWindow;
    }
}
</code>```

Body:
The first script (JumpFromMicrophone) I have created is a script where based on my MICROPHONE audio input, the game object (player) moves up on the Y axis. The game object also automatically moves forward using speed on the Z axis.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class JumpFromMicrophone : MonoBehaviour
{
    public AudioSource source;
    public AudioLoudnessDetection detector;
    public Vector3 minPosition;
    public Vector3 maxPosition;
    public float speed = 2;

    public float loudnessSensibility = 100;
    public float threshold = 0.1f;

    // The duration of the smooth transition
    public float smoothTime = 0.1f;
    private Vector3 velocity = Vector3.zero;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float loudness = detector.GetLoudnessFromMicrophone() * loudnessSensibility;

        if (loudness < threshold)
            loudness = 0;
        else
            loudness = (loudness - threshold) / (1 - threshold);

        // Calculate the target position, keeping the current X and Z values
        Vector3 targetPosition = Vector3.Lerp(minPosition, maxPosition, loudness);
        targetPosition.x = transform.localPosition.x;
        targetPosition.z = transform.localPosition.z;

        // Smoothly move the object towards the target position
        transform.localPosition = Vector3.SmoothDamp(transform.localPosition, targetPosition, ref velocity, smoothTime);

        transform.Translate(Vector3.forward * speed * Time.deltaTime);

    }

    // reloads the scene if obstacle hits player
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Obstacle")
        {
            SceneManager.LoadScene("Game");
        }
    }

}

The second script (RNP) created records this audio picked up by the MICROPHONE and then plays it back to the player using a recording from a generated AudioSource. This is done using MaxRecordingTime, which I am fine using as I am going to relate it to timed game audio once this issue has been resolved.

public class RNP : MonoBehaviour
{
    // The AudioClip that will be recorded
    public AudioClip recordedClip;

    // The maximum recording time in seconds
    public int maxRecordingTime = 10;

    void Start()
    {

        // Start the recording and playback coroutine
        StartCoroutine(RecordAndPlayback());
    }

    IEnumerator RecordAndPlayback()
    {
        // Start recording from the default microphone
        recordedClip = Microphone.Start(null, true, maxRecordingTime, 44100);

        // Wait for the specified number of seconds
        yield return new WaitForSeconds(maxRecordingTime);

        // Stop the recording
        Microphone.End(null);

        // Create an AudioSource to play the recorded audio
        AudioSource audioSource = gameObject.AddComponent<AudioSource>();
        audioSource.clip = recordedClip;
        audioSource.loop = false;
        audioSource.Play();

        // Wait for the audio to finish playing
        yield return new WaitWhile(() => audioSource.isPlaying);

        // Destroy the AudioSource
        Destroy(audioSource);
    }
}

However, the second script seems to clash with the first and implementing the second script does not allow for some aspects of the first script to work, I am beginning to think it might be something to do with the use of the Microphone for both scripts clashing, but I have no idea how to solve this issue so that both work together without disabling one another.

The JumpOnMicrophone script does not allow the player to move up the Y axis when the RNP script is added as a compenent onto the game object (player), but the player still moves along the Z axis.

Some fixes I have attemped that did not work:

Placing the 2nd script on another GameObject rather than the player

Combining both scripts

If anyone could help me figure this out, it would be greatly appreciated.

*** EDIT ***

AudioLoudnessDetection script

public class AudioLoudnessDetection : MonoBehaviour
{
    public int sampleWindow = 64;
    private AudioClip microphoneClip;

    // Start is called before the first frame update
    void Start()
    {
        MicrophoneToAudioClip();
    }

    // Update is called once per frame
    void FixedUpdate()
    {

    }

    public void MicrophoneToAudioClip()
    {
        string microphoneName = Microphone.devices[0];
        microphoneClip = Microphone.Start(microphoneName, true, 20, AudioSettings.outputSampleRate);
    }

    public float GetLoudnessFromMicrophone()
    {
        return GetLoudnessFromAudioClip(Microphone.GetPosition(Microphone.devices[0]), microphoneClip);
    }

    public float GetLoudnessFromAudioClip(int clipPosition,AudioClip clip)
    {
        int startPosition = clipPosition - sampleWindow;

        if (startPosition < 0)
            return 0;

        float[] waveData = new float[sampleWindow];
        clip.GetData(waveData, startPosition);

        // compute loudness
        float totalLoudness = 0;

        for (int i = 0; i < sampleWindow; i++)
        {
            totalLoudness += Mathf.Abs(waveData[i]);
        }

        return totalLoudness/ sampleWindow;
    }
}


问:
Perform Instance Segmentation Using Mask R-CNN
i just following 'Perform Instance Segmentation Using Mask R-CNN' example
URL : "https://kr.mathworks.com/help/vision/ug/example-InstanceSegmentationUsingMaskRCNNDeepLearningExample.html"
I have download the file(instances_train2014.json, cocoapi-master,  unpackAnnotations.m(was in helper file) )
but i don't know how to compling gason.

enter image description here

so i get a error, matlab can not read coco annotation file
enter image description here

i just copy the example code and change the file path

```<code>matlab 2022b
%download traindata
imageFolder = fullfile(dataFolder,"images");
captionsFolder = fullfile(dataFolder,"annotations");
if ~exist(imageFolder,"dir")
    mkdir(imageFolder)
    mkdir(captionsFolder)
end
annotationFile = fullfile(captionsFolder,"instances_train2014.json");
str = fileread(annotationFile);
%read and process training data
trainClassNames = ["person","car"];
numClasses = length(trainClassNames);
imageSizeTrain = [800 800 3];
cocoAPIDir = fullfile(dataFolder,"cocoapi-master","MatlabAPI");
addpath(cocoAPIDir);
unpackAnnotationDir = fullfile(dataFolder,"annotations_unpacked","matFiles");
if ~exist(unpackAnnotationDir,'dir')
    mkdir(unpackAnnotationDir)
end
helper.unpackAnnotations(trainClassNames,annotationFile,imageFolder,unpackAnnotationDir);
%create data
</code>```

i want to train coco dataset but i don't know c++ compling
what is the gason complie..?
how can i get complied annodation data with gason..?

Body:
i just following 'Perform Instance Segmentation Using Mask R-CNN' example
URL : "https://kr.mathworks.com/help/vision/ug/example-InstanceSegmentationUsingMaskRCNNDeepLearningExample.html"
I have download the file(instances_train2014.json, cocoapi-master,  unpackAnnotations.m(was in helper file) )
but i don't know how to compling gason.

enter image description here

so i get a error, matlab can not read coco annotation file
enter image description here

i just copy the example code and change the file path

matlab 2022b
%download traindata
imageFolder = fullfile(dataFolder,"images");
captionsFolder = fullfile(dataFolder,"annotations");
if ~exist(imageFolder,"dir")
    mkdir(imageFolder)
    mkdir(captionsFolder)
end
annotationFile = fullfile(captionsFolder,"instances_train2014.json");
str = fileread(annotationFile);
%read and process training data
trainClassNames = ["person","car"];
numClasses = length(trainClassNames);
imageSizeTrain = [800 800 3];
cocoAPIDir = fullfile(dataFolder,"cocoapi-master","MatlabAPI");
addpath(cocoAPIDir);
unpackAnnotationDir = fullfile(dataFolder,"annotations_unpacked","matFiles");
if ~exist(unpackAnnotationDir,'dir')
    mkdir(unpackAnnotationDir)
end
helper.unpackAnnotations(trainClassNames,annotationFile,imageFolder,unpackAnnotationDir);
%create data

i want to train coco dataset but i don't know c++ compling
what is the gason complie..?
how can i get complied annodation data with gason..?


问:
How do I make a search API call in flutter
I have been using the infinite_scroll_pagination package to make API calls from a backend with pagination. However, I have reached a point where I have to implement searching with the same pagination backend but it's giving me some unusual data.

This is my search bar where I type in my search param

```<code>SearchBar(
                readOnly: false,
                onChanged: (val) {
                  if (val.trim() == '') {
                    setState(() {
                      startSearch = false;
                    });
                  } else if (val.length >= 3) {
                    if (!startSearch) {
                      setState(() {
                        startSearch = true;
                      });
                    }
                    _pagingController.refresh();

                    _pagingController.addPageRequestListener(
                      (pageKey) {
                        _fetchPage(pageKey, val.trim());
                      },
                    );
                  }
                },
              ),
            ),
</code>```

Below is also my repository where I convert the data i am recieving from the backend to my data models

```<code>import 'dart:developer';

import 'package:aspire/data/data_providers/high_school.dart';
import 'package:aspire/data/models/high_school_model/high_school.dart';

class HighSchoolRepo {
  Future<Map<String, dynamic>> get({
    required int page,
    required String token,
    required String category,
    required bool isSearching,
    String? searchParam,
  }) async {
    print(searchParam); // Whenever I type something, it prints all the previous typed keys and also includes the recent one typed. meaning it's kind of making many requests
    List<HighSchool> highSchoolsList = [];
    try {
      final result = await HighSchoolProvider.getSchools(
        isSearching: isSearching,
        searchParam: searchParam,
        page: page,
        category: category,
        token: token,
      );
      highSchoolsList.clear();
      for (var value in result['data']['schools']) {
        highSchoolsList.add(
          HighSchool.fromJson(value),
        );
      }
      return {
        'hasNextPage': result['data']['hasNextPage'],
        'schools': highSchoolsList,
      };
    } catch (err) {
      rethrow;
    }
  }
}

</code>```

Although it works upon searching university in my postman, it returns 3 but mine is returning a lot of data relating and not relating to what I searched

Body:
I have been using the infinite_scroll_pagination package to make API calls from a backend with pagination. However, I have reached a point where I have to implement searching with the same pagination backend but it's giving me some unusual data.

This is my search bar where I type in my search param

SearchBar(
                readOnly: false,
                onChanged: (val) {
                  if (val.trim() == '') {
                    setState(() {
                      startSearch = false;
                    });
                  } else if (val.length >= 3) {
                    if (!startSearch) {
                      setState(() {
                        startSearch = true;
                      });
                    }
                    _pagingController.refresh();

                    _pagingController.addPageRequestListener(
                      (pageKey) {
                        _fetchPage(pageKey, val.trim());
                      },
                    );
                  }
                },
              ),
            ),

Below is also my repository where I convert the data i am recieving from the backend to my data models

import 'dart:developer';

import 'package:aspire/data/data_providers/high_school.dart';
import 'package:aspire/data/models/high_school_model/high_school.dart';

class HighSchoolRepo {
  Future<Map<String, dynamic>> get({
    required int page,
    required String token,
    required String category,
    required bool isSearching,
    String? searchParam,
  }) async {
    print(searchParam); // Whenever I type something, it prints all the previous typed keys and also includes the recent one typed. meaning it's kind of making many requests
    List<HighSchool> highSchoolsList = [];
    try {
      final result = await HighSchoolProvider.getSchools(
        isSearching: isSearching,
        searchParam: searchParam,
        page: page,
        category: category,
        token: token,
      );
      highSchoolsList.clear();
      for (var value in result['data']['schools']) {
        highSchoolsList.add(
          HighSchool.fromJson(value),
        );
      }
      return {
        'hasNextPage': result['data']['hasNextPage'],
        'schools': highSchoolsList,
      };
    } catch (err) {
      rethrow;
    }
  }
}

Although it works upon searching university in my postman, it returns 3 but mine is returning a lot of data relating and not relating to what I searched


问:
xarray.dataset.where() does not seem to work for extreme values
I have an hourly rainfall data want to find values corresponding to an hourly extreme rainfall.

I tried to use where() function but does not seem to give me what i want.

```<code>ds = xr.open_dataset('./precip.nc')

precip = ds['cp']

rainfall=precip.where(ds.cp> 10, drop=True)
</code>```

Body:
I have an hourly rainfall data want to find values corresponding to an hourly extreme rainfall.

I tried to use where() function but does not seem to give me what i want.

ds = xr.open_dataset('./precip.nc')

precip = ds['cp']

rainfall=precip.where(ds.cp> 10, drop=True)


问:
React Native TV, Unwanted Focusing on Text element
For a react native tv application using react-native-template-typescript-tv / react-native-tvos

The first focus is on Text and on press down it is focusing on the TouchableHighlight
How do I prevent the focus on a Text element?

I tried adding the prop focusable={false} and fiddled with the hasTVPreferredFocus

```<code><View>
  <Text>Title</Text>
  <TouchableHighlight>Click Me</TouchableHighlight>
</View>
</code>```

Body:
For a react native tv application using react-native-template-typescript-tv / react-native-tvos

The first focus is on Text and on press down it is focusing on the TouchableHighlight
How do I prevent the focus on a Text element?

I tried adding the prop focusable={false} and fiddled with the hasTVPreferredFocus

<View>
  <Text>Title</Text>
  <TouchableHighlight>Click Me</TouchableHighlight>
</View>


问:
Why does it show firebase data as null at the first time? (React)
This part of the code is connected to onSubmit of the project
It works and fetches the data for logging from Firebase
But the problem is here, as soon as you log in for the first time, it shows null states, and when you click the second time, it fetches the data from the server.
Does anyone know what the problem is? Thank you.</p>
```<code>const onSubmit = (event) => {
    event.preventDefault();
    if (handleValidation()) {
      AXIOS.get("/MEMBERS/EMAILS.json")
        .then((response) => {
          for (const item in response.data) {
            if (Username === response.data[item]) {
              setIsLoggedIn(true);
              break;
            }
          }
        })
        .catch((error) => {
          alert(error);
        });
      AXIOS.get("/MEMBERS/PASSS.json")
        .then((response) => {})
        .catch((error) => {
          alert(error);
        });
    }
  };
</code>```

Body:
This part of the code is connected to onSubmit of the project
It works and fetches the data for logging from Firebase
But the problem is here, as soon as you log in for the first time, it shows null states, and when you click the second time, it fetches the data from the server.
Does anyone know what the problem is? Thank you.

const onSubmit = (event) => {
    event.preventDefault();
    if (handleValidation()) {
      AXIOS.get("/MEMBERS/EMAILS.json")
        .then((response) => {
          for (const item in response.data) {
            if (Username === response.data[item]) {
              setIsLoggedIn(true);
              break;
            }
          }
        })
        .catch((error) => {
          alert(error);
        });
      AXIOS.get("/MEMBERS/PASSS.json")
        .then((response) => {})
        .catch((error) => {
          alert(error);
        });
    }
  };


问:
How to print text after the input prompt while input is still happening?
I am trying to get things to print after the input area in python so that I can get something like this:

-----------------------------------
 > (this is where this input is)
-----------------------------------
```
<p>This is my original snippet:</p>
```input("-----------------------------------\n > "); print("-----------------------------------")
```

I am asking if there is a way to get things to print before the user hits enter while input() is getting input.

Body:
I am trying to get things to print after the input area in python so that I can get something like this:

-----------------------------------
 > (this is where this input is)
-----------------------------------

This is my original snippet:

input("-----------------------------------\n > "); print("-----------------------------------")

I am asking if there is a way to get things to print before the user hits enter while input() is getting input.


问:
Listen for value changes in an object property, slice and subscribe to the changed value
I use the Async local-storage with angular to store data in the indexedDB.
The library has a method to listen to / watch for changes.

This method returns an Observable with the complete object.

What I want is to slice the changed property value, object, or the array of the object and subscribe to it.

My example object would be:

```<code>{
    fetched: boolean,
    loaded: boolean,
    item: null, // object
    list: [],   // object arry
}
</code>```

Now I need to watch for the changes in each property as an Observable.

```<code>fetched$.subscribe((fetched: boolean)) => {}
loaded$.subscribe((loaded: boolean)) => {}
item$.subscribe((item: any)) => {}
list$.subscribe((list: any[])) => {}
</code>```

Here is the code I used to slice the changed value so far.

```<code>// slice an individual value
function sliceValue<T>(
  repo: BaseRepository<T>,
  key: string
): Observable<any> {
  if (!repo.key || !repo.store.has(repo.key)) {
     return of (null);
  }

  return repo.store.watch(repo.key).pipe(
    distinctUntilChanged((prev, curr) => {
      if (!prev || !curr) return false;
      return prev[KEY.D][key] === curr[KEY.D][key];
    }),
    switchMap((ctx: any) => repo.store.get(repo.key)),
    map((ctx: any) => ctx[KEY.D][key]));
}

// State class
export class TestState extends BaseRepository<TestModel> {

  public fetched$: Observable<boolean> = sliceValue(this, 'fetched');
  public loaded$: Observable<boolean> = sliceValue(this, 'loaded');
  public item$: Observable<any> = sliceObject(this, 'item');
  public list$: Observable<any[]> = sliceList(this, 'list');

  constructor(
    public readonly store: StorageMap,
  ) {
    super(store);
  }

}
</code>```

But I do not know the efficient way to do it.

If there is any other best way to do it, I would like to know and try it out.

Thank you very much.

Body:
I use the Async local-storage with angular to store data in the indexedDB.
The library has a method to listen to / watch for changes.

This method returns an Observable with the complete object.

What I want is to slice the changed property value, object, or the array of the object and subscribe to it.

My example object would be:

{
    fetched: boolean,
    loaded: boolean,
    item: null, // object
    list: [],   // object arry
}

Now I need to watch for the changes in each property as an Observable.

fetched$.subscribe((fetched: boolean)) => {}
loaded$.subscribe((loaded: boolean)) => {}
item$.subscribe((item: any)) => {}
list$.subscribe((list: any[])) => {}

Here is the code I used to slice the changed value so far.

// slice an individual value
function sliceValue<T>(
  repo: BaseRepository<T>,
  key: string
): Observable<any> {
  if (!repo.key || !repo.store.has(repo.key)) {
     return of (null);
  }

  return repo.store.watch(repo.key).pipe(
    distinctUntilChanged((prev, curr) => {
      if (!prev || !curr) return false;
      return prev[KEY.D][key] === curr[KEY.D][key];
    }),
    switchMap((ctx: any) => repo.store.get(repo.key)),
    map((ctx: any) => ctx[KEY.D][key]));
}

// State class
export class TestState extends BaseRepository<TestModel> {

  public fetched$: Observable<boolean> = sliceValue(this, 'fetched');
  public loaded$: Observable<boolean> = sliceValue(this, 'loaded');
  public item$: Observable<any> = sliceObject(this, 'item');
  public list$: Observable<any[]> = sliceList(this, 'list');

  constructor(
    public readonly store: StorageMap,
  ) {
    super(store);
  }

}

But I do not know the efficient way to do it.

If there is any other best way to do it, I would like to know and try it out.

Thank you very much.


问:
Entity Framework Core not making nullable int? (foreign key) as nullable column until I explicitly mark the referring object as nullable
I am using EF Core and I am facing a strange issue which never occurred before. I am using PostgreSQL provider.

The issue is I am creating a foreign key column as nullable like this

```<code>[ForeignKey(nameof(TeamLead))]
public int? TeamLeadId { get; set; }

public User TeamLead { get; set; }
</code>```

but the in the generated query it is used as not nullable.

After trying many solutions, when I make User explicitly nullable, it works. But it's strange because objects are by default nullable.

Like this:

```<code>[ForeignKey(nameof(TeamLead))]
public int? TeamLeadId { get; set; }

public User? TeamLead { get; set; }
</code>```

What could be the issue - any suggestions?

Body:
I am using EF Core and I am facing a strange issue which never occurred before. I am using PostgreSQL provider.

The issue is I am creating a foreign key column as nullable like this

[ForeignKey(nameof(TeamLead))]
public int? TeamLeadId { get; set; }

public User TeamLead { get; set; }

but the in the generated query it is used as not nullable.

After trying many solutions, when I make User explicitly nullable, it works. But it's strange because objects are by default nullable.

Like this:

[ForeignKey(nameof(TeamLead))]
public int? TeamLeadId { get; set; }

public User? TeamLead { get; set; }

What could be the issue - any suggestions?


问:
TIFFReadDirectory:Failed to read directory at offset 725954560
while Im executing this code in google colab,
def read_raster(raster_file):
"""
Function
--------
read_raster

```<code>Given a raster file, get the pixel size, pixel location, and pixel value

Parameters
----------
raster_file : string
    Path to the raster file

Returns
-------
x_size : float
    Pixel size
top_left_x_coords : numpy.ndarray  shape: (number of columns,)
    Longitude of the top-left point in each pixel
top_left_y_coords : numpy.ndarray  shape: (number of rows,)
    Latitude of the top-left point in each pixel
centroid_x_coords : numpy.ndarray  shape: (number of columns,)
    Longitude of the centroid in each pixel
centroid_y_coords : numpy.ndarray  shape: (number of rows,)
    Latitude of the centroid in each pixel
bands_data : numpy.ndarray  shape: (number of rows, number of columns, 1)
    Pixel value
"""
raster_dataset = gdal.Open(raster_file, gdal.GA_ReadOnly)
# get project coordination
proj = raster_dataset.GetProjectionRef()
bands_data = []
# Loop through all raster bands
for b in range(1, raster_dataset.RasterCount + 1):
    band = raster_dataset.GetRasterBand(b)
    bands_data.append(band.ReadAsArray())
    no_data_value = band.GetNoDataValue()
bands_data = np.dstack(bands_data)
rows, cols, n_bands = bands_data.shape

# Get the metadata of the raster
geo_transform = raster_dataset.GetGeoTransform()
(upper_left_x, x_size, x_rotation, upper_left_y, y_rotation, y_size) = geo_transform

# Get location of each pixel
x_size = 1.0 / int(round(1 / float(x_size)))
y_size = - x_size
y_index = np.arange(bands_data.shape[0])
x_index = np.arange(bands_data.shape[1])
top_left_x_coords = upper_left_x + x_index * x_size
top_left_y_coords = upper_left_y + y_index * y_size
# Add half of the cell size to get the centroid of the cell
centroid_x_coords = top_left_x_coords + (x_size / 2)
centroid_y_coords = top_left_y_coords + (y_size / 2)

return (x_size, top_left_x_coords, top_left_y_coords, centroid_x_coords, centroid_y_coords, bands_data)
</code>```

Helper function to get the pixel index of the point

def get_cell_idx(lon, lat, top_left_x_coords, top_left_y_coords):
"""
Function
--------
get_cell_idx

```<code>Given a point location and all the pixel locations of the raster file,
get the column and row index of the point in the raster

Parameters
----------
lon : float
    Longitude of the point
lat : float
    Latitude of the point
top_left_x_coords : numpy.ndarray  shape: (number of columns,)
    Longitude of the top-left point in each pixel
top_left_y_coords : numpy.ndarray  shape: (number of rows,)
    Latitude of the top-left point in each pixel

Returns
-------
lon_idx : int
    Column index
lat_idx : int
    Row index
"""
lon_idx = np.where(top_left_x_coords < lon)[0][-1]
lat_idx = np.where(top_left_y_coords > lat)[0][-1]
return lon_idx, lat_idx
</code>```

raster_file = '/content/image.tif'
x_size, top_left_x_coords, top_left_y_coords, centroid_x_coords, centroid_y_coords, bands_data = read_raster(raster_file)

save the result in compressed format

np.savez('/content/nightlight.npz', top_left_x_coords=top_left_x_coords, top_left_y_coords=top_left_y_coords, bands_data=bands_data)

I got this error
RuntimeError                              Traceback (most recent call last)
 in
2
3 raster_file = '/content/image.tif'
----> 4 x_size, top_left_x_coords, top_left_y_coords, centroid_x_coords, centroid_y_coords, bands_data = read_raster(raster_file)
5
6 # save the result in compressed format

1 frames
/usr/local/lib/python3.8/dist-packages/osgeo/gdal.py in Open(*args)
3017 def Open(*args):
3018     """Open(char const * utf8_path, GDALAccess eAccess) -> Dataset"""
-> 3019     return _gdal.Open(*args)
3020
3021 def OpenEx(*args, **kwargs):

RuntimeError: TIFFReadDirectory:Failed to read directory at offset 725954560
Can anyone help me out for solving this problem?

Body:
while Im executing this code in google colab,
def read_raster(raster_file):
"""
Function
--------
read_raster

Given a raster file, get the pixel size, pixel location, and pixel value

Parameters
----------
raster_file : string
    Path to the raster file

Returns
-------
x_size : float
    Pixel size
top_left_x_coords : numpy.ndarray  shape: (number of columns,)
    Longitude of the top-left point in each pixel
top_left_y_coords : numpy.ndarray  shape: (number of rows,)
    Latitude of the top-left point in each pixel
centroid_x_coords : numpy.ndarray  shape: (number of columns,)
    Longitude of the centroid in each pixel
centroid_y_coords : numpy.ndarray  shape: (number of rows,)
    Latitude of the centroid in each pixel
bands_data : numpy.ndarray  shape: (number of rows, number of columns, 1)
    Pixel value
"""
raster_dataset = gdal.Open(raster_file, gdal.GA_ReadOnly)
# get project coordination
proj = raster_dataset.GetProjectionRef()
bands_data = []
# Loop through all raster bands
for b in range(1, raster_dataset.RasterCount + 1):
    band = raster_dataset.GetRasterBand(b)
    bands_data.append(band.ReadAsArray())
    no_data_value = band.GetNoDataValue()
bands_data = np.dstack(bands_data)
rows, cols, n_bands = bands_data.shape

# Get the metadata of the raster
geo_transform = raster_dataset.GetGeoTransform()
(upper_left_x, x_size, x_rotation, upper_left_y, y_rotation, y_size) = geo_transform

# Get location of each pixel
x_size = 1.0 / int(round(1 / float(x_size)))
y_size = - x_size
y_index = np.arange(bands_data.shape[0])
x_index = np.arange(bands_data.shape[1])
top_left_x_coords = upper_left_x + x_index * x_size
top_left_y_coords = upper_left_y + y_index * y_size
# Add half of the cell size to get the centroid of the cell
centroid_x_coords = top_left_x_coords + (x_size / 2)
centroid_y_coords = top_left_y_coords + (y_size / 2)

return (x_size, top_left_x_coords, top_left_y_coords, centroid_x_coords, centroid_y_coords, bands_data)

Helper function to get the pixel index of the point

def get_cell_idx(lon, lat, top_left_x_coords, top_left_y_coords):
"""
Function
--------
get_cell_idx

Given a point location and all the pixel locations of the raster file,
get the column and row index of the point in the raster

Parameters
----------
lon : float
    Longitude of the point
lat : float
    Latitude of the point
top_left_x_coords : numpy.ndarray  shape: (number of columns,)
    Longitude of the top-left point in each pixel
top_left_y_coords : numpy.ndarray  shape: (number of rows,)
    Latitude of the top-left point in each pixel

Returns
-------
lon_idx : int
    Column index
lat_idx : int
    Row index
"""
lon_idx = np.where(top_left_x_coords < lon)[0][-1]
lat_idx = np.where(top_left_y_coords > lat)[0][-1]
return lon_idx, lat_idx

raster_file = '/content/image.tif'
x_size, top_left_x_coords, top_left_y_coords, centroid_x_coords, centroid_y_coords, bands_data = read_raster(raster_file)

save the result in compressed format

np.savez('/content/nightlight.npz', top_left_x_coords=top_left_x_coords, top_left_y_coords=top_left_y_coords, bands_data=bands_data)

I got this error
RuntimeError                              Traceback (most recent call last)
 in
2
3 raster_file = '/content/image.tif'
----> 4 x_size, top_left_x_coords, top_left_y_coords, centroid_x_coords, centroid_y_coords, bands_data = read_raster(raster_file)
5
6 # save the result in compressed format

1 frames
/usr/local/lib/python3.8/dist-packages/osgeo/gdal.py in Open(*args)
3017 def Open(*args):
3018     """Open(char const * utf8_path, GDALAccess eAccess) -> Dataset"""
-> 3019     return _gdal.Open(*args)
3020
3021 def OpenEx(*args, **kwargs):

RuntimeError: TIFFReadDirectory:Failed to read directory at offset 725954560
Can anyone help me out for solving this problem?


问:
Github-cli codespace ssh ubuntu@localhost: permission denied (publickey,password)
I wanted to connect to my Codespace through terminal using gh or github-cli. But when I try to connect to my codespace I encounter this error.

[xyz@xyzPC  ~]$ gh cs ssh ? Choose codespace: code50/93048025 (main): ideal disco ubuntu@localhost: Permission denied (publickey,password). shell closed: exit status 255
If anyone would tell me what am I doing worng.

I tried setting the,
sshd_config  PasswordAuthentication No to Yes
Deleting .ssh and reinstalling
Tried in other linux systems.


问:
Error ORA-00936: I dont know how to use a sequence number in this solution
When I run the code below in oracle developer, I get error

ORA-00936: missing expression . CREATE TABLE table_prc4 ( name VARCHAR2(20) );
this code :

```<code>CREATE OR REPLACE PROCEDURE addnewmembe (
    str IN VARCHAR2
) AS
BEGIN
    INSERT INTO table_prc4 VALUES (
        SELECT
            regexp_substr(str, '[^,]+', 1, level) AS parts
        FROM
            dual
        CONNECT BY
            regexp_substr(str, '[^,]+', 1, level) IS NOT NULL
    );
commit;
END ;

BEGIN
    addnewmembe('saeed,amir,hossein');
END;
</code>```

I want to show in the result in the row sequence number and a name of the input string

Body:
When I run the code below in oracle developer, I get error

ORA-00936: missing expression . CREATE TABLE table_prc4 ( name VARCHAR2(20) );
this code :

CREATE OR REPLACE PROCEDURE addnewmembe (
    str IN VARCHAR2
) AS
BEGIN
    INSERT INTO table_prc4 VALUES (
        SELECT
            regexp_substr(str, '[^,]+', 1, level) AS parts
        FROM
            dual
        CONNECT BY
            regexp_substr(str, '[^,]+', 1, level) IS NOT NULL
    );
commit;
END ;

BEGIN
    addnewmembe('saeed,amir,hossein');
END;

I want to show in the result in the row sequence number and a name of the input string