问:
Why does the Windows Store modifies the app package?
I'm building a WPF application and I'm using Xaml Islands to add Windows 10 look and feel to the app. I'd like to use the Lottie library to play Adobe After Effects animations. Everything works fine until now.

When packaging the desktop bridge project, I receive an App manifest validation error. This issue appears on multiple places, and it seems that Microsoft won't fix it. Here, here, here, also here, etc. From this workaround, I added the following lines to the wap project:

```<code><Target Name="_RemoveWinMDFromAppxManifest" BeforeTargets="_GenerateCurrentProjectAppxManifest">
    <ItemGroup>
      <_AppxWinmdFilesToHarvest Remove="@(_AppxWinmdFilesToHarvest)" />
    </ItemGroup>
  </Target>
</code>```

With this, I could achieve to not to duplicate some dependencies in the AppxManifest.xaml when creating the build, so the issue has gone and I could create the package for the Store submission.

I could upload to the store, it is published, but when I install it from the store, the app crashes when it should display a lottie animation with the following exception:

```<code>* When the Lottie is initalized from Xaml:
(0x80004005): Error HRESULT E_FAIL has been returned from a call to a COM component.
   at Windows.UI.Xaml.UIElement.Measure(Size availableSize)
   at Microsoft.Toolkit.Uwp.UI.Controls.WrapPanel.MeasureOverride(Size availableSize)

* Exception, when it is initialized from the code behind:
Cannot create instance of type 'Microsoft.Toolkit.Uwp.UI.Lottie.LottieVisualSource' [Line: 0 Position: 0]
</code>```

The interesting part is that the animation is played when I install the exact same build from the local package. So the Store modifies the package during the publish procedure?

I would appreciate any ideas. What else can I do with the App manifest validation error to create the package? Can I remove the duplicate entries some other way from the AppxManifest during the build process? What can I do to make it work when it is installed from the Store?

Body:
I'm building a WPF application and I'm using Xaml Islands to add Windows 10 look and feel to the app. I'd like to use the Lottie library to play Adobe After Effects animations. Everything works fine until now.

When packaging the desktop bridge project, I receive an App manifest validation error. This issue appears on multiple places, and it seems that Microsoft won't fix it. Here, here, here, also here, etc. From this workaround, I added the following lines to the wap project:

<Target Name="_RemoveWinMDFromAppxManifest" BeforeTargets="_GenerateCurrentProjectAppxManifest">
    <ItemGroup>
      <_AppxWinmdFilesToHarvest Remove="@(_AppxWinmdFilesToHarvest)" />
    </ItemGroup>
  </Target>

With this, I could achieve to not to duplicate some dependencies in the AppxManifest.xaml when creating the build, so the issue has gone and I could create the package for the Store submission.

I could upload to the store, it is published, but when I install it from the store, the app crashes when it should display a lottie animation with the following exception:

* When the Lottie is initalized from Xaml:
(0x80004005): Error HRESULT E_FAIL has been returned from a call to a COM component.
   at Windows.UI.Xaml.UIElement.Measure(Size availableSize)
   at Microsoft.Toolkit.Uwp.UI.Controls.WrapPanel.MeasureOverride(Size availableSize)

* Exception, when it is initialized from the code behind:
Cannot create instance of type 'Microsoft.Toolkit.Uwp.UI.Lottie.LottieVisualSource' [Line: 0 Position: 0]

The interesting part is that the animation is played when I install the exact same build from the local package. So the Store modifies the package during the publish procedure?

I would appreciate any ideas. What else can I do with the App manifest validation error to create the package? Can I remove the duplicate entries some other way from the AppxManifest during the build process? What can I do to make it work when it is installed from the Store?


来源: stackexchange

问:
Is there any 3rd party service that allows me to verify bank account details received from my user?
I have some onboard flow where a user can sign in to my portal.

A user can provide bank details so in the future a user will be able to receive bank transfers from my portal. (Securely keeping that data is not related to that question)

Is there any 3rd party service that allows me to verify bank account details received from my user?

Let's say a user gives me a bank account number name, surname (or organisation name) and address.

How can I verify that data is related to the bank account number?

Are there any 3rd party services to do that?

ContentLicense: CC BY-SA 4.0


问:
How to make Selenium python ActionChains work
I am trying to switch tabs on a fullscreen browser window using Selenium. When I use the methods of the driver to change the tab (.switch_to.window) the window reverts back to non fullscreen and I have to enable full screen again. This causes flickering and the "press F11 to exit fullscreen" message to appear.

Instead I tried to send key commands to accomplish the same (CTRL + pgdn, etc...), but for the life of me I can't get it to work at all.

Example code

```<code>from selenium import webdriver
import time
# import Action chains
from selenium.webdriver.common.action_chains import ActionChains
# import KEYS
from selenium.webdriver.common.keys import Keys

# create webdriver object
driver = webdriver.Chrome()

driver.get("https://www.wikipedia.org/")
# create a new tab
driver.execute_script("window.open('{}','{}');".format("https://en.wikipedia.org/wiki/42","https://en.wikipedia.org/wiki/42"))
time.sleep(1)

# create action chain object
action = ActionChains(driver)
# perform the operation

time.sleep(1)
driver.find_element("tag name",'body').send_keys(Keys.CONTROL + 't') # open new tab method 1
time.sleep(1)
action.key_down(Keys.CONTROL).send_keys(Keys.PAGE_DOWN).key_up(Keys.CONTROL).perform() # open new tab method 2
time.sleep(1)
action.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perform() # open search
time.sleep(5)
</code>```

I am able to create a new tab by executing a javascript command just for testing, but the other methods of sending key commands don't work at all.
Method one simply sends the command to the body and the other uses ActionChains.
I have tried running each command separately as well.

I have also tried sending other commands like CTRL + F and others, but none do anything. Also tried Firefox instead of Chrome, but same result.

OS: Windows 10
python 3.9.13
Selenium version 4.7.2

Body:
I am trying to switch tabs on a fullscreen browser window using Selenium. When I use the methods of the driver to change the tab (.switch_to.window) the window reverts back to non fullscreen and I have to enable full screen again. This causes flickering and the "press F11 to exit fullscreen" message to appear.

Instead I tried to send key commands to accomplish the same (CTRL + pgdn, etc...), but for the life of me I can't get it to work at all.

Example code

from selenium import webdriver
import time
# import Action chains
from selenium.webdriver.common.action_chains import ActionChains
# import KEYS
from selenium.webdriver.common.keys import Keys

# create webdriver object
driver = webdriver.Chrome()

driver.get("https://www.wikipedia.org/")
# create a new tab
driver.execute_script("window.open('{}','{}');".format("https://en.wikipedia.org/wiki/42","https://en.wikipedia.org/wiki/42"))
time.sleep(1)

# create action chain object
action = ActionChains(driver)
# perform the operation

time.sleep(1)
driver.find_element("tag name",'body').send_keys(Keys.CONTROL + 't') # open new tab method 1
time.sleep(1)
action.key_down(Keys.CONTROL).send_keys(Keys.PAGE_DOWN).key_up(Keys.CONTROL).perform() # open new tab method 2
time.sleep(1)
action.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perform() # open search
time.sleep(5)

I am able to create a new tab by executing a javascript command just for testing, but the other methods of sending key commands don't work at all.
Method one simply sends the command to the body and the other uses ActionChains.
I have tried running each command separately as well.

I have also tried sending other commands like CTRL + F and others, but none do anything. Also tried Firefox instead of Chrome, but same result.

OS: Windows 10
python 3.9.13
Selenium version 4.7.2


问:
Using the OFFSET excel function in VBA .formula error
I'm trying to use the function OFFSET in a cells.formula and it returns me an erros 1004. I know that the formula work if I use it directly without macro

.Cells(5, c_write).Formula = "=MIN(OFFSET(data!" & Split(.Cells(1, c_read).Address, "$")(1) & "3;0;0;data_calc!" & .Cells(3, c_write + 1).Address & "))"

I tried with other formulas as MIN or COUNTA and it worked fine, but with OFFSET, it put an error 1004


问:
I try to get to the directory of where the current python script is located
I come from a R background and now want to learn Python. I run Python using RStudio and want to show the directory of where the current python script is located. For this I followed this tutorial. I have this script:

```<code>import os
result = os.path.join(os.path.dirname(__file__))
print(result)
</code>```

When I execute it I get this result:

```<code>>>> import os
>>> result = os.path.join(os.path.dirname(__file__))
NameError: name '__file__' is not defined
</code>```

Body:
I come from a R background and now want to learn Python. I run Python using RStudio and want to show the directory of where the current python script is located. For this I followed this tutorial. I have this script:

import os
result = os.path.join(os.path.dirname(__file__))
print(result)

When I execute it I get this result:

>>> import os
>>> result = os.path.join(os.path.dirname(__file__))
NameError: name '__file__' is not defined


问:
How to consume the click when opening an android app?
For my users, I send a verification email in Firebase. The link that I receive is:

```<code>https://myprojectid.firebaseapp.com/...
</code>```

When a user clicks the link I want to open my app and navigate to a specific screen. So here is what I have tried. Inside the manifest file I have:

```<code><activity
    android:name=".MainActivity"
    android:exported="true">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="https" android:host="myprojectid.firebaseapp.com"/>
    </intent-filter>
</activity>
</code>```

When I click the URL, the app opens, but it doesn't consume the click, and the email isn't verified. How to overcome this situation? Any help would be greatly appreciated.

Body:
For my users, I send a verification email in Firebase. The link that I receive is:

https://myprojectid.firebaseapp.com/...

When a user clicks the link I want to open my app and navigate to a specific screen. So here is what I have tried. Inside the manifest file I have:

<activity
    android:name=".MainActivity"
    android:exported="true">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="https" android:host="myprojectid.firebaseapp.com"/>
    </intent-filter>
</activity>

When I click the URL, the app opens, but it doesn't consume the click, and the email isn't verified. How to overcome this situation? Any help would be greatly appreciated.


问:
Pine Script short position not closing
I am trying to backtest a strategy, but my short entries are not closing. For reference, this is the strategy I am trying to backtest.

There is pyramiding involved, but the position should close within 2 hours on a EURUSD 5min chart (I am only limited to backtesting 5000 candles). The positions close fine when I only open long positions and remove the short related parts of the code.

```<code>strategy(title="5 minute MOMO", default_qty_type = strategy.percent_of_equity, default_qty_value = 100, overlay = true)

// Relevant indicators
ema20 = ta.ema(close, 20)
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)

// Functions
GetPipSize() =>
    syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)

var float entryPrice = 0
var int position = 0 // 1 for long, 2 for short
var float longSLPrice = 0
var bool longTP1 = false
float longTSLPrice = longTP1 ? ema20 - 15 * GetPipSize() : 0
var float shortSLPrice = 0
var bool shortTP1 = false
float shortTSLPrice = shortTP1 ? ema20 + 15 * GetPipSize() : 0

// Conditions
longCondition = strategy.position_size == 0 and close > ema20 and macdLine > 0
shortCondition = strategy.position_size == 0 and close < ema20 and macdLine < 0
longSL = strategy.position_size > 0 and position == 1 and (close <= (longTSLPrice > longSLPrice ? longTSLPrice : longSLPrice))
shortSL = strategy.position_size > 0 and position == 2 and (close >= (shortTSLPrice < shortSLPrice ? shortTSLPrice : shortSLPrice))

// Entry
if longCondition
    strategy.entry(id="Long", direction = strategy.long)

if shortCondition
    strategy.entry(id="Short", direction = strategy.short)

if longCondition[1]
    entryPrice := open
    position := 1
    longSLPrice := ema20 - 20 * GetPipSize()

if shortCondition[1]
    entryPrice := open
    position := 2
    shortSLPrice := ema20 + 20 * GetPipSize()

// Exit
if position == 1 and (close >= entryPrice + (entryPrice - longSLPrice)) and not longTP1 // Condition for first take profit long
    strategy.close("Long", qty_percent = 50)
    longSLPrice := entryPrice
    longTP1 := true
if position == 1 and longSL
    strategy.close("Long", qty_percent = 100)
    entryPrice := 0
    position := 0
    longSLPrice := 0
    longTP1 := false
if position == 2 and (close <= entryPrice - (shortSLPrice - entryPrice)) and not shortTP1 // Condition for first take profit short
    strategy.close("Short", qty_percent = 50)
    shortSLPrice := entryPrice
    shortTP1 := true
if position == 2 and shortSL
    strategy.close("Short", qty_percent = 100)
    entryPrice := 0
    position := 0
    shortSLPrice := 0
    shortTP1 := false

// For Visual Purpose
plot(ema20, color = color.black)
plot(ema20-15*GetPipSize(), color=color.orange)
plot(ema20-20*GetPipSize(), color=color.red)
plot(ema20+15*GetPipSize(), color=color.orange)
plot(ema20+20*GetPipSize(), color=color.red)```
```

Title: Pine Script short position not closing

Body:
I am trying to backtest a strategy, but my short entries are not closing. For reference, this is the strategy I am trying to backtest.

There is pyramiding involved, but the position should close within 2 hours on a EURUSD 5min chart (I am only limited to backtesting 5000 candles). The positions close fine when I only open long positions and remove the short related parts of the code.

strategy(title="5 minute MOMO", default_qty_type = strategy.percent_of_equity, default_qty_value = 100, overlay = true)

// Relevant indicators
ema20 = ta.ema(close, 20)
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)

// Functions
GetPipSize() =>
    syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)

var float entryPrice = 0
var int position = 0 // 1 for long, 2 for short
var float longSLPrice = 0
var bool longTP1 = false
float longTSLPrice = longTP1 ? ema20 - 15 * GetPipSize() : 0
var float shortSLPrice = 0
var bool shortTP1 = false
float shortTSLPrice = shortTP1 ? ema20 + 15 * GetPipSize() : 0

// Conditions
longCondition = strategy.position_size == 0 and close > ema20 and macdLine > 0
shortCondition = strategy.position_size == 0 and close < ema20 and macdLine < 0
longSL = strategy.position_size > 0 and position == 1 and (close <= (longTSLPrice > longSLPrice ? longTSLPrice : longSLPrice))
shortSL = strategy.position_size > 0 and position == 2 and (close >= (shortTSLPrice < shortSLPrice ? shortTSLPrice : shortSLPrice))

// Entry
if longCondition
    strategy.entry(id="Long", direction = strategy.long)

if shortCondition
    strategy.entry(id="Short", direction = strategy.short)

if longCondition[1]
    entryPrice := open
    position := 1
    longSLPrice := ema20 - 20 * GetPipSize()

if shortCondition[1]
    entryPrice := open
    position := 2
    shortSLPrice := ema20 + 20 * GetPipSize()

// Exit
if position == 1 and (close >= entryPrice + (entryPrice - longSLPrice)) and not longTP1 // Condition for first take profit long
    strategy.close("Long", qty_percent = 50)
    longSLPrice := entryPrice
    longTP1 := true
if position == 1 and longSL
    strategy.close("Long", qty_percent = 100)
    entryPrice := 0
    position := 0
    longSLPrice := 0
    longTP1 := false
if position == 2 and (close <= entryPrice - (shortSLPrice - entryPrice)) and not shortTP1 // Condition for first take profit short
    strategy.close("Short", qty_percent = 50)
    shortSLPrice := entryPrice
    shortTP1 := true
if position == 2 and shortSL
    strategy.close("Short", qty_percent = 100)
    entryPrice := 0
    position := 0
    shortSLPrice := 0
    shortTP1 := false

// For Visual Purpose
plot(ema20, color = color.black)
plot(ema20-15*GetPipSize(), color=color.orange)
plot(ema20-20*GetPipSize(), color=color.red)
plot(ema20+15*GetPipSize(), color=color.orange)
plot(ema20+20*GetPipSize(), color=color.red)```


问:
OnTeamsMessagingExtensionQueryAsync not getting hit
I am working on Microsoft.Bot.Builder for Teams for Search Message extension. My code is working fine in Local and Dev environment. But for production, I can see that OnTeamsMessagingExtensionQueryAsync not even get hit. I did remote debugging, it never reaches there and also I dont see any logs as well. I see that code reaches to the constructor(TeamsBot : TeamsActivityHandler) only. and then back to BotController api endpoint await _adapter.ProcessAsync(Request, Response, _bot);.

Can anyone help?  I am clueless here. My Bot id and password is correct , the api endpoint is on Https. This was working yesterday and now it stopped. Below are the logs:

2022-12-21 08:09:06.421 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request starting HTTP/1.1 POST https://teams.Myonline.app/api/messages application/json;+charset=utf-8 1130
2022-12-21 08:09:06.421 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executing endpoint 'My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp)'
2022-12-21 08:09:06.421 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Route matched with {action = "Post", controller = "Bot", page = ""}. Executing controller action with signature System.Threading.Tasks.Task PostAsync() on controller My.Office365.TeamsApp.Controllers.BotController (My.Office365.TeamsApp).
2022-12-21 08:09:06.422 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executing action method My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp) - Validation state: Valid
2022-12-21 08:09:06.422 +00:00 [Information] Microsoft.Bot.Builder.Integration.AspNet.Core.IBotFrameworkHttpAdapter: ProcessActivityAsync
2022-12-21 08:09:06.423 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action method My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp), returned result Microsoft.AspNetCore.Mvc.EmptyResult in 1.128ms.
2022-12-21 08:09:06.423 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp) in 1.4924ms
2022-12-21 08:09:06.423 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executed endpoint 'My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp)'
2022-12-21 08:09:06.423 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request finished HTTP/1.1 POST https://teams.Myonline.app/api/messages application/json;+charset=utf-8 1130 - 401 - - 2.0425ms
2022-12-21 08:09:06.969 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request starting HTTP/1.1 GET https://teams.Myonline.app/ - -
2022-12-21 08:09:06.970 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executing endpoint '/_Host'
2022-12-21 08:09:06.970 +00:00 [Information] Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker: Route matched with {page = "/_Host", action = "", controller = ""}. Executing page /_Host
2022-12-21 08:09:06.970 +00:00 [Information] Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker: Executing an implicit handler method - ModelState is Valid
2022-12-21 08:09:06.970 +00:00 [Information] Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker: Executed an implicit handler method, returned result Microsoft.AspNetCore.Mvc.RazorPages.PageResult.
2022-12-21 08:09:06.971 +00:00 [Information] Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker: Executed page /_Host in 1.0016ms
2022-12-21 08:09:06.971 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executed endpoint '/_Host'
2022-12-21 08:09:06.971 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request finished HTTP/1.1 GET https://teams.Myonline.app/ - - - 200 - text/html;+charset=utf-8 1.3705ms
2022-12-21 08:09:07.361 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request starting HTTP/1.1 POST https://teams.Myonline.app/api/messages application/json;+charset=utf-8 1128
2022-12-21 08:09:07.361 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executing endpoint 'My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp)'
2022-12-21 08:09:07.361 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Route matched with {action = "Post", controller = "Bot", page = ""}. Executing controller action with signature System.Threading.Tasks.Task PostAsync() on controller My.Office365.TeamsApp.Controllers.BotController (My.Office365.TeamsApp).
2022-12-21 08:09:07.361 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executing action method My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp) - Validation state: Valid
2022-12-21 08:09:07.361 +00:00 [Information] Microsoft.Bot.Builder.Integration.AspNet.Core.IBotFrameworkHttpAdapter: ProcessActivityAsync
2022-12-21 08:09:07.362 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action method My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp), returned result Microsoft.AspNetCore.Mvc.EmptyResult in 1.2481ms.
2022-12-21 08:09:07.362 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp) in 1.4749ms
2022-12-21 08:09:07.362 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executed endpoint 'My.Office365.TeamsApp.Controllers.BotController.PostAsync (My.Office365.TeamsApp)'
2022-12-21 08:09:07.363 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request finished HTTP/1.1 POST https://teams.Myonline.app/api/messages application/json;+charset=utf-8 1128 - 401 - - 2.0420ms


问:
Changing defaults in discord.py select view options
Im currently making a help command which should show the default embed which is the fun commands page, and having a select list with the default as "Fun commands". What I want to happen is so that when I choose the select list option as "General commands", it will edit the message with the general commands embed and the same select list but with the default set to "General commands instead of "Fun commands".</p>
```<code>if message.content.startswith('c!help'):
      select = Select(
        placeholder = "Choose a category",
        options=[
                       discord.SelectOption(
                         label="Fun commands",
                         description="j"),
                       discord.SelectOption(
                         label="General commands",
                         description="j3")
                               ])
      view = View()
      view.add_item(select)
      await message.channel.send(embed=fhelp,view=view)
      async def call_back(interaction):
        mainthing = select.values[0]
        if mainthing == "Fun commands":
          await interaction.response.edit_message(embed=fhelp,view=view)
        elif mainthing == "General commands":
          await interaction.response.edit_message(embed=ghelp,view=view)
      select.callback = call_back
</code>```

Body:
Im currently making a help command which should show the default embed which is the fun commands page, and having a select list with the default as "Fun commands". What I want to happen is so that when I choose the select list option as "General commands", it will edit the message with the general commands embed and the same select list but with the default set to "General commands instead of "Fun commands".

if message.content.startswith('c!help'):
      select = Select(
        placeholder = "Choose a category",
        options=[
                       discord.SelectOption(
                         label="Fun commands",
                         description="j"),
                       discord.SelectOption(
                         label="General commands",
                         description="j3")
                               ])
      view = View()
      view.add_item(select)
      await message.channel.send(embed=fhelp,view=view)
      async def call_back(interaction):
        mainthing = select.values[0]
        if mainthing == "Fun commands":
          await interaction.response.edit_message(embed=fhelp,view=view)
        elif mainthing == "General commands":
          await interaction.response.edit_message(embed=ghelp,view=view)
      select.callback = call_back


问:
Problem with row-alignment using React & Bootstrap GRID system
Using React.JS and BootStrap grid system, I'm aiming to build the following page.

However, with the code linked at the bottom, the page looks like this (the alignment of the elements is wrong in multiple places. For example, the banner and search bar aren't aligned with the rest of the elements.

What am I doing wrong in using the BootStrap Grid System?

Before that, I'd like to specify that all the 4 MinWidget.jsx components are wrapped inside a MinWidgetCollection.jsx component. And all the elements encompased by the red border are wrapped inside a PageInformation.jsx component. The MiniWidgetCollection must take 7/12 of the page width while the BigWidget one the rest of 5/12 (with BootStrap grid having a maximum of 12 columns per row). Similarly, the first chart below must have 7/12 of width while the second chart only 5/12.

This is the current code which produces errors in alignment.

```<code>function App() {
  return (
    <div className='container'>
      <Searchbar/>
      <Banner/>
      <PageInformation/>
    </div>
  )
}

export const Searchbar = (props) => {
  return (
    <div className='row mb-5' style={{border: "1px solid green"}}>
        <div className='card-header p-7 w-50'>
      </div>
  )

export const Banner = (props) => {
  return (
    <div className='row'>
        <div className='card mb-5 mb-xl-10'>
        </div>
      </div>

  )

export const PageInformation = (props) => {
  return (
    <div style={{border: "1px solid red"}}>

      <div className='row'>
        <MinWidgetCollection />
        <BigWidget />
      </div>
      <div className='row'>
        <Chart newClassname='col-md-7 col-xs-12' />
        <Chart newClassname='col-md-5 col-xs-12' />
      </div>
    </div>
  )
}

export const MinWidgetCollection = (props) => {
    return (
        <div className='row col-md-7 col-xs-12'>

            <MinWidget />
            <MinWidget />
            <MinWidget />
            <MinWidget />
        </div>

    )
}

export const MinWidget = (props) => {
  return (
    <div className='col-md-6 col-xs-12'>
      <div className='card card-md-6 card-xs-12 mb-xl-8'>
      </div>
    </div>
  )
}

export const BigWidget = (props) => {
  return (
    <div className='col-md-5 col-xs-12'>
        <div className="card card-xl-stretch mb-5 mb-xl-8 h-100">
        </div>
    </div>
  )
}

export const Chart = (props) => {
 <div className={props.newClassname}>
      <div className={`card mt-5 `}>
      </div>
    </div>

}
</code>```

Body:
Using React.JS and BootStrap grid system, I'm aiming to build the following page.

However, with the code linked at the bottom, the page looks like this (the alignment of the elements is wrong in multiple places. For example, the banner and search bar aren't aligned with the rest of the elements.

What am I doing wrong in using the BootStrap Grid System?

Before that, I'd like to specify that all the 4 MinWidget.jsx components are wrapped inside a MinWidgetCollection.jsx component. And all the elements encompased by the red border are wrapped inside a PageInformation.jsx component. The MiniWidgetCollection must take 7/12 of the page width while the BigWidget one the rest of 5/12 (with BootStrap grid having a maximum of 12 columns per row). Similarly, the first chart below must have 7/12 of width while the second chart only 5/12.

This is the current code which produces errors in alignment.

function App() {
  return (

      <Searchbar/>
      <Banner/>
      <PageInformation/>

  )
}

export const Searchbar = (props) => {
  return (

  )

export const Banner = (props) => {
  return (

  )

export const PageInformation = (props) => {
  return (

        <MinWidgetCollection />
        <BigWidget />

        <Chart newClassname='col-md-7 col-xs-12' />
        <Chart newClassname='col-md-5 col-xs-12' />

  )
}

export const MinWidgetCollection = (props) => {
    return (

            <MinWidget />
            <MinWidget />
            <MinWidget />
            <MinWidget />

    )
}

export const MinWidget = (props) => {
  return (

  )
}

export const BigWidget = (props) => {
  return (

  )
}

export const Chart = (props) => {

      <div className={`card mt-5 `}>

}


问:
How to instantly close all async running tasks
I can't figure out how I can get out of an async loop. I have some code that has to run until I get all the data I want.

```<code>async def subscribe(url, subs):
    ws_responses = []
    async with websockets.connect(url) as websocket:
        for sub in subs:
            sub_str = json.dumps(sub)
            await websocket.send(sub_str)
        while len(ws_responses) <= len(subs):
            rsp = json.loads(await websocket.recv())
            if 'data' in rsp:
                ws_responses.append(rsp['data']['s'])
            if len(ws_responses) == len(subs):
                break
        return ws_responses

def main():
    market_url = 'wss://stream.bybit.com/spot/quote/ws/v2'
    market_subs = [{
        "topic": "depth",
        "event": "sub",
        "params": {
            "symbol": "BTCUSDT",
        }}
    ]
    while True:
        try:
            response = asyncio.get_event_loop().run_until_complete(
                subscribe(market_url, market_subs))
            return response
        except Exception as e:
            traceback.print_exc()
            print('websocket connection error. reconnect rightnow')

if __name__ == "__main__":
    print(main())
</code>```

this action is done in a second, but the data is not printed until 40 seconds later. I need to know how to end all async processes instantly. I need to return data, because the main function will be used in another program

I tried closing the connection in subscribe websocket.close(), but it did not change anything.also i tried creating loop = asyncio.get_event_loop() after loop.create_task(subcribe(market_url, market_subs)) and loop.close(), but it also didn't help me.

Body:
I can't figure out how I can get out of an async loop. I have some code that has to run until I get all the data I want.

async def subscribe(url, subs):
    ws_responses = []
    async with websockets.connect(url) as websocket:
        for sub in subs:
            sub_str = json.dumps(sub)
            await websocket.send(sub_str)
        while len(ws_responses) <= len(subs):
            rsp = json.loads(await websocket.recv())
            if 'data' in rsp:
                ws_responses.append(rsp['data']['s'])
            if len(ws_responses) == len(subs):
                break
        return ws_responses

def main():
    market_url = 'wss://stream.bybit.com/spot/quote/ws/v2'
    market_subs = [{
        "topic": "depth",
        "event": "sub",
        "params": {
            "symbol": "BTCUSDT",
        }}
    ]
    while True:
        try:
            response = asyncio.get_event_loop().run_until_complete(
                subscribe(market_url, market_subs))
            return response
        except Exception as e:
            traceback.print_exc()
            print('websocket connection error. reconnect rightnow')

if __name__ == "__main__":
    print(main())

this action is done in a second, but the data is not printed until 40 seconds later. I need to know how to end all async processes instantly. I need to return data, because the main function will be used in another program

I tried closing the connection in subscribe websocket.close(), but it did not change anything.also i tried creating loop = asyncio.get_event_loop() after loop.create_task(subcribe(market_url, market_subs)) and loop.close(), but it also didn't help me.


问:
Trying to size a legend issue in Streamlit
I have a legend with far too many values, i have implemented a scroll function however i cannot figure out how to properly size my chart and legend

This is what i have, and when i run this just on my computer not pushing to streamlit the scroll bar works but this displays the entire legend on streamlit everytime i try to change the size i continue with similar outputs. This is an image of my webpage right now, as you can see the legend continues down the page, i need to make it cut off so i can use the scroll function:

```<code>fig1 = plt.figure(figsize=(7, 3))
axx = fig.add_axes([0.1, 0.6, 0.3, 0.3])
p1 = volcanos["Country"].value_counts()

fig1, axx = plt.subplots()
axx.pie(p1, labels=p1.keys(), autopct='%1.1f%%',
                    shadow=True, startangle=90)
legend = axx.legend(loc="upper left", bbox_to_anchor=(1.02, 0, 0.07, 1))

# pixels to scroll per mousewheel event
d = {"down" : 30, "up" : -30}
def func(evt):
    if legend.contains(evt):
        bbox = legend.get_bbox_to_anchor()
        bbox = Bbox.from_bounds(bbox.x0, bbox.y0+d[evt.button], bbox.width, bbox.height)
        tr = legend.axes.transAxes.inverted()
        legend.set_bbox_to_anchor(bbox.transformed(tr))
        fig1.canvas.draw_idle()

fig1.canvas.mpl_connect("scroll_event", func)

st.pyplot(fig1)
</code>```

Body:
I have a legend with far too many values, i have implemented a scroll function however i cannot figure out how to properly size my chart and legend

This is what i have, and when i run this just on my computer not pushing to streamlit the scroll bar works but this displays the entire legend on streamlit everytime i try to change the size i continue with similar outputs. This is an image of my webpage right now, as you can see the legend continues down the page, i need to make it cut off so i can use the scroll function:

fig1 = plt.figure(figsize=(7, 3))
axx = fig.add_axes([0.1, 0.6, 0.3, 0.3])
p1 = volcanos["Country"].value_counts()

fig1, axx = plt.subplots()
axx.pie(p1, labels=p1.keys(), autopct='%1.1f%%',
                    shadow=True, startangle=90)
legend = axx.legend(loc="upper left", bbox_to_anchor=(1.02, 0, 0.07, 1))

# pixels to scroll per mousewheel event
d = {"down" : 30, "up" : -30}
def func(evt):
    if legend.contains(evt):
        bbox = legend.get_bbox_to_anchor()
        bbox = Bbox.from_bounds(bbox.x0, bbox.y0+d[evt.button], bbox.width, bbox.height)
        tr = legend.axes.transAxes.inverted()
        legend.set_bbox_to_anchor(bbox.transformed(tr))
        fig1.canvas.draw_idle()

fig1.canvas.mpl_connect("scroll_event", func)

st.pyplot(fig1)


问:
Sequelize order and limit data by 10 after getting all result
```<code>      // returnJson: false,
      model: Organization,
      where: where,
      limit: 10,
      offset: 0,
      order: [[{ model: Events }, "name", "desc"]],
      include: [
        {
          model: Events,
          through: { model: Organization_Event },
          ...softDeleteFilter,
        },
      ],
    });
</code>```

**Organization can be linked to multiple events and vice versa. **

I want to order and limit data code is working fine. But when I apply for the order by asc or desc It orders the rows from the first 10 results.

I am expecting the following result:-
first to get all data and then apply the order after that return 10 result on database level

database: mysql

Body:
      // returnJson: false,
      model: Organization,
      where: where,
      limit: 10,
      offset: 0,
      order: [[{ model: Events }, "name", "desc"]],
      include: [
        {
          model: Events,
          through: { model: Organization_Event },
          ...softDeleteFilter,
        },
      ],
    });

**Organization can be linked to multiple events and vice versa. **

I want to order and limit data code is working fine. But when I apply for the order by asc or desc It orders the rows from the first 10 results.

I am expecting the following result:-
first to get all data and then apply the order after that return 10 result on database level

database: mysql


问:
Can't determine local email address; with spring boot when my application runs in AWS
When the application runs on my local machine I don't get this error but since I run my back end in aws with ECS I get the following error:

"org.springframework.mail.MailSendException: Failed messages: javax.mail.MessagingException: can't determine local email address; message exceptions (1) are:
Failed message 1: javax.mail.MessagingException: can't determine local email address"

with status code 500.

```<code> public void sendConformationEmail(User user, Locale locale, String appUrl){

    String token = UUID.randomUUID().toString();
    createVerificationToken(user, token);

    String recipientAddress = user.getEmail();
    String subject = "IO Employee Registration Confirmation";
    String confirmationUrl = appUrl + "/email/confirm?token=" + token;
    String message = messages.getMessage("message.regSuccLink", null, "You registered successfully. To confirm your registration, please click on the below link.", locale);

    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo(recipientAddress);
    email.setSubject(subject);
    email.setFrom(env.getProperty("spring.mail.username"));

    email.setText(message + "\r\n" + serverAddress + confirmationUrl);
    mailSender.send(email);
}
</code>```

I use the Gmail SMTP server.

As you can see I use setFrom() so that can not be the issue. can't determine local email address : Spring boot

Body:
When the application runs on my local machine I don't get this error but since I run my back end in aws with ECS I get the following error:

"org.springframework.mail.MailSendException: Failed messages: javax.mail.MessagingException: can't determine local email address; message exceptions (1) are:
Failed message 1: javax.mail.MessagingException: can't determine local email address"

with status code 500.

 public void sendConformationEmail(User user, Locale locale, String appUrl){

    String token = UUID.randomUUID().toString();
    createVerificationToken(user, token);

    String recipientAddress = user.getEmail();
    String subject = "IO Employee Registration Confirmation";
    String confirmationUrl = appUrl + "/email/confirm?token=" + token;
    String message = messages.getMessage("message.regSuccLink", null, "You registered successfully. To confirm your registration, please click on the below link.", locale);

    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo(recipientAddress);
    email.setSubject(subject);
    email.setFrom(env.getProperty("spring.mail.username"));

    email.setText(message + "\r\n" + serverAddress + confirmationUrl);
    mailSender.send(email);
}

I use the Gmail SMTP server.

As you can see I use setFrom() so that can not be the issue. can't determine local email address : Spring boot


问:
redirect requests to the old endpoints to the new controllers
In my app the Frontend sends request to

```<code>resources :orders, only: [:index, :create]
</code>```

but I built another route with a new controller, which is this one:

```<code>resources :new_orders, only: [:index, :create]
</code>```

Is there a way to redirect all requests coming from orders to the new created controller of new_orders?

I tried something like this:

```<code>:orders, only: [:index, :create], to: redirect('/new_orders')
</code>```

It uses the correct NewOrdersController and returns the json specified this controller. However the frontend can't find the orders.

Body:
In my app the Frontend sends request to

resources :orders, only: [:index, :create]

but I built another route with a new controller, which is this one:

resources :new_orders, only: [:index, :create]

Is there a way to redirect all requests coming from orders to the new created controller of new_orders?

I tried something like this:

:orders, only: [:index, :create], to: redirect('/new_orders')

It uses the correct NewOrdersController and returns the json specified this controller. However the frontend can't find the orders.


问:
SparkR logging method
What is the logging method for SparkR, the equivalent of SparklyR spark_log(sc, -1) method

E.g:get the SparklyR and in SparkR context
sc <- get_spark_connection()
sparkR.session()

#set the logging definition in SparkyR and SparkR
setup_logging(spark = "INFO", megdp = "INFO")
setLogLevel("ERROR")

How to get the logging object in SparkR please ?
Below the method in SparklyR

```<code>`logs <- spark_log(sc, -1)`
</code>```

Title: SparkR logging method

Body:
What is the logging method for SparkR, the equivalent of SparklyR spark_log(sc, -1) method

E.g:get the SparklyR and in SparkR context
sc <- get_spark_connection()
sparkR.session()

#set the logging definition in SparkyR and SparkR
setup_logging(spark = "INFO", megdp = "INFO")
setLogLevel("ERROR")

How to get the logging object in SparkR please ?
Below the method in SparklyR

`logs <- spark_log(sc, -1)`


问:
nativescript font awesome icons don't display on tabs template
I created an application using the tabs template in plain javcascript and the icons are not showing up.
Initializing photos also doesn't work, they only display via http/https.

I checked if the files from fontawesome are in the project, and I also used the documentation, but still nothing helped.

image


问:
Safari, Angular 15, and HTML Videos - Will not Autoplay in Safari
I have been banging my head againest the wall trying to figure this issue out. Consistently safari will not play html videos despite adding all the properties older stack overflow posts have shown. I have tried programatically showing the videos, manually typing the videos in the HTML and still have the same issues. This is with the video as a @ViewChild although I have also tried it as a native element using raw JS to target with the same issue being presented. How do I autoplay videos in safari?!

Error I usually get when I promisify video.play():

Play failed AbortError: The operation was aborted.

Formats:

Videos are all confirmed to be encoded in mp4 with audio tracks that also are supported in Safari according tot heir docs.

CDN the videos are stored on is a cloudfront CDN and does support Range GET requests

Versions I have tried (all with the same results):

<video
  #videoElement
  preload="none"
  [src]="src+'?ngsw-bypass=true'"
  [muted]="true"
  [playsInline]="true"
  [autoplay]="true"
  [loop]="true"
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  [src]="src"
  [muted]="true"
  [playsInline]="true"
  [autoplay]="true"
  [loop]="true"
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  [src]="src"
  muted
  playsInline
  autoplay
  loop
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  [src]="src"
  muted
  playsInline
  autoplay
  loop
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  muted
  playsInline
  autoplay
  loop>
  <source [src]="src" type="video/mp4"></source>
</video>

<video
  #videoElement
  [src]="src"
  type="video/mp4
>
</video>

```
<h3>TS Angular Component</h3>
<pre class="lang-js prettyprint-override"><code>
import {
  AfterViewInit,
  Component,
  ElementRef,
  Input,
  ViewChild,
} from '@angular/core';

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss'],
})
export class VideoComponent implements AfterViewInit {
  @ViewChild('videoElement') video: ElementRef<HTMLVideoElement>;
  @Input() src: string = '';

  constructor() {}

  async ngAfterViewInit() {
    if (this.video) {
      try {
        this.video.nativeElement.autoplay = true;
        this.video.nativeElement.loop = true;
        this.video.nativeElement.muted = true;
        this.video.nativeElement.playsInline = true;
        this.video.nativeElement.play()
      } catch (error) {
        console.log('Error Playing', error);
      }
  }
}

</code>```

Image of console error:

Body:
I have been banging my head againest the wall trying to figure this issue out. Consistently safari will not play html videos despite adding all the properties older stack overflow posts have shown. I have tried programatically showing the videos, manually typing the videos in the HTML and still have the same issues. This is with the video as a @ViewChild although I have also tried it as a native element using raw JS to target with the same issue being presented. How do I autoplay videos in safari?!

Error I usually get when I promisify video.play():

Play failed AbortError: The operation was aborted.

Formats:

Videos are all confirmed to be encoded in mp4 with audio tracks that also are supported in Safari according tot heir docs.

CDN the videos are stored on is a cloudfront CDN and does support Range GET requests

Versions I have tried (all with the same results):

<video
  #videoElement
  preload="none"
  [src]="src+'?ngsw-bypass=true'"
  [muted]="true"
  [playsInline]="true"
  [autoplay]="true"
  [loop]="true"
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  [src]="src"
  [muted]="true"
  [playsInline]="true"
  [autoplay]="true"
  [loop]="true"
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  [src]="src"
  muted
  playsInline
  autoplay
  loop
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  [src]="src"
  muted
  playsInline
  autoplay
  loop
  type="video/mp4">
</video>

<video
  #videoElement
  preload="none"
  muted
  playsInline
  autoplay
  loop>
  <source [src]="src" type="video/mp4"></source>
</video>

<video
  #videoElement
  [src]="src"
  type="video/mp4
>
</video>

TS Angular Component

import {
  AfterViewInit,
  Component,
  ElementRef,
  Input,
  ViewChild,
} from '@angular/core';

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss'],
})
export class VideoComponent implements AfterViewInit {
  @ViewChild('videoElement') video: ElementRef<HTMLVideoElement>;
  @Input() src: string = '';

  constructor() {}

  async ngAfterViewInit() {
    if (this.video) {
      try {
        this.video.nativeElement.autoplay = true;
        this.video.nativeElement.loop = true;
        this.video.nativeElement.muted = true;
        this.video.nativeElement.playsInline = true;
        this.video.nativeElement.play()
      } catch (error) {
        console.log('Error Playing', error);
      }
  }
}

Image of console error:


问:
Bar plot from two different datasets with different data range
I have the following datasets:

```<code>df1 = {'lower':[3.99,4.99,5.99,1700], 'percentile':[1,2,5,10,50,100]}
df2 = {'lower':[2.99,4.50,5,1850], 'percentile':[2,4,7,15,55,100]}
</code>```

The data:

The percentile refers to the percentage of the data that corresponds
to a particular price e.g: 3.99 would represent 1% of the data while
all values under 5.99 would represent 5% of the data.

The length of the two datasets is 100 given that we are showing percentiles, but they vary between the two datasets as the price.

What I have done so far:

What I need help with:

As you see in the third graph, I can plot the two datasets overlayed, which is what I need, but I have been unsuccessful trying to change the legend and the weird tick x values on the third graph. It is not showing the percentile, or other metrics I might use the x axis with.

Any help?

Body:
I have the following datasets:

df1 = {'lower':[3.99,4.99,5.99,1700], 'percentile':[1,2,5,10,50,100]}
df2 = {'lower':[2.99,4.50,5,1850], 'percentile':[2,4,7,15,55,100]}

The data:

The percentile refers to the percentage of the data that corresponds
to a particular price e.g: 3.99 would represent 1% of the data while
all values under 5.99 would represent 5% of the data.

The length of the two datasets is 100 given that we are showing percentiles, but they vary between the two datasets as the price.

What I have done so far:

What I need help with:

As you see in the third graph, I can plot the two datasets overlayed, which is what I need, but I have been unsuccessful trying to change the legend and the weird tick x values on the third graph. It is not showing the percentile, or other metrics I might use the x axis with.

Any help?


问:
MongoDB Aggregator to Group a list of objects into periods of 15 minutes
The idea here would be to group these values into periods of 15 minutes. But i'm not even completely sure where to start with the aggregators, in fact, since this are all a single MongoDb entity i'm not even sure if aggregators are the best way to go at this.

All the data needed for a single day is within the "value" key.

```<code>{
  "_id": {
    "$oid": "63a1d8cfcf1a43844d68ca0a"
  },
  "date": "2022-01-01",
  "values": [
    {
      "timestamp": "2022-01-01T00:00:00",
      "meterValue": "6",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:05:00",
      "meterValue": "20",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:10:00",
      "meterValue": "13",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:15:00",
      "meterValue": "4",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:20:00",
      "meterValue": "11",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:25:00",
      "meterValue": "5",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:30:00",
      "meterValue": "3",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:35:00",
      "meterValue": "16",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:40:00",
      "meterValue": "1",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:45:00",
      "meterValue": "0",
      "locationID": "LIS-00001"
    },...
  ]
}
</code>```

This would output something like:

```<code>{
  "date: "2022-01-01T00:15:00",
  "meterValueSum": 39
},
{
  "date": "2022-01-01T00:30:00",
  "meterValueSum": 20
},
{
  "date": "2022-01-01T00:45:00",
  "meterValueSum": 20
},...
</code>```

Body:
The idea here would be to group these values into periods of 15 minutes. But i'm not even completely sure where to start with the aggregators, in fact, since this are all a single MongoDb entity i'm not even sure if aggregators are the best way to go at this.

All the data needed for a single day is within the "value" key.

{
  "_id": {
    "$oid": "63a1d8cfcf1a43844d68ca0a"
  },
  "date": "2022-01-01",
  "values": [
    {
      "timestamp": "2022-01-01T00:00:00",
      "meterValue": "6",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:05:00",
      "meterValue": "20",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:10:00",
      "meterValue": "13",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:15:00",
      "meterValue": "4",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:20:00",
      "meterValue": "11",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:25:00",
      "meterValue": "5",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:30:00",
      "meterValue": "3",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:35:00",
      "meterValue": "16",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:40:00",
      "meterValue": "1",
      "locationID": "LIS-00001"
    },
    {
      "timestamp": "2022-01-01T00:45:00",
      "meterValue": "0",
      "locationID": "LIS-00001"
    },...
  ]
}

This would output something like:

{
  "date: "2022-01-01T00:15:00",
  "meterValueSum": 39
},
{
  "date": "2022-01-01T00:30:00",
  "meterValueSum": 20
},
{
  "date": "2022-01-01T00:45:00",
  "meterValueSum": 20
},...


问:
Ionic Cordova Camera Image Upload Issue
I am using MediaCapture library but getting 403. Below is my code:

```<code>MediaCapture.captureImage(options).then(
        async (data: any) => {
          const contents: any = await Filesystem.readFile({
            path: data[0].fullPath,
          });

          setPreviewImage(contents);
          let blobData: any = {};
          let formdata = new FormData();

          formdata.append(
            "file",
            `data:${data[0].type};base64,${contents.data}`
          );
          const response = (await axios.post(
            Endpoints.userCover,
            formdata
          )) as ServerResponse;
          if (response.status) {
            console.log(response);
            console.log("-------------------- IMAGE Camera");
          }
        },
        (err) => console.error(err, " error")
      );
</code>```

enter image description here

Getting 403 on MediaCapture library when using Camera but it's working when selecting image from the android Gallery.

Title: Ionic Cordova Camera Image Upload Issue

Body:
I am using MediaCapture library but getting 403. Below is my code:

MediaCapture.captureImage(options).then(
        async (data: any) => {
          const contents: any = await Filesystem.readFile({
            path: data[0].fullPath,
          });

          setPreviewImage(contents);
          let blobData: any = {};
          let formdata = new FormData();

          formdata.append(
            "file",
            `data:${data[0].type};base64,${contents.data}`
          );
          const response = (await axios.post(
            Endpoints.userCover,
            formdata
          )) as ServerResponse;
          if (response.status) {
            console.log(response);
            console.log("-------------------- IMAGE Camera");
          }
        },
        (err) => console.error(err, " error")
      );

enter image description here

Getting 403 on MediaCapture library when using Camera but it's working when selecting image from the android Gallery.


问:
pyttsx3 - interrupting as utterance not working
pyttsx3.init().stop() function not working.

I was finding a way to stop pyttsx3.innit.say() function and came across its
documentation.
And I got to know that it has a stop function given in an example. So I ran the code but it doesn't do anything. Also the code provided in the website has some errors too, like missing parentheses.

Coded provided on website:-

```<code>import pyttsx3
def onWord(name, location, length):
   print 'word', name, location, length
   if location > 10:
      engine.stop()
engine = pyttsx3.init()
engine.connect('started-word', onWord)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
</code>```

Body:
pyttsx3.init().stop() function not working.

I was finding a way to stop pyttsx3.innit.say() function and came across its
documentation.
And I got to know that it has a stop function given in an example. So I ran the code but it doesn't do anything. Also the code provided in the website has some errors too, like missing parentheses.

Coded provided on website:-

import pyttsx3
def onWord(name, location, length):
   print 'word', name, location, length
   if location > 10:
      engine.stop()
engine = pyttsx3.init()
engine.connect('started-word', onWord)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()


问:
Spring4D Marshmallow and TGuid fields
how could I use TGuid type fields together with the Marshmallow ORM? Methods like FindOne, for example, expect parameters of type TValue and when trying to use im TGuid, the error occurs: incompatible types: TValue and TGUID.

thanks.

some information or example of how to make such use.

Title: Spring4D Marshmallow and TGuid fields


问:
How can tooltip highlighting on Android Studio (like VSCode)
When developing with Flutter, tooltips on Android Studio has no highlighting.

But VS Code has highlighting.

How to add highlighting to Android Studio?

Thanks.

I searched many extenstions, but can't find out.


问:
TypeError: Cannot read properties of undefined (reading 'F_OK'), cannot read a local xlsx file in browser with ExcelJs in nextjs
i have been trying to read and fetch data from a local Excel file located at the project folder itself, and using excel js while readFile() it reads in vsCode terminal but it shows the Error.

"TypeError: Cannot read properties of undefined (reading 'F_OK')" while runnig on browser...

Here is the code:

```<code>async function readExcel() {
    const filePath ='result.xlsx'
    const workbook = new Excel.Workbook();

    try {
      await workbook.xlsx.readFile(filePath).then(() => {
        console.log("File read");
      });
      const sheet = workbook.getWorksheet('Sheet1')
      const title = sheet.getRow(2).getCell(1).value;
      console.log(title);

    } catch (error) {
      throw(error);
    }
}
</code>```

i want to get data from specific columns from the excel file located in my project folder, and using exceljs library it works fine in my terminal and not on browser.

Body:
i have been trying to read and fetch data from a local Excel file located at the project folder itself, and using excel js while readFile() it reads in vsCode terminal but it shows the Error.

"TypeError: Cannot read properties of undefined (reading 'F_OK')" while runnig on browser...

Here is the code:

async function readExcel() {
    const filePath ='result.xlsx'
    const workbook = new Excel.Workbook();

    try {
      await workbook.xlsx.readFile(filePath).then(() => {
        console.log("File read");
      });
      const sheet = workbook.getWorksheet('Sheet1')
      const title = sheet.getRow(2).getCell(1).value;
      console.log(title);

    } catch (error) {
      throw(error);
    }
}

i want to get data from specific columns from the excel file located in my project folder, and using exceljs library it works fine in my terminal and not on browser.


问:
Modifying database class method to get filenames of batch
I need to modify my dataloader such that it outputs the filenames of the images in a batch. The getitem method of my class only outputs the image and target class for a given index:

```<code>def __getitem__(self, index):
   """
   Read image at index and convert to torch Tensor
   """

   # Read image
   image_path = self.image_paths[index]
   image_data = Image.open(image_path)

   # Resize and convert image to torch tensor
   if self.transform is not None:
     image = self.transform(image_data)

   return image, self.image_labels[index]
</code>```

I want to replace this method, but without needing to make a new class so that my code will generalise to different databases. Therefore, I want to replace this method with the following method which additionally outputs of the filename of an image:

```<code>def __getitem2__(self, index):
   """
   Read image at index and convert to torch Tensor
   """

   # Read image
   image_path = self.image_paths[index]
   image_data = Image.open(image_path)

   # Resize and convert image to torch tensor
   if self.transform is not None:
     image = self.transform(image_data)

   #outputs image, target class and filename
   return image, self.image_labels[index], image_path
</code>```

I am able to modify the method of the class using the following code:

```<code>new_dataset.__getitem__ = types.MethodType(__getitem2__, new_dataset)
</code>```

I can validate that this has worked as the following code:

```<code>new_dataset.__getitem__(0)
</code>```

which outputs the image, target class and filename for image with index 0. However, when I try to enumerate this dataset:

```<code>for _, (image, target, filename) in enumerate(new_dataset):
    print(filename)
</code>```

I get an error:

ValueError: too many values to unpack (expected 3)

as enumerating the dataset only outputs the image and target class. Is there a way to rectify this, any help would be appreciated.

Body:
I need to modify my dataloader such that it outputs the filenames of the images in a batch. The getitem method of my class only outputs the image and target class for a given index:

def __getitem__(self, index):
   """
   Read image at index and convert to torch Tensor
   """

   # Read image
   image_path = self.image_paths[index]
   image_data = Image.open(image_path)

   # Resize and convert image to torch tensor
   if self.transform is not None:
     image = self.transform(image_data)

   return image, self.image_labels[index]

I want to replace this method, but without needing to make a new class so that my code will generalise to different databases. Therefore, I want to replace this method with the following method which additionally outputs of the filename of an image:

def __getitem2__(self, index):
   """
   Read image at index and convert to torch Tensor
   """

   # Read image
   image_path = self.image_paths[index]
   image_data = Image.open(image_path)

   # Resize and convert image to torch tensor
   if self.transform is not None:
     image = self.transform(image_data)

   #outputs image, target class and filename
   return image, self.image_labels[index], image_path

I am able to modify the method of the class using the following code:

new_dataset.__getitem__ = types.MethodType(__getitem2__, new_dataset)

I can validate that this has worked as the following code:

new_dataset.__getitem__(0)

which outputs the image, target class and filename for image with index 0. However, when I try to enumerate this dataset:

for _, (image, target, filename) in enumerate(new_dataset):
    print(filename)

I get an error:

ValueError: too many values to unpack (expected 3)

as enumerating the dataset only outputs the image and target class. Is there a way to rectify this, any help would be appreciated.


问:
Laravel - Duplicate record to other database - eloquent model
I am trying to duplicate rows with a given product_id and a given cart_product_id from database mysqlProducts - table ind_products to database mysqlOrders - table cart_ind_products.

My models:

```<code>class IndProduct extends Model {
  use HasFactory;

  protected $connection = 'mysqlProducts';

  protected $table = "ind_products";

  protected $fillable = [
    'product_id',
    'name',
    'category',
    'subcategory',
    'description',
    'price_VAT_excl_per_unit',
    'price_VAT_incl_per_unit',
    'weight',
    'breed',
    'kind',
    'age',
    'bio',
    'grass_fed',
    'drying_time',
    'nr_of_pieces',
    'lifestyle',
    'part_of_animal',
    'confirmed',
    'saved',
  ];

  //an individual product belongs to a product
  public

  function products() {
    return $this - > setConnection('mysqlProducts') - > belongsTo(Product::class, 'product_id', 'id');
  }
}

class CartIndProduct extends Model {
  use HasFactory;

  protected $connection = 'mysqlOrders';

  protected $table = "cart_ind_products";

  protected $fillable = [
    'cart_product_id',
    'product1_id',
    'name',
    'category',
    'subcategory',
    'description',
    'price_VAT_excl_per_unit',
    'price_VAT_incl_per_unit',
    'weight',
    'breed',
    'kind',
    'age',
    'bio',
    'grass_fed',
    'drying_time',
    'nr_of_pieces',
    'lifestyle',
    'part_of_animal',
    'confirmed',
    'saved',
  ];

  //A cart individual product belongs to a cart product
  public

  function cart_products() {
    return $this - > setConnection('mysqlOrders') - > hasOne(CartProduct::class, 'cart_product_id', 'id');
  }
}
</code>```

CartIndProductController:

```<code>public function createCartIndProducts(Request $request, $cart_product_id, $product_id) {
  $ind_products = IndProduct::on('mysqlProducts') - > where('product_id', '=', $product_id) - > get() - > toArray();

  foreach($ind_products as $ind_product) {
    CartIndProduct::on('mysqlOrders') - > insert($ind_product);
  }
  return response() - > json([
    "status" => 1,
    "message" => "Cart individual products registered successfully in database.",
  ], 200);

}
</code>```

I get the following error:
"SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2022-10-28T19:54:12.000000Z' for column 'created_at' at row 1 (SQL: insert into cart_ind_products (id, name, category, subcategory, description, price_VAT_excl_per_unit, price_VAT_incl_per_unit, weight, created_at, updated_at, product_id, breed, kind, age, bio, grass_fed, drying_time, nr_of_pieces, lifestyle, part_of_animal, confirmed, saved) values (656, ?, Aardappelen, ?, ?, 0.00, 0.00, ?, 2022-10-28T19:54:12.000000Z, 2022-10-28T19:54:12.000000Z, 903, bjbg, ?, ?, 0, ?, ?, ?, ?, ?, 1, 1))"

I also tried the following, but also without luck..

```<code>public function createCartIndProducts(Request $request, $cart_product_id, $product_id) {
  $ind_products = IndProduct::on('mysqlProducts') - > where('product_id', '=', $product_id) - > get();

  foreach($ind_products as $ind_product) {
    $cart_ind_product = IndProduct::on('mysqlProducts') - > $ind_product - > replicate() -
      > fill(
        ['cart_product_id' => $cart_product_id, ]
      );
    $cart_ind_product - > CartIndProduct::on('mysqlOrders') - > save();

  }
  return response() - > json([
    "status" => 1,
    "message" => "Cart individual products registered successfully in database.",
    //    "data" => $cart_ind_products,
  ], 200);
}
</code>```

This time I recieve the following error:

"Property [{"id":656,"name":null,"category":"Aardappelen","subcategory":null,"description":null,"price_VAT_excl_per_unit":"0.00","price_VAT_incl_per_unit":"0.00","weight":null,"created_at":"2022-10-28T19:54:12.000000Z","updated_at":"2022-10-28T19:54:12.000000Z","product_id":903,"breed":"bjbg","kind":null,"age":null,"bio":0,"grass_fed":null,"drying_time":null,"nr_of_pieces":null,"lifestyle":null,"part_of_animal":null,"confirmed":1,"saved":1}] does not exist on the Eloquent builder instance.",

What am I doing wrong?

Body:
I am trying to duplicate rows with a given product_id and a given cart_product_id from database mysqlProducts - table ind_products to database mysqlOrders - table cart_ind_products.

My models:

class IndProduct extends Model {
  use HasFactory;

  protected $connection = 'mysqlProducts';

  protected $table = "ind_products";

  protected $fillable = [
    'product_id',
    'name',
    'category',
    'subcategory',
    'description',
    'price_VAT_excl_per_unit',
    'price_VAT_incl_per_unit',
    'weight',
    'breed',
    'kind',
    'age',
    'bio',
    'grass_fed',
    'drying_time',
    'nr_of_pieces',
    'lifestyle',
    'part_of_animal',
    'confirmed',
    'saved',
  ];

  //an individual product belongs to a product
  public

  function products() {
    return $this - > setConnection('mysqlProducts') - > belongsTo(Product::class, 'product_id', 'id');
  }
}

class CartIndProduct extends Model {
  use HasFactory;

  protected $connection = 'mysqlOrders';

  protected $table = "cart_ind_products";

  protected $fillable = [
    'cart_product_id',
    'product1_id',
    'name',
    'category',
    'subcategory',
    'description',
    'price_VAT_excl_per_unit',
    'price_VAT_incl_per_unit',
    'weight',
    'breed',
    'kind',
    'age',
    'bio',
    'grass_fed',
    'drying_time',
    'nr_of_pieces',
    'lifestyle',
    'part_of_animal',
    'confirmed',
    'saved',
  ];

  //A cart individual product belongs to a cart product
  public

  function cart_products() {
    return $this - > setConnection('mysqlOrders') - > hasOne(CartProduct::class, 'cart_product_id', 'id');
  }
}

CartIndProductController:

public function createCartIndProducts(Request $request, $cart_product_id, $product_id) {
  $ind_products = IndProduct::on('mysqlProducts') - > where('product_id', '=', $product_id) - > get() - > toArray();

  foreach($ind_products as $ind_product) {
    CartIndProduct::on('mysqlOrders') - > insert($ind_product);
  }
  return response() - > json([
    "status" => 1,
    "message" => "Cart individual products registered successfully in database.",
  ], 200);

}

I get the following error:
"SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2022-10-28T19:54:12.000000Z' for column 'created_at' at row 1 (SQL: insert into cart_ind_products (id, name, category, subcategory, description, price_VAT_excl_per_unit, price_VAT_incl_per_unit, weight, created_at, updated_at, product_id, breed, kind, age, bio, grass_fed, drying_time, nr_of_pieces, lifestyle, part_of_animal, confirmed, saved) values (656, ?, Aardappelen, ?, ?, 0.00, 0.00, ?, 2022-10-28T19:54:12.000000Z, 2022-10-28T19:54:12.000000Z, 903, bjbg, ?, ?, 0, ?, ?, ?, ?, ?, 1, 1))"

I also tried the following, but also without luck..

public function createCartIndProducts(Request $request, $cart_product_id, $product_id) {
  $ind_products = IndProduct::on('mysqlProducts') - > where('product_id', '=', $product_id) - > get();

  foreach($ind_products as $ind_product) {
    $cart_ind_product = IndProduct::on('mysqlProducts') - > $ind_product - > replicate() -
      > fill(
        ['cart_product_id' => $cart_product_id, ]
      );
    $cart_ind_product - > CartIndProduct::on('mysqlOrders') - > save();

  }
  return response() - > json([
    "status" => 1,
    "message" => "Cart individual products registered successfully in database.",
    //    "data" => $cart_ind_products,
  ], 200);
}

This time I recieve the following error:

"Property [{"id":656,"name":null,"category":"Aardappelen","subcategory":null,"description":null,"price_VAT_excl_per_unit":"0.00","price_VAT_incl_per_unit":"0.00","weight":null,"created_at":"2022-10-28T19:54:12.000000Z","updated_at":"2022-10-28T19:54:12.000000Z","product_id":903,"breed":"bjbg","kind":null,"age":null,"bio":0,"grass_fed":null,"drying_time":null,"nr_of_pieces":null,"lifestyle":null,"part_of_animal":null,"confirmed":1,"saved":1}] does not exist on the Eloquent builder instance.",

What am I doing wrong?


问:
My code to print an int variable in text in pygame isn't working, how can I make it work?
I enter this code but all that appears is a black rectangle. What do I do to make it output the player_score variable in text?.

```<code>font = pygame.font.Font("LEMONMILK-Regular.otf", 30)

player_score = 0
player_score_text = font.render(str(player_score), True, pygame.Color("black"), pygame.Color("white"))

player_score_rect = player_score_text.get_rect()
player_score_rect.center = (200,200)

pygame.draw.rect(screen, black, player_score_rect)

</code>```

I'm trying to make player_score appear on the screen in the LEMONMILK-Regular.otf font as text.

Body:
I enter this code but all that appears is a black rectangle. What do I do to make it output the player_score variable in text?.

font = pygame.font.Font("LEMONMILK-Regular.otf", 30)

player_score = 0
player_score_text = font.render(str(player_score), True, pygame.Color("black"), pygame.Color("white"))

player_score_rect = player_score_text.get_rect()
player_score_rect.center = (200,200)

pygame.draw.rect(screen, black, player_score_rect)

I'm trying to make player_score appear on the screen in the LEMONMILK-Regular.otf font as text.


问:
the trait `std::convert::From<rusqlite::Error>` is not implemented for `std::io::Error`
I've tried replacing Result<()> with Result<(), std::io::Error> But it results in: more errors.

Error:

```<code>error[E0277]: `?` couldn't convert the error to `std::io::Error`
  --> src/main.rs:48:53
   |
48 |     let conn = rusqlite::Connection::open("data.db")?;
   |                                                     ^ the trait `std::convert::From<rusqlite::Error>` is not implemented for `std::io::Error`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following other types implement trait `std::convert::From<T>`:
             <std::io::Error as std::convert::From<ErrorKind>>
             <std::io::Error as std::convert::From<IntoInnerError<W>>>
             <std::io::Error as std::convert::From<JoinError>>
             <std::io::Error as std::convert::From<flate2::mem::CompressError>>
             <std::io::Error as std::convert::From<flate2::mem::DecompressError>>
             <std::io::Error as std::convert::From<getrandom::error::Error>>
             <std::io::Error as std::convert::From<httpdate::Error>>
             <std::io::Error as std::convert::From<rand_core::error::Error>>
           and 5 others
   = note: required for `Result<(), std::io::Error>` to implement `FromResidual<Result<Infallible, rusqlite::Error>>`
</code>```

my code:

```<code>#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let conn = rusqlite::Connection::open("data.db")?;
    conn.execute(r#"
        CREATE TABLE IF NOT EXISTS user (
            usid INT,
            name VARCHAR(256),
            pass VARCHAR(512),
            mail VARCHAR(256)
        )
    "#, [])?;
    HttpServer::new(|| {
        App::new()
            .service(_main)
            // ... Multiple Other Services
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
</code>```

Body:
I've tried replacing Result<()> with Result<(), std::io::Error> But it results in: more errors.

Error:

error[E0277]: `?` couldn't convert the error to `std::io::Error`
  --> src/main.rs:48:53
   |
48 |     let conn = rusqlite::Connection::open("data.db")?;
   |                                                     ^ the trait `std::convert::From<rusqlite::Error>` is not implemented for `std::io::Error`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following other types implement trait `std::convert::From<T>`:
             <std::io::Error as std::convert::From<ErrorKind>>
             <std::io::Error as std::convert::From<IntoInnerError<W>>>
             <std::io::Error as std::convert::From<JoinError>>
             <std::io::Error as std::convert::From<flate2::mem::CompressError>>
             <std::io::Error as std::convert::From<flate2::mem::DecompressError>>
             <std::io::Error as std::convert::From<getrandom::error::Error>>
             <std::io::Error as std::convert::From<httpdate::Error>>
             <std::io::Error as std::convert::From<rand_core::error::Error>>
           and 5 others
   = note: required for `Result<(), std::io::Error>` to implement `FromResidual<Result<Infallible, rusqlite::Error>>`

my code:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let conn = rusqlite::Connection::open("data.db")?;
    conn.execute(r#"
        CREATE TABLE IF NOT EXISTS user (
            usid INT,
            name VARCHAR(256),
            pass VARCHAR(512),
            mail VARCHAR(256)
        )
    "#, [])?;
    HttpServer::new(|| {
        App::new()
            .service(_main)
            // ... Multiple Other Services
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}


问:
Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 11020), found shape=(None, 6819)
Everyone....
I got this error....
please give me solution on this error....

```<code>Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 11020), found shape=(None, 6819)

</code>```
```<code>model=Sequential([Dense(10000,activation='tanh',input_shape=(X_train.shape[1],)),
                 Dense(500,activation='relu'),
                 Dense(250,activation='tanh'),
                 Dense(3,activation='softmax')])
</code>```

model.summary()

model.compile(optimizer='adam',loss='SparseCategoricalCrossentropy',metrics=['accuracy'])

history=model.fit(X_train,Y_train,epochs=10,batch_size=500,validation_data=(X_test,Y_test))

Body:
Everyone....
I got this error....
please give me solution on this error....

Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 11020), found shape=(None, 6819)

model=Sequential([Dense(10000,activation='tanh',input_shape=(X_train.shape[1],)),
                 Dense(500,activation='relu'),
                 Dense(250,activation='tanh'),
                 Dense(3,activation='softmax')])

model.summary()

model.compile(optimizer='adam',loss='SparseCategoricalCrossentropy',metrics=['accuracy'])

history=model.fit(X_train,Y_train,epochs=10,batch_size=500,validation_data=(X_test,Y_test))


问:
How to check kubectl execution history of a kubernetes cluster?
Suppose I have a Kubernetes cluster, devops manages the cluster using kubectl. How can I track the kubectl execution on the cluster to monitor if there is any suspicious activities?</p>


问:
Trying to create & use a conan package: lib dir not set
I created a conan package for a 3rd party tool. I'm trying to test it, and it doesn't seem to add the lib dir so the linker can't find the package's lib. Not sure how to debug it.

Here's the conanfile.py for the package ("hjson"):

class HjsonConan(ConanFile):
    name = "hjson"
    version = "2.2"
    url = "https://github.com/hjson/hjson-cpp"
    license="MIT"

    # Optional metadata
    description = "hjson C++ json library"

    # Binary configuration
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False], "fPIC": [True, False], "version": "ANY"}
    default_options = {"shared": False, "fPIC": True, "version": "2.2"}

    # Sources are located in the same place as this recipe, copy them to the recipe
    exports_sources = ("hjson-src/*")

    def source(self):
        # unpacks into ./hjson-src
        get(self,
            f"https://github.com/hjson/hjson-cpp/archive/refs/tags/{self.options.version}.tar.gz",
            destination='hjson-src',
            strip_root=True)

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def layout(self):
        # Sets source=., build=build/Release, generators=build/generators
        cmake_layout(self)

    def generate(self):
        tc = CMakeToolchain(self)
        # Here is where to set CMake variables ("-DXYZ")
        tc.variables["HJSON_ENABLE_INSTALL"] = 1
        tc.generate()

    def build(self):
        cmake = CMake(self)
        cmake.configure(build_script_folder='hjson-src')
        cmake.build()

    def package(self):
        cmake = CMake(self)
        cmake.install()

    def package_info(self):
        self.cpp_info.libs = ["hjson"]
        # these are the defaults, here for clarity
        self.cpp_info.includedirs = ["include"]
        self.cpp_info.libdirs = ["lib"]
```
<p>Running <code>conan create .</code> works; it populates a subdir of my <code>~/.conan</code> with the lib and headers and other metadata.</p>
<p>So I try to use it, with this conanfile:</p>
<pre class="lang-py prettyprint-override"><code>from conan import ConanFile
from conan.tools.cmake import CMake, cmake_layout
from conan.tools.build import cross_building

class HJsonTestConan(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    # VirtualBuildEnv and VirtualRunEnv can be avoided if "tools.env.virtualenv:auto_use" is defined
    # (it will be defined in Conan 2.0)
    generators = "CMakeDeps", "CMakeToolchain", "VirtualBuildEnv", "VirtualRunEnv"
    apply_env = False
    test_type = "explicit"

    def requirements(self):
        self.requires("hjson/2.2")

    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

    def layout(self):
        cmake_layout(self)

    def test(self):
        if not cross_building(self):
            cmd = os.path.join(self.cpp.build.bindirs[0], "example")
            self.run(cmd, env="conanrun")
</code>```

with this CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.15)
project(PackageTest CXX)

find_package(hjson CONFIG REQUIRED)

add_executable(example src/example.cpp)
set_property(TARGET example PROPERTY CXX_STANDARD 20)
include_directories(${hjson_INCLUDE_DIRS})
link_directories(${hjson_LIB_DIRS})
target_link_libraries(example hjson)
</code>```

but the link fails because it's not passing -L<conanpath> on the link line. Poking around, it looks like hjson_LIB_DIRS is not set in the generated build/generators/hjson-config.cmake:

```<code>set(hjson_VERSION_STRING "2.2")
set(hjson_INCLUDE_DIRS ${hjson_INCLUDE_DIRS_RELEASE} )
set(hjson_INCLUDE_DIR ${hjson_INCLUDE_DIRS_RELEASE} )
set(hjson_LIBRARIES ${hjson_LIBRARIES_RELEASE} )
set(hjson_DEFINITIONS ${hjson_DEFINITIONS_RELEASE} )
</code>```

So where do I go to fix that? I did set the cpp_info.libdirs in the package, so not sure why it's not getting through to the generated config.

The created conan package looks like this, btw:

```<code>~/.conan/data/hjson/2.2/_/_/package/37c9d02f...91ef
├── conaninfo.txt
├── conanmanifest.txt
├── include
│  └── hjson
│     └── hjson.h
└── lib
   ├── hjson
   │  ├── hjson-config-version.cmake
   │  ├── hjson-config.cmake
   │  ├── hjson-release.cmake
   │  └── hjson.cmake
   └── libhjson.a
</code>```

Body:
I created a conan package for a 3rd party tool. I'm trying to test it, and it doesn't seem to add the lib dir so the linker can't find the package's lib. Not sure how to debug it.

Here's the conanfile.py for the package ("hjson"):

class HjsonConan(ConanFile):
    name = "hjson"
    version = "2.2"
    url = "https://github.com/hjson/hjson-cpp"
    license="MIT"

    # Optional metadata
    description = "hjson C++ json library"

    # Binary configuration
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False], "fPIC": [True, False], "version": "ANY"}
    default_options = {"shared": False, "fPIC": True, "version": "2.2"}

    # Sources are located in the same place as this recipe, copy them to the recipe
    exports_sources = ("hjson-src/*")

    def source(self):
        # unpacks into ./hjson-src
        get(self,
            f"https://github.com/hjson/hjson-cpp/archive/refs/tags/{self.options.version}.tar.gz",
            destination='hjson-src',
            strip_root=True)

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def layout(self):
        # Sets source=., build=build/Release, generators=build/generators
        cmake_layout(self)

    def generate(self):
        tc = CMakeToolchain(self)
        # Here is where to set CMake variables ("-DXYZ")
        tc.variables["HJSON_ENABLE_INSTALL"] = 1
        tc.generate()

    def build(self):
        cmake = CMake(self)
        cmake.configure(build_script_folder='hjson-src')
        cmake.build()

    def package(self):
        cmake = CMake(self)
        cmake.install()

    def package_info(self):
        self.cpp_info.libs = ["hjson"]
        # these are the defaults, here for clarity
        self.cpp_info.includedirs = ["include"]
        self.cpp_info.libdirs = ["lib"]

Running conan create . works; it populates a subdir of my ~/.conan with the lib and headers and other metadata.

So I try to use it, with this conanfile:

from conan import ConanFile
from conan.tools.cmake import CMake, cmake_layout
from conan.tools.build import cross_building

class HJsonTestConan(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    # VirtualBuildEnv and VirtualRunEnv can be avoided if "tools.env.virtualenv:auto_use" is defined
    # (it will be defined in Conan 2.0)
    generators = "CMakeDeps", "CMakeToolchain", "VirtualBuildEnv", "VirtualRunEnv"
    apply_env = False
    test_type = "explicit"

    def requirements(self):
        self.requires("hjson/2.2")

    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

    def layout(self):
        cmake_layout(self)

    def test(self):
        if not cross_building(self):
            cmd = os.path.join(self.cpp.build.bindirs[0], "example")
            self.run(cmd, env="conanrun")

with this CMakeLists.txt:

cmake_minimum_required(VERSION 3.15)
project(PackageTest CXX)

find_package(hjson CONFIG REQUIRED)

add_executable(example src/example.cpp)
set_property(TARGET example PROPERTY CXX_STANDARD 20)
include_directories(${hjson_INCLUDE_DIRS})
link_directories(${hjson_LIB_DIRS})
target_link_libraries(example hjson)

but the link fails because it's not passing -L<conanpath> on the link line. Poking around, it looks like hjson_LIB_DIRS is not set in the generated build/generators/hjson-config.cmake:

set(hjson_VERSION_STRING "2.2")
set(hjson_INCLUDE_DIRS ${hjson_INCLUDE_DIRS_RELEASE} )
set(hjson_INCLUDE_DIR ${hjson_INCLUDE_DIRS_RELEASE} )
set(hjson_LIBRARIES ${hjson_LIBRARIES_RELEASE} )
set(hjson_DEFINITIONS ${hjson_DEFINITIONS_RELEASE} )

So where do I go to fix that? I did set the cpp_info.libdirs in the package, so not sure why it's not getting through to the generated config.

The created conan package looks like this, btw:

~/.conan/data/hjson/2.2/_/_/package/37c9d02f...91ef
├── conaninfo.txt
├── conanmanifest.txt
├── include
│  └── hjson
│     └── hjson.h
└── lib
   ├── hjson
   │  ├── hjson-config-version.cmake
   │  ├── hjson-config.cmake
   │  ├── hjson-release.cmake
   │  └── hjson.cmake
   └── libhjson.a


问:
How to access native string formatting engine in browsers? (util.format for browser)
I find it very convenient to use native printf-like formatting abilities of the console for printing. However, I could not find a way to format strings the same way to reuse them (without printing).
I'm aware of ES6 literal templates, and util.format() in node.js, but looking for a way to access and use the same native formatting abilities of the console in browsers, without inventing a wheel and adding external dependencies.

Say, we have code:

const user1 = { name: "Mike", age: 42 };
const user2 = { name: "John", age: 24 };
const template = "Hi, %s! You are %d years old. Obj:";
```
<p>Example 1:</p>
<pre class="lang-js prettyprint-override"><code>console.log(template, user1.name, user1.age, user1);
some_func1(???);
some_func2(???);
console.log(template, user2.name, user2.age, user2);
some_func1(???);
some_func2(???);

// Problem: only prints, cannot re-use formatted string
</code>```

Example 2:

let str_out;
str_out = "Hi ${user1.name}! You are ${user1.age} years old. Obj: ${JSON.stringify(user1)}";
console.log(str_out);
some_func1(str_out);
some_func2(str_out);
str_out =  "Hi ${user2.name}! You are ${user2.age} years old. Obj: ${JSON.stringify(user2)}";
console.log(str_out);
some_func1(str_out);
some_func2(str_out);

// Problem: very inconvenient, very bulky code, have to copy-paste and edit code (very bad practices)
```
<p>Example 3:</p>
<pre class="lang-js prettyprint-override"><code>function sprintf(fmt, ...args) { return this.replace(...); }; // inventing a wheel
let str_out;
str_out = sprintf(template, user1.name, user1.age, user1);
console.log(str_out);
some_func1(str_out);
some_func2(str_out);
str_out = sprintf(template, user2.name, user2.age, user2);
console.log(str_out);
some_func1(str_out);
some_func2(str_out);

// Problem: have to use library or copy-paste code
</code>```

So, the question is: is it possible at all to access native printf-like string formatting abilities of the console for browsers? At least at the moment.

Body:
I find it very convenient to use native printf-like formatting abilities of the console for printing. However, I could not find a way to format strings the same way to reuse them (without printing).
I'm aware of ES6 literal templates, and util.format() in node.js, but looking for a way to access and use the same native formatting abilities of the console in browsers, without inventing a wheel and adding external dependencies.

Say, we have code:

const user1 = { name: "Mike", age: 42 };
const user2 = { name: "John", age: 24 };
const template = "Hi, %s! You are %d years old. Obj:";

Example 1:

console.log(template, user1.name, user1.age, user1);
some_func1(???);
some_func2(???);
console.log(template, user2.name, user2.age, user2);
some_func1(???);
some_func2(???);

// Problem: only prints, cannot re-use formatted string

Example 2:

let str_out;
str_out = "Hi ${user1.name}! You are ${user1.age} years old. Obj: ${JSON.stringify(user1)}";
console.log(str_out);
some_func1(str_out);
some_func2(str_out);
str_out =  "Hi ${user2.name}! You are ${user2.age} years old. Obj: ${JSON.stringify(user2)}";
console.log(str_out);
some_func1(str_out);
some_func2(str_out);

// Problem: very inconvenient, very bulky code, have to copy-paste and edit code (very bad practices)

Example 3:

function sprintf(fmt, ...args) { return this.replace(...); }; // inventing a wheel
let str_out;
str_out = sprintf(template, user1.name, user1.age, user1);
console.log(str_out);
some_func1(str_out);
some_func2(str_out);
str_out = sprintf(template, user2.name, user2.age, user2);
console.log(str_out);
some_func1(str_out);
some_func2(str_out);

// Problem: have to use library or copy-paste code

So, the question is: is it possible at all to access native printf-like string formatting abilities of the console for browsers? At least at the moment.


问:
How to wrap text in a "p" so It doesn't effect other elements
Text wrap issue (https://i.stack.imgur.com/kl1Y5.png)

Hi all, I have been learning html and css for about 3 weeks now. I am just screwing around with some personal beginner projects. Im having an issue with this one. I have more text in the
 for the kd shoe than I do with the jordan shoe so It spreads longer and shrinks the button. What are my options to fix this? Again very new please dont judge lol! I have attatched the image of whats wrong and my code. code
css

Again I am new and learning so dont roast me too hard.

I dont know what to try.


问:
How do I keep scipy's loadmat() from implicitly converting complex data types into reals while keeping the original data types?
Using SciPy 1.9.3 in Python 3.11.1, I am attempting to load data from a MATLAB mat file, which contains a couple matrices with complex doubles.  When I execute scipi.io.loadmat(filename, matlab_compatible=True), I get the following warning message:

```<code>ComplexWarning: Casting complex values to real discards the imaginary part
</code>```

And, indeed, the loaded matrices contain just the real component of the complex numbers. After trying some variations, I was finally able to get complex data loaded, with a caveat.  It seems the issue is related to the mat_dtype=True parameter, which is implicitly set with matlab_compatible=True.  If I set it to False, then I get complex numbers. However, it also means that various other loaded arrays in the file may be of a smaller storage class than they should be (because MATLAB will potentially use a smaller storage class to save space).

So, how do I keep the original storage class (as would be loaded in MATLAB), but also keep the complex numbers?

Body:
Using SciPy 1.9.3 in Python 3.11.1, I am attempting to load data from a MATLAB mat file, which contains a couple matrices with complex doubles.  When I execute scipi.io.loadmat(filename, matlab_compatible=True), I get the following warning message:

ComplexWarning: Casting complex values to real discards the imaginary part

And, indeed, the loaded matrices contain just the real component of the complex numbers. After trying some variations, I was finally able to get complex data loaded, with a caveat.  It seems the issue is related to the mat_dtype=True parameter, which is implicitly set with matlab_compatible=True.  If I set it to False, then I get complex numbers. However, it also means that various other loaded arrays in the file may be of a smaller storage class than they should be (because MATLAB will potentially use a smaller storage class to save space).

So, how do I keep the original storage class (as would be loaded in MATLAB), but also keep the complex numbers?


问:
here polyline does not show on openlayers 6
I m working width openlayer 6.
Data comes from here API.
I cant get to work route line from polyline.
code with working polyline example:

```<code>var coord = 'on`iJyxatCdT~RsStrAwMbj@sIjp@oWtdA{CfZgAff@iy@jEsTpIyN`VsL_Q';

                let icon_url = '//cdn.rawgit.com/openlayers/ol3/master/examples/data/icon.png';
                let styles = {
                    route: new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            width: 6, color: [40, 40, 40, 0.8]
                        })
                    })
                };
                let vectorSource = new ol.source.Vector();
                let vectorLayer = new ol.layer.Vector({
                    source: vectorSource
                });

                var route = new ol.format.Polyline({
                    factor: 1e5
                }).readGeometry(coord, {
                        dataProjection: 'EPSG:4326',
                        featureProjection: 'EPSG:3857'
                    });
                var feature = new ol.Feature({
                    type: 'route',
                    geometry: route
                });
                feature.setStyle(styles.route);
                vectorSource.addFeature(feature);

                map.addLayer(vectorLayer);
</code>```

but if i replace coord to here polyline then it does not work - no errors, no lines in map.
here polyline example:

```<code>var coord = 'BGo1kkxDkpvxuB_C0IjN_YjhB7G_E_d7L0K_Y4S3X4SrJ8GrOwCnBvCvCzK7B7G7BzF7B_EAzFTjDnBrEvCvC3DT3DUzF8BrEoBrET_E7BrEvC_JnGnGrErEvCzFvCvHjD_nB7QjmBzPoB7aoBnfoB_dU7kBAzZT7VnBvbTzPoBnBoBvCUjDTjDnBvC7BnBnBzP7BjS7B3SjDnarEnfrJnsC7B_OjI_gC7BjN_EjmB_Jn7C3DjcvCrTjDrYjD3X7B7Q3DnfnQ3gE_On0DvH_7BrEvlB3DvgBvCzZvC7avCjcvCjc_EzmC7G7gD7BzZnG_0CnLz2EzFrvC7Bze7Gj9CvC7kBrEz3BvC_djDvlBjDriBvCnajDvb3DnfnG3rB_EzerErY_EnazFvbnG3cvHnfvH3cvHna3Ijc3I7arJ3c_J_dzKvgB_qC7iHvwD71K7Q_xBrEjNrEjNzP3wBvgB7gDjIvWjI7VzFrOnG_O3IrTzFnL_JjS7G7LvHnLjInL3IzKrJnLrJzKzKnL7L7LvM7L_O3NrqC_gC7kBvgBztB3mBjX_T_TjSjN7L3IrJvHjIjIrJrJ7LvHnLvH7L7GvM7G3NzF3N_EjNzF7QzFrT_EjSrEjS7G_dnGjc7GjhBvbjgEriB3';
</code>```

is here polyline in some other encoded format ?
is it possible to decode here polyline to some other format ?

Body:
I m working width openlayer 6.
Data comes from here API.
I cant get to work route line from polyline.
code with working polyline example:

var coord = 'on`iJyxatCdT~RsStrAwMbj@sIjp@oWtdA{CfZgAff@iy@jEsTpIyN`VsL_Q';

                let icon_url = '//cdn.rawgit.com/openlayers/ol3/master/examples/data/icon.png';
                let styles = {
                    route: new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            width: 6, color: [40, 40, 40, 0.8]
                        })
                    })
                };
                let vectorSource = new ol.source.Vector();
                let vectorLayer = new ol.layer.Vector({
                    source: vectorSource
                });

                var route = new ol.format.Polyline({
                    factor: 1e5
                }).readGeometry(coord, {
                        dataProjection: 'EPSG:4326',
                        featureProjection: 'EPSG:3857'
                    });
                var feature = new ol.Feature({
                    type: 'route',
                    geometry: route
                });
                feature.setStyle(styles.route);
                vectorSource.addFeature(feature);

                map.addLayer(vectorLayer);

but if i replace coord to here polyline then it does not work - no errors, no lines in map.
here polyline example:

var coord = 'BGo1kkxDkpvxuB_C0IjN_YjhB7G_E_d7L0K_Y4S3X4SrJ8GrOwCnBvCvCzK7B7G7BzF7B_EAzFTjDnBrEvCvC3DT3DUzF8BrEoBrET_E7BrEvC_JnGnGrErEvCzFvCvHjD_nB7QjmBzPoB7aoBnfoB_dU7kBAzZT7VnBvbTzPoBnBoBvCUjDTjDnBvC7BnBnBzP7BjS7B3SjDnarEnfrJnsC7B_OjI_gC7BjN_EjmB_Jn7C3DjcvCrTjDrYjD3X7B7Q3DnfnQ3gE_On0DvH_7BrEvlB3DvgBvCzZvC7avCjcvCjc_EzmC7G7gD7BzZnG_0CnLz2EzFrvC7Bze7Gj9CvC7kBrEz3BvC_djDvlBjDriBvCnajDvb3DnfnG3rB_EzerErY_EnazFvbnG3cvHnfvH3cvHna3Ijc3I7arJ3c_J_dzKvgB_qC7iHvwD71K7Q_xBrEjNrEjNzP3wBvgB7gDjIvWjI7VzFrOnG_O3IrTzFnL_JjS7G7LvHnLjInL3IzKrJnLrJzKzKnL7L7LvM7L_O3NrqC_gC7kBvgBztB3mBjX_T_TjSjN7L3IrJvHjIjIrJrJ7LvHnLvH7L7GvM7G3NzF3N_EjNzF7QzFrT_EjSrEjS7G_dnGjc7GjhBvbjgEriB3';

is here polyline in some other encoded format ?
is it possible to decode here polyline to some other format ?


问:
How to troubleshoot docker not able to start
The docker was working fine for me but today I start seeing following error in Docker desktop.

Command line showing following error.

I have restarted the service but still getting the same error. I looked in events viewer but it does not show any error. Any idea how can I troubleshoot this issue?


问:
Lmfit fit produces huge uncertainties
I am using the lmfit library in Python and I get huge uncertainties. I have noticed it happens when the best fit parameter itself is very small. Do you know how the fitting uncertainties are evaluated?

Here I show an example of a Voigt fit result (Voigt is a convolution of a Gaussian and Lorentzian). The program suggests that the Lorentzian width (lwid8) is very, very small (so the profile should be just Gaussian I suppose). The first column is the best fit result and the second column is the error. [gaussian and lorenzian width output errors]

gwid8:   0.06615227 +/- 0.02554561 (38.62%) (init = 0.1)

lwid8:   1.0736e-04 +/- 1.51371359 (1409918.22%) (init = 0.001)

Title: Lmfit fit produces huge uncertainties