问:
Upgrade SQLite version on Lambda Python3.9
The built-in version of SQLite on the AWS Lambda runtime Python 3.9 is v3.7.17 which was released in 2013. I am unable to upgrade this version with a Layer or Code Deployment because library sources are arranged in such a away where it's not overridable since Python 3.9 is bundled with SQLite (batteries included and all). I believe Lambda finds sqlite.so in /var/runtime/lib

Is there a way to update SQLite in Lambda?

Python dumb of Lambda env vars:

```<code>'LAMBDA_RUNTIME_DIR': '/var/runtime',
'LAMBDA_TASK_ROOT': '/var/task',
'LANG': 'en_US.UTF-8',
'LD_LIBRARY_PATH': '/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib',
'PATH': '/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/bin',
'PWD': '/var/task',
'PYTHONPATH': '/var/runtime',
'SHLVL': '0',
'TZ': ':UTC',
</code>```

And sys.path

```<code>[
'/var/task',
'/opt/python/lib/python3.8/site-packages',
'/opt/python',
'/var/runtime',
'/var/lang/lib/python38.zip',
'/var/lang/lib/python3.8',
'/var/lang/lib/python3.8/lib-dynload',
'/var/lang/lib/python3.8/site-packages',
'/opt/python/lib/python3.8/site-packages',
'/opt/python'
]
</code>```

Proof:

import sqlite3
print("sqlite3:")
sqlite3_version = ".".join(str(x) for x in sqlite3.version_info)
sqlite3_lib_version = ".".join(str(x) for x in sqlite3.sqlite_version_info)
print(f"Version: v{sqlite3_version}")
print(f"SQLite Library Version: v{sqlite3_lib_version}")
```
```sqlite3:
Version: v2.6.0
SQLite Library Version: v3.7.17
```

Body:
The built-in version of SQLite on the AWS Lambda runtime Python 3.9 is v3.7.17 which was released in 2013. I am unable to upgrade this version with a Layer or Code Deployment because library sources are arranged in such a away where it's not overridable since Python 3.9 is bundled with SQLite (batteries included and all). I believe Lambda finds sqlite.so in /var/runtime/lib

Is there a way to update SQLite in Lambda?

Python dumb of Lambda env vars:

'LAMBDA_RUNTIME_DIR': '/var/runtime',
'LAMBDA_TASK_ROOT': '/var/task',
'LANG': 'en_US.UTF-8',
'LD_LIBRARY_PATH': '/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib',
'PATH': '/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/bin',
'PWD': '/var/task',
'PYTHONPATH': '/var/runtime',
'SHLVL': '0',
'TZ': ':UTC',

And sys.path

[
'/var/task',
'/opt/python/lib/python3.8/site-packages',
'/opt/python',
'/var/runtime',
'/var/lang/lib/python38.zip',
'/var/lang/lib/python3.8',
'/var/lang/lib/python3.8/lib-dynload',
'/var/lang/lib/python3.8/site-packages',
'/opt/python/lib/python3.8/site-packages',
'/opt/python'
]

Proof:

import sqlite3
print("sqlite3:")
sqlite3_version = ".".join(str(x) for x in sqlite3.version_info)
sqlite3_lib_version = ".".join(str(x) for x in sqlite3.sqlite_version_info)
print(f"Version: v{sqlite3_version}")
print(f"SQLite Library Version: v{sqlite3_lib_version}")

sqlite3:
Version: v2.6.0
SQLite Library Version: v3.7.17


来源: stackexchange

问:
How do I run two python functions simultaneously and stop others when any one them returns a value?
I want to write two python functions that request data from two different APIs (with similar data). Both the functions should start simultaneously and as soon as one of the functions (say fun1()) returns the result, the other function (say fun2()) is terminated and the rest of the program is carried out with the result obtained from fun1().

For example,

```<code>from datetime import datetime
def fun1(n): #Obtaining data from Source 1
        sums = -1
        if n > -1:
                sums = sum([x*x for x in range(n)])
        return sums

def fun2(n): #Obtaining data from source 2
        sums = -1
        if n > -1:
                sums = (n*(2*n+1)*(n+1))/6
        return int(sums)

if __name__ == '__main__':
        no = 999999
        print(fun1(no)) #Function Call 1
        print(fun2(no)) #Function Call 2
</code>```

So I want to run both the functions fun1() and fun2() simultaneously so that as soon as one of them returns the value, the program stops the other function and prints the value from fun1().

I tried to explore multiprocessing in python that offers parallel processing but in addition to that, I'm looking for some solution that stops other functions as soon as one of the functions returns some value.

Note: I'm using Python 3.10.6 on Ubuntu. The program above is just a dummy program to represent the problem.

ContentLicense: CC BY-SA 4.0

Body:
I want to write two python functions that request data from two different APIs (with similar data). Both the functions should start simultaneously and as soon as one of the functions (say fun1()) returns the result, the other function (say fun2()) is terminated and the rest of the program is carried out with the result obtained from fun1().

For example,

from datetime import datetime
def fun1(n): #Obtaining data from Source 1
        sums = -1
        if n > -1:
                sums = sum([x*x for x in range(n)])
        return sums

def fun2(n): #Obtaining data from source 2
        sums = -1
        if n > -1:
                sums = (n*(2*n+1)*(n+1))/6
        return int(sums)

if __name__ == '__main__':
        no = 999999
        print(fun1(no)) #Function Call 1
        print(fun2(no)) #Function Call 2

So I want to run both the functions fun1() and fun2() simultaneously so that as soon as one of them returns the value, the program stops the other function and prints the value from fun1().

I tried to explore multiprocessing in python that offers parallel processing but in addition to that, I'm looking for some solution that stops other functions as soon as one of the functions returns some value.

Note: I'm using Python 3.10.6 on Ubuntu. The program above is just a dummy program to represent the problem.


问:
Eclipse ignoring the git hooks
Is there a way to make the eclipse read the hooks created from .git/hooks directory? I tried to use the hooks on cli/shell level and it’s working as expected but on eclipse ide,it completely ignores the hooks.</p>

Title: Eclipse ignoring the git hooks


问:
Why does pandas keep becoming an empty data frame when I put my code into a function?
I have a pandas program that edits a CSV file to what I need for work. This program works great when I run it on its own. I am now trying to build a GUI with PySimpleGUI that allows me to select which program I need to run, and then runs it with the correct file attached. My problem is that if I turn my pandas program into a function it does not seem to carry any information over from the CSV except the header (top row) and says 'Empty Dataframe'. I am not sure how to correct this as I cannot call the program without it being in a function. The first code block is the original code, and it works correctly(some information was redacted due to work privacy):

```<code>df = pd.read_csv('XXX_test_file.csv', sep=',', dtype={'MemberIdentifer': int})

df = df[['MemberIdentifier', 'FirstName', 'LastName', 'BirthDate', 'Zip', 'HireDate',
         'MedicalPlan', 'Division', 'GenderCode', 'EmailAddress']]

df['Region'] = pd.Series(dtype=str)
df['Role'] = pd.Series(dtype=str)
df['Company'] = pd.Series(dtype=str)
df['Action'] = pd.Series(dtype=str)
df['PrimaryMemberEmployeeId'] = pd.Series(dtype=str)
df['PrimaryMemberEmail'] = pd.Series(dtype=str)

df.rename(columns={'MemberIdentifier': 'EmployeeId', 'BirthDate': 'DateOfBirth', 'Division': 'Location',
                   'GenderCode': 'Gender', 'Zip': 'ZipCode', 'EmailAddress': 'Email'}, inplace=True)

df = df.reindex(columns=['FirstName', 'LastName', 'Location', 'EmployeeId', 'DateOfBirth', 'Gender', 'ZipCode', 'Email',
                         'Role', 'PrimaryMemberEmail', 'PrimaryMemberEmployeeId', 'HireDate', 'Company', 'Action'
    , 'MedicalPlan'])

# stops copy error
pd.set_option('mode.chained_assignment', None)

p = -1
for _ in (df['EmployeeId']):
    p = (p + len(df['EmployeeId']) - (len(df['EmployeeId']) - 1))
    EEID = df['EmployeeId'].iloc[p]

    if df['MedicalPlan'].iloc[p] == 'XXX Health Plan':
        df['Role'].iloc[p] = 'Employee On Plan'

df['PrimaryMemberEmail'] = (df['PrimaryMemberEmployeeId']
                            .map(df.set_index('EmployeeId')['Email'])
                            .fillna(df['PrimaryMemberEmail'])
                            )

df['Company'].fillna('XXX', inplace=True)

df.to_csv('XXX_company.csv', header=True, index=False)
</code>```

Naturally, I thought I could break this into two functions, one to get the CSV ready for data-management, and another to parse through the data. When I do this, the whole system seems to fall apart, however, as the Dataframe becomes empty. I am unsure how to pass the Dataframe into a variable without it wiping clean. I am new and learning, and after much googling, this is still stumping me. Below is the modified code(some information redacted due to work privacy):

```<code>pd.set_option('mode.chained_assignment', None)
dft = pd.read_csv('input_file.csv', sep=',', dtype={'MemberIdentifer': int})
def get_file_and_format(dft):
    df = dft

    df = df[['MemberIdentifier', 'FirstName', 'LastName', 'BirthDate', 'Zip', 'HireDate',
             'MedicalPlan', 'Division', 'GenderCode', 'EmailAddress']]
    df['Region'] = pd.Series(dtype=str)
    df['Role'] = pd.Series(dtype=str)
    df['Company'] = pd.Series(dtype=str)
    df['Action'] = pd.Series(dtype=str)
    df['PrimaryMemberEmployeeId'] = pd.Series(dtype=str)
    df['PrimaryMemberEmail'] = pd.Series(dtype=str)
    df.rename(columns={'MemberIdentifier': 'EmployeeId', 'BirthDate': 'DateOfBirth', 'Division': 'Location',
                       'GenderCode': 'Gender', 'Zip': 'ZipCode', 'EmailAddress': 'Email'}, inplace=True)

    df = df.reindex(
        columns=['FirstName', 'LastName', 'Location', 'EmployeeId', 'DateOfBirth', 'Gender', 'ZipCode', 'Email',
                 'Role', 'PrimaryMemberEmail', 'PrimaryMemberEmployeeId', 'HireDate', 'Company', 'Action',
                 'MedicalPlan'])

    # stops copy error
    pd.set_option('mode.chained_assignment', None)
    return df

def parse_data(df):

    p = -1
    for _ in (df['EmployeeId']):
        p = (p + len(df['EmployeeId']) - (len(df['EmployeeId']) - 1))
        EEID = df['EmployeeId'].iloc[p]

        if df['MedicalPlan'].iloc[p] == 'Health Plan':
            df['Role'].iloc[p] = 'Employee On Plan'

    df['PrimaryMemberEmail'] = (df['PrimaryMemberEmployeeId']
                            .map(df.set_index('EmployeeId')['Email'])
                            .fillna(df['PrimaryMemberEmail'])
                            )

    df['Company'].fillna('XXX_company', inplace=True)

file = get_file_and_format(dft)

</code>```

Body:
I have a pandas program that edits a CSV file to what I need for work. This program works great when I run it on its own. I am now trying to build a GUI with PySimpleGUI that allows me to select which program I need to run, and then runs it with the correct file attached. My problem is that if I turn my pandas program into a function it does not seem to carry any information over from the CSV except the header (top row) and says 'Empty Dataframe'. I am not sure how to correct this as I cannot call the program without it being in a function. The first code block is the original code, and it works correctly(some information was redacted due to work privacy):

df = pd.read_csv('XXX_test_file.csv', sep=',', dtype={'MemberIdentifer': int})

df = df[['MemberIdentifier', 'FirstName', 'LastName', 'BirthDate', 'Zip', 'HireDate',
         'MedicalPlan', 'Division', 'GenderCode', 'EmailAddress']]

df['Region'] = pd.Series(dtype=str)
df['Role'] = pd.Series(dtype=str)
df['Company'] = pd.Series(dtype=str)
df['Action'] = pd.Series(dtype=str)
df['PrimaryMemberEmployeeId'] = pd.Series(dtype=str)
df['PrimaryMemberEmail'] = pd.Series(dtype=str)

df.rename(columns={'MemberIdentifier': 'EmployeeId', 'BirthDate': 'DateOfBirth', 'Division': 'Location',
                   'GenderCode': 'Gender', 'Zip': 'ZipCode', 'EmailAddress': 'Email'}, inplace=True)

df = df.reindex(columns=['FirstName', 'LastName', 'Location', 'EmployeeId', 'DateOfBirth', 'Gender', 'ZipCode', 'Email',
                         'Role', 'PrimaryMemberEmail', 'PrimaryMemberEmployeeId', 'HireDate', 'Company', 'Action'
    , 'MedicalPlan'])

# stops copy error
pd.set_option('mode.chained_assignment', None)

p = -1
for _ in (df['EmployeeId']):
    p = (p + len(df['EmployeeId']) - (len(df['EmployeeId']) - 1))
    EEID = df['EmployeeId'].iloc[p]

    if df['MedicalPlan'].iloc[p] == 'XXX Health Plan':
        df['Role'].iloc[p] = 'Employee On Plan'

df['PrimaryMemberEmail'] = (df['PrimaryMemberEmployeeId']
                            .map(df.set_index('EmployeeId')['Email'])
                            .fillna(df['PrimaryMemberEmail'])
                            )

df['Company'].fillna('XXX', inplace=True)

df.to_csv('XXX_company.csv', header=True, index=False)

Naturally, I thought I could break this into two functions, one to get the CSV ready for data-management, and another to parse through the data. When I do this, the whole system seems to fall apart, however, as the Dataframe becomes empty. I am unsure how to pass the Dataframe into a variable without it wiping clean. I am new and learning, and after much googling, this is still stumping me. Below is the modified code(some information redacted due to work privacy):

pd.set_option('mode.chained_assignment', None)
dft = pd.read_csv('input_file.csv', sep=',', dtype={'MemberIdentifer': int})
def get_file_and_format(dft):
    df = dft

    df = df[['MemberIdentifier', 'FirstName', 'LastName', 'BirthDate', 'Zip', 'HireDate',
             'MedicalPlan', 'Division', 'GenderCode', 'EmailAddress']]
    df['Region'] = pd.Series(dtype=str)
    df['Role'] = pd.Series(dtype=str)
    df['Company'] = pd.Series(dtype=str)
    df['Action'] = pd.Series(dtype=str)
    df['PrimaryMemberEmployeeId'] = pd.Series(dtype=str)
    df['PrimaryMemberEmail'] = pd.Series(dtype=str)
    df.rename(columns={'MemberIdentifier': 'EmployeeId', 'BirthDate': 'DateOfBirth', 'Division': 'Location',
                       'GenderCode': 'Gender', 'Zip': 'ZipCode', 'EmailAddress': 'Email'}, inplace=True)

    df = df.reindex(
        columns=['FirstName', 'LastName', 'Location', 'EmployeeId', 'DateOfBirth', 'Gender', 'ZipCode', 'Email',
                 'Role', 'PrimaryMemberEmail', 'PrimaryMemberEmployeeId', 'HireDate', 'Company', 'Action',
                 'MedicalPlan'])

    # stops copy error
    pd.set_option('mode.chained_assignment', None)
    return df

def parse_data(df):

    p = -1
    for _ in (df['EmployeeId']):
        p = (p + len(df['EmployeeId']) - (len(df['EmployeeId']) - 1))
        EEID = df['EmployeeId'].iloc[p]

        if df['MedicalPlan'].iloc[p] == 'Health Plan':
            df['Role'].iloc[p] = 'Employee On Plan'

    df['PrimaryMemberEmail'] = (df['PrimaryMemberEmployeeId']
                            .map(df.set_index('EmployeeId')['Email'])
                            .fillna(df['PrimaryMemberEmail'])
                            )

    df['Company'].fillna('XXX_company', inplace=True)

file = get_file_and_format(dft)


问:
Javascript clearTimeout function doesnt work
I created an interactive banner and need to monitor some user behavior. The first interactivity is that when the user clicks on the banner it expands and if there is no more interactivity it contracts again. When the banner expands, a dropdown opens with multiple choices and each one plays a different video.

When the banner expands, I start a function to find out if there is any more user interaction with the banner, and if the mouse is moving or using the keyboard. If there is no interactivity the banner is collapsed.

But if the user clicks on one of the dropdown options, I call a function to stop the setTimeout and create a listener to monitor when the video ends and then I call the first function again to reset the banner.

But the function for the stops timeout (stopTimer) is not working, here is the code.

Initializing the variables

```<code>  var timeoutInMiliseconds = 10000
  var timeoutId
</code>```

Listener to expand the banner and open the dropdown and starts setupTimers function

```<code>dropbtn.addEventListener('click', function(e) {
    if(running) {
      inner();
      bannerSize();
      running = false
    }
    elem3.classList.add('is-active')
    drop.classList.add('is-active')
    seta.classList.add('is-active')

    console.log('timer start')
    setupTimers()
  })
</code>```

Listener to monitor dropdown options clicks
As you can see, I call stopTimer function to stop the setupTimers function and create another listener to monitor when the video ends

```<code>click1.addEventListener('click', function(e){
    console.log('stop timer')
    stopTimer()

    bg()
    contentVideo.classList.add('show')
    source.setAttribute('src', './diesel-r.mp4')
    source.setAttribute('type', 'video/mp4')
    video.appendChild(source)
    video.play()
    video.muted = true
    btn.addEventListener('click', function(e) {
      window.open('https://www.youtube.com/embed/ojaR_wiAkIM')
    })

    video.addEventListener('ended', function() {
      console.log('start timer after video ended')
      setupTimers()
    })
  })
</code>```

Functions responsible for starting the setTimeout, stopping, resetting, and closing the banner and other elements

```<code>function stopTimer() {
  window.clearTimeout(timeoutId)
}

function resetTimer() {
  window.clearTimeout(timeoutId)
  startTimer();
}

function startTimer() {
  timeoutId = window.setTimeout(doInactive, timeoutInMiliseconds)
}

function doInactive() {
  console.log('reseted')
  running = true
  reset()
  bgReset()
  elem3.classList.remove('is-active')
  drop.classList.remove('is-active')
  seta.classList.remove('is-active')
  seta.classList.remove('anima-seta')

  for (var i = 0; i < dropdownContent.length; i++) {
    dropdownContent[i].classList.remove('show')
  }
  contentVideo.classList.remove('show')
  video.pause()
  video.currentTime = 0
  video.removeAttribute('src')
  video.load()
}

function setupTimers() {
  document.addEventListener("mousemove", resetTimer, false)
  document.addEventListener("mousedown", resetTimer, false)
  document.addEventListener("keypress", resetTimer, false)
  document.addEventListener("touchmove", resetTimer, false)

  startTimer()
}
</code>```

Body:
I created an interactive banner and need to monitor some user behavior. The first interactivity is that when the user clicks on the banner it expands and if there is no more interactivity it contracts again. When the banner expands, a dropdown opens with multiple choices and each one plays a different video.

When the banner expands, I start a function to find out if there is any more user interaction with the banner, and if the mouse is moving or using the keyboard. If there is no interactivity the banner is collapsed.

But if the user clicks on one of the dropdown options, I call a function to stop the setTimeout and create a listener to monitor when the video ends and then I call the first function again to reset the banner.

But the function for the stops timeout (stopTimer) is not working, here is the code.

Initializing the variables

  var timeoutInMiliseconds = 10000
  var timeoutId

Listener to expand the banner and open the dropdown and starts setupTimers function

dropbtn.addEventListener('click', function(e) {
    if(running) {
      inner();
      bannerSize();
      running = false
    }
    elem3.classList.add('is-active')
    drop.classList.add('is-active')
    seta.classList.add('is-active')

    console.log('timer start')
    setupTimers()
  })

Listener to monitor dropdown options clicks
As you can see, I call stopTimer function to stop the setupTimers function and create another listener to monitor when the video ends

click1.addEventListener('click', function(e){
    console.log('stop timer')
    stopTimer()

    bg()
    contentVideo.classList.add('show')
    source.setAttribute('src', './diesel-r.mp4')
    source.setAttribute('type', 'video/mp4')
    video.appendChild(source)
    video.play()
    video.muted = true
    btn.addEventListener('click', function(e) {
      window.open('https://www.youtube.com/embed/ojaR_wiAkIM')
    })

    video.addEventListener('ended', function() {
      console.log('start timer after video ended')
      setupTimers()
    })
  })

Functions responsible for starting the setTimeout, stopping, resetting, and closing the banner and other elements

function stopTimer() {
  window.clearTimeout(timeoutId)
}

function resetTimer() {
  window.clearTimeout(timeoutId)
  startTimer();
}

function startTimer() {
  timeoutId = window.setTimeout(doInactive, timeoutInMiliseconds)
}

function doInactive() {
  console.log('reseted')
  running = true
  reset()
  bgReset()
  elem3.classList.remove('is-active')
  drop.classList.remove('is-active')
  seta.classList.remove('is-active')
  seta.classList.remove('anima-seta')

  for (var i = 0; i < dropdownContent.length; i++) {
    dropdownContent[i].classList.remove('show')
  }
  contentVideo.classList.remove('show')
  video.pause()
  video.currentTime = 0
  video.removeAttribute('src')
  video.load()
}

function setupTimers() {
  document.addEventListener("mousemove", resetTimer, false)
  document.addEventListener("mousedown", resetTimer, false)
  document.addEventListener("keypress", resetTimer, false)
  document.addEventListener("touchmove", resetTimer, false)

  startTimer()
}


问:
Configuration cannot be resolved to a type error in maven project
When I am configuring the hibernate project  with the help of maven project ,I included all the dependencies like hibernate maven and mysql and after that I wanted to connect hibernate to my mysql in eclipse edition . when I am creating object of Configuration class in App.java that time I am getting Configuration cannot resolved to a type in eclipse editor .
Right now I am using jdk 17 version .
Please help me .

I am trying to connect the hibernate to mysql in eclipse editor .


问:
Btach size in output layer is None Keras Tensorflow
```<code>I was running this code  and i Had the issue below

> import urllib
import zipfile

import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt

def download_and_extract_data():
    url = 'https://storage.googleapis.com/download.tensorflow.org/data/certificate/household_power.zip'
    urllib.request.urlretrieve(url, 'household_power.zip')
    with zipfile.ZipFile('household_power.zip', 'r') as zip_ref:
        zip_ref.extractall()

# This function normalizes the dataset using min max scaling.
# DO NOT CHANGE THIS CODE
def normalize_series(data, min, max):
    data = data - min
    data = data / max
    return data

# DO NOT CHANGE THIS CODE
def windowed_dataset(series, batch_size, n_past=24, n_future=24, shift=1):
    ds = tf.data.Dataset.from_tensor_slices(series)
    ds = ds.window(size=n_past + n_future, shift=shift, drop_remainder=True)
    ds = ds.flat_map(lambda w: w.batch(n_past + n_future))
    ds = ds.map(lambda w: (w[:n_past], w[n_past:]))
    return ds.batch(batch_size).prefetch(1)

def solution_model():

    download_and_extract_data()
    # Reads the dataset from the CSV.
    df = pd.read_csv('household_power_consumption.csv', sep=',',
                     infer_datetime_format=True, index_col='datetime', header=0)

    N_FEATURES = len(df.columns)  # DO NOT CHANGE THIS

    # Normalizes the data
    data = df.values
    data = normalize_series(data, data.min(axis=0), data.max(axis=0))

    # Splits the data into training and validation sets.
    SPLIT_TIME = int(len(data) * 0.5)  # DO NOT CHANGE THIS
    x_train = data[:SPLIT_TIME]
    x_valid = data[SPLIT_TIME:]

    # DO NOT CHANGE THIS CODE
    tf.keras.backend.clear_session()
    tf.random.set_seed(42)

    BATCH_SIZE = 32  # ADVISED NOT TO CHANGE THIS

    # predicted
    N_PAST = 24  # DO NOT CHANGE THIS

    # Number of future time steps which are to be predicted.
    N_FUTURE = 24  # DO NOT CHANGE THIS

    SHIFT = 1  # DO NOT CHANGE THIS

    train_set = windowed_dataset(series=x_train, batch_size=BATCH_SIZE,
                                 n_past=N_PAST, n_future=N_FUTURE,
                                 shift=SHIFT)
    valid_set = windowed_dataset(series=x_valid, batch_size=BATCH_SIZE,
                                 n_past=N_PAST, n_future=N_FUTURE,
                                 shift=SHIFT)

    # Code to define your model.
    model = tf.keras.models.Sequential([

        tf.keras.Input(batch_input_shape=[BATCH_SIZE, N_PAST, N_FEATURES]),
        tf.keras.layers.SimpleRNN(100, return_sequences=True),

        tf.keras.layers.Dense(N_FEATURES)
    ])

    model.summary()

    optimizer = tf.keras.optimizers.SGD(lr=1e-5, momentum=0.9)
    # Code to train and compile the model
    model.compile(loss=tf.keras.losses.Huber(),
                  optimizer=optimizer,
                  metrics=["mae"]
                  )
    # save best model
    model_checkpoint = tf.keras.callbacks.ModelCheckpoint(
        "mymodel.h5", save_best_only=True)
    # early stopping
    early_stopping = tf.keras.callbacks.EarlyStopping(patience=50)

    history = model.fit(
        # YOUR CODE HERE
        train_set, epochs=5, validation_data=valid_set, callbacks=[early_stopping, model_checkpoint]
    )
    return  model

if __name__ == '__main__':
    model = solution_model()
    model.save("mymodel.h5")

</code>```
```<code>
</code>```
```<code>Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 simple_rnn (SimpleRNN)      (32, 24, 100)             10800

 dense (Dense)               (32, 24, 7)               707

=================================================================
Total params: 11,507
Trainable params: 11,507
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
   1345/Unknown - 21s 15ms/step - loss: 0.0439 - mae: 0.2033
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-16-68785683b308> in <module>
    107
    108 if __name__ == '__main__':
--> 109     model = solution_model()
    110     model.save("mymodel.h5")
    111

2 frames
/usr/local/lib/python3.8/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     52   try:
     53     ctx.ensure_initialized()
---> 54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     55                                         inputs, attrs, num_outputs)
     56   except core._NotOkStatusException as e:

InvalidArgumentError: Graph execution error:

Detected at node 'sequential/simple_rnn/TensorArrayUnstack/TensorListFromTensor' defined at (most recent call last):
    File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
      return _run_code(code, main_globals, None,
    File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
      exec(code, run_globals)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel_launcher.py", line 16, in <module>
      app.launch_new_instance()
    File "/usr/local/lib/python3.8/dist-packages/traitlets/config/application.py", line 992, in launch_instance
      app.start()
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelapp.py", line 612, in start
      self.io_loop.start()
    File "/usr/local/lib/python3.8/dist-packages/tornado/platform/asyncio.py", line 149, in start
      self.asyncio_loop.run_forever()
    File "/usr/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
      self._run_once()
    File "/usr/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
      handle._run()
    File "/usr/lib/python3.8/asyncio/events.py", line 81, in _run
      self._context.run(self._callback, *self._args)
    File "/usr/local/lib/python3.8/dist-packages/tornado/ioloop.py", line 690, in <lambda>
      lambda f: self._run_callback(functools.partial(callback, future))
    File "/usr/local/lib/python3.8/dist-packages/tornado/ioloop.py", line 743, in _run_callback
      ret = callback()
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 787, in inner
      self.run()
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 748, in run
      yielded = self.gen.send(value)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelbase.py", line 365, in process_one
      yield gen.maybe_future(dispatch(*args))
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 209, in wrapper
      yielded = next(result)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelbase.py", line 268, in dispatch_shell
      yield gen.maybe_future(handler(stream, idents, msg))
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 209, in wrapper
      yielded = next(result)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelbase.py", line 543, in execute_request
      self.do_execute(
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 209, in wrapper
      yielded = next(result)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/ipkernel.py", line 306, in do_execute
      res = shell.run_cell(code, store_history=store_history, silent=silent)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/zmqshell.py", line 536, in run_cell
      return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 2854, in run_cell
      result = self._run_cell(
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 2881, in _run_cell
      return runner(coro)
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/async_helpers.py", line 68, in _pseudo_sync_runner
      coro.send(None)
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 3057, in run_cell_async
      has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 3249, in run_ast_nodes
      if (await self.run_code(code, result,  async_=asy)):
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 3326, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-16-68785683b308>", line 109, in <module>
      model = solution_model()
    File "<ipython-input-16-68785683b308>", line 101, in solution_model
      history = model.fit(
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1409, in fit
      tmp_logs = self.train_function(iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1051, in train_function
      return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1040, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1030, in run_step
      outputs = model.train_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 889, in train_step
      y_pred = self(x, training=True)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 490, in __call__
      return super().__call__(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
      outputs = call_fn(inputs, *args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/sequential.py", line 374, in call
      return super(Sequential, self).call(inputs, training=training, mask=mask)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/functional.py", line 458, in call
      return self._run_internal_graph(
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/functional.py", line 596, in _run_internal_graph
      outputs = node.layer(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/layers/rnn/base_rnn.py", line 515, in __call__
      return super(RNN, self).__call__(inputs, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
      outputs = call_fn(inputs, *args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/layers/rnn/simple_rnn.py", line 391, in call
      return super(SimpleRNN, self).call(
    File "/usr/local/lib/python3.8/dist-packages/keras/layers/rnn/base_rnn.py", line 652, in call
      last_output, outputs, states = backend.rnn(
    File "/usr/local/lib/python3.8/dist-packages/keras/backend.py", line 4612, in rnn
      input_ta = tuple(
    File "/usr/local/lib/python3.8/dist-packages/keras/backend.py", line 4613, in <genexpr>
      ta.unstack(input_) if not go_backwards else ta
Node: 'sequential/simple_rnn/TensorArrayUnstack/TensorListFromTensor'
Specified a list with shape [32,7] from a tensor with shape [17,7]
     [[{{node sequential/simple_rnn/TensorArrayUnstack/TensorListFromTensor}}]] [Op:__inference_train_function_7904]
</code>```
```<code>
</code>```

Note that the Batch size shouldn't be None, I tried other architecture but the the value of the batch size is None

```<code>
</code>```

model = tf.keras.models.Sequential([

```<code>    keras.layers.Conv1D(filters=32, kernel_size=5,
                  strides=1, padding="causal",
                  activation="relu",
                  input_shape=[N_PAST, N_FEATURES]),
    tf.keras.layers.SimpleRNN(100, return_sequences=True),

    tf.keras.layers.Dense(N_FEATURES)
])
</code>```
```<code>
</code>```

Model: "sequential_1"

Layer (type)                Output Shape              Param #

conv1d (Conv1D)             (None, 24, 32)            1152

simple_rnn_1 (SimpleRNN)    (None, 24, 100)           13300

dense_1 (Dense)             (None, 24, 7)             707

=================================================================
Total params: 15,159
Trainable params: 15,159
Non-trainable params: 0

```<code>
</code>```

Body:
I was running this code  and i Had the issue below

> import urllib
import zipfile

import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt

def download_and_extract_data():
    url = 'https://storage.googleapis.com/download.tensorflow.org/data/certificate/household_power.zip'
    urllib.request.urlretrieve(url, 'household_power.zip')
    with zipfile.ZipFile('household_power.zip', 'r') as zip_ref:
        zip_ref.extractall()

# This function normalizes the dataset using min max scaling.
# DO NOT CHANGE THIS CODE
def normalize_series(data, min, max):
    data = data - min
    data = data / max
    return data

# DO NOT CHANGE THIS CODE
def windowed_dataset(series, batch_size, n_past=24, n_future=24, shift=1):
    ds = tf.data.Dataset.from_tensor_slices(series)
    ds = ds.window(size=n_past + n_future, shift=shift, drop_remainder=True)
    ds = ds.flat_map(lambda w: w.batch(n_past + n_future))
    ds = ds.map(lambda w: (w[:n_past], w[n_past:]))
    return ds.batch(batch_size).prefetch(1)

def solution_model():

    download_and_extract_data()
    # Reads the dataset from the CSV.
    df = pd.read_csv('household_power_consumption.csv', sep=',',
                     infer_datetime_format=True, index_col='datetime', header=0)

    N_FEATURES = len(df.columns)  # DO NOT CHANGE THIS

    # Normalizes the data
    data = df.values
    data = normalize_series(data, data.min(axis=0), data.max(axis=0))

    # Splits the data into training and validation sets.
    SPLIT_TIME = int(len(data) * 0.5)  # DO NOT CHANGE THIS
    x_train = data[:SPLIT_TIME]
    x_valid = data[SPLIT_TIME:]

    # DO NOT CHANGE THIS CODE
    tf.keras.backend.clear_session()
    tf.random.set_seed(42)

    BATCH_SIZE = 32  # ADVISED NOT TO CHANGE THIS

    # predicted
    N_PAST = 24  # DO NOT CHANGE THIS

    # Number of future time steps which are to be predicted.
    N_FUTURE = 24  # DO NOT CHANGE THIS

    SHIFT = 1  # DO NOT CHANGE THIS

    train_set = windowed_dataset(series=x_train, batch_size=BATCH_SIZE,
                                 n_past=N_PAST, n_future=N_FUTURE,
                                 shift=SHIFT)
    valid_set = windowed_dataset(series=x_valid, batch_size=BATCH_SIZE,
                                 n_past=N_PAST, n_future=N_FUTURE,
                                 shift=SHIFT)

    # Code to define your model.
    model = tf.keras.models.Sequential([

        tf.keras.Input(batch_input_shape=[BATCH_SIZE, N_PAST, N_FEATURES]),
        tf.keras.layers.SimpleRNN(100, return_sequences=True),

        tf.keras.layers.Dense(N_FEATURES)
    ])

    model.summary()

    optimizer = tf.keras.optimizers.SGD(lr=1e-5, momentum=0.9)
    # Code to train and compile the model
    model.compile(loss=tf.keras.losses.Huber(),
                  optimizer=optimizer,
                  metrics=["mae"]
                  )
    # save best model
    model_checkpoint = tf.keras.callbacks.ModelCheckpoint(
        "mymodel.h5", save_best_only=True)
    # early stopping
    early_stopping = tf.keras.callbacks.EarlyStopping(patience=50)

    history = model.fit(
        # YOUR CODE HERE
        train_set, epochs=5, validation_data=valid_set, callbacks=[early_stopping, model_checkpoint]
    )
    return  model

if __name__ == '__main__':
    model = solution_model()
    model.save("mymodel.h5")

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 simple_rnn (SimpleRNN)      (32, 24, 100)             10800

 dense (Dense)               (32, 24, 7)               707

=================================================================
Total params: 11,507
Trainable params: 11,507
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
   1345/Unknown - 21s 15ms/step - loss: 0.0439 - mae: 0.2033
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-16-68785683b308> in <module>
    107
    108 if __name__ == '__main__':
--> 109     model = solution_model()
    110     model.save("mymodel.h5")
    111

2 frames
/usr/local/lib/python3.8/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     52   try:
     53     ctx.ensure_initialized()
---> 54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     55                                         inputs, attrs, num_outputs)
     56   except core._NotOkStatusException as e:

InvalidArgumentError: Graph execution error:

Detected at node 'sequential/simple_rnn/TensorArrayUnstack/TensorListFromTensor' defined at (most recent call last):
    File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
      return _run_code(code, main_globals, None,
    File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
      exec(code, run_globals)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel_launcher.py", line 16, in <module>
      app.launch_new_instance()
    File "/usr/local/lib/python3.8/dist-packages/traitlets/config/application.py", line 992, in launch_instance
      app.start()
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelapp.py", line 612, in start
      self.io_loop.start()
    File "/usr/local/lib/python3.8/dist-packages/tornado/platform/asyncio.py", line 149, in start
      self.asyncio_loop.run_forever()
    File "/usr/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
      self._run_once()
    File "/usr/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
      handle._run()
    File "/usr/lib/python3.8/asyncio/events.py", line 81, in _run
      self._context.run(self._callback, *self._args)
    File "/usr/local/lib/python3.8/dist-packages/tornado/ioloop.py", line 690, in <lambda>
      lambda f: self._run_callback(functools.partial(callback, future))
    File "/usr/local/lib/python3.8/dist-packages/tornado/ioloop.py", line 743, in _run_callback
      ret = callback()
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 787, in inner
      self.run()
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 748, in run
      yielded = self.gen.send(value)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelbase.py", line 365, in process_one
      yield gen.maybe_future(dispatch(*args))
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 209, in wrapper
      yielded = next(result)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelbase.py", line 268, in dispatch_shell
      yield gen.maybe_future(handler(stream, idents, msg))
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 209, in wrapper
      yielded = next(result)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/kernelbase.py", line 543, in execute_request
      self.do_execute(
    File "/usr/local/lib/python3.8/dist-packages/tornado/gen.py", line 209, in wrapper
      yielded = next(result)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/ipkernel.py", line 306, in do_execute
      res = shell.run_cell(code, store_history=store_history, silent=silent)
    File "/usr/local/lib/python3.8/dist-packages/ipykernel/zmqshell.py", line 536, in run_cell
      return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 2854, in run_cell
      result = self._run_cell(
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 2881, in _run_cell
      return runner(coro)
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/async_helpers.py", line 68, in _pseudo_sync_runner
      coro.send(None)
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 3057, in run_cell_async
      has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 3249, in run_ast_nodes
      if (await self.run_code(code, result,  async_=asy)):
    File "/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py", line 3326, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-16-68785683b308>", line 109, in <module>
      model = solution_model()
    File "<ipython-input-16-68785683b308>", line 101, in solution_model
      history = model.fit(
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1409, in fit
      tmp_logs = self.train_function(iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1051, in train_function
      return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1040, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1030, in run_step
      outputs = model.train_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 889, in train_step
      y_pred = self(x, training=True)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 490, in __call__
      return super().__call__(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
      outputs = call_fn(inputs, *args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/sequential.py", line 374, in call
      return super(Sequential, self).call(inputs, training=training, mask=mask)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/functional.py", line 458, in call
      return self._run_internal_graph(
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/functional.py", line 596, in _run_internal_graph
      outputs = node.layer(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/layers/rnn/base_rnn.py", line 515, in __call__
      return super(RNN, self).__call__(inputs, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
      outputs = call_fn(inputs, *args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.8/dist-packages/keras/layers/rnn/simple_rnn.py", line 391, in call
      return super(SimpleRNN, self).call(
    File "/usr/local/lib/python3.8/dist-packages/keras/layers/rnn/base_rnn.py", line 652, in call
      last_output, outputs, states = backend.rnn(
    File "/usr/local/lib/python3.8/dist-packages/keras/backend.py", line 4612, in rnn
      input_ta = tuple(
    File "/usr/local/lib/python3.8/dist-packages/keras/backend.py", line 4613, in <genexpr>
      ta.unstack(input_) if not go_backwards else ta
Node: 'sequential/simple_rnn/TensorArrayUnstack/TensorListFromTensor'
Specified a list with shape [32,7] from a tensor with shape [17,7]
     [[{{node sequential/simple_rnn/TensorArrayUnstack/TensorListFromTensor}}]] [Op:__inference_train_function_7904]

Note that the Batch size shouldn't be None, I tried other architecture but the the value of the batch size is None

model = tf.keras.models.Sequential([

    keras.layers.Conv1D(filters=32, kernel_size=5,
                  strides=1, padding="causal",
                  activation="relu",
                  input_shape=[N_PAST, N_FEATURES]),
    tf.keras.layers.SimpleRNN(100, return_sequences=True),

    tf.keras.layers.Dense(N_FEATURES)
])

Model: "sequential_1"

Layer (type)                Output Shape              Param #

conv1d (Conv1D)             (None, 24, 32)            1152

simple_rnn_1 (SimpleRNN)    (None, 24, 100)           13300

dense_1 (Dense)             (None, 24, 7)             707

=================================================================
Total params: 15,159
Trainable params: 15,159
Non-trainable params: 0


问:
Uploading multiple images to Firebase Storage fails with an inner exception
everyone. I want to upload multiple images to Firebase Storage. These are in my gallery and the user can choose from these 6 images in total. After clicking on a button, all images should be loaded into the storage one after the other and the respective download URL should be returned. If I try the whole thing with the following code, I run into the addOnFailureListener() method with the log output:

com.google.firebase.storage.StorageException: An unknown error occurred, please check the HTTP result code and inner exception for server response.

What could be the mistake? Thank you very much!

```<code>val storage = Firebase.storage
val storageRef = storage.reference

 private fun uploadImages() {

    val progressDialog = ProgressDialog(context).apply {
        setTitle("Uploading Picture....")
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        show()
    }

    for (i in 0 until listImg.size) {

        var file = Uri.fromFile(File(listImg[i].toString()))
        val riversRef = storageRef.child("images/${file.lastPathSegment}")
        var uploadTask = riversRef.putFile(file)

        uploadTask.addOnProgressListener { taskSnapshot  ->
            val progress = (100.0 * taskSnapshot.bytesTransferred) / taskSnapshot.totalByteCount
            Log.d("TAG", "Upload is $progress% done")
            progressDialog.setMessage("Uploaded.. " + progress.toInt() + "%")

        }.addOnPausedListener {
            Log.d("TAG", "Upload is paused")
        }.addOnFailureListener {
            Log.e("ERROR:",it.toString())
            progressDialog.dismiss()
        }.addOnSuccessListener {
            progressDialog.dismiss()
            val uri = riversRef.downloadUrl

            Log.d("DownloadURL:" ,uri.toString())
        }

    }

 }
</code>```

This is the path to the respective file in which is in the list:

My Rules on Firebase Storage:

I have the following dependencies:

```<code>implementation platform('com.google.firebase:firebase-bom:31.1.1')
implementation 'com.google.firebase:firebase-storage-ktx'
</code>```

I have the following dependencies:

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

Body:
everyone. I want to upload multiple images to Firebase Storage. These are in my gallery and the user can choose from these 6 images in total. After clicking on a button, all images should be loaded into the storage one after the other and the respective download URL should be returned. If I try the whole thing with the following code, I run into the addOnFailureListener() method with the log output:

com.google.firebase.storage.StorageException: An unknown error occurred, please check the HTTP result code and inner exception for server response.

What could be the mistake? Thank you very much!

val storage = Firebase.storage
val storageRef = storage.reference

 private fun uploadImages() {

    val progressDialog = ProgressDialog(context).apply {
        setTitle("Uploading Picture....")
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        show()
    }

    for (i in 0 until listImg.size) {

        var file = Uri.fromFile(File(listImg[i].toString()))
        val riversRef = storageRef.child("images/${file.lastPathSegment}")
        var uploadTask = riversRef.putFile(file)

        uploadTask.addOnProgressListener { taskSnapshot  ->
            val progress = (100.0 * taskSnapshot.bytesTransferred) / taskSnapshot.totalByteCount
            Log.d("TAG", "Upload is $progress% done")
            progressDialog.setMessage("Uploaded.. " + progress.toInt() + "%")

        }.addOnPausedListener {
            Log.d("TAG", "Upload is paused")
        }.addOnFailureListener {
            Log.e("ERROR:",it.toString())
            progressDialog.dismiss()
        }.addOnSuccessListener {
            progressDialog.dismiss()
            val uri = riversRef.downloadUrl

            Log.d("DownloadURL:" ,uri.toString())
        }

    }

 }

This is the path to the respective file in which is in the list:

My Rules on Firebase Storage:

I have the following dependencies:

implementation platform('com.google.firebase:firebase-bom:31.1.1')
implementation 'com.google.firebase:firebase-storage-ktx'

I have the following dependencies:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


问:
Having problems with the logic of prefix sums
I'm trying to solve this problem: https://open.kattis.com/problems/alicedigital

Basically my solution is to take inputs as a prefix sum array instead of storing the inputs themselves while also keeping track of the index of every minimum element in the array. Then, I can get each sum that contains the minimum value once and print the maximum of these sums

This is my code so far:

```<code>import java.util.*;
class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    while (num-- > 0)
      {
        int n = sc.nextInt(), m = sc.nextInt();
        int[] pfs = new int[n];
        ArrayList<Integer> min = new ArrayList<>();
        //min.add(-1);
        for (int i = 0; i < n; i++)
          {
            int input = sc.nextInt();
            if (input == m)
              min.add(i);
            if (i == 0)
              pfs[0] = input;
            else
              pfs[i] = pfs[i-1] + input;
          }
        min.add(n);
        ArrayList<Integer> sums = new ArrayList<>();
        for (int i = 0; i < min.size()-1; i++)
          {
            if (i == 0)
              sums.add(pfs[min.get(i+1)-1]);
            else
              sums.add(pfs[min.get(i+1)-1] - pfs[min.get(i-1)]);
          }
        //System.out.println(sums);
        System.out.println(Collections.max(sums));
      }
  }
}
</code>```

I'm not sure how, but this gives the wrong answer on one of the test cases. I think it's in issue with how I calculated the prefix sums since I not familiar with them at all

Body:
I'm trying to solve this problem: https://open.kattis.com/problems/alicedigital

Basically my solution is to take inputs as a prefix sum array instead of storing the inputs themselves while also keeping track of the index of every minimum element in the array. Then, I can get each sum that contains the minimum value once and print the maximum of these sums

This is my code so far:

import java.util.*;
class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    while (num-- > 0)
      {
        int n = sc.nextInt(), m = sc.nextInt();
        int[] pfs = new int[n];
        ArrayList<Integer> min = new ArrayList<>();
        //min.add(-1);
        for (int i = 0; i < n; i++)
          {
            int input = sc.nextInt();
            if (input == m)
              min.add(i);
            if (i == 0)
              pfs[0] = input;
            else
              pfs[i] = pfs[i-1] + input;
          }
        min.add(n);
        ArrayList<Integer> sums = new ArrayList<>();
        for (int i = 0; i < min.size()-1; i++)
          {
            if (i == 0)
              sums.add(pfs[min.get(i+1)-1]);
            else
              sums.add(pfs[min.get(i+1)-1] - pfs[min.get(i-1)]);
          }
        //System.out.println(sums);
        System.out.println(Collections.max(sums));
      }
  }
}

I'm not sure how, but this gives the wrong answer on one of the test cases. I think it's in issue with how I calculated the prefix sums since I not familiar with them at all


问:
power automate to fill nested repeater control in word template
I have a requirement to fill a word document template using power automate. In the template I need to have nested repeating section content control. Is it possible use power automate to fill the template?

I have tried this but the power automate does not show the nested Json in the populate word template step.


问:
Jar file execution and Appium
I have created a jar file for automate testing using Appium.
the jar file is using android driver.

My question is if I want to run this jar file on another PC that doesn't have Appium server
I will be able to run this jar file form the lib in jar or I have to to install Appium server on the other computers.

Title: Jar file execution and Appium


问:
How to access field values in a map in firestore
I have two apps. I'll call the first one RiderApp and the second one DriverApp. The users on the RiderApp can access a page where they can see a list of 6 different questions. The 6 questions are dropdown menus where they can check off the boxes that best fit their answer to each question and then save their answers. Each Each question is saved in Cloud Firestore as a Map and the answers are saved as fields which hold a boolean value. Fields marked as true are boxes that the user checked off and false are boxes that the user didn't check off.

This is where my issue comes into play. On the DriverApp, I have set up a page where the users can see this page that the user on the RiderApp has saved. They can see each question BUT I am having trouble tapping into this data in order for the users on the DriverApp to see which boxes were checked off by the user on the RiderApp.

I'm trying to do something on the DriverApp where I want to show a checkmark Icon next to the answers that the user on the RiderApp checked off.

I have everything pushing to the database correctly I'm just not sure how I can now access it in order to show in the DriverApp correctly.

Any help would be much appreciated! Below are some screenshots. Apologies for the red boxes. Had to cover up some sensitive information.


问:
How can I stop WordPress from changing my category links in page builder?
I have a problem with my WordPress category links.

My Theme (Uncode) uses the WPBakery Page Builder and when I create a specific link to a category (for example https://homeiswhereyourbagis.com/laender-und-orte/suedostasien/thailand/koh-samui/), the page builder changes these pretty links to something like https://homeiswhereyourbagis.com/?cat_ID=51 after saving. This happens only in WPBakery Page Builder and not on posts that are created with standard Gutenberg editor.

The problem about this is, that these links (/?cat_ID=51) are not working anymore. Instead, I'm redirected to the home page, which is obviously not what I want. On the other hand, links like https://homeiswhereyourbagis.com/?p=24100 are working fine.

So my 2 questions would be:

Is there maybe any way to stop WPBakery Page Builder from creating these unpretty links and force it to use the pretty links that I have created? Or:

What could the problem be about links like /?cat_ID=51 not working anymore. I already tried to deactivate some plugins like Yoast, WPML, etc. I couldn't figure it out.

Any help or any hint is very much appreciated! :)


问:
Gradle build does not publish jar to artifactory
Need help figuring out why my single module build script doesn't publish jar to JFrog artifactory. Here is my build gradle file

```<code>buildscript {
    ext {
        springBootVersion = '2.1.1.RELEASE'
    }
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '4.15.1')
    }
}
apply plugin:'com.jfrog.artifactory'
apply plugin: 'java'
apply plugin: "maven-publish"

group = 'com.<company_name>.<app_name>.api'
version = '1.0.0'

jar {
    baseName = '<app_name>-client'
}

repositories {
    mavenCentral()
    maven {
        url "https://artifactory.build.<companyname>.com/artifactory/ext-snapshot-local/"
        credentials {
            username <artifactory_user>
            password <artifactory_password>
        }
    }
    maven {
        url "https://artifactory.build.<companyname>.com/artifactory/ext-release-local/"
        credentials {
            username <artifactory_user>
            password <artifactory_password>
        }
    }
    maven { url "http://repo.spring.io/release" }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }
}
artifactory {
    contextUrl = "$repository_url"
    publish{
        repository {
            username = "$repoUser"
            password  = "$repoPassword"
            maven = true
        }
        defaults {
            publications('mavenJava')
            publishArtifacts = true
            publishPom = true
        }
    }
}
dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web:2.1.1.RELEASE'){
        exclude module: 'mysql:mysql-connector-java:5.1.47'
    }
    ...
   ...
}
</code>```

Below is the output and gradle command I m using..

```<code>gradle clean build jar artifactoryPublish
</code>```
```<code>> Task :extractModuleInfo
No publisher config found for project: <app_name>

> Task :artifactoryDeploy
Deploying build descriptor to: https://artifactory-private.build.<company_name>.com/artifactory/api/build
Build successfully deployed. Browse it in Artifactory under https://artifactory-private.build.<company_name>.com/artifactory/webapp/builds/<app_name>/<random_number>
</code>```

Body:
Need help figuring out why my single module build script doesn't publish jar to JFrog artifactory. Here is my build gradle file

buildscript {
    ext {
        springBootVersion = '2.1.1.RELEASE'
    }
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '4.15.1')
    }
}
apply plugin:'com.jfrog.artifactory'
apply plugin: 'java'
apply plugin: "maven-publish"

group = 'com.<company_name>.<app_name>.api'
version = '1.0.0'

jar {
    baseName = '<app_name>-client'
}

repositories {
    mavenCentral()
    maven {
        url "https://artifactory.build.<companyname>.com/artifactory/ext-snapshot-local/"
        credentials {
            username <artifactory_user>
            password <artifactory_password>
        }
    }
    maven {
        url "https://artifactory.build.<companyname>.com/artifactory/ext-release-local/"
        credentials {
            username <artifactory_user>
            password <artifactory_password>
        }
    }
    maven { url "http://repo.spring.io/release" }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }
}
artifactory {
    contextUrl = "$repository_url"
    publish{
        repository {
            username = "$repoUser"
            password  = "$repoPassword"
            maven = true
        }
        defaults {
            publications('mavenJava')
            publishArtifacts = true
            publishPom = true
        }
    }
}
dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web:2.1.1.RELEASE'){
        exclude module: 'mysql:mysql-connector-java:5.1.47'
    }
    ...
   ...
}

Below is the output and gradle command I m using..

gradle clean build jar artifactoryPublish

> Task :extractModuleInfo
No publisher config found for project: <app_name>

> Task :artifactoryDeploy
Deploying build descriptor to: https://artifactory-private.build.<company_name>.com/artifactory/api/build
Build successfully deployed. Browse it in Artifactory under https://artifactory-private.build.<company_name>.com/artifactory/webapp/builds/<app_name>/<random_number>


问:
PaperTrail override column in object_changes before save
Currently I am using PaperTrail for model versioning an I have a situation in which I invite a team member. The created records after the "create" event is fired up is:

```<code><PaperTrail::Version:0x0000558aeeff2b38
id: 327,
item_type: "TeamMember",
item_id: 12,
event: "create",
whodunnit: "1",
object: nil,
created_at: Wed, 21 Dec 2022 15:57:04 UTC +00:00,
object_changes: {"user_id"=>[nil, 42]}>
</code>```

As shown below TeamMember model has an association with user and when it is created I save the user_id. PaperTrail keeps track of user_id and saved the id of user but instead I am interested of user name. I cannot do a find with the id when I display the log because the user with that id may not exist anymore in the future and it will result in record not found. On the other hand I cannot use reify because
this is a "create" event and reify results in nil.
Please help me how can I save user_name instead of user id on object_changes.

Body:
Currently I am using PaperTrail for model versioning an I have a situation in which I invite a team member. The created records after the "create" event is fired up is:

<PaperTrail::Version:0x0000558aeeff2b38
id: 327,
item_type: "TeamMember",
item_id: 12,
event: "create",
whodunnit: "1",
object: nil,
created_at: Wed, 21 Dec 2022 15:57:04 UTC +00:00,
object_changes: {"user_id"=>[nil, 42]}>

As shown below TeamMember model has an association with user and when it is created I save the user_id. PaperTrail keeps track of user_id and saved the id of user but instead I am interested of user name. I cannot do a find with the id when I display the log because the user with that id may not exist anymore in the future and it will result in record not found. On the other hand I cannot use reify because
this is a "create" event and reify results in nil.
Please help me how can I save user_name instead of user id on object_changes.


问:
Maven multi module project giving classNotFound exception
I have Maven multi module project which runs fine with JDK8. Where I have one parent pom and other sub modules. Now module A calls some functionality of module B and B loads some third party class dynamically at runtime. Now this third party class jar is included as dependency in module B pom.

```<code><dependency>
    <groupId>com.sybase.jconnect</groupId>
    <artifactId>jconn4</artifactId>
    <version>16.039-27463</version>
</dependency>
</code>```

Recently I am migrating this application to JDK17. But at runtime I am getting

Could not load JDBC driver class [com.sybase.jdbc4.jdbc.SybDriver]

which is part of jconn4 dependency.

If anyone faced similar issue and what workaround you followed?

Body:
I have Maven multi module project which runs fine with JDK8. Where I have one parent pom and other sub modules. Now module A calls some functionality of module B and B loads some third party class dynamically at runtime. Now this third party class jar is included as dependency in module B pom.

<dependency>
    <groupId>com.sybase.jconnect</groupId>
    <artifactId>jconn4</artifactId>
    <version>16.039-27463</version>
</dependency>

Recently I am migrating this application to JDK17. But at runtime I am getting

Could not load JDBC driver class [com.sybase.jdbc4.jdbc.SybDriver]

which is part of jconn4 dependency.

If anyone faced similar issue and what workaround you followed?


问:
Why am I getting Illegal Number of Operator Errors for these assembly Instructions?
I have a C++ project where I use various bits of assembly code.

My project wont compile with the following lines, it says "Illegal number of operands". How can I fix this?

These are examples of the lines that are causing the issues...

```<code>__asm
{
    FST DWORD PTR SS : [ESP + 0x0C] , ST(0)
    FSTP DWORD PTR SS : [ESP + 0x08] , ST(0)
    FILD ST(0), DWORD PTR SS : [ESP + 0x98]
}
</code>```

Body:
I have a C++ project where I use various bits of assembly code.

My project wont compile with the following lines, it says "Illegal number of operands". How can I fix this?

These are examples of the lines that are causing the issues...

__asm
{
    FST DWORD PTR SS : [ESP + 0x0C] , ST(0)
    FSTP DWORD PTR SS : [ESP + 0x08] , ST(0)
    FILD ST(0), DWORD PTR SS : [ESP + 0x98]
}


问:
Get Document from Firestore by ID
I am trying to get a document from Firestore by the ID but it doesnt work. An empty document is returned.

I want to get the document with ID '5a' from collection 'class'.

Here is a picture of Firestore web:

And that is the way, I am trying to get the data:

```<code>DocumentSnapshot doc = await db.collection('class').doc('5a').get();

print(doc.exists()); // => false
</code>```

But no filled document is returned.

(Permissions are not required and I am getting no error.)

Here is the whole code for the methode

```<code>Future<Class> getClassFromFirestore(String clas) async {

DocumentSnapshot doc = await db.collection('class').doc('5a').get();

    SplayTreeMap<String, List<Lesson>> days = SplayTreeMap();
    List<String> subjects = [];
    try {
      (await doc[ClassFields.days]).forEach((date, lessonsRaw) async {
        print('hep');
        List<Lesson> lessons = [];
        lessonsRaw.forEach((lessonRaw) async {
          Lesson lesson = Lesson(
            id: lessonRaw[LessonFields.id].toString().trim(),
            timeblock: int.parse(lessonRaw[LessonFields.timeblock].toString().trim()),
            subject: lessonRaw[LessonFields.subject].toString().trim(),
            teacher: lessonRaw[LessonFields.teacher].toString().trim(),
            room: lessonRaw[LessonFields.room].toString().trim()
          );
          lessons.add(lesson);
        });
        days[date] = lessons;
      });
      (await doc[ClassFields.subjects]).forEach((subject) {
        subjects.add(subject.toString());
      });
    } catch (e) {
      print(e.toString());
      // cant get doc
    }

    print(days);

    return Class(name: clas, days: days, subjects: subjects);
  }
</code>```

Title: Get Document from Firestore by ID

Body:
I am trying to get a document from Firestore by the ID but it doesnt work. An empty document is returned.

I want to get the document with ID '5a' from collection 'class'.

Here is a picture of Firestore web:

And that is the way, I am trying to get the data:

DocumentSnapshot doc = await db.collection('class').doc('5a').get();

print(doc.exists()); // => false

But no filled document is returned.

(Permissions are not required and I am getting no error.)

Here is the whole code for the methode

Future<Class> getClassFromFirestore(String clas) async {

DocumentSnapshot doc = await db.collection('class').doc('5a').get();

    SplayTreeMap<String, List<Lesson>> days = SplayTreeMap();
    List<String> subjects = [];
    try {
      (await doc[ClassFields.days]).forEach((date, lessonsRaw) async {
        print('hep');
        List<Lesson> lessons = [];
        lessonsRaw.forEach((lessonRaw) async {
          Lesson lesson = Lesson(
            id: lessonRaw[LessonFields.id].toString().trim(),
            timeblock: int.parse(lessonRaw[LessonFields.timeblock].toString().trim()),
            subject: lessonRaw[LessonFields.subject].toString().trim(),
            teacher: lessonRaw[LessonFields.teacher].toString().trim(),
            room: lessonRaw[LessonFields.room].toString().trim()
          );
          lessons.add(lesson);
        });
        days[date] = lessons;
      });
      (await doc[ClassFields.subjects]).forEach((subject) {
        subjects.add(subject.toString());
      });
    } catch (e) {
      print(e.toString());
      // cant get doc
    }

    print(days);

    return Class(name: clas, days: days, subjects: subjects);
  }


问:
How to programmatically implement scroll anchor behavior across browsers with JS & React?
Scroll anchor is a feature that has been around for some time now, but it is still not fully supported.

overflow-anchor MDN

Surprisingly, it seems not to work properly on Firefox as well, depending on the use case, which is not the focus of this thread.

Regardless of the extend of the support of this feature across browsers, what could be a clean and concise way of implementing this exact behavior with JS& React.js?

Taking an excerpt from this explanation:

When the anchor node moves, the browser computes its previous location L0 and its new location L1 in the coordinate space of the scrolling content. It then reads the current scroll position S0 and computes a new scroll position S1:

S1 = S0 + (L1 - L0)

By setting the scroll position to S1 at the same time that the anchor node moves to L1, we preserve the location of the anchor node relative to the viewport, and no "jump" is visible.

Would it be the case of storing the scroll position and within a certain trigger, on a event listener, do the trick manually, while disabling the css rule overflow-anchor: none on the overflowing element?

Interesting findings to consider:

When disabling overflow-anchor cssproperty and dynamically adding content, while listening to scroll events on the overflowing element, no event is triggered.


问:
Check if the specified file already exists in an URL, if yes the keep the older file and upload the newer file also-- using python?
I have an URL https://....//error.txt .  Firstly I want to check if this URL already exists, if yes I need to upload another file to the same location and name it as https://....//error_1.txt again need to check ; if these 2 are already present then name the next upload as https://....//error_2.txt and so on. How to accomplish this. I already have the upload function. I have the python file like this

```<code>with open("../../../error.txt","w") as f:
    f.write("Now the file has more content!")
    f.close()
</code>```

and the upload function contains the source and target locations

```<code>#upload(source,destination)
upload("C:\DISK_D\Work\error.txt","https://....//error.txt")
</code>```

Body:
I have an URL https://....//error.txt .  Firstly I want to check if this URL already exists, if yes I need to upload another file to the same location and name it as https://....//error_1.txt again need to check ; if these 2 are already present then name the next upload as https://....//error_2.txt and so on. How to accomplish this. I already have the upload function. I have the python file like this

with open("../../../error.txt","w") as f:
    f.write("Now the file has more content!")
    f.close()

and the upload function contains the source and target locations

#upload(source,destination)
upload("C:\DISK_D\Work\error.txt","https://....//error.txt")


问:
Unable to compile this basic nodejs addon
What I am trying to do is to call a custom-made DLL in nodejs(javascript) from nodejs addon api(c++ / napi). I have created what I believe to be working code when I compile it, I get an error. The error is
kernel32.lib(KERNEL32.dll) : fatal error LNK1103: debugging information corrupt; recompile module.

From the code below, i know its caused by line 50 and 51, even though they should be the type std:string (or at least i think).I tried different ways of converting such values to string but still get the same error.

Perhaps there is an issue with my machine/environment.

Or there really is an issue with the code? FYI, I'm not a C++ programmer

Any help is highly appreciated!

```<code>#include <windows.h>
#include <string>
#include <napi.h>

typedef std::string (__stdcall *functionWithoutArguments)();
typedef std::string (*functionWith1Args)(const std::string&);
typedef std::string (*functionWith2Args)(const std::string&, const std::string&);

std::string CallDllFunction(const std::string& functionName, const std::string& arg1="", const std::string& arg2="") {
  HMODULE hmodule = LoadLibraryW(L"CustomDll.dll");
  if (hmodule == NULL) {
    return "Unable to load CustomDll.dll";
  }

  bool arg1Exists = static_cast<int>(arg1.length()) > 0;
  bool arg2Exists = static_cast<int>(arg2.length()) > 0;
  std::string result = "";

  if(arg1Exists && arg1Exists){
    functionWith2Args function = (functionWith2Args)GetProcAddress(hmodule, functionName.c_str());
    if(function == NULL) return "Function does not exist";
    std::string result = function(arg1.c_str(), arg2.c_str());

  }else if(arg1Exists){
    functionWith1Args function = (functionWith1Args)GetProcAddress(hmodule, functionName.c_str());
    if(function == NULL) return "Function does not exist";
    std::string result = function(arg1.c_str());
  }else{
    functionWithoutArguments function = (functionWithoutArguments)GetProcAddress(hmodule, functionName.c_str());
    if(function == NULL) return "Function does not exist";
    std::string result = function();
  }

  FreeLibrary(hmodule);

  return result;
}

Napi::Value ExecFunction(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();

if (info.Length() == 0) {
  Napi::TypeError::New(env, "Wrong number of arguments")
      .ThrowAsJavaScriptException();
  return env.Null();
}

if (info[0].IsString()) {
  std::string arg0 = info[0].ToString().Utf8Value();
  std::string result = CallDllFunction(arg0);

  return Napi::String::New(env, result);
}

}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "ExecFunction"), Napi::Function::New(env, ExecFunction));
return exports;
}

NODE_API_MODULE(cMath, Init)

</code>```

Heres the contents of binding.gyp

```<code>{
  "targets": [
    {
      "target_name": "NodeBridge", #Compiled node addon name.
      "cflags!": [
        "-fno-exceptions"
      ],
      "cflags_cc!": [
        "-fno-exceptions"
      ],
      "sources": [ #Source files required to build.
        "Source.cc",
      ],
      "include_dirs": [ #If you use any library in cpp project, write here header files path.
        "<!@(node -p \"require('node-addon-api').include\")",
      ],
      "libraries": [#If you use any libray in cpp projecy, write here library lib files path.
      ],
      "configurations": {#Compilation settings, default RuntimeTypeInfo is closed.
        "Release": {
          'output_dir': '../CustomDLL/bin/NodeBridge',
          "msvs_settings": {
            "VCCLCompilerTool": {
              "ExceptionHandling": "2",
              "RuntimeTypeInfo": "true",
              "AdditionalOptions": [
                "/std:c++17"
              ]
            }
          }
        }
      },
      "dependencies": [
        "<!(node -p \"require('node-addon-api').gyp\")"
      ],
      "defines":[
       "WIN",
       '_HAS_EXCEPTIONS=1' #To handle exceptions occurred in cpp project.
       ]
    }
  ]
}
</code>```

Body:
What I am trying to do is to call a custom-made DLL in nodejs(javascript) from nodejs addon api(c++ / napi). I have created what I believe to be working code when I compile it, I get an error. The error is
kernel32.lib(KERNEL32.dll) : fatal error LNK1103: debugging information corrupt; recompile module.

From the code below, i know its caused by line 50 and 51, even though they should be the type std:string (or at least i think).I tried different ways of converting such values to string but still get the same error.

Perhaps there is an issue with my machine/environment.

Or there really is an issue with the code? FYI, I'm not a C++ programmer

Any help is highly appreciated!

#include <windows.h>
#include <string>
#include <napi.h>

typedef std::string (__stdcall *functionWithoutArguments)();
typedef std::string (*functionWith1Args)(const std::string&);
typedef std::string (*functionWith2Args)(const std::string&, const std::string&);

std::string CallDllFunction(const std::string& functionName, const std::string& arg1="", const std::string& arg2="") {
  HMODULE hmodule = LoadLibraryW(L"CustomDll.dll");
  if (hmodule == NULL) {
    return "Unable to load CustomDll.dll";
  }

  bool arg1Exists = static_cast<int>(arg1.length()) > 0;
  bool arg2Exists = static_cast<int>(arg2.length()) > 0;
  std::string result = "";

  if(arg1Exists && arg1Exists){
    functionWith2Args function = (functionWith2Args)GetProcAddress(hmodule, functionName.c_str());
    if(function == NULL) return "Function does not exist";
    std::string result = function(arg1.c_str(), arg2.c_str());

  }else if(arg1Exists){
    functionWith1Args function = (functionWith1Args)GetProcAddress(hmodule, functionName.c_str());
    if(function == NULL) return "Function does not exist";
    std::string result = function(arg1.c_str());
  }else{
    functionWithoutArguments function = (functionWithoutArguments)GetProcAddress(hmodule, functionName.c_str());
    if(function == NULL) return "Function does not exist";
    std::string result = function();
  }

  FreeLibrary(hmodule);

  return result;
}

Napi::Value ExecFunction(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();

if (info.Length() == 0) {
  Napi::TypeError::New(env, "Wrong number of arguments")
      .ThrowAsJavaScriptException();
  return env.Null();
}

if (info[0].IsString()) {
  std::string arg0 = info[0].ToString().Utf8Value();
  std::string result = CallDllFunction(arg0);

  return Napi::String::New(env, result);
}

}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "ExecFunction"), Napi::Function::New(env, ExecFunction));
return exports;
}

NODE_API_MODULE(cMath, Init)

Heres the contents of binding.gyp

{
  "targets": [
    {
      "target_name": "NodeBridge", #Compiled node addon name.
      "cflags!": [
        "-fno-exceptions"
      ],
      "cflags_cc!": [
        "-fno-exceptions"
      ],
      "sources": [ #Source files required to build.
        "Source.cc",
      ],
      "include_dirs": [ #If you use any library in cpp project, write here header files path.
        "<!@(node -p \"require('node-addon-api').include\")",
      ],
      "libraries": [#If you use any libray in cpp projecy, write here library lib files path.
      ],
      "configurations": {#Compilation settings, default RuntimeTypeInfo is closed.
        "Release": {
          'output_dir': '../CustomDLL/bin/NodeBridge',
          "msvs_settings": {
            "VCCLCompilerTool": {
              "ExceptionHandling": "2",
              "RuntimeTypeInfo": "true",
              "AdditionalOptions": [
                "/std:c++17"
              ]
            }
          }
        }
      },
      "dependencies": [
        "<!(node -p \"require('node-addon-api').gyp\")"
      ],
      "defines":[
       "WIN",
       '_HAS_EXCEPTIONS=1' #To handle exceptions occurred in cpp project.
       ]
    }
  ]
}


问:
Restored SharePoint 2013 content database appears to be empty
I recently added a new site collection to a SharePoint 2013 environment and attached a restored content database from a different environment (also 2013).

The process involved was:

backup SP database on original environment

restore database to new environment

add restored db as new content database in SP

create new site collection to use the new db

It all worked fine, with no issues occurring, but when I view the Site Contents in SP, the only libraries visible are the standard ones (Documents, Site Assets, Site Pages, etc) - none of the libraries that were part of the restored database appear. A count of AllDocs confirms that the documents are in the db.

I can confirm in the Site Collection List in SP Central Admin that the new site collection is pointing to the right db. I've also double checked this from PowerShell using:

```<code>$site=Get-SPSite "http://<sp_url>"
write-host $site.ContentDatabase.Name
</code>```

Did I do something wrong? Or miss something out?

The backup and restore of the original SP database was done by the DBAs and was pretty lengthy due to its size (~3.8TB), so I'm really hoping that doesn't have to get re-done!

Thanks...

Body:
I recently added a new site collection to a SharePoint 2013 environment and attached a restored content database from a different environment (also 2013).

The process involved was:

backup SP database on original environment

restore database to new environment

add restored db as new content database in SP

create new site collection to use the new db

It all worked fine, with no issues occurring, but when I view the Site Contents in SP, the only libraries visible are the standard ones (Documents, Site Assets, Site Pages, etc) - none of the libraries that were part of the restored database appear. A count of AllDocs confirms that the documents are in the db.

I can confirm in the Site Collection List in SP Central Admin that the new site collection is pointing to the right db. I've also double checked this from PowerShell using:

$site=Get-SPSite "http://<sp_url>"
write-host $site.ContentDatabase.Name

Did I do something wrong? Or miss something out?

The backup and restore of the original SP database was done by the DBAs and was pretty lengthy due to its size (~3.8TB), so I'm really hoping that doesn't have to get re-done!

Thanks...


问:
Speed type tester - how to reference variables out of scope?
I am relatively new to python and I am struggling with building this speed type tester, I am not sure as to why I can seem to change the value of ''time_over'' from false to true in the first function, but can't seem to change the 'text' variable from being empty to get the string I am trying to pass through the input and feed it to the 'counter' function.

I don't want to look up for solutions online as I am sure that there are thousand of speed type testers written in Python, so I tried to focus on building separate functions that have a specific task, trying to divide the problem into smaller parts. Please be kind, I'm only a newbie!

```<code>import time

def start_timer():
    """Starts the timer // returns (time_over = True) if timer hits 0"""
    time_over = False

    for secs in range(60, -1, -1):
        time.sleep(1)
        if secs == 30:
            print('Time remaining:', secs)
        elif secs == 10:
            print('Time remaining:', secs)
        elif secs == 0:
            time_over = True
            print('@@@ Ding Ding Ding, time is over champ! @@@')

    return time_over

def counter(some_string):
    """Counts the characters in a given string or list"""
    total_chars = len(some_string)
    print(f'You typed {total_chars} in total, wow!')

print('You will have 1 minute to write as many words as possible')
start_question = input('type y when you are ready or n to exit.').lower()
if start_question == 'y':
    start_timer()
    text = ''
    while not start_timer:

        text = input()

    if start_timer:

        counter(text)

</code>```

Body:
I am relatively new to python and I am struggling with building this speed type tester, I am not sure as to why I can seem to change the value of ''time_over'' from false to true in the first function, but can't seem to change the 'text' variable from being empty to get the string I am trying to pass through the input and feed it to the 'counter' function.

I don't want to look up for solutions online as I am sure that there are thousand of speed type testers written in Python, so I tried to focus on building separate functions that have a specific task, trying to divide the problem into smaller parts. Please be kind, I'm only a newbie!

import time

def start_timer():
    """Starts the timer // returns (time_over = True) if timer hits 0"""
    time_over = False

    for secs in range(60, -1, -1):
        time.sleep(1)
        if secs == 30:
            print('Time remaining:', secs)
        elif secs == 10:
            print('Time remaining:', secs)
        elif secs == 0:
            time_over = True
            print('@@@ Ding Ding Ding, time is over champ! @@@')

    return time_over

def counter(some_string):
    """Counts the characters in a given string or list"""
    total_chars = len(some_string)
    print(f'You typed {total_chars} in total, wow!')

print('You will have 1 minute to write as many words as possible')
start_question = input('type y when you are ready or n to exit.').lower()
if start_question == 'y':
    start_timer()
    text = ''
    while not start_timer:

        text = input()

    if start_timer:

        counter(text)


问:
Conditionally display columns in datagrid jsf
I'm using datagrid to display list of items. inside the datagrid it is decided condionally to display the column or not. But even if the condition is false and nothing is displayed datagrid still creates an empty div for it which leaves a large gap in between the items. Is there any way I can tackle this.

```<code><h:datagrid var="item" value="itemList" columns="{value from some code}" ><h:column rendered="{some condition}" >....... </h:column></h:datagrid>
</code>```

Note: I cannot change the item List because of some dependency in code.

Body:
I'm using datagrid to display list of items. inside the datagrid it is decided condionally to display the column or not. But even if the condition is false and nothing is displayed datagrid still creates an empty div for it which leaves a large gap in between the items. Is there any way I can tackle this.

<h:datagrid var="item" value="itemList" columns="{value from some code}" ><h:column rendered="{some condition}" >....... </h:column></h:datagrid>

Note: I cannot change the item List because of some dependency in code.


问:
Linq - Grouping by range results in "sub-query returns more than one row"
I am using the following LINQ to group by a variable range (as per question here)

```<code> var ranges = new List<decimal> { 5m, 10m, 20m };

 var grouped = entities.PointTransaction.Where( x => x.UserInfo.College == collegeID
                  && x.Amount < 0)
                 .GroupBy( x=> ranges.FirstOrDefault( r => r >= Math.Abs( (decimal) x.Amount) )
                  ).ToList();
</code>```

However, I will get the error:

```<code>single-row subquery returns more than one row
</code>```

When none of the rows match any of the ranges ( say, the values are all less than 5), the query will work.

I am using DevArt Dotconnect for Oracle, Entity Framework 4

ContentLicense: CC BY-SA 3.0

Body:
I am using the following LINQ to group by a variable range (as per question here)

 var ranges = new List<decimal> { 5m, 10m, 20m };

 var grouped = entities.PointTransaction.Where( x => x.UserInfo.College == collegeID
                  && x.Amount < 0)
                 .GroupBy( x=> ranges.FirstOrDefault( r => r >= Math.Abs( (decimal) x.Amount) )
                  ).ToList();

However, I will get the error:

single-row subquery returns more than one row

When none of the rows match any of the ranges ( say, the values are all less than 5), the query will work.

I am using DevArt Dotconnect for Oracle, Entity Framework 4


问:
Why am I obtaining this error message running a very old Access application? Some .mbd file are missing?
I am absolutly not into Microsoft Access and I have the following problem.

A cliend gave me a .mbd file that should contain an old Access "application" (DB + DB queries + forms). The data contained into this old management system implemented in Access has to be migrated into a brand new management system.

I checked and this Access "application" works fine on the client PC (they use Microsoft Access 2003) but when I try to open on my system (I am using Office 365) I obtain the following view:

So, as you can see in the previous printscreen, it seems that I can list the objects that compose my Access application (DB tables, DB queries, Forms) but when I try to accessto the content of a specific table (selecting it) I am obtaining this error message:

......access is not a valid path. make sure that the path name is spelled
correctly and that you are connected to the server on which the files
resides

Reading better the error it seems that it is refferring to a specific file that is not the one that I am running.

So my doubt is: is it possible that an Access application is composed by more than a single file and that these data are into this file named copia di Agenda medica be.md? In case do you think that adding this file in the expected path (or can I change this path from Access settings in some way?) it should work?


问:
Block "[name of widget]" constains errors and doesn't work correctly. More information could found in tools for programmers
I'm doing the tutorial for widget makers (WordPress). I wrote this code like in tutorial but Wordpress dispaly me the error "Block "[name of widget]" constains errors and doesn't work correctly. More information could found in tools for programmers." when I try use this widget</p>
```<code> <?php

    class Skpp_widget extends WP_Widget {
        function __construct(){
            parent::__construct(
                'first_widget',
                'Widget FIRST',
                array(
                    'classname' => 'first_widget',
                    'description' => 'This is my first widget'
                )
            );
        }

        function widget($args, $instance) {

            echo $args['before_widget'];
            echo  'This is my first widget';
            echo $args['after_widget'];

        }
    }

add_action( 'widgets_init', function(){
    register_widget( 'First_widget' );
});
</code>```

Body:
I'm doing the tutorial for widget makers (WordPress). I wrote this code like in tutorial but Wordpress dispaly me the error "Block "[name of widget]" constains errors and doesn't work correctly. More information could found in tools for programmers." when I try use this widget

 <?php

    class Skpp_widget extends WP_Widget {
        function __construct(){
            parent::__construct(
                'first_widget',
                'Widget FIRST',
                array(
                    'classname' => 'first_widget',
                    'description' => 'This is my first widget'
                )
            );
        }

        function widget($args, $instance) {

            echo $args['before_widget'];
            echo  'This is my first widget';
            echo $args['after_widget'];

        }
    }

add_action( 'widgets_init', function(){
    register_widget( 'First_widget' );
});


问:
Async line read python
```<code>async def parsing_bsc_1inch():
    async with aiofiles.open('test.txt', mode='r') as f:
        async for line in f:
            async with httpx.AsyncClient() as client:
                response = await client.get(line.rstrip())
            print(f'{response} for {line.rstrip()}')

asyncio.run(parsing_bsc_1inch())

</code>```

I want to do async reading of lines in the file (test.txt). Here is the file itself

```<code>https://www.example.com/
https://www.twitch.tv/
https://www.python-httpx.org/async/
https://habr.com/
https://www.twitch.tv/
https://www.python-httpx.org/async/
</code>```

The fourth site specifically doesn't work (blocked by my ISP). As I see it, I should get the output of line number 5 immediately after the third request, then line number 6 and after that an error about the request for line 4, but I wait 10 seconds and get the error "Traceback (most recent call last):".
Am I doing something wrong or can't the async work the way I think it should?

Title: Async line read python

Body:
async def parsing_bsc_1inch():
    async with aiofiles.open('test.txt', mode='r') as f:
        async for line in f:
            async with httpx.AsyncClient() as client:
                response = await client.get(line.rstrip())
            print(f'{response} for {line.rstrip()}')

asyncio.run(parsing_bsc_1inch())

I want to do async reading of lines in the file (test.txt). Here is the file itself

https://www.example.com/
https://www.twitch.tv/
https://www.python-httpx.org/async/
https://habr.com/
https://www.twitch.tv/
https://www.python-httpx.org/async/

The fourth site specifically doesn't work (blocked by my ISP). As I see it, I should get the output of line number 5 immediately after the third request, then line number 6 and after that an error about the request for line 4, but I wait 10 seconds and get the error "Traceback (most recent call last):".
Am I doing something wrong or can't the async work the way I think it should?


问:
registerActivityForResult unresolved reference kotlin android
I am using registerForActivityResult to signin using Google authentication API. For some unknown reason, the method is unresolved reference. I tried both options Appcompat and ComponentActivity.How can I resolve method registerForActivityResult? I get 'this' is not defined in this context when I use ComponentActivity

```<code>import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity

private val launcher = (this as ComponentActivity).registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
    if (result.resultCode == Activity.RESULT_OK){
        val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
        handleSignInResult(task)
    }
}
</code>```

Body:
I am using registerForActivityResult to signin using Google authentication API. For some unknown reason, the method is unresolved reference. I tried both options Appcompat and ComponentActivity.How can I resolve method registerForActivityResult? I get 'this' is not defined in this context when I use ComponentActivity

import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity

private val launcher = (this as ComponentActivity).registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
    if (result.resultCode == Activity.RESULT_OK){
        val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
        handleSignInResult(task)
    }
}


问:
POWER BI REST API - executedatasetqueries to return measure value
I am trying to evaluate\return a measure value using below Power BI Rest API

executedatasetqueries

What would be the correct way to put the measure name?

Below is what I tried in Body Section:

```<code>{
  "queries": [
    {
      "query": "EVALUATE ROW("MyMeasure", TableName[MyMeasure])"
    }
  ],
  "serializerSettings": {
    "includeNulls": true
  }
}
</code>```

It returned a syntax issue, below doesn't work as well:

```<code>EVALUATE SUMMARIZECOLUMNS("MyMeasure", [MyMeasure])
</code>```

Am I missing something?

Body:
I am trying to evaluate\return a measure value using below Power BI Rest API

executedatasetqueries

What would be the correct way to put the measure name?

Below is what I tried in Body Section:

{
  "queries": [
    {
      "query": "EVALUATE ROW("MyMeasure", TableName[MyMeasure])"
    }
  ],
  "serializerSettings": {
    "includeNulls": true
  }
}

It returned a syntax issue, below doesn't work as well:

EVALUATE SUMMARIZECOLUMNS("MyMeasure", [MyMeasure])

Am I missing something?