问:
how to change my current LSTM model from uni to bi-directional?
I have built an LSTM model through nn.module. This code is a toy code that I'm using to do stock prediction. I'm trying to make it bidirectional by simply changing the input from bidirectional = False to bidirectional = True . Although the model runs fine, the problem happens at the for loop of the epoch part where I tried to evaluate the test_loss from nn.MSEloss.

the error code is

RuntimeError: The size of tensor a (1534) must match the size of tensor b (767) at non-singleton dimension 0

my model:

```<code>class RNN(nn.Module):
  def __init__(self, i_size, h_size, n_layers, o_size, dropout=0.1, bidirectional = True):
    super(RNN, self).__init__()
    self.num_directions = bidirectional+1
    self.rnn = nn.LSTM(
        input_size=i_size,
        hidden_size=h_size,
        num_layers = n_layers,
        dropout = dropout,
        bidirectional = bidirectional
    )
    self.out = nn.Linear(h_size, o_size)

  def forward(self, x, h_state):
    r_out, hidden_state = self.rnn(x, h_state)

    hidden_size=  hidden_state[-1].size(-1)
    r_out = r_out.view(-1, self.num_directions, hidden_size)
    outs = self.out(r_out)

    return outs, hidden_state
</code>```

my input:

```<code>input_size = 100
hidden_size = 64
num_layers = 3
output_size = 1
batch_size = 128

learning_rate = 0.001
num_epochs = 500

rnn = RNN(input_size, hidden_size, num_layers, output_size, bidirectional =True)
rnn.cuda()

optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
criterion = nn.MSELoss()

hidden_state = None
</code>```

my evaluation process:

```<code>history = []
x_test_cuda = torch.tensor(x_test).float().cuda()
y_test_cuda = torch.tensor(y_test).float().cuda()

inputs_cuda = torch.tensor(x_train).float().cuda()
labels_cuda = torch.tensor(y_train).float().cuda()

for epoch in range(num_epochs):
  rnn.train()
  output, _ = rnn(inputs_cuda, hidden_state)
  print(output.size())

  loss = criterion(output[:,0,:].view(-1), labels_cuda)
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

  if epoch % 20 == 0:
    rnn.eval()
    test_output, _ = rnn(x_test_cuda, hidden_state)
    test_loss = criterion(test_output.view(-1), y_test_cuda)
    print('epoch {}, loss {}, eval loss {}'.format(epoch, loss.item(), test_loss.item()))
  else:
    print('epoch {}, loss {}'.format(epoch, loss.item()))

  history.append(loss.item())
</code>```

I realized it  is not just a simple change from a True to a False type of question. I have tried to floor division in

hidden_size=h_size, or get rid of IF-ELSE part. but it doesn't help.

Body:
I have built an LSTM model through nn.module. This code is a toy code that I'm using to do stock prediction. I'm trying to make it bidirectional by simply changing the input from bidirectional = False to bidirectional = True . Although the model runs fine, the problem happens at the for loop of the epoch part where I tried to evaluate the test_loss from nn.MSEloss.

the error code is

RuntimeError: The size of tensor a (1534) must match the size of tensor b (767) at non-singleton dimension 0

my model:

class RNN(nn.Module):
  def __init__(self, i_size, h_size, n_layers, o_size, dropout=0.1, bidirectional = True):
    super(RNN, self).__init__()
    self.num_directions = bidirectional+1
    self.rnn = nn.LSTM(
        input_size=i_size,
        hidden_size=h_size,
        num_layers = n_layers,
        dropout = dropout,
        bidirectional = bidirectional
    )
    self.out = nn.Linear(h_size, o_size)

  def forward(self, x, h_state):
    r_out, hidden_state = self.rnn(x, h_state)

    hidden_size=  hidden_state[-1].size(-1)
    r_out = r_out.view(-1, self.num_directions, hidden_size)
    outs = self.out(r_out)

    return outs, hidden_state

my input:

input_size = 100
hidden_size = 64
num_layers = 3
output_size = 1
batch_size = 128

learning_rate = 0.001
num_epochs = 500

rnn = RNN(input_size, hidden_size, num_layers, output_size, bidirectional =True)
rnn.cuda()

optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
criterion = nn.MSELoss()

hidden_state = None

my evaluation process:

history = []
x_test_cuda = torch.tensor(x_test).float().cuda()
y_test_cuda = torch.tensor(y_test).float().cuda()

inputs_cuda = torch.tensor(x_train).float().cuda()
labels_cuda = torch.tensor(y_train).float().cuda()

for epoch in range(num_epochs):
  rnn.train()
  output, _ = rnn(inputs_cuda, hidden_state)
  print(output.size())

  loss = criterion(output[:,0,:].view(-1), labels_cuda)
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

  if epoch % 20 == 0:
    rnn.eval()
    test_output, _ = rnn(x_test_cuda, hidden_state)
    test_loss = criterion(test_output.view(-1), y_test_cuda)
    print('epoch {}, loss {}, eval loss {}'.format(epoch, loss.item(), test_loss.item()))
  else:
    print('epoch {}, loss {}'.format(epoch, loss.item()))

  history.append(loss.item())

I realized it  is not just a simple change from a True to a False type of question. I have tried to floor division in

hidden_size=h_size, or get rid of IF-ELSE part. but it doesn't help.


来源: stackexchange

问:
How to fix BootStrap5 Button Spacing?
So, i have been trying to create a actual decent navigation bar with buttons, but the spacing doesn't really work out with it.

(I don't really know if its because of Python Flask, but i put that as a tag anyway)

This is what happends when i run my code:
https://ibb.co/nC7cX7s

Here is my code in Python Flask:

```<code>    <a class="navbar-brand" href="/">
      <img src="/static/img/AdiAvi.png" width="30" height="30" class="d-inline-block align-top" alt="">
      AdiAvi
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a {% if homePage %} class="nav-link active" {% endif %} {% if dashboardPage %} class="nav-link active" {% endif %} class="nav-link"  href="/">Home</a>
        </li>
        <li class="nav-item">
          <a {% if contactPage %} class="nav-link active" {% endif %} class="nav-link" href="/contact">Contact</a>
        </li>
        {% if baseTemplate %}
        <button type="button" id="loginButton" class="ml-2 btn btn-danger navbar-btn">
          Login
      </button>
        {% endif %}
        {% if baseTemplate %}
        <button type="button" id="registerTrigger" class="ml-2 btn btn-primary navbar-btn">
            Register
        </button>
        {% endif %}
      </ul>
    </div>
  </nav>
</code>```

And here is my code when i run my application:

```<code>

  <nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #333;">
    <a class="navbar-brand" href="/">
      <img src="/static/img/AdiAvi.png" width="30" height="30" class="d-inline-block align-top" alt="">
      AdiAvi
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a  class="nav-link active"   class="nav-link"  href="/">Home</a>
        </li>
        <li class="nav-item">
          <a  class="nav-link" href="/contact">Contact</a>
        </li>

        <button type="button" id="loginButton" class="ml-2 btn btn-danger navbar-btn">
          Login
      </button>

        <button type="button" id="registerTrigger" class="ml-2 btn btn-primary navbar-btn">
            Register
        </button>

      </ul>
    </div>
  </nav>
</code>```

As you can see, i tried adding the class="ml-2 btn btn-danger navbar-btn" to each of the buttons, expecting for it to move to a right a little bit, but instead nothing happened. It just stayed the exact same.

Does anyone know how to fix this issue?

I also tried using other posts answers for this problem, but at the end it still hasn't really worked out for me

ContentLicense: CC BY-SA 4.0

Title: How to fix BootStrap5 Button Spacing?

Body:
So, i have been trying to create a actual decent navigation bar with buttons, but the spacing doesn't really work out with it.

(I don't really know if its because of Python Flask, but i put that as a tag anyway)

This is what happends when i run my code:
https://ibb.co/nC7cX7s

Here is my code in Python Flask:

      AdiAvi

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

          Contact

        {% if baseTemplate %}
        <button type="button" id="loginButton" class="ml-2 btn btn-danger navbar-btn">
          Login
      </button>
        {% endif %}
        {% if baseTemplate %}
        <button type="button" id="registerTrigger" class="ml-2 btn btn-primary navbar-btn">
            Register
        </button>
        {% endif %}

And here is my code when i run my application:

      AdiAvi

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

          Contact

        <button type="button" id="loginButton" class="ml-2 btn btn-danger navbar-btn">
          Login
      </button>

        <button type="button" id="registerTrigger" class="ml-2 btn btn-primary navbar-btn">
            Register
        </button>

As you can see, i tried adding the class="ml-2 btn btn-danger navbar-btn" to each of the buttons, expecting for it to move to a right a little bit, but instead nothing happened. It just stayed the exact same.

Does anyone know how to fix this issue?

I also tried using other posts answers for this problem, but at the end it still hasn't really worked out for me


问:
How to wait for an input validation to complete using HTMX sync?
I have an input field (ex: Sort By parameter for a table) and a submit button in a different section of the page (not under the same form element). The input field has a hx-get request for validation which is triggered on change.

The problem I'm having is that if someone selects a value in the input field and directly clicks the submit button, both the validation call and the submit call are triggered simultaneously.

I want the validation request to be complete before the submit call is made. From the htmx documentation I think the hx-sync functionality is what I need. However, I could not get the submit call to wait for the input call to finish.

  <input
    id="title"
    name="title"
    type="text"
    hx-get="https://httpbin.org/delay/5"
    hx-trigger="change"
    hx-sync="#submit-button:queue first"
  >

  <button
    id="submit-button"
    hx-include="[name='title']"
    hx-post="https://httpbin.org/post"
    hx-trigger="click"
    type="submit"
  >
    Submit
  </button>

```

How do I get the submit to trigger after the input validation is complete?

Body:
I have an input field (ex: Sort By parameter for a table) and a submit button in a different section of the page (not under the same form element). The input field has a hx-get request for validation which is triggered on change.

The problem I'm having is that if someone selects a value in the input field and directly clicks the submit button, both the validation call and the submit call are triggered simultaneously.

I want the validation request to be complete before the submit call is made. From the htmx documentation I think the hx-sync functionality is what I need. However, I could not get the submit call to wait for the input call to finish.

  <input
    id="title"
    name="title"
    type="text"
    hx-get="https://httpbin.org/delay/5"
    hx-trigger="change"
    hx-sync="#submit-button:queue first"
  >

  <button
    id="submit-button"
    hx-include="[name='title']"
    hx-post="https://httpbin.org/post"
    hx-trigger="click"
    type="submit"
  >
    Submit
  </button>

How do I get the submit to trigger after the input validation is complete?


问:
Build error when trying to deploy Next app with Vercel
I'm trying to deploy an app to Vercel and getting this error in the build logs:

```<code>Running "npm run build"
> next-portfolio@0.1.0 build
> next build
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
info  - Linting and checking validity of types...
Failed to compile.
./portfolio-2/sanity.cli.ts:1:31
Type error: Cannot find module 'sanity/cli' or its corresponding type declarations.
> 1 | import {defineCliConfig} from 'sanity/cli'
    |                               ^
  2 |
  3 | export default defineCliConfig({
  4 |   api: {
Error: Command "npm run build" exited with 1
</code>```

It's a project that uses Next.js, React, Tailwind CSS, and Sanity.io

Body:
I'm trying to deploy an app to Vercel and getting this error in the build logs:

Running "npm run build"
> next-portfolio@0.1.0 build
> next build
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
info  - Linting and checking validity of types...
Failed to compile.
./portfolio-2/sanity.cli.ts:1:31
Type error: Cannot find module 'sanity/cli' or its corresponding type declarations.
> 1 | import {defineCliConfig} from 'sanity/cli'
    |                               ^
  2 |
  3 | export default defineCliConfig({
  4 |   api: {
Error: Command "npm run build" exited with 1

It's a project that uses Next.js, React, Tailwind CSS, and Sanity.io


问:
Occasional false positive memory leak when using std::future and _CrtMemDifference on Windows
Below is a minimal repro of the memory leak I see when using std::future. Inside ParallelForEach I create an array of std::future with a subsequent get that should block the execution of the main thread until all the tasks for vec are finished. Once the function ParallelForEach returns, the vector of futures must be cleaned up. But building with debug and _CrtMemDifference I see an occasional memory leak which I suspect to be false positive and its just windows not cleaning up the threads in time until process exit.

```<code>Total bytes leaked: 49128
</code>```

This is a problem since I have mem leak check in my tests that I don't want to get rid of. Why does this leak happen and how can I use both _CrtMemDifference and std::future?

```<code>#include <iostream>
#include <vector>
#include <future>
#include <crtdbg.h>

int func(int x) {
  return x * x;
}

void ParallelForEach(const std::vector<int>& vec) {
  std::vector<std::future<int>> futures;
  for (const auto& x : vec) {
    futures.push_back(std::async(std::launch::async, func, x));
  }
  for (auto& f : futures) {
    f.get();
  }
}

void MemoryLeakTest()
{
  std::vector<int> vec(64, 12);

  _CrtMemState before;
  _CrtMemCheckpoint(&before);

  ParallelForEach(vec);

  _CrtMemState after;
  _CrtMemCheckpoint(&after);

  _CrtMemState leaked;
  if (_CrtMemDifference(&leaked, &before, &after) != 0) {
    std::cout << "Total bytes leaked: " << leaked.lTotalCount << std::endl;
  }
}

int main() {
  for (int i = 0; i < 10000; i++)
  {
    MemoryLeakTest();
  }
  return 0;
}

</code>```

I tried std::for_each with parallel execution and this works without mem leak, but is not available in all targeted systems. I expect there to be a way/workaround to use std::future without Crt reporting false memory leaks.

Body:
Below is a minimal repro of the memory leak I see when using std::future. Inside ParallelForEach I create an array of std::future with a subsequent get that should block the execution of the main thread until all the tasks for vec are finished. Once the function ParallelForEach returns, the vector of futures must be cleaned up. But building with debug and _CrtMemDifference I see an occasional memory leak which I suspect to be false positive and its just windows not cleaning up the threads in time until process exit.

Total bytes leaked: 49128

This is a problem since I have mem leak check in my tests that I don't want to get rid of. Why does this leak happen and how can I use both _CrtMemDifference and std::future?

#include <iostream>
#include <vector>
#include <future>
#include <crtdbg.h>

int func(int x) {
  return x * x;
}

void ParallelForEach(const std::vector<int>& vec) {
  std::vector<std::future<int>> futures;
  for (const auto& x : vec) {
    futures.push_back(std::async(std::launch::async, func, x));
  }
  for (auto& f : futures) {
    f.get();
  }
}

void MemoryLeakTest()
{
  std::vector<int> vec(64, 12);

  _CrtMemState before;
  _CrtMemCheckpoint(&before);

  ParallelForEach(vec);

  _CrtMemState after;
  _CrtMemCheckpoint(&after);

  _CrtMemState leaked;
  if (_CrtMemDifference(&leaked, &before, &after) != 0) {
    std::cout << "Total bytes leaked: " << leaked.lTotalCount << std::endl;
  }
}

int main() {
  for (int i = 0; i < 10000; i++)
  {
    MemoryLeakTest();
  }
  return 0;
}

I tried std::for_each with parallel execution and this works without mem leak, but is not available in all targeted systems. I expect there to be a way/workaround to use std::future without Crt reporting false memory leaks.


问:
Seaborn kdeplot is not well fitted to my histogram
I'm using the kdeplot function of the seaborn package in python and I have a dataset called BH and the weight called MT of each value. Both variables are numpy arrays.

```<code>import seaborn as sns
import matplotlib.pyplot as plt
BH = np.array([141.19618068420274, 191.2406412961248, 346.01168490938585, 230.14257295050672, 185.01589850153252, 245.67488131757796, 175.6108949133985, 325.03739349020094, 379.41413332517686, 105.59295515652147 ])

MT = np.array([0.015004641668689452, 0.011144290004860507, 0.007974195145875648, 0.019437031417186952, 0.0036642005992589023, 0.0036642005992589023, 0.0036642005992589023,0.0036642005992589023, 0.0023554322266426775,0.0023554322266426775 ])

sns.kdeplot(x=BH, weights=MT, bw_adjust=0.2, log_scale=True, common_grid=True, bw_method='silverman')
plt.hist(BH, weights=MT, bins=np.logspace(2, 7.5, num=50), log=True, histtype='step', density=True)
plt.show()
</code>```

As you can see, the solid blue line is the kde plot and the orange line is the histogram. The problem is that the kde is 10 times large than the values of the histogram which clearly changes my results. Do you know how to fix this? I'm really new using seaborn.

Thanks,

Body:
I'm using the kdeplot function of the seaborn package in python and I have a dataset called BH and the weight called MT of each value. Both variables are numpy arrays.

import seaborn as sns
import matplotlib.pyplot as plt
BH = np.array([141.19618068420274, 191.2406412961248, 346.01168490938585, 230.14257295050672, 185.01589850153252, 245.67488131757796, 175.6108949133985, 325.03739349020094, 379.41413332517686, 105.59295515652147 ])

MT = np.array([0.015004641668689452, 0.011144290004860507, 0.007974195145875648, 0.019437031417186952, 0.0036642005992589023, 0.0036642005992589023, 0.0036642005992589023,0.0036642005992589023, 0.0023554322266426775,0.0023554322266426775 ])

sns.kdeplot(x=BH, weights=MT, bw_adjust=0.2, log_scale=True, common_grid=True, bw_method='silverman')
plt.hist(BH, weights=MT, bins=np.logspace(2, 7.5, num=50), log=True, histtype='step', density=True)
plt.show()

As you can see, the solid blue line is the kde plot and the orange line is the histogram. The problem is that the kde is 10 times large than the values of the histogram which clearly changes my results. Do you know how to fix this? I'm really new using seaborn.

Thanks,


问:
Error after migrating django database to postgresql
I have recently changed my database from sqlite3 in django to postgresql as I prepare my app for production. After making changes in settings.py, I have tried making migrations and I am getting an error. After running python manage.py migrate --run-syncdb
I get the error below in the terminal

```<code>System check identified some issues:

WARNINGS:
users.Document.uploaded_at: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
users.Order.amount: (fields.W122) 'max_length' is ignored when used with IntegerField.
        HINT: Remove 'max_length' from field
users.buyer.uploaded_at: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Operations to perform:
  Synchronize unmigrated apps: channels, chatapp, crispy_forms, messages, payments, staticfiles, users
  Apply all migrations: admin, auth, contenttypes, sessions
Synchronizing apps without migrations:
  Creating tables...
    Creating table users_user
    Creating table users_document
    Creating table users_buyer
    Creating table users_category
    Creating table users_service
    Creating table users_profile
    Creating table users_gig
    Creating table users_order
    Creating table users_product
    Running deferred SQL...
Traceback (most recent call last):
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "auth_group" does not exist

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 214, in handle
    self.sync_apps(connection, executor.loader.unmigrated_apps)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 353, in sync_apps
    self.stdout.write('    Running deferred SQL...')
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 118, in __exit__
    self.execute(sql)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 145, in execute
    cursor.execute(sql, params)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_group" does not exist
</code>```

In my models.py, I have used the AbstractUser model. And here is my database in settings.py

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'demo',
        'USER': 'demouser',
        'PASSWORD': '12345678',
        'HOST': 'localhost',
        'PORT': '',
    }
}
</code>```

Any help will be highly appreciated. Thanks.

Body:
I have recently changed my database from sqlite3 in django to postgresql as I prepare my app for production. After making changes in settings.py, I have tried making migrations and I am getting an error. After running python manage.py migrate --run-syncdb
I get the error below in the terminal

System check identified some issues:

WARNINGS:
users.Document.uploaded_at: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
users.Order.amount: (fields.W122) 'max_length' is ignored when used with IntegerField.
        HINT: Remove 'max_length' from field
users.buyer.uploaded_at: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Operations to perform:
  Synchronize unmigrated apps: channels, chatapp, crispy_forms, messages, payments, staticfiles, users
  Apply all migrations: admin, auth, contenttypes, sessions
Synchronizing apps without migrations:
  Creating tables...
    Creating table users_user
    Creating table users_document
    Creating table users_buyer
    Creating table users_category
    Creating table users_service
    Creating table users_profile
    Creating table users_gig
    Creating table users_order
    Creating table users_product
    Running deferred SQL...
Traceback (most recent call last):
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "auth_group" does not exist

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 214, in handle
    self.sync_apps(connection, executor.loader.unmigrated_apps)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 353, in sync_apps
    self.stdout.write('    Running deferred SQL...')
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 118, in __exit__
    self.execute(sql)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 145, in execute
    cursor.execute(sql, params)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/kiprono/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_group" does not exist

In my models.py, I have used the AbstractUser model. And here is my database in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'demo',
        'USER': 'demouser',
        'PASSWORD': '12345678',
        'HOST': 'localhost',
        'PORT': '',
    }
}

Any help will be highly appreciated. Thanks.


问:
Converting crypto to crypto-js script (AES-256-CFB)
Can you help me convert this script (node js crypto module ) to crypto-js. I've searched but haven't found a solution.

```<code>const crypto = require('crypto')
const encryptionKey = "8U8BKkTTyVLRy2ovQgAkRvqSgKLwz2Sg"
const message_to_encrypt = '123456'

const EncryptBase64AES = (text) => {
    const iv = crypto.randomBytes(16)
    const cipher = crypto.createCipheriv('aes-256-cfb', encryptionKey, iv)
    let encrypted = [iv, cipher.update(text, 'utf8')];
    encrypted.push(cipher.final());
    return Buffer.concat(encrypted).toString('base64url');
}

const DecryptBase64AES = (encrypted) => {
    const contents = Buffer.from(encrypted, 'base64url');
    const iv = contents.subarray(0,16)
    const textBytes = contents.subarray(16);
    const decipher = crypto.createDecipheriv('aes-256-cfb', encryptionKey, iv)
    let res = decipher.update(textBytes, '', 'utf8');
    res += decipher.final('utf8');
    return res;
}

console.log(EncryptBase64AES(message_to_encrypt))
console.log(DecryptBase64AES(EncryptBase64AES(message_to_encrypt)))
</code>```

I have used this script (crypto for encrypting) and crypto-js for decrypting, but cannot decrypting

```<code>
const CryptoJS = require('crypto-js')
const crypto = require('crypto')
const CRYPTO_IV_LENGTH = 16
const encryptionKey = "8U8BKkTTyVLRy2ovQgAkRvqSgKLwz2Sg"
const message_to_encrypt = '123456'

const EncryptBase64AES2 = (text) => {
    const iv  = CryptoJS.lib.WordArray.random(16);
    const encrypted = CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(encryptionKey), {
        iv:iv,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.Pkcs7
    })
    return CryptoJS.enc.Base64url.stringify(encrypted.ciphertext)
}

const DecryptBase64AES2 = (encrypted) => {
    const contents = Buffer.from(encrypted, 'base64url');
    const iv = contents.subarray(0,16)
    const textBytes = contents.subarray(16);
    const decipher = crypto.createDecipheriv('aes-256-cfb', encryptionKey, iv)
    let res = decipher.update(textBytes, '', 'utf8');
    res += decipher.final('utf8');
    return res;
}

console.log(EncryptBase64AES2(message_to_encrypt))
console.log(DecryptBase64AES2(EncryptBase64AES2(message_to_encrypt)))
</code>```

Body:
Can you help me convert this script (node js crypto module ) to crypto-js. I've searched but haven't found a solution.

const crypto = require('crypto')
const encryptionKey = "8U8BKkTTyVLRy2ovQgAkRvqSgKLwz2Sg"
const message_to_encrypt = '123456'

const EncryptBase64AES = (text) => {
    const iv = crypto.randomBytes(16)
    const cipher = crypto.createCipheriv('aes-256-cfb', encryptionKey, iv)
    let encrypted = [iv, cipher.update(text, 'utf8')];
    encrypted.push(cipher.final());
    return Buffer.concat(encrypted).toString('base64url');
}

const DecryptBase64AES = (encrypted) => {
    const contents = Buffer.from(encrypted, 'base64url');
    const iv = contents.subarray(0,16)
    const textBytes = contents.subarray(16);
    const decipher = crypto.createDecipheriv('aes-256-cfb', encryptionKey, iv)
    let res = decipher.update(textBytes, '', 'utf8');
    res += decipher.final('utf8');
    return res;
}

console.log(EncryptBase64AES(message_to_encrypt))
console.log(DecryptBase64AES(EncryptBase64AES(message_to_encrypt)))

I have used this script (crypto for encrypting) and crypto-js for decrypting, but cannot decrypting

const CryptoJS = require('crypto-js')
const crypto = require('crypto')
const CRYPTO_IV_LENGTH = 16
const encryptionKey = "8U8BKkTTyVLRy2ovQgAkRvqSgKLwz2Sg"
const message_to_encrypt = '123456'

const EncryptBase64AES2 = (text) => {
    const iv  = CryptoJS.lib.WordArray.random(16);
    const encrypted = CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(encryptionKey), {
        iv:iv,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.Pkcs7
    })
    return CryptoJS.enc.Base64url.stringify(encrypted.ciphertext)
}

const DecryptBase64AES2 = (encrypted) => {
    const contents = Buffer.from(encrypted, 'base64url');
    const iv = contents.subarray(0,16)
    const textBytes = contents.subarray(16);
    const decipher = crypto.createDecipheriv('aes-256-cfb', encryptionKey, iv)
    let res = decipher.update(textBytes, '', 'utf8');
    res += decipher.final('utf8');
    return res;
}

console.log(EncryptBase64AES2(message_to_encrypt))
console.log(DecryptBase64AES2(EncryptBase64AES2(message_to_encrypt)))


问:
Sort pagination
Basically I want to sort them based on the highest - lowest avg rating but I can't do it since I've already fetched the data (paginate(12)).

Adding sortBy in the if else section is not possible since I do not have yet the avg_rating data. I tried it after foreach but keeps throwing error.

Any workarounds here so I can dynamically sort it out?

```<code>public function render()
    {
        $recipe_default = Recipe::where('is_approved', 1);
        if(is_null($this->name_atoz))
        {
            $recipe_default = $recipe_default->orderBy('id', 'asc')->paginate(12);
        }
        elseif($this->name_atoz == true)
        {
            $recipe_default = $recipe_default->orderBy('recipe_name')->paginate(12);
        }
        elseif($this->name_atoz == false)
        {
            $recipe_default = $recipe_default->orderBy('recipe_name', 'desc')->paginate(12);
        }

        foreach($recipe_default as $key => $value)
        {
            $recipe_default[$key]->avg_rating = Feedback::where('recipe_id', $value->id)->avg('rating');

            $recipe_default[$key]->feedback_count = Feedback::where('recipe_id', $value->id)->count();

            $recipe_default[$key]->tag_name = Taggable::where('taggable_id', $value->id)->where('taggable_type', 'recipe')->value('tag_name');
        }

        return view('livewire.content-management', [
            'recipes' => $recipe_default
        ]);
    }

</code>```

Title: Sort pagination

Body:
Basically I want to sort them based on the highest - lowest avg rating but I can't do it since I've already fetched the data (paginate(12)).

Adding sortBy in the if else section is not possible since I do not have yet the avg_rating data. I tried it after foreach but keeps throwing error.

Any workarounds here so I can dynamically sort it out?

public function render()
    {
        $recipe_default = Recipe::where('is_approved', 1);
        if(is_null($this->name_atoz))
        {
            $recipe_default = $recipe_default->orderBy('id', 'asc')->paginate(12);
        }
        elseif($this->name_atoz == true)
        {
            $recipe_default = $recipe_default->orderBy('recipe_name')->paginate(12);
        }
        elseif($this->name_atoz == false)
        {
            $recipe_default = $recipe_default->orderBy('recipe_name', 'desc')->paginate(12);
        }

        foreach($recipe_default as $key => $value)
        {
            $recipe_default[$key]->avg_rating = Feedback::where('recipe_id', $value->id)->avg('rating');

            $recipe_default[$key]->feedback_count = Feedback::where('recipe_id', $value->id)->count();

            $recipe_default[$key]->tag_name = Taggable::where('taggable_id', $value->id)->where('taggable_type', 'recipe')->value('tag_name');
        }

        return view('livewire.content-management', [
            'recipes' => $recipe_default
        ]);
    }


问:
Python/Tkinter: loading a PhotoImage from within a class
The following code defines a custom tkinter button as a class. The class includes a .png image file which sits in the button. If I load the png file within the main application and pass it to this class, it displays correctly. However, as you can see in this code, I would rather have the class load the image itself. However, this does not work. I get the 'no such file or directory' error message. Note that the png image file is in the same folder as the class document, so I can see no reason why it shouldn't work. But it doesn't.

```<code>import tkinter as tk

class MyButton(tk.Button):
  def __init__(self,master,placecol,placerow,btntext):
    super().__init__(master)

    # initialize instance variables
    self.master = master
    self.placecol = placecol
    self.placerow = placerow
    self.btntext = btntext

    # load button image
    btnimage = tk.PhotoImage(file="GreenButton.png")

    # set parameters based on instance variables
    self.configure(text=btntext)
    self.place(x=placecol,y=placerow)
    self.image = btnimage
    self.configure(image=btnimage)

    # set additional parameters
    self.configure(borderwidth=0)
    self.configure(fg="white")
    self.configure(bg="#2B2B2B")
    self.configure(activebackground="#2B2B2B")
    self.configure(activeforeground="white")
    self.configure(compound=tk.CENTER)
</code>```

Any advice appreciated.

Body:
The following code defines a custom tkinter button as a class. The class includes a .png image file which sits in the button. If I load the png file within the main application and pass it to this class, it displays correctly. However, as you can see in this code, I would rather have the class load the image itself. However, this does not work. I get the 'no such file or directory' error message. Note that the png image file is in the same folder as the class document, so I can see no reason why it shouldn't work. But it doesn't.

import tkinter as tk

class MyButton(tk.Button):
  def __init__(self,master,placecol,placerow,btntext):
    super().__init__(master)

    # initialize instance variables
    self.master = master
    self.placecol = placecol
    self.placerow = placerow
    self.btntext = btntext

    # load button image
    btnimage = tk.PhotoImage(file="GreenButton.png")

    # set parameters based on instance variables
    self.configure(text=btntext)
    self.place(x=placecol,y=placerow)
    self.image = btnimage
    self.configure(image=btnimage)

    # set additional parameters
    self.configure(borderwidth=0)
    self.configure(fg="white")
    self.configure(bg="#2B2B2B")
    self.configure(activebackground="#2B2B2B")
    self.configure(activeforeground="white")
    self.configure(compound=tk.CENTER)

Any advice appreciated.


问:
Is it legal to cast function pointers?

Possible Duplicate:

  Casting a function pointer to another type

```<code>int primes[] = {11, 5, 3, 7, 19, 13, 2, 17};
int comp(const int*, const int*);
qsort(primes, 8, sizeof(int), (int(*)(const void*, const void*))comp);
</code>```

Is the cast in the third line legal? Or must comp take const void* arguments and do the cast inside?

ContentLicense: CC BY-SA 3.0

Title: Is it legal to cast function pointers?

Body:
Possible Duplicate:

  Casting a function pointer to another type

int primes[] = {11, 5, 3, 7, 19, 13, 2, 17};
int comp(const int*, const int*);
qsort(primes, 8, sizeof(int), (int(*)(const void*, const void*))comp);

Is the cast in the third line legal? Or must comp take const void* arguments and do the cast inside?


问:
I was coding a music bot for me and my friends when i found this error
The error was -> discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceState' object has no attribute 'play'

Here is the code that gave me the error

```<code> vc = ctx.author.voice
    if vc:
        await vc.channel.connect()

        vc.play(discord.FFmpegPCMAudio(f"{video_info['title']}.mp3"))
</code>```

I searched through stackoverflow to find the answer, but nothing was working .

Body:
The error was -> discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceState' object has no attribute 'play'

Here is the code that gave me the error

 vc = ctx.author.voice
    if vc:
        await vc.channel.connect()

        vc.play(discord.FFmpegPCMAudio(f"{video_info['title']}.mp3"))

I searched through stackoverflow to find the answer, but nothing was working .


问:
Is there a way to wrap the elements of a variadic type in Python?
Here's a trivial example of what I'm looking for. Suppose you want a function that returns an iterable of the same type as x for each argument x to the function. So without type signatures, it looks like this;

```<code>def trivial(*args):
    return tuple([[arg] for arg in args])
</code>```

How would I type a function like this? Is this supported?

Body:
Here's a trivial example of what I'm looking for. Suppose you want a function that returns an iterable of the same type as x for each argument x to the function. So without type signatures, it looks like this;

def trivial(*args):
    return tuple([[arg] for arg in args])

How would I type a function like this? Is this supported?


问:
Syntax error when creating tables using SQlite3
I can't seem to find the syntax error IDLE seems to be pointing in this code. The error says that it is found near 'transaction'.

```<code>import sqlite3
from sqlite3 import Error

def Create_Tables():
    #Goes through the array of variables and executes the
    #SQL stored in them
    for i in range (len(dbTables)):
        c.execute(dbTables[i])
        print(dbTables[i])

def DB_Conn():
    global c

    conn = None
    try:
        conn = sqlite3.connect('MM.db')
        print('connected')
        c = conn.cursor()
    except Error as e:
        print(e)

    Create_Tables()

#SQL stored in variables
custTable = ''' CREATE TABLE IF NOT EXISTS customer(
                    custID text PRIMARY KEY,
                    fname text,
                    lname  text,
                    dob text,
                    email text,
                    password text,
                    phoneNum text,
                    address text,
                    postcode text); '''

staffTable = ''' CREATE TABLE IF NOT EXISTS staff(
                    staffID text PRIMARY KEY,
                    fname text,
                    lname  text,
                    dob text,
                    email text,
                    password text,
                    phoneNum text,
                    address text,
                    postcode text,
                    jobTitle text); '''

productTable = ''' CREATE TABLE IF NOT EXISTS product(
                        productID text PRIMARY KEY,
                        productName text,
                        category text,
                        dateAdded text,
                        brand text,
                        material text,
                        condition text,
                        key text,
                        description text,
                        price real,
                        stockLevel integer);'''

cardTable = ''' CREATE TABLE IF NOT EXISTS card(
                    permanentAccountNumber text PRIMARY KEY,
                    expiryDate text,
                    CVV text,
                    custID text,
                    FOREIGN KEY (custID) REFERENCES customer(custID));'''

transactionTable = '''CREATE TABLE IF NOT EXISTS transaction(
                    transactionID text PRIMARY KEY,
                    purchaseDate text,
                    permanentAccountNumber text,
                    FOREIGN KEY (permanentAccountNumber) REFERENCES card(permanentAccountNumber));'''

orderTable = ''' CREATE TABLE IF NOT EXISTS order(
                    orderID text PRIMARY KEY,
                    deliveryStatus text,
                    deliveryDate text,
                    numItems integer,
                    totalCost real,
                    transactionID text,
                    FOREIGN KEY (transactionID)REFERENCES transaction(transactionID));'''

productOrder = ''' CREATE TABLE IF NOT EXISTS productOrder(
                                productID text,
                                orderID text,
                                PRIMARY KEY (productID, orderID));'''

reviewTable = ''' CREATE TABLE IF NOT EXISTS review(
                    reviewID text PRIMARY KEY,
                    productID text,
                    FOREIGN KEY(productID) REFERENCES product(productID),
                    FOREIGN KEY(custID) REFERENCES customer(custID));'''

#Array to be used when creating tables
dbTables = [custTable, staffTable, productTable, cardTable, transactionTable,
            productOrder, orderTable, reviewTable]
</code>```

Result: sqlite3.OperationalError: near "transaction": syntax error

I have checked the SQL and it seems fine. The function is able to create every table apart from transaction, order and review.  What could be the syntax error?

Body:
I can't seem to find the syntax error IDLE seems to be pointing in this code. The error says that it is found near 'transaction'.

import sqlite3
from sqlite3 import Error

def Create_Tables():
    #Goes through the array of variables and executes the
    #SQL stored in them
    for i in range (len(dbTables)):
        c.execute(dbTables[i])
        print(dbTables[i])

def DB_Conn():
    global c

    conn = None
    try:
        conn = sqlite3.connect('MM.db')
        print('connected')
        c = conn.cursor()
    except Error as e:
        print(e)

    Create_Tables()

#SQL stored in variables
custTable = ''' CREATE TABLE IF NOT EXISTS customer(
                    custID text PRIMARY KEY,
                    fname text,
                    lname  text,
                    dob text,
                    email text,
                    password text,
                    phoneNum text,
                    address text,
                    postcode text); '''

staffTable = ''' CREATE TABLE IF NOT EXISTS staff(
                    staffID text PRIMARY KEY,
                    fname text,
                    lname  text,
                    dob text,
                    email text,
                    password text,
                    phoneNum text,
                    address text,
                    postcode text,
                    jobTitle text); '''

productTable = ''' CREATE TABLE IF NOT EXISTS product(
                        productID text PRIMARY KEY,
                        productName text,
                        category text,
                        dateAdded text,
                        brand text,
                        material text,
                        condition text,
                        key text,
                        description text,
                        price real,
                        stockLevel integer);'''

cardTable = ''' CREATE TABLE IF NOT EXISTS card(
                    permanentAccountNumber text PRIMARY KEY,
                    expiryDate text,
                    CVV text,
                    custID text,
                    FOREIGN KEY (custID) REFERENCES customer(custID));'''

transactionTable = '''CREATE TABLE IF NOT EXISTS transaction(
                    transactionID text PRIMARY KEY,
                    purchaseDate text,
                    permanentAccountNumber text,
                    FOREIGN KEY (permanentAccountNumber) REFERENCES card(permanentAccountNumber));'''

orderTable = ''' CREATE TABLE IF NOT EXISTS order(
                    orderID text PRIMARY KEY,
                    deliveryStatus text,
                    deliveryDate text,
                    numItems integer,
                    totalCost real,
                    transactionID text,
                    FOREIGN KEY (transactionID)REFERENCES transaction(transactionID));'''

productOrder = ''' CREATE TABLE IF NOT EXISTS productOrder(
                                productID text,
                                orderID text,
                                PRIMARY KEY (productID, orderID));'''

reviewTable = ''' CREATE TABLE IF NOT EXISTS review(
                    reviewID text PRIMARY KEY,
                    productID text,
                    FOREIGN KEY(productID) REFERENCES product(productID),
                    FOREIGN KEY(custID) REFERENCES customer(custID));'''

#Array to be used when creating tables
dbTables = [custTable, staffTable, productTable, cardTable, transactionTable,
            productOrder, orderTable, reviewTable]

Result: sqlite3.OperationalError: near "transaction": syntax error

I have checked the SQL and it seems fine. The function is able to create every table apart from transaction, order and review.  What could be the syntax error?


问:
Timezone doesn't seem to be converting probably
I'm trying to make a function that can convert one timezone to another timezone.

```<code>def SetTimezone(TimezoneIn, TimezoneOut, year, month, day, hours, minutes, seconds):
  local = pytz.timezone(TimezoneOut)
  naive = datetime.strptime(f"{year}-{month}-{day} {hours}:{minutes}:{seconds}", "%Y-%m-%d %H:%M:%S")
  local_dt = local.localize(naive, is_dst=None)
  utc_dt = local_dt.astimezone(getattr(pytz, TimezoneIn))
  print("utc_dt:", utc_dt)

SetTimezone("utc", "America/Los_Angeles", 2022, 12, 16, 23, 21, 45)
</code>```

The time is supposed to be 3:21 PM, 45 seconds in, on December 16th 2022. However, the output is instead returning as this:

utc_dt: 2022-12-17 07:21:45+00.00

Tried checking the UTC timezone in 24-hour time and it was 23:21:45 as I put into the arguments correctly. I don't know if this is important, but this code is for a Discord bot that will have a command that can convert timezones. Does anyone know why this problem is happening or, better yet, a more efficient way to convert timezones easily?

Body:
I'm trying to make a function that can convert one timezone to another timezone.

def SetTimezone(TimezoneIn, TimezoneOut, year, month, day, hours, minutes, seconds):
  local = pytz.timezone(TimezoneOut)
  naive = datetime.strptime(f"{year}-{month}-{day} {hours}:{minutes}:{seconds}", "%Y-%m-%d %H:%M:%S")
  local_dt = local.localize(naive, is_dst=None)
  utc_dt = local_dt.astimezone(getattr(pytz, TimezoneIn))
  print("utc_dt:", utc_dt)

SetTimezone("utc", "America/Los_Angeles", 2022, 12, 16, 23, 21, 45)

The time is supposed to be 3:21 PM, 45 seconds in, on December 16th 2022. However, the output is instead returning as this:

utc_dt: 2022-12-17 07:21:45+00.00

Tried checking the UTC timezone in 24-hour time and it was 23:21:45 as I put into the arguments correctly. I don't know if this is important, but this code is for a Discord bot that will have a command that can convert timezones. Does anyone know why this problem is happening or, better yet, a more efficient way to convert timezones easily?


问:
How do I render a svg as a mesh in three js
Im trying to render a SVG file as a mesh using SVGLoader in my three js application, but its not working

I followed the documentation to the SVGLoader step by step but still nothing

here is the documentation : https://threejs.org/docs/index.html?q=svg#examples/en/loaders/SVGLoader

and here is my code that i've tried :

```<code>    const loader = new SVGLoader();
    const group = new Group();
    loader.load(
      "../public/assets/svg/logo.svg",
      function (data) {
        const paths = data.paths;

        for (let i = 0; i < paths.length; i++) {
          const path = paths[i];

          const material = new MeshBasicMaterial({
            color: path.color,
            side: DoubleSide,
            depthWrite: false,
          });

          const shapes = SVGLoader.createShapes(path);

          for (let j = 0; j < shapes.length; j++) {
            const shape = shapes[j];
            const geometry = new ShapeGeometry(shape);
            const mesh = new Mesh(geometry, material);
            group.add(mesh);
          }
        }
      },
      function (xhr) {
        console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
      },
      function (error) {
        console.log("An error happened", error);
      }
    );

    scene.add(group);
</code>```

Im not getting any error messages when I run my code.

Body:
Im trying to render a SVG file as a mesh using SVGLoader in my three js application, but its not working

I followed the documentation to the SVGLoader step by step but still nothing

here is the documentation : https://threejs.org/docs/index.html?q=svg#examples/en/loaders/SVGLoader

and here is my code that i've tried :

    const loader = new SVGLoader();
    const group = new Group();
    loader.load(
      "../public/assets/svg/logo.svg",
      function (data) {
        const paths = data.paths;

        for (let i = 0; i < paths.length; i++) {
          const path = paths[i];

          const material = new MeshBasicMaterial({
            color: path.color,
            side: DoubleSide,
            depthWrite: false,
          });

          const shapes = SVGLoader.createShapes(path);

          for (let j = 0; j < shapes.length; j++) {
            const shape = shapes[j];
            const geometry = new ShapeGeometry(shape);
            const mesh = new Mesh(geometry, material);
            group.add(mesh);
          }
        }
      },
      function (xhr) {
        console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
      },
      function (error) {
        console.log("An error happened", error);
      }
    );

    scene.add(group);

Im not getting any error messages when I run my code.


问:
Can fluentbit forward fluentbit_metrics as plain text instead of a JSON object to a port?
I am trying to send fluentbit metrics to an external source for processing. My understanding from the documentation is that the fluentbit_metrics input is intended to be used with output plugins that are for specific telemetry solutions like Prometheus, OpenTelemetry, etc. However, for my purposes, I cannot actually use any of those solutions and instead have to use a different bespoke metrics solution. For this to work, I would like to just send lines of text to a port that my metrics solution is listening on.

I am trying to use the fluentbit forward output to send data to this endpoint, but I am getting an error in response from my metrics solution because it is receiving a big JSON object which it can't parse. However, when I output the same fluentbit_metrics input to a file or to stdout, the contents of the file is more like what I would expect, where each metric is just a line of text. If these text lines were what was being sent to my metrics endpoint, I wouldn't have any issue ingesting them.

I know that I could take on the work to change my metrics solution to parse and process this JSON map, but before I do that, I wanted to check if this is the only way forward for me. So, my question is, is there a way to get fluentbit to send fluentbit_metrics to a forward output where it does not convert the metrics into a big JSON object? Is the schema for that JSON object specific to prometheus? Is there a reason why the outputs differ so substantially?

Here is a copy of an example config I am using with fluentbit:

```<code>[SERVICE]
    # This is a commented line
    Daemon    off
    log_level info
    log_file C:\MyFolder\fluentlog.txt
    flush 1
    parsers_file    .\parsers.conf

[INPUT]
    name            fluentbit_metrics
    tag             internal_metrics
    scrape_interval 2

[OUTPUT]
    Name          forward
    Match         internal_metrics
    Host          127.0.0.1
    Port          28232
    tag           internal_metrics
    Time_as_Integer true

[OUTPUT]
    name  stdout
    match *
</code>```

And here is the output from the forward output plugin:

```<code>{
    "meta": {
        "cmetrics": {},
        "external": {},
        "processing": {
            "static_labels": []
        }
    },
    "metrics": [
        {
            "meta": {
                "ver": 2,
                "type": 0,
                "opts": {
                    "ns": "fluentbit",
                    "ss": "",
                    "name": "uptime",
                    "desc": "Number of seconds that Fluent Bit has been running."
                },
                "labels": [
                    "hostname"
                ],
                "aggregation_type": 2
            },
            "values": [
                {
                    "ts": 1670884364820306500,
                    "value": 22,
                    "labels": [
                        "myHostName"
                    ],
                    "hash": 16603984480778988994
                }
            ]
        }, etc.
</code>```

and here is the output of the same metrics from stdout:

```<code>2022-12-12T22:02:13.444100300Z fluentbit_uptime{hostname="myHostName"} = 2
2022-12-12T22:02:11.721859000Z fluentbit_input_bytes_total{name="tail.0"} = 1138
2022-12-12T22:02:11.721859000Z fluentbit_input_records_total{name="tail.0"} = 12
2022-12-12T22:02:11.444943400Z fluentbit_input_files_opened_total{name="tail.0"} = 1
</code>```

Body:
I am trying to send fluentbit metrics to an external source for processing. My understanding from the documentation is that the fluentbit_metrics input is intended to be used with output plugins that are for specific telemetry solutions like Prometheus, OpenTelemetry, etc. However, for my purposes, I cannot actually use any of those solutions and instead have to use a different bespoke metrics solution. For this to work, I would like to just send lines of text to a port that my metrics solution is listening on.

I am trying to use the fluentbit forward output to send data to this endpoint, but I am getting an error in response from my metrics solution because it is receiving a big JSON object which it can't parse. However, when I output the same fluentbit_metrics input to a file or to stdout, the contents of the file is more like what I would expect, where each metric is just a line of text. If these text lines were what was being sent to my metrics endpoint, I wouldn't have any issue ingesting them.

I know that I could take on the work to change my metrics solution to parse and process this JSON map, but before I do that, I wanted to check if this is the only way forward for me. So, my question is, is there a way to get fluentbit to send fluentbit_metrics to a forward output where it does not convert the metrics into a big JSON object? Is the schema for that JSON object specific to prometheus? Is there a reason why the outputs differ so substantially?

Here is a copy of an example config I am using with fluentbit:

[SERVICE]
    # This is a commented line
    Daemon    off
    log_level info
    log_file C:\MyFolder\fluentlog.txt
    flush 1
    parsers_file    .\parsers.conf

[INPUT]
    name            fluentbit_metrics
    tag             internal_metrics
    scrape_interval 2

[OUTPUT]
    Name          forward
    Match         internal_metrics
    Host          127.0.0.1
    Port          28232
    tag           internal_metrics
    Time_as_Integer true

[OUTPUT]
    name  stdout
    match *

And here is the output from the forward output plugin:

{
    "meta": {
        "cmetrics": {},
        "external": {},
        "processing": {
            "static_labels": []
        }
    },
    "metrics": [
        {
            "meta": {
                "ver": 2,
                "type": 0,
                "opts": {
                    "ns": "fluentbit",
                    "ss": "",
                    "name": "uptime",
                    "desc": "Number of seconds that Fluent Bit has been running."
                },
                "labels": [
                    "hostname"
                ],
                "aggregation_type": 2
            },
            "values": [
                {
                    "ts": 1670884364820306500,
                    "value": 22,
                    "labels": [
                        "myHostName"
                    ],
                    "hash": 16603984480778988994
                }
            ]
        }, etc.

and here is the output of the same metrics from stdout:

2022-12-12T22:02:13.444100300Z fluentbit_uptime{hostname="myHostName"} = 2
2022-12-12T22:02:11.721859000Z fluentbit_input_bytes_total{name="tail.0"} = 1138
2022-12-12T22:02:11.721859000Z fluentbit_input_records_total{name="tail.0"} = 12
2022-12-12T22:02:11.444943400Z fluentbit_input_files_opened_total{name="tail.0"} = 1


问:
Updating table with COALESCE and JOIN PostgreSQL
My data set is a list of house sales. I am trying to update the address column so that any NULL values get replaced with an actual address. I am getting these replacement addresses from other inputs within the data. There are other sales of the same house so they share a "parcelid". I am doing an UPDATE with COALESCE and an INNER JOIN to complete the task. I am doing so with this code.

UPDATE house
SET property_address =
    COALESCE(house1.property_address,house2.property_address)
FROM house AS house1
JOIN house AS house2
    ON house1.parcelid = house2.parcelid
    AND house1.uniqueid != house2.uniqueid
WHERE house1.property_address IS NULL```
</div>
</div>
</p>
<p>When I look at my 'house' table though, every single entry in the 'property_address' line has been updated to the same address. When I did some digging that address is the first address that occurs when I look at the join with this code.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>SELECT
    house1.parcelid,
    house2.parcelid,
    house1.property_address,
    house2.property_address,
    COALESCE(house1.property_address,house2.property_address)
FROM house AS house1
JOIN house AS house2
    ON house1.parcelid = house2.parcelid
    AND house1.uniqueid != house2.uniqueid
WHERE house1.property_address IS NULL</code>```

How to I get it to one ignore any addresses that are not null and two update to the appropriate address and not just keep copying the same address. Thanks for the help. (This is my first time asking a question here so any pointers on how to properly format would be appreciated)

Body:
My data set is a list of house sales. I am trying to update the address column so that any NULL values get replaced with an actual address. I am getting these replacement addresses from other inputs within the data. There are other sales of the same house so they share a "parcelid". I am doing an UPDATE with COALESCE and an INNER JOIN to complete the task. I am doing so with this code.

UPDATE house
SET property_address =
    COALESCE(house1.property_address,house2.property_address)
FROM house AS house1
JOIN house AS house2
    ON house1.parcelid = house2.parcelid
    AND house1.uniqueid != house2.uniqueid
WHERE house1.property_address IS NULL

When I look at my 'house' table though, every single entry in the 'property_address' line has been updated to the same address. When I did some digging that address is the first address that occurs when I look at the join with this code.

SELECT
    house1.parcelid,
    house2.parcelid,
    house1.property_address,
    house2.property_address,
    COALESCE(house1.property_address,house2.property_address)
FROM house AS house1
JOIN house AS house2
    ON house1.parcelid = house2.parcelid
    AND house1.uniqueid != house2.uniqueid
WHERE house1.property_address IS NULL

How to I get it to one ignore any addresses that are not null and two update to the appropriate address and not just keep copying the same address. Thanks for the help. (This is my first time asking a question here so any pointers on how to properly format would be appreciated)


问:
How are scale-in actions for custom auto-scale condition in Azure App Service aggregated when we have multiple scale in actions?
I have an Azure App Service with the scale-out option set to custom auto-scale. In my custom auto-scale, I have two scale-in rules with different actions if they apply. One will "Decrease count by 1, cool-down 5 min" and one will "Decrease count by 2, cool-down 5 min".

Since both scale-in rules should apply for scale-in to take place, which operation will apply? "Decrease count by 1", "Decrease count by 2", or a certain aggregation of them?

Here is a screenshot of the scale-out configuration

In my trial, I started with three instances and gave it some time. The instances count is first scaled to 2 and then 1. Even though it suggests that the rule "Decrease count by 1" is selected, is that really the case? how are those actions for scale-in rules aggregated?


问:
Prevent Alexa Skill Timeout on Lock Screen
I’ve created an Alexa skill using Python sdk and lambda as endpoint. Lambda retrieves some data from API and Alexa reads data. Sometimes data read takes 2-3 minutes. Everything works fine on my echo but on Alexa mobile app if the screen dims then locks Alexa shuts off. I know I can increase screen lock timeout on mobile but is there anything on Alexa app or SDK to prevent screen timeout while a response is given? Somehow this is done for other audio but I’m guessing it’s because it plays a audio file. Thanks</p>


问:
Cropping image from Camera to Cameraoverlay Size - Flutter
I am attempting to take an image from the phone camera using flutter which has a square center overlay as widget above the camerapreview as a "focus area" (see picture: https://i.stack.imgur.com/vHpYz.jpg)  and crop just the focus part. So basically punching a square out of the image where the square is located. This of course will be done across different devices with different screen sized/resolutions as well as presumably image resolutions that come from the camera.

I have tried everything I can think of but simply can't figure out the code to properly crop the image resulting from the camera capture.

Here is my code:

The code for the camera overlay which lays atop the CameraPreviewWidget

```<code>Widget cameraOverlay(
    {required double padding,
    required double aspectRatio,
    required Color color,
    required Function disposeFunction,
    required CameraController cameraController}) {
  return LayoutBuilder(builder: (context, constraints) {
    double parentAspectRatio = constraints.maxWidth / constraints.maxHeight;
    double horizontalPadding;
    double verticalPadding;

    if (parentAspectRatio < aspectRatio) {
      horizontalPadding = padding;
      verticalPadding = (constraints.maxHeight -
              ((constraints.maxWidth - 2 * padding) / aspectRatio)) /
          2;
    } else {
      verticalPadding = padding;
      horizontalPadding = (constraints.maxWidth -
              ((constraints.maxHeight - 2 * padding) * aspectRatio)) /
          2;
    }

    return Stack(fit: StackFit.expand, children: [
      Align(
          alignment: Alignment.centerLeft,
          child: Container(width: horizontalPadding, color: color)),
      Align(
          alignment: Alignment.centerRight,
          child: Container(width: horizontalPadding, color: color)),
      Align(
          alignment: Alignment.topCenter,
          child: Container(
              margin: EdgeInsets.only(
                  left: horizontalPadding, right: horizontalPadding),
              height: verticalPadding,
              color: color)),
      Align(
          alignment: Alignment.bottomCenter,
          child: Container(
              margin: EdgeInsets.only(
                  left: horizontalPadding, right: horizontalPadding),
              height: verticalPadding,
              color: color)),
      Container(
        margin: EdgeInsets.symmetric(
            horizontal: horizontalPadding, vertical: verticalPadding),
        decoration: BoxDecoration(border: Border.all(color: Colors.cyan)),
      )
    ]);
  });
}
</code>```

I then place this overlay above the camerapreviewwidget from the flutter camera package as such:

```<code>return SafeArea(
        child: Scaffold(
      body: Stack(children: [
        (_cameraController!.value.isInitialized)
            ? _cameraPreviewWidget()
            : Container(
                color: Colors.black,
                child: const Center(child: CircularProgressIndicator()),
              ),
        cameraOverlay(
            padding: (MediaQuery.of(context).size.width) * 0.2,
            aspectRatio: 1,
            color: Color(0x55000000),
            disposeFunction: dispose,
            cameraController: _cameraController!),
</code>```

After capturing the image I would then like to center crop leaving me an image that corresponds to the square overlay.

I am currently attempting to achieve this with the copyCrop function of the flutter image package (documentation: https://pub.dev/documentation/image/latest/image/copyCrop.html) However I am unable to figure out how I would programatically get the required x,y,w,h for the crop.

Any ideas?

Body:
I am attempting to take an image from the phone camera using flutter which has a square center overlay as widget above the camerapreview as a "focus area" (see picture: https://i.stack.imgur.com/vHpYz.jpg)  and crop just the focus part. So basically punching a square out of the image where the square is located. This of course will be done across different devices with different screen sized/resolutions as well as presumably image resolutions that come from the camera.

I have tried everything I can think of but simply can't figure out the code to properly crop the image resulting from the camera capture.

Here is my code:

The code for the camera overlay which lays atop the CameraPreviewWidget

Widget cameraOverlay(
    {required double padding,
    required double aspectRatio,
    required Color color,
    required Function disposeFunction,
    required CameraController cameraController}) {
  return LayoutBuilder(builder: (context, constraints) {
    double parentAspectRatio = constraints.maxWidth / constraints.maxHeight;
    double horizontalPadding;
    double verticalPadding;

    if (parentAspectRatio < aspectRatio) {
      horizontalPadding = padding;
      verticalPadding = (constraints.maxHeight -
              ((constraints.maxWidth - 2 * padding) / aspectRatio)) /
          2;
    } else {
      verticalPadding = padding;
      horizontalPadding = (constraints.maxWidth -
              ((constraints.maxHeight - 2 * padding) * aspectRatio)) /
          2;
    }

    return Stack(fit: StackFit.expand, children: [
      Align(
          alignment: Alignment.centerLeft,
          child: Container(width: horizontalPadding, color: color)),
      Align(
          alignment: Alignment.centerRight,
          child: Container(width: horizontalPadding, color: color)),
      Align(
          alignment: Alignment.topCenter,
          child: Container(
              margin: EdgeInsets.only(
                  left: horizontalPadding, right: horizontalPadding),
              height: verticalPadding,
              color: color)),
      Align(
          alignment: Alignment.bottomCenter,
          child: Container(
              margin: EdgeInsets.only(
                  left: horizontalPadding, right: horizontalPadding),
              height: verticalPadding,
              color: color)),
      Container(
        margin: EdgeInsets.symmetric(
            horizontal: horizontalPadding, vertical: verticalPadding),
        decoration: BoxDecoration(border: Border.all(color: Colors.cyan)),
      )
    ]);
  });
}

I then place this overlay above the camerapreviewwidget from the flutter camera package as such:

return SafeArea(
        child: Scaffold(
      body: Stack(children: [
        (_cameraController!.value.isInitialized)
            ? _cameraPreviewWidget()
            : Container(
                color: Colors.black,
                child: const Center(child: CircularProgressIndicator()),
              ),
        cameraOverlay(
            padding: (MediaQuery.of(context).size.width) * 0.2,
            aspectRatio: 1,
            color: Color(0x55000000),
            disposeFunction: dispose,
            cameraController: _cameraController!),

After capturing the image I would then like to center crop leaving me an image that corresponds to the square overlay.

I am currently attempting to achieve this with the copyCrop function of the flutter image package (documentation: https://pub.dev/documentation/image/latest/image/copyCrop.html) However I am unable to figure out how I would programatically get the required x,y,w,h for the crop.

Any ideas?


问:
What is a good way to. mock api calls in VSCode Extensions tests?
My VSCode extension makes an api calls but I want to make sure it's not actually making that call when I'm running the test. I'm using the default testing stack when you initialize a VSCode repo with yo code.

I tried look around the docs but it seems like there's not a log of information in this area.


问:
Sending back map as part of responseObj comes back as empty map
In my code I loop through an array to populate a map with string keys and an array of js objects. The map gets filled fine as I can print its contents. My issue is that when I send back the object by placing it in a JS object (responseObj) my test returns that the obj is empty.
console.log

```<code>let memo:Map<string,{}[]> = new Map<string,{}[]>();
let total_row_count:number = 0;
for(let i = 0; i < assetLoadQuery.length; i++) {
    const arrayOfPerformanceResourceTiming:any[] = JSON.parse(assetLoadQuery[i].performanceResourceTimingJSON);
    console.log(arrayOfPerformanceResourceTiming);
    const viewID:string = assetLoadQuery[i].viewID.substring(assetLoadQuery[i].viewID.length-8);
    if(memo.has(viewID)) {
        const preconcat = memo.get(viewID);
        const concat = preconcat!.concat(arrayOfPerformanceResourceTiming);
        console.log(concat)
        memo.set(viewID, concat);
    } else {
        memo.set(viewID, arrayOfPerformanceResourceTiming);
    }
    total_row_count++;
}
console.log(memo);
const responseObj = {
    data: memo.entries(),
    meta: {
        message: "This endpoint is in development and is subject to change without warning",
    },
    total_tow_count: total_row_count,
}
return res.send(responseObj).status(200);
</code>```

Heres the expected and recieved objects

```<code>expected {
  data: Map(2) { '88888888' => [ [Object] ], '77777777' => [ [Object] ] },
  meta: {
    message: 'This endpoint is in development and is subject to change without warning'
  },
  total_row_count: 3
} response body, got {
  data: {},
  meta: {
    message: 'This endpoint is in development and is subject to change without warning'
  },
  total_tow_count: 3
}
</code>```

Body:
In my code I loop through an array to populate a map with string keys and an array of js objects. The map gets filled fine as I can print its contents. My issue is that when I send back the object by placing it in a JS object (responseObj) my test returns that the obj is empty.
console.log

let memo:Map<string,{}[]> = new Map<string,{}[]>();
let total_row_count:number = 0;
for(let i = 0; i < assetLoadQuery.length; i++) {
    const arrayOfPerformanceResourceTiming:any[] = JSON.parse(assetLoadQuery[i].performanceResourceTimingJSON);
    console.log(arrayOfPerformanceResourceTiming);
    const viewID:string = assetLoadQuery[i].viewID.substring(assetLoadQuery[i].viewID.length-8);
    if(memo.has(viewID)) {
        const preconcat = memo.get(viewID);
        const concat = preconcat!.concat(arrayOfPerformanceResourceTiming);
        console.log(concat)
        memo.set(viewID, concat);
    } else {
        memo.set(viewID, arrayOfPerformanceResourceTiming);
    }
    total_row_count++;
}
console.log(memo);
const responseObj = {
    data: memo.entries(),
    meta: {
        message: "This endpoint is in development and is subject to change without warning",
    },
    total_tow_count: total_row_count,
}
return res.send(responseObj).status(200);

Heres the expected and recieved objects

expected {
  data: Map(2) { '88888888' => [ [Object] ], '77777777' => [ [Object] ] },
  meta: {
    message: 'This endpoint is in development and is subject to change without warning'
  },
  total_row_count: 3
} response body, got {
  data: {},
  meta: {
    message: 'This endpoint is in development and is subject to change without warning'
  },
  total_tow_count: 3
}


问:
Flutter In_App_Purchase Error: Error [ERR_REQUIRE_ESM]: change require() of ES Module \node_modules\camelcase-keys\index.js to dynamic import()
I am trying to setup Flutter In_App_Purchase (The offical Flutter In_App_Purchase Package) and I run into a problem with the firebase-backend. Whenever I try to deploy it, I run into the following error:

Failed to load function definition from source: Failed to generate manifest from function source: Error
[ERR_REQUIRE_ESM]: require() of ES Module C:\Users\larak\Desktop\Fashionbook\FashionLookbook_FlutterIAP_Backend-IAP\firebase-backend\functions\node_modules\camelcase-keys\index.js from C:\Users\larak\Desktop\Fashionbook\FashionLookbook_FlutterIAP_Backend-IAP\firebase-backend\functions\lib\app-store.purchase-handler.js not supported.
Instead change the require of index.js in C:\Users\larak\Desktop\Fashionbook\FashionLookbook_FlutterIAP_Backend-IAP\firebase-backend\functions\lib\app-store.purchase-handler.js to a dynamic import() which is available in all CommonJS modules.

I think it's related to this line in app-store.purchase-handler.ts:

import camelCaseKeys from "firebase-backend/functions/scr/camelcase-keys";

Full example code here: https://github.com/flutter/codelabs/tree/master/in_app_purchases/complete/firebase-backend

I tried to change it as described in the error message, but I wasn't able to achieve it. I have zero experience with TypeScript. I'm a Flutter developer and I usually use Node.js with JavaScript.


问:
How to pass custom parameter to ssh-node connection?
I am using node-ssh library for ssh terminal connection.
Guessing if there is a way to pass a custom parameter, for example: "-t monitor".

ssh localhost -l steel -t monitor

Until now I can just pass the defined parameters in the object:

```<code>ssh.connect({
  host: 'localhost',
  username: 'steel',
  privateKey: Buffer.from('...')
})
</code>```

I am checking the examples in the github page but still don't know if at least is possible to pass custom options/parameters and how to achieve it.

Thanks in advance.

Body:
I am using node-ssh library for ssh terminal connection.
Guessing if there is a way to pass a custom parameter, for example: "-t monitor".

ssh localhost -l steel -t monitor

Until now I can just pass the defined parameters in the object:

ssh.connect({
  host: 'localhost',
  username: 'steel',
  privateKey: Buffer.from('...')
})

I am checking the examples in the github page but still don't know if at least is possible to pass custom options/parameters and how to achieve it.

Thanks in advance.


问:
connect 2 different .csv files in mysql with a composed key
I'm a newbie in the programming stuff, and I need to create 2 tables in MySql. Tb1 will have ingredients, and the Tb2 will have dishes made with "pairs" of Tb1 ingredients. I will make 2 diferent files in Excel (.csv) and the doubt is how to connect the data from one to another. The idea is to have a composed key (with both id's of the Tb1 ingridients) in the Tb2. Is that possible, and how do I do it?

Thanks

I don't have code made. I know how to do the basic to load data to a table, the problem it's just the connection between both .csv files.


问:
how to combine multiple html files with plots with same width and height
Here i tried to combine 2 html world maps as plots but they are combined within 2 rows and the size i.e., height of the plots is reduced, but since i am combining them as html i expect that the we can scroll the html so the plots should be displayed with full width and height as they appear as original.

the gplot1 and gplot2 are 2 ggplotly graphs

gplot1 <- ggplotly(gplot, tooltip = "text")
gplot2 <- ggplotly(gplot, tooltip = "text")

manipulateWidget::combineWidgets(title = "Location of PHUSE Global Events 2022 & 2023",
                gplot1, gplot2,
                byrow = T
 )
```

The single html appears as below

whereas the 2 html combined with htmlwidget appears as below

Body:
Here i tried to combine 2 html world maps as plots but they are combined within 2 rows and the size i.e., height of the plots is reduced, but since i am combining them as html i expect that the we can scroll the html so the plots should be displayed with full width and height as they appear as original.

the gplot1 and gplot2 are 2 ggplotly graphs

gplot1 <- ggplotly(gplot, tooltip = "text")
gplot2 <- ggplotly(gplot, tooltip = "text")

manipulateWidget::combineWidgets(title = "Location of PHUSE Global Events 2022 & 2023",
                gplot1, gplot2,
                byrow = T
 )

The single html appears as below

whereas the 2 html combined with htmlwidget appears as below


问:
Facebook graph API me endpoint errors out the first time and successful the next time
I am using facebook login in my coldfusion application. I went through all the steps to get access_token. I am making cfhttp call to "/me" endpoint with access_token and fields parameters and getting "I/O Exception: peer not authenticated" error in the response/Errordetail. I made the same cfhttp call again and able to get successful response of id and name mentioned in fields parameters.

I am expecting the successful response in the first call but have to call twice, so the first call errors out and second one succeeds.

Any help on how to debug or find the issue with the first call. so i should be making one call and get a successful response of current user's information.

i should be making one call and get a successful response of current user's information

```<code><cfscript>

if (code EQ "") {
    cfoauth(type = 'facebook', clientid = appId, secretkey = appSecret, result = "res", scope = "public_profile, email", redirecturi = redirectUri);
}

if (code NEQ "") { // code is a parameter I get from url redirect after cfoauth response
    try {
        cfhttp(method = "GET", charset = "utf-8", url = "https://graph.facebook.com/v15.0/oauth/access_token", result = "fbcoderesponse") {
            cfhttpparam(name = "code", type = "url", value = code);
            cfhttpparam(name = "client_id", type = "url", value = appId);
            cfhttpparam(name = "client_secret", type = "url", value = appSecret);
            cfhttpparam(name = "redirect_uri", type = "url", value = redirectUri);
        }
        dresponse = deserializeJSON(fbcoderesponse.filecontent);
        accessToken = dresponse.access_token;
        writedump(accessToken);

        accessTokenurl = "https://graph.facebook.com/v15.0/me?fields=id,name&access_token=" & accessToken;
        writedump(accessTokenurl);

    } catch (any e) {
        writeoutput(e);
    }

    if (accessToken NEQ "") {
        try {

          cfhttp(method = "GET", charset = "utf-8", url = accessTokenurl, result = "fbaccesstokenresponse”){}
          writedump(fbaccesstokenresponse);

          if (fbaccesstokenresponse.errordetail != "") {
            cfhttp(method = "GET", charset = "utf-8", url = accessTokenurl, result = "fbaccesstokenresponse1");
            writeoutput("fbaccesstokenresponse1 response");
            writedump(fbaccesstokenresponse1);
          }

        } catch (any e) {
             writeoutput("exception of daccesstokenresponse");
             writedump(e);
            }
    } else {
      writeoutput("accesstoken is empty");
    }
 }
</cfscript>
</code>```

Body:
I am using facebook login in my coldfusion application. I went through all the steps to get access_token. I am making cfhttp call to "/me" endpoint with access_token and fields parameters and getting "I/O Exception: peer not authenticated" error in the response/Errordetail. I made the same cfhttp call again and able to get successful response of id and name mentioned in fields parameters.

I am expecting the successful response in the first call but have to call twice, so the first call errors out and second one succeeds.

Any help on how to debug or find the issue with the first call. so i should be making one call and get a successful response of current user's information.

i should be making one call and get a successful response of current user's information

<cfscript>

if (code EQ "") {
    cfoauth(type = 'facebook', clientid = appId, secretkey = appSecret, result = "res", scope = "public_profile, email", redirecturi = redirectUri);
}

if (code NEQ "") { // code is a parameter I get from url redirect after cfoauth response
    try {
        cfhttp(method = "GET", charset = "utf-8", url = "https://graph.facebook.com/v15.0/oauth/access_token", result = "fbcoderesponse") {
            cfhttpparam(name = "code", type = "url", value = code);
            cfhttpparam(name = "client_id", type = "url", value = appId);
            cfhttpparam(name = "client_secret", type = "url", value = appSecret);
            cfhttpparam(name = "redirect_uri", type = "url", value = redirectUri);
        }
        dresponse = deserializeJSON(fbcoderesponse.filecontent);
        accessToken = dresponse.access_token;
        writedump(accessToken);

        accessTokenurl = "https://graph.facebook.com/v15.0/me?fields=id,name&access_token=" & accessToken;
        writedump(accessTokenurl);

    } catch (any e) {
        writeoutput(e);
    }

    if (accessToken NEQ "") {
        try {

          cfhttp(method = "GET", charset = "utf-8", url = accessTokenurl, result = "fbaccesstokenresponse”){}
          writedump(fbaccesstokenresponse);

          if (fbaccesstokenresponse.errordetail != "") {
            cfhttp(method = "GET", charset = "utf-8", url = accessTokenurl, result = "fbaccesstokenresponse1");
            writeoutput("fbaccesstokenresponse1 response");
            writedump(fbaccesstokenresponse1);
          }

        } catch (any e) {
             writeoutput("exception of daccesstokenresponse");
             writedump(e);
            }
    } else {
      writeoutput("accesstoken is empty");
    }
 }
</cfscript>


问:
justInTimeInstall for a Messaging Extension app not working on mobile (iOS/Android) Teams client
Working on a Messaging Extension app for Teams that opens a Task Module in a Teams Meeting. This app is installed from the "Built for your org" section of the Teams store after being loaded into a Tenant by a Teams Admin. Any tenant user who has the app installed can select the messaging extension from the … menu in a Teams Meeting to initialize the Task Module.

Before initializing the Task Module, the app's bot must be added to the meeting chat so an "Add app" button is presented after selecting the messaging extension. This button sends through a payload with the justInTimeInstall value set to true. When a new Teams user who has never used the messaging extension before tries to tap on this Add app button on a mobile device, the button either does nothing and the user is returned to the chat (iOS) or an error page with a retry button is presented and the retry button keeps presenting the same error page (Android).

When examining a network trace of this button press, a 502 code is being returned with the following JSON:

```<code>{
    "errorCode": 1008,
    "message": "<BotError>Bot returned unsuccessful status code Forbidden",
    "standardizedError": {
        "errorCode": 1008,
        "errorSubCode": 1,
        "errorDescription": "<BotError>Bot returned unsuccessful status code Forbidden"
    }
}
</code>```

This combined with some other logging makes it seem like the response isn't even getting to the app's server. This is only a problem on mobile for a Teams user who hasn't used this messaging extension app. If the same user adds the app to the meeting from desktop/web, then they can come back on mobile and the "add app" button will work in any meeting from that point forward.

Is this a known issue or is there something that I might be missing here that's preventing the app from being added for new users on mobile?

Body:
Working on a Messaging Extension app for Teams that opens a Task Module in a Teams Meeting. This app is installed from the "Built for your org" section of the Teams store after being loaded into a Tenant by a Teams Admin. Any tenant user who has the app installed can select the messaging extension from the … menu in a Teams Meeting to initialize the Task Module.

Before initializing the Task Module, the app's bot must be added to the meeting chat so an "Add app" button is presented after selecting the messaging extension. This button sends through a payload with the justInTimeInstall value set to true. When a new Teams user who has never used the messaging extension before tries to tap on this Add app button on a mobile device, the button either does nothing and the user is returned to the chat (iOS) or an error page with a retry button is presented and the retry button keeps presenting the same error page (Android).

When examining a network trace of this button press, a 502 code is being returned with the following JSON:

{
    "errorCode": 1008,
    "message": "<BotError>Bot returned unsuccessful status code Forbidden",
    "standardizedError": {
        "errorCode": 1008,
        "errorSubCode": 1,
        "errorDescription": "<BotError>Bot returned unsuccessful status code Forbidden"
    }
}

This combined with some other logging makes it seem like the response isn't even getting to the app's server. This is only a problem on mobile for a Teams user who hasn't used this messaging extension app. If the same user adds the app to the meeting from desktop/web, then they can come back on mobile and the "add app" button will work in any meeting from that point forward.

Is this a known issue or is there something that I might be missing here that's preventing the app from being added for new users on mobile?