问:
How to pass the id inside of the column index Angular
I'm trying to pass my response id to this.names[i].ArrayListID per column index but it won't get it. how to achieve that?

```<code>export interface Names {
  ArrayListID: number;
  itemName: string;
}

names: Names[] = [];
responseID:any;
</code>```

this.names

```<code>[Array[2]]
   0: Array[2]
    0: Object
    ArrayListID: 0
    itemName: "TEST001A"
    <prototype>: Object
   1: Object
    ArrayListID: 0
    itemName: "TEST001B"
    <prototype>: Object
</code>```

i get the response.id but it won't fill the ArrayListID in this.names[i].

```<code> onSave() {
  for(let id of this.formGroup.value){
  this.services.PostID(id).subscribe((response)=>{
    this.responseID = response.id
    for (let i = 0; i < this.names.length; i++) {
      this.names[i].ArrayListID = this.responseID
     this.services.PostArray(this.names[i]).subscribe((res)=>{
      console.log(res)
      })
    }
   })
  }
  }
</code>```

Body:
I'm trying to pass my response id to this.names[i].ArrayListID per column index but it won't get it. how to achieve that?

export interface Names {
  ArrayListID: number;
  itemName: string;
}

names: Names[] = [];
responseID:any;

this.names

[Array[2]]
   0: Array[2]
    0: Object
    ArrayListID: 0
    itemName: "TEST001A"
    <prototype>: Object
   1: Object
    ArrayListID: 0
    itemName: "TEST001B"
    <prototype>: Object

i get the response.id but it won't fill the ArrayListID in this.names[i].

 onSave() {
  for(let id of this.formGroup.value){
  this.services.PostID(id).subscribe((response)=>{
    this.responseID = response.id
    for (let i = 0; i < this.names.length; i++) {
      this.names[i].ArrayListID = this.responseID
     this.services.PostArray(this.names[i]).subscribe((res)=>{
      console.log(res)
      })
    }
   })
  }
  }


来源: stackexchange

问:
trying to find cube via this code in shell?
I have written this code to find cube of the number which I am passing while executing this script like:
./my_script.sh 6

The code is working fine till 6 but after 6 it start producing unexpected results. For 7 it should give me cubeof(7) which is 343 but this code gives me 87 for that.

```<code>cube () {
        return `expr "$1" \* "$1" \* "$1" `;
}

cube $1;
echo $?;
</code>```

Some more test cases:

For 8 expected answer should be 512 but it gives 0
same as 9 it gives 217 as results

ContentLicense: CC BY-SA 4.0

Body:
I have written this code to find cube of the number which I am passing while executing this script like:
./my_script.sh 6

The code is working fine till 6 but after 6 it start producing unexpected results. For 7 it should give me cubeof(7) which is 343 but this code gives me 87 for that.

cube () {
        return `expr "$1" \* "$1" \* "$1" `;
}

cube $1;
echo $?;

Some more test cases:

For 8 expected answer should be 512 but it gives 0
same as 9 it gives 217 as results


问:
fix error: 64 bit sm2s-imx8mp-toolchain searches for long-double-32.h
I am compiling with sm2s-imx8mp-toolchain (generated by yocto populate sdk) out of yocto. My platform is 64 arm sm2s-imx8mp. I see that toolchain folder contains long-double-64.h and long-double.h files in /path/to/sm2s-imx8mp-toolchain-with-ext-libs-04-01-2023/sysroots/cortexa53-crypto-poky-linux/usr/include/bits/ folder, which seems correct to me.

My cpp file includes <time.h>, and compilation fails with a strange error:

[  45%] Building CXX object xxx/BaseService.cpp.o

In file included from /yyy/sm2s-imx8mp-toolchain-with-ext-libs-04-01-2023/sysroots/cortexa53-crypto-poky-linux/usr/include/sys/cdefs.h:463,
from /yyy/sm2s-imx8mp-toolchain-with-ext-libs-04-01-2023/sysroots/cortexa53-crypto-poky-linux/usr/include/features.h:473,
from /yyy/sm2s-imx8mp-toolchain-with-ext-libs-04-01-2023/sysroots/cortexa53-crypto-poky-linux/usr/include/time.h:25,
from /xxx/BaseService.cpp:3:
/yyy/sm2s-imx8mp-toolchain-with-ext-libs-04-01-2023/sysroots/cortexa53-crypto-poky-linux/usr/include/bits/long-double.h:23:10: fatal error: bits/long-double-32.h: No such file or directory
23 | #include <bits/long-double-32.h>

I really can't understand why compiler searches 32 bit header? And how to fix this?


问:
ImportError: DLL load failed importing XXX: %1 is not a valid Win32 application

The problem is when trying to import a custom generated .pyd file into a Python file it is showing DLL error.

I am trying to import a C file containing C code and Python Extension of C code which is build using setup.py file which generated a .pyd file. When I tring to import the module it is showing DLL load failed for the module. I am using Pycharm for coding. When running in terminal also it shows the same issue. Can someone help me in this? Thanks in advance.


问:
How to create a show more button for list items in two separate lists?
I'm trying to create a show more button which would display all the li elements together. But currently it seems like they are taking a block level display, even though I have explicitly mentioned the display:inline.
I want to place all the marketing li's next to Human Resources just in the same fashion as all the li's previous to the same.

Could someone please help me out with this? Any help would be appreciated :)

function showMore() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("show-more");
  var btnText = document.getElementById("show-more-button");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Show more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Show less";
    moreText.style.display = "inline";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#show-more {
  display: none;
}

#show-more li {
  display: inline-flex;
  flex-wrap: wrap;
}</code>```

> There is another `ul` which has all the `li's` from Engineering to Human Resources in it.

SUGGESTED SEARCHES

 Engineering

Business Development

Finance

          Administrative Assistant

Retail Associate

Customer Service

Operations

Information Technology

Marketing

Human Resources

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

      <button onclick="showMore()" id="show-more-button">Show More</button>

```

Body:
I'm trying to create a show more button which would display all the li elements together. But currently it seems like they are taking a block level display, even though I have explicitly mentioned the display:inline.
I want to place all the marketing li's next to Human Resources just in the same fashion as all the li's previous to the same.

Could someone please help me out with this? Any help would be appreciated :)

function showMore() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("show-more");
  var btnText = document.getElementById("show-more-button");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Show more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Show less";
    moreText.style.display = "inline";
  }
}

#show-more {
  display: none;
}

#show-more li {
  display: inline-flex;
  flex-wrap: wrap;
}

> There is another `ul` which has all the `li's` from Engineering to Human Resources in it.

SUGGESTED SEARCHES

 Engineering

Business Development

Finance

          Administrative Assistant

Retail Associate

Customer Service

Operations

Information Technology

Marketing

Human Resources

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

Marketing

      <button onclick="showMore()" id="show-more-button">Show More</button>


问:
WPF clickonce issue on azure devops
I have a runtime error when I published a .NetFramework WPF app from an azure devops pipeline.

The error is the following :

```<code>2023-01-09 16:26:01,230 [1] ERROR XXX.Logging.Log - 'Impossible d'inscrire l'objet nommé. Impossible d'inscrire le nom dupliqué 'tbLogin' dans cette portée.' numéro de ligne '26' et position de ligne '14'.
Impossible d'inscrire le nom dupliqué 'tbLogin' dans cette portée.
Data :System.Collections.DictionaryEntry
StackTrace:
   à System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   à System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   à System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   à System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   à System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   à MS.Internal.AppModel.AppModelKnownContentFactory.BamlConverter(Stream stream, Uri baseUri, Boolean canUseTopLevelBrowser, Boolean sandboxExternalContent, Boolean allowAsync, Boolean isJournalNavigation, XamlReader& asyncObjectConverter)
   à MS.Internal.AppModel.MimeObjectFactory.GetObjectAndCloseStream(Stream s, ContentType contentType, Uri baseUri, Boolean canUseTopLevelBrowser, Boolean sandboxExternalContent, Boolean allowAsync, Boolean isJournalNavigation, XamlReader& asyncObjectConverter)
   à System.Windows.Navigation.NavigationService.GetObjectFromResponse(WebRequest request, WebResponse response, Uri destinationUri, Object navState)
   à System.Windows.Navigation.NavigationService.DoNavigate(Uri source, NavigationMode f, Object navState)
   à System.Windows.Navigation.NavigateQueueItem.Dispatch(Object obj)
   à System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   à System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   à System.Windows.Threading.DispatcherOperation.InvokeImpl()
   à MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   à MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   à System.Windows.Threading.DispatcherOperation.Invoke()
   à System.Windows.Threading.Dispatcher.ProcessQueue()
   à System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   à MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   à MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   à System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   à System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   à System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   à MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   à MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   à System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   à System.Windows.Application.RunDispatcher(Object ignore)
   à System.Windows.Application.RunInternal(Window window)
   à Apps.XXX.BO.WPF.App.Main()
Source:
PresentationFramework
TargetSite:
Void RewrapException(System.Exception, System.Xaml.IXamlLineInfo, System.Uri)
BaseException:
System.ArgumentException: Impossible d'inscrire le nom dupliqué 'tbLogin' dans cette portée.
   à System.Xaml.NameScope.RegisterName(String name, Object scopedElement)
   à System.Xaml.XamlObjectWriter.RegisterName(ObjectWriterContext ctx, String name, Object inst, XamlType xamlType, INameScope nameScope, INameScope parentNameScope, Boolean isRoot)
</code>```

I don't have this runtime error when I publish on my computer from Visual Studio.

The publish task on the pipeline is defined as :

```<code>- task: MSBuild@1
  displayName: "Build solution with ClickOnce Deploy"
  inputs:
    solution: '**/$(ProjectName).csproj'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
    msbuildArguments: '/target:Publish /p:ApplicationVersion=$(AssemblyVersion) /p:PublishDir="$(build.ArtifactStagingDirectory)/Publish" /p:ProductName="$(ProductName)" /p:InstallUrl="$(blobStorageUrl)$(Configuration)/" /p:PublishUrl=$(blobStorageUrl)'
</code>```

Do any of you have any idea what is causing the problem?

Thanks,

Note : tbLogin is defined only once in the application.

Update

Problem solved.

I follow this instructions : Cannot register duplicate name error when using unique name in a Page namescope in WPF app

On the MainWindow, I had a frame describe as follow :

```<code><Frame x:Name="FrmMain" Grid.Row="1" NavigationUIVisibility="Hidden" Source="/<XXX>;component/Views/LoginView.xaml" />
</code>```

I replace it by :

```<code><Frame x:Name="FrmMain" Grid.Row="1" NavigationUIVisibility="Hidden" Source="LoginView.xaml" />
</code>```

And everything work as expected after my devops publish.

Title: WPF clickonce issue on azure devops

Body:
I have a runtime error when I published a .NetFramework WPF app from an azure devops pipeline.

The error is the following :

2023-01-09 16:26:01,230 [1] ERROR XXX.Logging.Log - 'Impossible d'inscrire l'objet nommé. Impossible d'inscrire le nom dupliqué 'tbLogin' dans cette portée.' numéro de ligne '26' et position de ligne '14'.
Impossible d'inscrire le nom dupliqué 'tbLogin' dans cette portée.
Data :System.Collections.DictionaryEntry
StackTrace:
   à System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   à System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   à System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   à System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   à System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   à MS.Internal.AppModel.AppModelKnownContentFactory.BamlConverter(Stream stream, Uri baseUri, Boolean canUseTopLevelBrowser, Boolean sandboxExternalContent, Boolean allowAsync, Boolean isJournalNavigation, XamlReader& asyncObjectConverter)
   à MS.Internal.AppModel.MimeObjectFactory.GetObjectAndCloseStream(Stream s, ContentType contentType, Uri baseUri, Boolean canUseTopLevelBrowser, Boolean sandboxExternalContent, Boolean allowAsync, Boolean isJournalNavigation, XamlReader& asyncObjectConverter)
   à System.Windows.Navigation.NavigationService.GetObjectFromResponse(WebRequest request, WebResponse response, Uri destinationUri, Object navState)
   à System.Windows.Navigation.NavigationService.DoNavigate(Uri source, NavigationMode f, Object navState)
   à System.Windows.Navigation.NavigateQueueItem.Dispatch(Object obj)
   à System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   à System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   à System.Windows.Threading.DispatcherOperation.InvokeImpl()
   à MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   à MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   à System.Windows.Threading.DispatcherOperation.Invoke()
   à System.Windows.Threading.Dispatcher.ProcessQueue()
   à System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   à MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   à MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   à System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   à System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   à System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   à MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   à MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   à System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   à System.Windows.Application.RunDispatcher(Object ignore)
   à System.Windows.Application.RunInternal(Window window)
   à Apps.XXX.BO.WPF.App.Main()
Source:
PresentationFramework
TargetSite:
Void RewrapException(System.Exception, System.Xaml.IXamlLineInfo, System.Uri)
BaseException:
System.ArgumentException: Impossible d'inscrire le nom dupliqué 'tbLogin' dans cette portée.
   à System.Xaml.NameScope.RegisterName(String name, Object scopedElement)
   à System.Xaml.XamlObjectWriter.RegisterName(ObjectWriterContext ctx, String name, Object inst, XamlType xamlType, INameScope nameScope, INameScope parentNameScope, Boolean isRoot)

I don't have this runtime error when I publish on my computer from Visual Studio.

The publish task on the pipeline is defined as :

- task: MSBuild@1
  displayName: "Build solution with ClickOnce Deploy"
  inputs:
    solution: '**/$(ProjectName).csproj'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
    msbuildArguments: '/target:Publish /p:ApplicationVersion=$(AssemblyVersion) /p:PublishDir="$(build.ArtifactStagingDirectory)/Publish" /p:ProductName="$(ProductName)" /p:InstallUrl="$(blobStorageUrl)$(Configuration)/" /p:PublishUrl=$(blobStorageUrl)'

Do any of you have any idea what is causing the problem?

Thanks,

Note : tbLogin is defined only once in the application.

Update

Problem solved.

I follow this instructions : Cannot register duplicate name error when using unique name in a Page namescope in WPF app

On the MainWindow, I had a frame describe as follow :

<Frame x:Name="FrmMain" Grid.Row="1" NavigationUIVisibility="Hidden" Source="/<XXX>;component/Views/LoginView.xaml" />

I replace it by :

<Frame x:Name="FrmMain" Grid.Row="1" NavigationUIVisibility="Hidden" Source="LoginView.xaml" />

And everything work as expected after my devops publish.


问:
LZ77 and LZ78 differences in dictionaries
you can find in many sources this statement regarding LZ77 and LZ78.

They are both theoretically dictionary coders. LZ77 maintains a
sliding window during compression. This was equivalent to the
explicit dictionary constructed by LZ78 however, they are only
equivalent when the entire data is intended to be decompressed.

I have difficulties understanding this, in the text mentioned, equivalency of an LZ77 to LZ78 (explicit dictionary).
Could anybody explain it?


问:
json manipulation and comprison typescripts (test equal)
and thanks for the support.

i am haveing prbolem to compare two obj of City, one created and one read and hopefully "converted" from a json file.

The one imported:

```<code>import * as citiesJson from '../resources/cities.json';
const cities_test: City[] = citiesJson as City[];
</code>```

The one created:

```<code>const milan: City = { name: 'Milan', population: 1371498 };
    const napels: City = { name: 'Napels', population: 911000 };
    const rome: City = { name: 'Rome', population: 2758334 };
    const resultSort: City[] = [milan, napels, rome];
</code>```

the test result expect(getSortedItems(cities_imported)).toEqual(city_created); failed and the console.log of them both is:

Imported

```<code>console.log
{
  '0': [Getter],
  '1': [Getter],
  '2': [Getter],
  default: [
    { name: 'Milan', population: 1371498 },
    { name: 'Naples', population: 911000 },
    { name: 'Rome', population: 2758334 }
  ]
}

     at Object.<anonymous> (dao/sortAlg.test.ts:30:17)
</code>```

Created

```<code>console.log
   [
     { name: 'Milan', population: 1371498 },
     { name: 'Napels', population: 911000 },
     { name: 'Rome', population: 2758334 }
   ]

     at Object.<anonymous> (dao/sortAlg.test.ts:31:17)
</code>```

i am doing something wrong but is not clear where. the first idea is about the printing of the imported json file and this part:

```<code>{
  '0': [Getter],
  '1': [Getter],
  '2': [Getter],
  default:
</code>```

is there a way to manipulate json file in order to make the comparison succesfull?

Body:
and thanks for the support.

i am haveing prbolem to compare two obj of City, one created and one read and hopefully "converted" from a json file.

The one imported:

import * as citiesJson from '../resources/cities.json';
const cities_test: City[] = citiesJson as City[];

The one created:

const milan: City = { name: 'Milan', population: 1371498 };
    const napels: City = { name: 'Napels', population: 911000 };
    const rome: City = { name: 'Rome', population: 2758334 };
    const resultSort: City[] = [milan, napels, rome];

the test result expect(getSortedItems(cities_imported)).toEqual(city_created); failed and the console.log of them both is:

Imported

console.log
{
  '0': [Getter],
  '1': [Getter],
  '2': [Getter],
  default: [
    { name: 'Milan', population: 1371498 },
    { name: 'Naples', population: 911000 },
    { name: 'Rome', population: 2758334 }
  ]
}

     at Object.<anonymous> (dao/sortAlg.test.ts:30:17)

Created

console.log
   [
     { name: 'Milan', population: 1371498 },
     { name: 'Napels', population: 911000 },
     { name: 'Rome', population: 2758334 }
   ]

     at Object.<anonymous> (dao/sortAlg.test.ts:31:17)

i am doing something wrong but is not clear where. the first idea is about the printing of the imported json file and this part:

{
  '0': [Getter],
  '1': [Getter],
  '2': [Getter],
  default:

is there a way to manipulate json file in order to make the comparison succesfull?


问:
How to serve Flask app on waitress and socket.io using eventlet server simultaneously?
I'm using waitress server to deploy the flask app for production. I'm also using flask's socketio along with the eventlet server which requires its own app run.

Currently only serving app on waitress:
serve(app, host='0.0.0.0', port=8080)

How do I include the socket.run command for running the socket server?
socketio.run(app)

My code:
This snippet sets up server for the flask socketio on which it is to be run and in the if name part I serve the app on waitress if in prod mode.

app.py

```<code>import eventlet
async_mode = None
if async_mode is None:
    try:
        async_mode = 'eventlet'
    except ImportError:
        pass
if async_mode is None:
    async_mode = 'threading'
print('async_mode is ' + async_mode)
if async_mode == 'eventlet':
    eventlet.monkey_patch()
    socketio = socketIO(app,cors_allowed_origins='*',async_mode=async_mode)

if __name__=='__main__':
    if env_mode=='dev':
        app.run(host='0.0.0.0', port=8080)
    elif env_mode=='prod':
        serve(app, host='0.0.0.0', port=8080)
</code>```

Body:
I'm using waitress server to deploy the flask app for production. I'm also using flask's socketio along with the eventlet server which requires its own app run.

Currently only serving app on waitress:
serve(app, host='0.0.0.0', port=8080)

How do I include the socket.run command for running the socket server?
socketio.run(app)

My code:
This snippet sets up server for the flask socketio on which it is to be run and in the if name part I serve the app on waitress if in prod mode.

app.py

import eventlet
async_mode = None
if async_mode is None:
    try:
        async_mode = 'eventlet'
    except ImportError:
        pass
if async_mode is None:
    async_mode = 'threading'
print('async_mode is ' + async_mode)
if async_mode == 'eventlet':
    eventlet.monkey_patch()
    socketio = socketIO(app,cors_allowed_origins='*',async_mode=async_mode)

if __name__=='__main__':
    if env_mode=='dev':
        app.run(host='0.0.0.0', port=8080)
    elif env_mode=='prod':
        serve(app, host='0.0.0.0', port=8080)


问:
OptimisticLockException test behaviour with unit test
I want to test the behavior of an OptimisticLockException.

My entity:

```<code>@Entity(name = "")
@Table(name = "")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class EntityA
{

   @Id
   private String id;
   @Version
   private Timestamp lastChange;
</code>```

My update Method:

```<code>public void update(EntityA entityA, String attribute)
try {
            entityA.setSomeAttribute(attribute);
            jpaRepository.save(entityA);
            return;
         } catch (OptimisticLockException e) {
            log.debug(e.getMessage());
         }
</code>```

My Unittest:

```<code>EntityA entity_1 = createEntity("789", 2);
EntityA entity_2 = createEntity("987", 2);
service.update(entity_1);
assertThrows(OptimisticLockException.class, () -> service.update(entity_2)); // this one should throw an OptimisticLockException
verify(jpaRepository).save(entity_1);
</code>```

The second call of update doesn't throw an OptimisticLockException

Body:
I want to test the behavior of an OptimisticLockException.

My entity:

@Entity(name = "")
@Table(name = "")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class EntityA
{

   @Id
   private String id;
   @Version
   private Timestamp lastChange;

My update Method:

public void update(EntityA entityA, String attribute)
try {
            entityA.setSomeAttribute(attribute);
            jpaRepository.save(entityA);
            return;
         } catch (OptimisticLockException e) {
            log.debug(e.getMessage());
         }

My Unittest:

EntityA entity_1 = createEntity("789", 2);
EntityA entity_2 = createEntity("987", 2);
service.update(entity_1);
assertThrows(OptimisticLockException.class, () -> service.update(entity_2)); // this one should throw an OptimisticLockException
verify(jpaRepository).save(entity_1);

The second call of update doesn't throw an OptimisticLockException


问:
Why object has a weird behavior in case of collision?
I have the problem with collision. Beginning creating the 3D game, I noticed that Player (gameObject) when moving in case of collision either falls down, or passes through the object, or repels from the object if it is inside it. I want to Player in case of collision couldn't pass through objects. Objects have colliders, Player has both collider, and Rigidbody with Physic Material. I'm beginner, so I don not know how to solve this problem. What is wrong?
Below script Player:

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

public class Player : MonoBehaviour
{
    [SerializeField] public int speed;
    public bool ground;
    public float jumpPower = 2500f;
    public Rigidbody rb;

    void Start()
    {
        rb= GetComponent<Rigidbody>();
    }

    void Update()
    {
        GetInput();
    }

    private void GetInput()
    {
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += transform.forward * speed * Time.deltaTime;
        }
        // Movement Player...

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (ground == true)
            {
                rb.AddForce(transform.up * jumpPower);
            }
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            ground = true;
        }

        if (collision.gameObject.tag == "Gem")
        {
            Destroy(collision.gameObject);
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            ground = false;
        }
    }
}
</code>```

Body:
I have the problem with collision. Beginning creating the 3D game, I noticed that Player (gameObject) when moving in case of collision either falls down, or passes through the object, or repels from the object if it is inside it. I want to Player in case of collision couldn't pass through objects. Objects have colliders, Player has both collider, and Rigidbody with Physic Material. I'm beginner, so I don not know how to solve this problem. What is wrong?
Below script Player:

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

public class Player : MonoBehaviour
{
    [SerializeField] public int speed;
    public bool ground;
    public float jumpPower = 2500f;
    public Rigidbody rb;

    void Start()
    {
        rb= GetComponent<Rigidbody>();
    }

    void Update()
    {
        GetInput();
    }

    private void GetInput()
    {
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += transform.forward * speed * Time.deltaTime;
        }
        // Movement Player...

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (ground == true)
            {
                rb.AddForce(transform.up * jumpPower);
            }
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            ground = true;
        }

        if (collision.gameObject.tag == "Gem")
        {
            Destroy(collision.gameObject);
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            ground = false;
        }
    }
}


问:
woocommerce importer: read, replace and insert name attribute
the following code is in the Wooimporter.php page (a plugin to import products into woocommerce), the script reads the data taken from a web page and imports them as products, I have to make sure that when importing it reads an attribute of name 'red oranges' must replace it and insert it in the database with name 'reds', the code is as follows:

how to edit or add php code? thank you

```<code>public static function addAttributes(array $features, $product_id)
    {
        if (!$product = \wc_get_product($product_id))
            return false;

        $attributes = $product->get_attributes();
        $taxonomy_count = 0;
        foreach ($features as $feature)
        {
            $f_name = \wc_clean($feature['name']);
            $f_slug = self::getSlug($f_name);

            // exists?
            if (isset($attributes[$f_slug]) || isset($attributes['pa_' . $f_slug]))
                continue;

            $f_value = \wc_sanitize_term_text_based($feature['value']);
            $f_value_array = self::value2Array($f_value);
            $term_ids = array();
            $taxonomy = '';

            //  Taxonomy exists?
            if (\taxonomy_exists(\wc_attribute_taxonomy_name($f_name)))
            {
                // Taxonomy attribute
                $taxonomy_count++;

                if ($attr_id = self::createTaxonomyAttribute($f_name, $f_slug))
                {
                    $taxonomy = \wc_attribute_taxonomy_name_by_id($attr_id);

                    // Register the taxonomy now so that the import works!
                    if (!\taxonomy_exists($taxonomy))
                    {
                        $taxonomy = TextHelper::truncate($taxonomy, 32, '');
                        \register_taxonomy($taxonomy, apply_filters('woocommerce_taxonomy_objects_' . $taxonomy, array('product')), apply_filters('woocommerce_taxonomy_args_' . $taxonomy, array('hierarchical' => true, 'show_ui' => false, 'query_var' => true, 'rewrite' => false)));
                    }

                    // Creates the term and taxonomy relationship if it doesn't already exist.
                    // It may be confusing but the returned array consists of term_taxonomy_ids instead of term_ids.
                    \wp_set_object_terms($product->get_id(), $f_value_array, $taxonomy);

                    $term_ids = array();
                    foreach ($f_value_array as $term)
                    {
                        if ($term_info = \term_exists($term, $taxonomy))
                            $term_ids[] = $term_info['term_id'];
                    }
                    $term_ids = array_map('intval', $term_ids);
                } else
                    $attr_id = 0;
            } else
            {
                // Local Attribute
                $attr_id = 0;
            }

            $attribute = new \WC_Product_Attribute();
            $attribute->set_id($attr_id); // 0 for product level attributes. ID for global attributes.
            if ($taxonomy)
                $attribute->set_name($taxonomy);
            else
                $attribute->set_name($f_name);

            // attribute value or array of term ids/names.
            if ($term_ids)
                $attribute->set_options($term_ids);
            else
                $attribute->set_options($f_value_array);

            $attribute->set_visible(true); // If visible on frontend.
            $attributes[] = $attribute;
        }
        $product->set_attributes($attributes);
        $res = $product->save();

        if ($taxonomy_count)
            \flush_rewrite_rules();
        return $res;
    }

    public static function createTaxonomyAttribute($slug, $name, $type = 'text')
    {
        global $wpdb;

        $attribute = array();
        $attribute['attribute_label'] = \wc_clean($slug);
        $attribute['attribute_name'] = \wc_sanitize_taxonomy_name($name);
        $attribute['attribute_type'] = $type;
        $attribute['attribute_orderby'] = 'menu_order';

        // validate slug
        if (strlen($attribute['attribute_name']) >= 28 || \wc_check_if_attribute_name_is_reserved($attribute['attribute_name']))
            return false;

        if (\taxonomy_exists(\wc_attribute_taxonomy_name($attribute['attribute_name'])))
            return \wc_attribute_taxonomy_id_by_name($attribute['attribute_name']);

        // Create the taxonomy
        $insert = $wpdb->insert($wpdb->prefix . 'woocommerce_attribute_taxonomies', $attribute);

        if (\is_wp_error($insert))
            return false;

        $id = $wpdb->insert_id;

        \wp_schedule_single_event(time(), 'woocommerce_flush_rewrite_rules');
        \delete_transient('wc_attribute_taxonomies');

        return $id;
    }
</code>```

Body:
the following code is in the Wooimporter.php page (a plugin to import products into woocommerce), the script reads the data taken from a web page and imports them as products, I have to make sure that when importing it reads an attribute of name 'red oranges' must replace it and insert it in the database with name 'reds', the code is as follows:

how to edit or add php code? thank you

public static function addAttributes(array $features, $product_id)
    {
        if (!$product = \wc_get_product($product_id))
            return false;

        $attributes = $product->get_attributes();
        $taxonomy_count = 0;
        foreach ($features as $feature)
        {
            $f_name = \wc_clean($feature['name']);
            $f_slug = self::getSlug($f_name);

            // exists?
            if (isset($attributes[$f_slug]) || isset($attributes['pa_' . $f_slug]))
                continue;

            $f_value = \wc_sanitize_term_text_based($feature['value']);
            $f_value_array = self::value2Array($f_value);
            $term_ids = array();
            $taxonomy = '';

            //  Taxonomy exists?
            if (\taxonomy_exists(\wc_attribute_taxonomy_name($f_name)))
            {
                // Taxonomy attribute
                $taxonomy_count++;

                if ($attr_id = self::createTaxonomyAttribute($f_name, $f_slug))
                {
                    $taxonomy = \wc_attribute_taxonomy_name_by_id($attr_id);

                    // Register the taxonomy now so that the import works!
                    if (!\taxonomy_exists($taxonomy))
                    {
                        $taxonomy = TextHelper::truncate($taxonomy, 32, '');
                        \register_taxonomy($taxonomy, apply_filters('woocommerce_taxonomy_objects_' . $taxonomy, array('product')), apply_filters('woocommerce_taxonomy_args_' . $taxonomy, array('hierarchical' => true, 'show_ui' => false, 'query_var' => true, 'rewrite' => false)));
                    }

                    // Creates the term and taxonomy relationship if it doesn't already exist.
                    // It may be confusing but the returned array consists of term_taxonomy_ids instead of term_ids.
                    \wp_set_object_terms($product->get_id(), $f_value_array, $taxonomy);

                    $term_ids = array();
                    foreach ($f_value_array as $term)
                    {
                        if ($term_info = \term_exists($term, $taxonomy))
                            $term_ids[] = $term_info['term_id'];
                    }
                    $term_ids = array_map('intval', $term_ids);
                } else
                    $attr_id = 0;
            } else
            {
                // Local Attribute
                $attr_id = 0;
            }

            $attribute = new \WC_Product_Attribute();
            $attribute->set_id($attr_id); // 0 for product level attributes. ID for global attributes.
            if ($taxonomy)
                $attribute->set_name($taxonomy);
            else
                $attribute->set_name($f_name);

            // attribute value or array of term ids/names.
            if ($term_ids)
                $attribute->set_options($term_ids);
            else
                $attribute->set_options($f_value_array);

            $attribute->set_visible(true); // If visible on frontend.
            $attributes[] = $attribute;
        }
        $product->set_attributes($attributes);
        $res = $product->save();

        if ($taxonomy_count)
            \flush_rewrite_rules();
        return $res;
    }

    public static function createTaxonomyAttribute($slug, $name, $type = 'text')
    {
        global $wpdb;

        $attribute = array();
        $attribute['attribute_label'] = \wc_clean($slug);
        $attribute['attribute_name'] = \wc_sanitize_taxonomy_name($name);
        $attribute['attribute_type'] = $type;
        $attribute['attribute_orderby'] = 'menu_order';

        // validate slug
        if (strlen($attribute['attribute_name']) >= 28 || \wc_check_if_attribute_name_is_reserved($attribute['attribute_name']))
            return false;

        if (\taxonomy_exists(\wc_attribute_taxonomy_name($attribute['attribute_name'])))
            return \wc_attribute_taxonomy_id_by_name($attribute['attribute_name']);

        // Create the taxonomy
        $insert = $wpdb->insert($wpdb->prefix . 'woocommerce_attribute_taxonomies', $attribute);

        if (\is_wp_error($insert))
            return false;

        $id = $wpdb->insert_id;

        \wp_schedule_single_event(time(), 'woocommerce_flush_rewrite_rules');
        \delete_transient('wc_attribute_taxonomies');

        return $id;
    }


问:
Custom jinja variable in apache superset
I created the custom variable {{year_var}} in SQL lab and assigned a value in the parameter menù: {"year_var":2014}. After checking that the query is running I created a virtual dataset, a chart and a dashboard.
My question is: How can I assign a value to {{year_var}} from the filter menù in the dashboard?</p>


问:
In development mode, components are rendered twice if in strict mode and if the component contains state
this is a theory based problem in react.

I'm expecting an detailed explanation on this topic that how react reanders components.


问:
Can I change Netty pipeline by events?
My app should do the next:

Send a POST request to server to get the token.

Connect to the websocket using this token in the headers while handshake.

Short question: To activate WebSocketClientProtocolHandler I have to fire event ctx.fireChannelActive() but from channelRead method because in this method I receive token from server . Is it correct place?

I implemented custom ChannelInboundHandlerAdapter and override:

```<code>@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);

    authenticator.authenticate(ctx.channel()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (!channelFuture.isSuccess()) {
                authPromise.tryFailure(channelFuture.cause());
                ctx.fireExceptionCaught(new RuntimeException("Auth is failed."));
            } else {
                ctx.fireUserEventTriggered("Auth is successful");
            }
        }
    });
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpResponse)) {
        ctx.fireChannelRead(msg);
    }

    FullHttpResponse response = (FullHttpResponse) msg;
    try {
        authenticator.finishAuthentication(ctx.channel(), response);
        authPromise.trySuccess();
        ctx.pipeline().remove(this);
        ctx.fireChannelActive();
    } finally {
        response.release();
    }
}
</code>```

Authenticator class adds needed handlers, sends POST request and then it should parse response from server and change the pipeline.

```<code>public class Authenticator {

private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

private final ObjectMapper mapper = new ObjectMapper();
private final MessengerConfig messengerConfig;

public Authenticator(MessengerConfig messengerConfig) {
    this.messengerConfig = messengerConfig;
}

public ChannelFuture authenticate(Channel channel) {
    this.preCheck(channel);
    return this.authenticate(channel, channel.newPromise());
}

private void preCheck(Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();

    HttpClientCodec httpClientCodec = pipeline.get(HttpClientCodec.class);
    if (httpClientCodec == null) {
        LOGGER.warn("Pipeline does not contain HttpClientCodec.");
        pipeline.addFirst(HttpClientCodec.class.getName(), new HttpClientCodec());
        LOGGER.info("HttpClientCodec was added to pipeline.");
    }

    HttpObjectAggregator httpObjectAggregator = pipeline.get(HttpObjectAggregator.class);
    if (httpObjectAggregator == null) {
        LOGGER.warn("Pipeline does not contain HttpObjectAggregator.");
        pipeline.addAfter(
                HttpClientCodec.class.getName(),
                HttpObjectAggregator.class.getName(),
                new HttpObjectAggregator(8192)
        );
        LOGGER.info("HttpObjectAggregator was added to pipeline.");
    }
}

private ChannelFuture authenticate(Channel channel, ChannelPromise promise) {

    HttpRequest request = createAuthRequest();

    try {
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    promise.setSuccess();
                } else {
                    promise.setFailure(new RuntimeException(""));
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error("Error", e);
    }

    return promise;
}

public void finishAuthentication(Channel channel, FullHttpResponse response) {
    ByteBuf content = response.content();
    AuthenticationData authenticationData = null;
    try {
        authenticationData = this.mapper.readValue(content.toString(CharsetUtil.UTF_8), AuthenticationData.class);
    } catch (JsonProcessingException e) {
        LOGGER.error("Can't parse authentication data.", e);
        throw new RuntimeException((e));
    }
    LOGGER.info(Objects.toString(authenticationData));

    DefaultWebSocketClientProtocolHandlerFactory factory = new DefaultWebSocketClientProtocolHandlerFactory();
    WebSocketClientProtocolHandler handler = factory.getHandler(this.messengerConfig, authenticationData);

    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast(WebSocketClientProtocolHandler.class.getName(), handler);
    LOGGER.info("WebSocketClientProtocolHandler was added.");
    pipeline.addLast(MessageHandler.class.getName(), new MessageHandler());
    LOGGER.info("MessageHandler was added.");
}
</code>```

So here I have two stages:

Auth stage with a pipeline:

io.netty.handler.codec.http.HttpClientCodec

io.netty.handler.codec.http.HttpObjectAggregator

AuthenticationHandler

2 Web-socket stage with a pipeline:

io.netty.handler.codec.http.HttpClientCodec

io.netty.handler.codec.http.HttpObjectAggregator

io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandshakeHandler

io.netty.handler.codec.http.websocketx.Utf8FrameValidator

io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler

com.github.apsyvenko.client.messaging.MessageHandler

To activate second stage I have to fire event - ctx.fireChannelActive() but from channelRead.

As a result I got an exception:

18:19:37.055 [nioEventLoopGroup-2-1] WARN  i.n.channel.DefaultChannelPipeline - An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
java.net.SocketException: Connection reset

after hand-shake had started.

Title: Can I change Netty pipeline by events?

Body:
My app should do the next:

Send a POST request to server to get the token.

Connect to the websocket using this token in the headers while handshake.

Short question: To activate WebSocketClientProtocolHandler I have to fire event ctx.fireChannelActive() but from channelRead method because in this method I receive token from server . Is it correct place?

I implemented custom ChannelInboundHandlerAdapter and override:

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);

    authenticator.authenticate(ctx.channel()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (!channelFuture.isSuccess()) {
                authPromise.tryFailure(channelFuture.cause());
                ctx.fireExceptionCaught(new RuntimeException("Auth is failed."));
            } else {
                ctx.fireUserEventTriggered("Auth is successful");
            }
        }
    });
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpResponse)) {
        ctx.fireChannelRead(msg);
    }

    FullHttpResponse response = (FullHttpResponse) msg;
    try {
        authenticator.finishAuthentication(ctx.channel(), response);
        authPromise.trySuccess();
        ctx.pipeline().remove(this);
        ctx.fireChannelActive();
    } finally {
        response.release();
    }
}

Authenticator class adds needed handlers, sends POST request and then it should parse response from server and change the pipeline.

public class Authenticator {

private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

private final ObjectMapper mapper = new ObjectMapper();
private final MessengerConfig messengerConfig;

public Authenticator(MessengerConfig messengerConfig) {
    this.messengerConfig = messengerConfig;
}

public ChannelFuture authenticate(Channel channel) {
    this.preCheck(channel);
    return this.authenticate(channel, channel.newPromise());
}

private void preCheck(Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();

    HttpClientCodec httpClientCodec = pipeline.get(HttpClientCodec.class);
    if (httpClientCodec == null) {
        LOGGER.warn("Pipeline does not contain HttpClientCodec.");
        pipeline.addFirst(HttpClientCodec.class.getName(), new HttpClientCodec());
        LOGGER.info("HttpClientCodec was added to pipeline.");
    }

    HttpObjectAggregator httpObjectAggregator = pipeline.get(HttpObjectAggregator.class);
    if (httpObjectAggregator == null) {
        LOGGER.warn("Pipeline does not contain HttpObjectAggregator.");
        pipeline.addAfter(
                HttpClientCodec.class.getName(),
                HttpObjectAggregator.class.getName(),
                new HttpObjectAggregator(8192)
        );
        LOGGER.info("HttpObjectAggregator was added to pipeline.");
    }
}

private ChannelFuture authenticate(Channel channel, ChannelPromise promise) {

    HttpRequest request = createAuthRequest();

    try {
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    promise.setSuccess();
                } else {
                    promise.setFailure(new RuntimeException(""));
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error("Error", e);
    }

    return promise;
}

public void finishAuthentication(Channel channel, FullHttpResponse response) {
    ByteBuf content = response.content();
    AuthenticationData authenticationData = null;
    try {
        authenticationData = this.mapper.readValue(content.toString(CharsetUtil.UTF_8), AuthenticationData.class);
    } catch (JsonProcessingException e) {
        LOGGER.error("Can't parse authentication data.", e);
        throw new RuntimeException((e));
    }
    LOGGER.info(Objects.toString(authenticationData));

    DefaultWebSocketClientProtocolHandlerFactory factory = new DefaultWebSocketClientProtocolHandlerFactory();
    WebSocketClientProtocolHandler handler = factory.getHandler(this.messengerConfig, authenticationData);

    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast(WebSocketClientProtocolHandler.class.getName(), handler);
    LOGGER.info("WebSocketClientProtocolHandler was added.");
    pipeline.addLast(MessageHandler.class.getName(), new MessageHandler());
    LOGGER.info("MessageHandler was added.");
}

So here I have two stages:

Auth stage with a pipeline:

io.netty.handler.codec.http.HttpClientCodec

io.netty.handler.codec.http.HttpObjectAggregator

AuthenticationHandler

2 Web-socket stage with a pipeline:

io.netty.handler.codec.http.HttpClientCodec

io.netty.handler.codec.http.HttpObjectAggregator

io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandshakeHandler

io.netty.handler.codec.http.websocketx.Utf8FrameValidator

io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler

com.github.apsyvenko.client.messaging.MessageHandler

To activate second stage I have to fire event - ctx.fireChannelActive() but from channelRead.

As a result I got an exception:

18:19:37.055 [nioEventLoopGroup-2-1] WARN  i.n.channel.DefaultChannelPipeline - An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
java.net.SocketException: Connection reset

after hand-shake had started.


问:
Migration from Bugtracker to Atlassian JIRA (Html tags)
I am trying to migrate some bugtracker data to jira using C# and te soap client interface. So far so good with the implementation but i need to parse some html information to wiki confluence(I guess that is what jira uses). I do understand that wiki does not support break lines but on the following example. how do I parse this text to a proper wiki style. (

```<code><h1>This is a text</h1><p> Hello World Luis Mayorga </p><br />
</code>```

). Unless there is a library or external code that i can use on this C# migration tool.

```<code>content = content.Replace("<br />", "\\");
content = Regex.Replace(content, "<p>(.*?)</p>", "$1");
content = Regex.Replace(content, "<h1>(.*?)</h1>", "h1. $1");
</code>```

Any Help

ContentLicense: CC BY-SA 3.0

Body:
I am trying to migrate some bugtracker data to jira using C# and te soap client interface. So far so good with the implementation but i need to parse some html information to wiki confluence(I guess that is what jira uses). I do understand that wiki does not support break lines but on the following example. how do I parse this text to a proper wiki style. (

This is a text

 Hello World Luis Mayorga

). Unless there is a library or external code that i can use on this C# migration tool.

content = content.Replace("
", "\\");
content = Regex.Replace(content, "
(.*?)
", "$1");
content = Regex.Replace(content, "
(.*?)
", "h1. $1");

Any Help


问:
How to use httpd command instead of apache2 on Ubuntu?
Is there a way to create httpd as an alias on Ubuntu that points to apache2?  I'd like to be able to use the systemctl reload httpd and systemctl reload apache2 commands interchangeably, since I often use both CentOS and Ubuntu.


问:
Library "Generate-password" stop working with latest NODE.js deployment
I am beginner in node.Js, React and here in this forum.

I installed latest node.JS package and my app-web in React stopped working and receive this error. :(

Compiled with problems:

ERROR in ./src/components/grid/customGrid.jsx 313:25-43

export 'default' (imported as 'generator') was not found in 'generate-password' (possible exports: __esModule, generate, generateMultiple)

ERROR in ./node_modules/generate-password/src/generate.js 1:0-53

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\app-web\node_modules\generate-password\src'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }

I would like to say thanks for the solution.

I am expecting a solution from specialists.


问:
Fernet raising InvalidToken error even tough it seems I'm storing it?
I ma writing a simple "write_csv-row' and "read_csv_row" functions that encrypts part of the row and then uses the un-encrypted part (email) to identify the row, decrypt it and check in password is correct.

The "write" function works, but it appears I cannot decode it. I thought it is because my "read" function regenerate the key, but it seems that it uses the same one that is stored?

still getting a  "cryptography.fernet.InvalidToken" error.

Here's the code:

```<code>import csv
import os
import base64
from cryptography.fernet import Fernet

# Generate a random secret key
secret_key = Fernet.generate_key()

# Write a function to encrypt data using the secret key
def encrypt_data(data):
  fernet = Fernet(secret_key)
  encrypted_data = fernet.encrypt(bytes(data, 'utf-8'))
  return encrypted_data

def write_csv_row(data):
  # Open the CSV file in append mode
  with open('user_data.csv', 'a', newline='') as csv_file:
    writer = csv.writer(csv_file)
    # Write the first two rows (Name and Email Address) unencrypted
    unencrypted_data = [data[0], data[1]]
    # Encrypt the remaining rows and write them to the file
    encrypted_data = [encrypt_data(str(item)) for item in data[2:]]
   # Combine the unencrypted and encrypted data into a single row
    combined_data = unencrypted_data + encrypted_data
    # Write the combined data to the file
    writer.writerow(combined_data)

# Write a function to read a row of data from the CSV file based on email and password
def read_csv_row(email, password):
  # Open the CSV file in read mode
  with open('user_data.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Read each row from the file
    for row in reader:
      # Check if the email address in the second column matches the specified email
      if row[1] == email:
        # Decrypt the password using the secret key
        fernet = Fernet(secret_key)
        decrypted_password = fernet.decrypt(row[2]).decode('utf-8')
        # Check if the decrypted password matches the specified password
        if decrypted_password == password:
          # Decrypt the rest of the row using the secret key
          decrypted_row = [row[0], row[1]] + [fernet.decrypt(item).decode('utf-8') for item in row[3:]]
          return decrypted_row

# Write some example data to the CSV file
write_csv_row(['Alice', 'alice@example.com', 'password123', 'Pro', '1234 5678 9012 3456', '01/23', '123', '123 Main St', '', 'New York', 'NY', '12345', 'USA', 'high', 'active', 'diversified', 'Exchange A', 'public_key_123', 'private_key_456'])

# Read the first row of data from the CSV file
row = read_csv_row('alice@example.com', 'password123')
print(row)
</code>```

Looked on here for answers but it didn't help.

Body:
I ma writing a simple "write_csv-row' and "read_csv_row" functions that encrypts part of the row and then uses the un-encrypted part (email) to identify the row, decrypt it and check in password is correct.

The "write" function works, but it appears I cannot decode it. I thought it is because my "read" function regenerate the key, but it seems that it uses the same one that is stored?

still getting a  "cryptography.fernet.InvalidToken" error.

Here's the code:

import csv
import os
import base64
from cryptography.fernet import Fernet

# Generate a random secret key
secret_key = Fernet.generate_key()

# Write a function to encrypt data using the secret key
def encrypt_data(data):
  fernet = Fernet(secret_key)
  encrypted_data = fernet.encrypt(bytes(data, 'utf-8'))
  return encrypted_data

def write_csv_row(data):
  # Open the CSV file in append mode
  with open('user_data.csv', 'a', newline='') as csv_file:
    writer = csv.writer(csv_file)
    # Write the first two rows (Name and Email Address) unencrypted
    unencrypted_data = [data[0], data[1]]
    # Encrypt the remaining rows and write them to the file
    encrypted_data = [encrypt_data(str(item)) for item in data[2:]]
   # Combine the unencrypted and encrypted data into a single row
    combined_data = unencrypted_data + encrypted_data
    # Write the combined data to the file
    writer.writerow(combined_data)

# Write a function to read a row of data from the CSV file based on email and password
def read_csv_row(email, password):
  # Open the CSV file in read mode
  with open('user_data.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Read each row from the file
    for row in reader:
      # Check if the email address in the second column matches the specified email
      if row[1] == email:
        # Decrypt the password using the secret key
        fernet = Fernet(secret_key)
        decrypted_password = fernet.decrypt(row[2]).decode('utf-8')
        # Check if the decrypted password matches the specified password
        if decrypted_password == password:
          # Decrypt the rest of the row using the secret key
          decrypted_row = [row[0], row[1]] + [fernet.decrypt(item).decode('utf-8') for item in row[3:]]
          return decrypted_row

# Write some example data to the CSV file
write_csv_row(['Alice', 'alice@example.com', 'password123', 'Pro', '1234 5678 9012 3456', '01/23', '123', '123 Main St', '', 'New York', 'NY', '12345', 'USA', 'high', 'active', 'diversified', 'Exchange A', 'public_key_123', 'private_key_456'])

# Read the first row of data from the CSV file
row = read_csv_row('alice@example.com', 'password123')
print(row)

Looked on here for answers but it didn't help.


问:
onChange handler that formats numbers with commas and allows up to two decimal places
I am struggling to figure out the proper onChange handler that will allow me to format a number input with commas and also allow up to two decimal places.

Test Cases:
input: '1234.56' -> output: '1,234.56'
input 'aaaa1234567.34' -> output: '1,234,567.34'

I do not want this formatting to occur onBlur, I want the formatting to occur onChange so the commas are inserted as you type.

This is my first stack-overflow question so forgive me if my write up is not great.

I have searched for working examples on stack-overflow. The closest thing I found was this, but it does not work in Safari (I followed the comments but could not find a solution). I am not great at regex and have spent about 5 hours trying to figure this out.


问:
System users can not have duplicate names. System users can not have duplicate names. Use another name
I'm having a problem with the Facebook setup with Shopify, I have an error sentence that says:
"System users can not have duplicate names.
System users can not have duplicate names. Use another name."

I have tried everything but the problem persists!
Who knows how to solve this problem please?

enter image description here

I have contacted Facebook support several times, but each time they tell me to do something but it never solved the problem.


问:
How do I return Http Response Content Length for ResponseEntity<List<Object>> without formatting issues or losing data from my response body?
I'm trying to set the content length of my ResponseEntity<List> but the full list isn't returned in the response. I tried something like

```<code>    long contentLength = staticMethodGetsContentLength(List<Object> objectList);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Length", String.valueOf(contentLength));
    return Response.ok().headers(headers).body(objectList);
</code>```

and then what is returned is a JSON list like

[
{
"data": "data"

without closing brackets or the full list of objects. Is there an easy fix for this or an alternative to what I'm doing?

Body:
I'm trying to set the content length of my ResponseEntity<List> but the full list isn't returned in the response. I tried something like

    long contentLength = staticMethodGetsContentLength(List<Object> objectList);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Length", String.valueOf(contentLength));
    return Response.ok().headers(headers).body(objectList);

and then what is returned is a JSON list like

[
{
"data": "data"

without closing brackets or the full list of objects. Is there an easy fix for this or an alternative to what I'm doing?


问:
White line appearing when viewport is odd number of pixels
I am trying to achieve a layout where I have an outer row with 2 columns of 50% width, with the left column containing 3x2 images & the right column containing a single image. Whilst Firefox displays this layout fine, however, Chrome & IE display a white line when the viewport is an odd number of pixels wide. Does anyone have any idea what's causing this? I'm leaning towards Chromium bug at this point, having spent many hours trying all sorts of solutions (playing with flexbox, positioning, font-size, line-height etc.).

CodePen: https://codepen.io/richard-clarke/pen/RwBKXYQ

.img div {
  aspect-ratio: 1/1;
  background-size: cover;
}

.img.img-lg div {
  aspect-ratio: 3/2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid g-0">
  <div class="row g-0">
    <div class="col-12 col-lg-6">
      <div class="row g-0">
        <div class="col-12 col-sm-6 col-lg-4 img">
          <div style="background-image: url('https://via.placeholder.com/768')"></div>
        </div>
        <div class="col-12 col-sm-6 col-lg-4 img">
          <div style="background-image: url('https://via.placeholder.com/768')"></div>
        </div>
        <div class="col-12 col-sm-6 col-lg-4 img">
          <div style="background-image: url('https://via.placeholder.com/768')"></div>
        </div>
        <div class="col-12 col-sm-6 col-lg-4 img">
          <div style="background-image: url('https://via.placeholder.com/768')"></div>
        </div>
        <div class="col-12 col-sm-6 col-lg-4 img">
          <div style="background-image: url('https://via.placeholder.com/768')"></div>
        </div>
        <div class="col-12 col-sm-6 col-lg-4 img">
          <div style="background-image: url('https://via.placeholder.com/768')"></div>
        </div>
      </div>
    </div>
    <div class="col-12 col-lg-6 img img-lg">
      <div style="background-image: url('https://via.placeholder.com/2304x1536')"></div>
    </div>
  </div>
</div></code>```

The issue is worse on the real site in that the white line appears on any number of sides of any of the images & is not restricted to odd pixels, as in the below image. I suspect that resolving this for the CodePen example would resolve all of the issues on the real site.

Edit:

Adding my current solution here. It's horrible & not really what I would call a solution, but it achieves the seamless effect on the images that I am looking for. Time to move onto something else & come back to this if I have time.

Body:
I am trying to achieve a layout where I have an outer row with 2 columns of 50% width, with the left column containing 3x2 images & the right column containing a single image. Whilst Firefox displays this layout fine, however, Chrome & IE display a white line when the viewport is an odd number of pixels wide. Does anyone have any idea what's causing this? I'm leaning towards Chromium bug at this point, having spent many hours trying all sorts of solutions (playing with flexbox, positioning, font-size, line-height etc.).

CodePen: https://codepen.io/richard-clarke/pen/RwBKXYQ

.img div {
  aspect-ratio: 1/1;
  background-size: cover;
}

.img.img-lg div {
  aspect-ratio: 3/2;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>

The issue is worse on the real site in that the white line appears on any number of sides of any of the images & is not restricted to odd pixels, as in the below image. I suspect that resolving this for the CodePen example would resolve all of the issues on the real site.

Edit:

Adding my current solution here. It's horrible & not really what I would call a solution, but it achieves the seamless effect on the images that I am looking for. Time to move onto something else & come back to this if I have time.


问:
How can I configure autodetected languages in VSCode?
I often paste snippets of Javascript code into VSC, and the detected language is JavaScript. Can I modify that default to other installed language, like JavaScript for Automation ?


问:
Subfigures in latex never shrinks to be on one row (pfd file)
I'm trying to adjust two subfigures into one row. This is my code:

```<code>\begin{figure}[ht]
    \centering
\caption{Migration rates and nightlights in Albania in 1992-1995}

         \begin{subfigure}[a]{0.3\textwidth}

           \caption{Emigration rate before 1995 at the municipality level}
         \label{fig: migration_rate}
    \includegraphics[width=\linewidth, trim = 5cm 0cm 5cm 0cm, clip]{Figures/migration_rate.pdf}

    \end{subfigure}

     \begin{subfigure}[b]{0.3\textwidth}
      \caption{Night luminosity in 1992}
     \label{fig: nighlights}
    \includegraphics[width=\linewidth, trim = 5cm 0cm 5cm 0cm, clip]{Figures/nightlight.pdf}

    \end{subfigure}

     \caption*{\footnotesize{\textbf{Notes}:}}.

     \end{figure}

</code>```

enter image description here

Even if I shrink the subfigure to tiny size (for example {0.01\textwidth}), the two always appear in one column. I have deep blank space on the left and right of both figures that I have tried to trim. Including or excluding "trim" does not change much.

How do I get the two into one row?

Thank you!

Body:
I'm trying to adjust two subfigures into one row. This is my code:

\begin{figure}[ht]
    \centering
\caption{Migration rates and nightlights in Albania in 1992-1995}

         \begin{subfigure}[a]{0.3\textwidth}

           \caption{Emigration rate before 1995 at the municipality level}
         \label{fig: migration_rate}
    \includegraphics[width=\linewidth, trim = 5cm 0cm 5cm 0cm, clip]{Figures/migration_rate.pdf}

    \end{subfigure}

     \begin{subfigure}[b]{0.3\textwidth}
      \caption{Night luminosity in 1992}
     \label{fig: nighlights}
    \includegraphics[width=\linewidth, trim = 5cm 0cm 5cm 0cm, clip]{Figures/nightlight.pdf}

    \end{subfigure}

     \caption*{\footnotesize{\textbf{Notes}:}}.

     \end{figure}

enter image description here

Even if I shrink the subfigure to tiny size (for example {0.01\textwidth}), the two always appear in one column. I have deep blank space on the left and right of both figures that I have tried to trim. Including or excluding "trim" does not change much.

How do I get the two into one row?

Thank you!


问:
PhpStorm reformat array
I lost my previous settings from PhpStorm for formatting an array like this:

$array = [
    'short_key' => 'value1',
    'a_much_longer_key' => 'value2',
    'another_long_key' => 'value3',
];
```
<p>by hitting <kbd>Ctrl + Alt + L</kbd> it would become like this:</p>
<pre class="lang-php prettyprint-override"><code>$array = [
    'short_key'         => 'value1',
    'a_much_longer_key' => 'value2',
    'another_long_key'  => 'value3',
];
</code>```

How is this setting called? How to make PhpStorm do this? It has to be somewhere under "Settings -> Code Style".

Title: PhpStorm reformat array

Body:
I lost my previous settings from PhpStorm for formatting an array like this:

$array = [
    'short_key' => 'value1',
    'a_much_longer_key' => 'value2',
    'another_long_key' => 'value3',
];

by hitting Ctrl + Alt + L it would become like this:

$array = [
    'short_key'         => 'value1',
    'a_much_longer_key' => 'value2',
    'another_long_key'  => 'value3',
];

How is this setting called? How to make PhpStorm do this? It has to be somewhere under "Settings -> Code Style".


问:
How do I exclude functions from properties on formal verification model?
I want to exclude the genesis mint function from the conserves-mass property

```<code>(module account GOVERNANCE
@doc "Account doc"
@model
[ (defproperty conserves-mass
    (= (column-delta ledger 'balance ) 0.0))]
...
(defun transfer-create:string
    ( sender:string
      receiver:string
      receiver-guard:guard
      amount:decimal )
@doc "create account when transfer doc"
@model [ (property conserves-mass)] <- I want to exclude mint function here

...

</code>```

I found this example
https://github.com/kadena-io/pact/blob/4971ab6078b75eb612d83d56f1e7cd139a5a2ba8/examples/verified-accounts/accounts.pact#L27

where they do an except logic but it makes no sense to me how this 'except work and I can't make it work. I don't know what I'm missing.

I found nothing about this on the documentation
https://pact-language.readthedocs.io/en/stable/pact-properties.html

```<code>  @model
    [
...
     ; every function should conserve mass except for the admin fund-account,
     ; and debit / credit which should be private
     (property conserves-mass
       {'except: [fund-account, debit, credit]})
...
    ]
</code>```

Body:
I want to exclude the genesis mint function from the conserves-mass property

(module account GOVERNANCE
@doc "Account doc"
@model
[ (defproperty conserves-mass
    (= (column-delta ledger 'balance ) 0.0))]
...
(defun transfer-create:string
    ( sender:string
      receiver:string
      receiver-guard:guard
      amount:decimal )
@doc "create account when transfer doc"
@model [ (property conserves-mass)] <- I want to exclude mint function here

...

I found this example
https://github.com/kadena-io/pact/blob/4971ab6078b75eb612d83d56f1e7cd139a5a2ba8/examples/verified-accounts/accounts.pact#L27

where they do an except logic but it makes no sense to me how this 'except work and I can't make it work. I don't know what I'm missing.

I found nothing about this on the documentation
https://pact-language.readthedocs.io/en/stable/pact-properties.html

  @model
    [
...
     ; every function should conserve mass except for the admin fund-account,
     ; and debit / credit which should be private
     (property conserves-mass
       {'except: [fund-account, debit, credit]})
...
    ]


问:
SwiftUI & requestReview() – review popup not displaying
I am building an app with SwiftUI and would like to use requestReview() to display a review request popup. However, the popup is not displaying. From what I understand from the documentation, when the app is in development mode, the popup should display every time.

I've tested the app in the Xcode simulator and on a real device, I'm using Xcode 14.1. and the app builds without issue. (I'm also a SwiftUI newbie, I think I must be missing something obvious).

```<code>import SwiftUI
import StoreKit

struct DetailView: View {
        @Environment(\.requestReview) var requestReview
        @AppStorage("AppUsedCount") private var appUsedCount: Int = 0

        var body: some View {
            VStack {...}.onAppear{
                let updatedAppUsedCount: Int = appUsedCount + 1
                UserDefaults.standard.set(updatedAppUsedCount, forKey: "AppUsedCount")
                if (appUsedCount > 5){
                requestReview()
                }
        }
    }
}
</code>```

I also tested without the IF statement, but still no popup. appUsedCount updates as expected.

Thanks in advance!

Body:
I am building an app with SwiftUI and would like to use requestReview() to display a review request popup. However, the popup is not displaying. From what I understand from the documentation, when the app is in development mode, the popup should display every time.

I've tested the app in the Xcode simulator and on a real device, I'm using Xcode 14.1. and the app builds without issue. (I'm also a SwiftUI newbie, I think I must be missing something obvious).

import SwiftUI
import StoreKit

struct DetailView: View {
        @Environment(\.requestReview) var requestReview
        @AppStorage("AppUsedCount") private var appUsedCount: Int = 0

        var body: some View {
            VStack {...}.onAppear{
                let updatedAppUsedCount: Int = appUsedCount + 1
                UserDefaults.standard.set(updatedAppUsedCount, forKey: "AppUsedCount")
                if (appUsedCount > 5){
                requestReview()
                }
        }
    }
}

I also tested without the IF statement, but still no popup. appUsedCount updates as expected.

Thanks in advance!


问:
Flutter Awesome notifications not showing in background or when app is terminated
Good day.

I am using Awesome notifications in a food ordering app to notify users when their food is ready.

Notifications come through when the app is open, but not when the app is in the background/terminated. Once I re-open the app, all the notifcations that triggered while the app was in the background/terminated come through at once.

I have activated listeners in my main.dart file. These listeners listen for changes made to the my database (I am using Firebase), and generate local notifications  when specific changes occur. For example, if the "order status" attribute in the database changes from "accepted" to "completed", the user will get a notification that their order is ready to collect.

Am I missing something? I thought this plugin automatically handled notifcations when the app is in the background or is terminated.

Any help would be greatly appreciated!!

Listeners are activated in my main.dart file when the app builds and a user is logged in:

```<code>class AuthenticationWrapper extends StatelessWidget {
  const AuthenticationWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) => Scaffold(
        body: StreamBuilder<User?>(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return const Center(child: Text("Something went wrong :("));
            } else if (snapshot.hasData) {
              //The following methods are only executed if a user is logged in.
              //The methods below require the userID, therefore the user must fist be logged in for them to work
              listenForAcceptedOrders();
              listenForRejectedOrders();
              listenForCompletedOrders();

              //Listner for tapping on a notification or dismissing one
              AwesomeNotifications().setListeners(
                  onActionReceivedMethod:
                      NotificationController.onActionReceivedMethod,
                  onDismissActionReceivedMethod:
                      NotificationController.onDismissActionReceivedMethod);

              return const HomePage();
            } else {
              return SignInPage();
            }
          },
        ),
      );
}
</code>```

The notificationlistner methods:

```<code>void listenForAcceptedOrders() async {
  print("Current User ID-------->>>$loggedInUserID");
//This method listens for accepted orders and displays a notification
//It checks for new records entered into the managedOrders table containing the same customerID as the user currently logged in.
//If the customerID matches the ID of the current user logged in, it means that an order placed by THIS user has been accepted.
  _orderStream = _dbRef.child("ManagedOrders").onChildAdded.listen((event) {
    databaseMapper = event.snapshot.value as Map;
    String customerID = databaseMapper["customerID"].toString();
    String orderNum = databaseMapper["orderNum"].toString();
    String status = databaseMapper["status"].toString();

    print("CUSTOMERID ______......>>$customerID");

    if (customerID == loggedInUserID && status == "accepted") {
      acceptedOrderNotification(orderNum);
    } else {
      print("NO MATCH FOUND");
    }
  });
}

void listenForRejectedOrders() async {
  print("Current User ID-------->>>$loggedInUserID");
//This method listens for rejected orders and displays a notification
//It checks for new records entered into the managedOrders table containing the same customerID as the user currently logged in AND a status = rejetced
//If the customerID matches the ID of the current user logged in, it means that an order placed by THIS user has been accepted.
  _orderStream = _dbRef.child("ManagedOrders").onChildAdded.listen((event) {
    databaseMapper = event.snapshot.value as Map;
    String customerID = databaseMapper["customerID"].toString();
    String orderNum = databaseMapper["orderNum"].toString();
    String status = databaseMapper["status"].toString();

    print("CUSTOMERID ______......>>$customerID");

    if (customerID == loggedInUserID && status == "rejected") {
      rejectedOrderNotification(orderNum);
    }
  });
}

void listenForCompletedOrders() async {
//This method listens for completed orders and displays a notification
//It checks for new records entered into the CompleteOrders table containing the same customerID as the user currently logged in.
//If the customerID matches the ID of the current user logged in, it means that an order placed by THIS user has been completed.

  _orderStream = _dbRef.child("CompleteOrders").onChildAdded.listen((event) {
    databaseMapper = event.snapshot.value as Map;
    String customerID = databaseMapper["customerID"].toString();
    String orderNum = databaseMapper["orderNum"].toString();

    if (customerID == loggedInUserID) {
      completedOrderNotification(orderNum);
    } else {
      print("NO MATCH FOUND");
    }
  });

</code>```

Notifications code:

```<code>import 'package:awesome_notifications/awesome_notifications.dart';

Future<void> placeOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 001,
          channelKey: 'basic_channel',
          title:
              "${Emojis.activites_balloon} Your order request has been sent! (OrderNo: $orderNo)",
          body: "Nandos will update your order status shortly..."));
}

Future<void> acceptedOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 002,
          channelKey: 'basic_channel',
          title:
              "${Emojis.hand_thumbs_up} Your order (OrderNo: $orderNo) has been accepted!",
          body: "Nandos is now preparing your order"));
}

Future<void> rejectedOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 003,
          channelKey: 'basic_channel',
          title:
              "${Emojis.hand_thumbs_down} Your order (OrderNo: $orderNo) has been rejected!",
          body: "Nandos cannot take your order at this time"));
}

Future<void> completedOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 004,
          channelKey: 'basic_channel',
          title:
              "${Emojis.activites_fireworks} Your order (OrderNo: $orderNo) is ready to be collected!",
          body: "Please go collect your order at Nandos"));
}

</code>```

Body:
Good day.

I am using Awesome notifications in a food ordering app to notify users when their food is ready.

Notifications come through when the app is open, but not when the app is in the background/terminated. Once I re-open the app, all the notifcations that triggered while the app was in the background/terminated come through at once.

I have activated listeners in my main.dart file. These listeners listen for changes made to the my database (I am using Firebase), and generate local notifications  when specific changes occur. For example, if the "order status" attribute in the database changes from "accepted" to "completed", the user will get a notification that their order is ready to collect.

Am I missing something? I thought this plugin automatically handled notifcations when the app is in the background or is terminated.

Any help would be greatly appreciated!!

Listeners are activated in my main.dart file when the app builds and a user is logged in:

class AuthenticationWrapper extends StatelessWidget {
  const AuthenticationWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) => Scaffold(
        body: StreamBuilder<User?>(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return const Center(child: Text("Something went wrong :("));
            } else if (snapshot.hasData) {
              //The following methods are only executed if a user is logged in.
              //The methods below require the userID, therefore the user must fist be logged in for them to work
              listenForAcceptedOrders();
              listenForRejectedOrders();
              listenForCompletedOrders();

              //Listner for tapping on a notification or dismissing one
              AwesomeNotifications().setListeners(
                  onActionReceivedMethod:
                      NotificationController.onActionReceivedMethod,
                  onDismissActionReceivedMethod:
                      NotificationController.onDismissActionReceivedMethod);

              return const HomePage();
            } else {
              return SignInPage();
            }
          },
        ),
      );
}

The notificationlistner methods:

void listenForAcceptedOrders() async {
  print("Current User ID-------->>>$loggedInUserID");
//This method listens for accepted orders and displays a notification
//It checks for new records entered into the managedOrders table containing the same customerID as the user currently logged in.
//If the customerID matches the ID of the current user logged in, it means that an order placed by THIS user has been accepted.
  _orderStream = _dbRef.child("ManagedOrders").onChildAdded.listen((event) {
    databaseMapper = event.snapshot.value as Map;
    String customerID = databaseMapper["customerID"].toString();
    String orderNum = databaseMapper["orderNum"].toString();
    String status = databaseMapper["status"].toString();

    print("CUSTOMERID ______......>>$customerID");

    if (customerID == loggedInUserID && status == "accepted") {
      acceptedOrderNotification(orderNum);
    } else {
      print("NO MATCH FOUND");
    }
  });
}

void listenForRejectedOrders() async {
  print("Current User ID-------->>>$loggedInUserID");
//This method listens for rejected orders and displays a notification
//It checks for new records entered into the managedOrders table containing the same customerID as the user currently logged in AND a status = rejetced
//If the customerID matches the ID of the current user logged in, it means that an order placed by THIS user has been accepted.
  _orderStream = _dbRef.child("ManagedOrders").onChildAdded.listen((event) {
    databaseMapper = event.snapshot.value as Map;
    String customerID = databaseMapper["customerID"].toString();
    String orderNum = databaseMapper["orderNum"].toString();
    String status = databaseMapper["status"].toString();

    print("CUSTOMERID ______......>>$customerID");

    if (customerID == loggedInUserID && status == "rejected") {
      rejectedOrderNotification(orderNum);
    }
  });
}

void listenForCompletedOrders() async {
//This method listens for completed orders and displays a notification
//It checks for new records entered into the CompleteOrders table containing the same customerID as the user currently logged in.
//If the customerID matches the ID of the current user logged in, it means that an order placed by THIS user has been completed.

  _orderStream = _dbRef.child("CompleteOrders").onChildAdded.listen((event) {
    databaseMapper = event.snapshot.value as Map;
    String customerID = databaseMapper["customerID"].toString();
    String orderNum = databaseMapper["orderNum"].toString();

    if (customerID == loggedInUserID) {
      completedOrderNotification(orderNum);
    } else {
      print("NO MATCH FOUND");
    }
  });

Notifications code:

import 'package:awesome_notifications/awesome_notifications.dart';

Future<void> placeOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 001,
          channelKey: 'basic_channel',
          title:
              "${Emojis.activites_balloon} Your order request has been sent! (OrderNo: $orderNo)",
          body: "Nandos will update your order status shortly..."));
}

Future<void> acceptedOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 002,
          channelKey: 'basic_channel',
          title:
              "${Emojis.hand_thumbs_up} Your order (OrderNo: $orderNo) has been accepted!",
          body: "Nandos is now preparing your order"));
}

Future<void> rejectedOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 003,
          channelKey: 'basic_channel',
          title:
              "${Emojis.hand_thumbs_down} Your order (OrderNo: $orderNo) has been rejected!",
          body: "Nandos cannot take your order at this time"));
}

Future<void> completedOrderNotification(String orderNo) async {
  await AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 004,
          channelKey: 'basic_channel',
          title:
              "${Emojis.activites_fireworks} Your order (OrderNo: $orderNo) is ready to be collected!",
          body: "Please go collect your order at Nandos"));
}


问:
Dash model with separate button callbacks
In Python I am working with Dash and Dash bootstrap components. I am having trouble with the bootstrap Modal component. My most basic implementation of the modal, using the first example here, works fine. However, If I try to replace their single callback with two separate callbacks for the buttons, it stops working. Can anybody explain to me why this is and help me get it working? The callbacks don't seem difficult at all.

Most basic implementation of their code (this works for me):

```<code>from dash import Dash, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_bootstrap_components.themes import LUMEN

app = Dash(external_stylesheets=[LUMEN])
app.title = "Test"
app.layout = html.Div(
    [
        dbc.Button("Open modal", id="open", n_clicks=0),
        dbc.Modal(
            [
                dbc.ModalHeader(dbc.ModalTitle("Header")),
                dbc.ModalBody("This is the content of the modal"),
                dbc.ModalFooter(
                    dbc.Button(
                        "Close", id="close", className="ms-auto", n_clicks=0
                    )
                ),
            ],
            id="modal",
            is_open=False,
        ),
    ]
)

@app.callback(
    Output("modal", "is_open"),
    [Input("open", "n_clicks"), Input("close", "n_clicks")],
    [State("modal", "is_open")],
)
def toggle_modal(n1, n2, is_open):
    print(is_open)
    print(type(is_open))
    if n1 or n2:
        return not is_open
    return is_open

app.run()
</code>```

Code with their callbacks replaced by two separate callbacks for the buttons (not working):

```<code>from dash import Dash, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_bootstrap_components.themes import LUMEN

app = Dash(external_stylesheets=[LUMEN])
app.title = "Test"
app.layout = html.Div(
    [
        dbc.Button("Open modal", id="open", n_clicks=0),
        dbc.Modal(
            [
                dbc.ModalHeader(dbc.ModalTitle("Header")),
                dbc.ModalBody("This is the content of the modal"),
                dbc.ModalFooter(
                    dbc.Button(
                        "Close", id="close", className="ms-auto", n_clicks=0
                    )
                ),
            ],
            id="modal",
            is_open=False,
        ),
    ]
)

@app.callback(
    Output("modal", "is_open"),
    Input("open", "n_clicks")
)
def toggle_modal_open(n1):
    if n1:
        return True

@app.callback(
    Output("modal", "is_open"),
    Input("close", "n_clicks")
)
def toggle_modal_close(n1):
    if n1:
        return False

app.run()
</code>```

Body:
In Python I am working with Dash and Dash bootstrap components. I am having trouble with the bootstrap Modal component. My most basic implementation of the modal, using the first example here, works fine. However, If I try to replace their single callback with two separate callbacks for the buttons, it stops working. Can anybody explain to me why this is and help me get it working? The callbacks don't seem difficult at all.

Most basic implementation of their code (this works for me):

from dash import Dash, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_bootstrap_components.themes import LUMEN

app = Dash(external_stylesheets=[LUMEN])
app.title = "Test"
app.layout = html.Div(
    [
        dbc.Button("Open modal", id="open", n_clicks=0),
        dbc.Modal(
            [
                dbc.ModalHeader(dbc.ModalTitle("Header")),
                dbc.ModalBody("This is the content of the modal"),
                dbc.ModalFooter(
                    dbc.Button(
                        "Close", id="close", className="ms-auto", n_clicks=0
                    )
                ),
            ],
            id="modal",
            is_open=False,
        ),
    ]
)

@app.callback(
    Output("modal", "is_open"),
    [Input("open", "n_clicks"), Input("close", "n_clicks")],
    [State("modal", "is_open")],
)
def toggle_modal(n1, n2, is_open):
    print(is_open)
    print(type(is_open))
    if n1 or n2:
        return not is_open
    return is_open

app.run()

Code with their callbacks replaced by two separate callbacks for the buttons (not working):

from dash import Dash, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_bootstrap_components.themes import LUMEN

app = Dash(external_stylesheets=[LUMEN])
app.title = "Test"
app.layout = html.Div(
    [
        dbc.Button("Open modal", id="open", n_clicks=0),
        dbc.Modal(
            [
                dbc.ModalHeader(dbc.ModalTitle("Header")),
                dbc.ModalBody("This is the content of the modal"),
                dbc.ModalFooter(
                    dbc.Button(
                        "Close", id="close", className="ms-auto", n_clicks=0
                    )
                ),
            ],
            id="modal",
            is_open=False,
        ),
    ]
)

@app.callback(
    Output("modal", "is_open"),
    Input("open", "n_clicks")
)
def toggle_modal_open(n1):
    if n1:
        return True

@app.callback(
    Output("modal", "is_open"),
    Input("close", "n_clicks")
)
def toggle_modal_close(n1):
    if n1:
        return False

app.run()


问:
How can I hide an image in a material ui custom select when that menu item is selected?
I have a material ui (v4) custom select and I wanted a delete option for custom created statuses.  The last 2 are deleteable.

However, Once selected I no longer want the delete image there...

Here's my overrided select...

```<code><Select>
    {items?.map(({ value, label }) => (
      <MenuItem
        classes={{
          root: classes.selectMenuItem,
          selected: classes.selectMenuItemSelected
        }}
        value={value}
        key={value || Math.random()}
      >
        { deleteable && value > 11 && (
        <ListItemIcon>
              <DeleteForeverRoundedIcon />
        </ListItemIcon>
        )}
        {label || value}
      </MenuItem>
    ))}
  </Select>
</code>```

and my custom select...

```<code><CustomSelect
  value={leadStatus}
  leadStatus={leadStatus}
  onChange={e => {
    setLeadStatus(e.target.value);
  }}
  data={defaultLeadStatuses}
  deleteable={true}
/>
</code>```

Appreciate any guidance!

Body:
I have a material ui (v4) custom select and I wanted a delete option for custom created statuses.  The last 2 are deleteable.

However, Once selected I no longer want the delete image there...

Here's my overrided select...

<Select>
    {items?.map(({ value, label }) => (
      <MenuItem
        classes={{
          root: classes.selectMenuItem,
          selected: classes.selectMenuItemSelected
        }}
        value={value}
        key={value || Math.random()}
      >
        { deleteable && value > 11 && (
        <ListItemIcon>
              <DeleteForeverRoundedIcon />
        </ListItemIcon>
        )}
        {label || value}
      </MenuItem>
    ))}
  </Select>

and my custom select...

<CustomSelect
  value={leadStatus}
  leadStatus={leadStatus}
  onChange={e => {
    setLeadStatus(e.target.value);
  }}
  data={defaultLeadStatuses}
  deleteable={true}
/>

Appreciate any guidance!


问:
Show canvas grid option does not work with latest versions
The option look & feel "Show Canvas Grid" does not work anymore with PDI 9.3 / 9.4

OS: Windows 10 Entreprise

C:\ProgramData\portable\jdk-11\bin>java -version
java version "11.0.15.1" 2022-04-22 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.15.1+2-LTS-10)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.15.1+2-LTS-10, mixed mode)

Thanks!

After enabling the option & restart spoon.bat, the canvas grid does not appear on the screen.


问:
Make call to my local machine using os.system() from within a docker container
Docker for Windows.

I've written a docker image for a python project.

When I start a container based on this image, one of the instructions that gets executed is the following:

```<code>os.system(f"start \"\" "path/to/pdf_file.pdf")
</code>```

which simply opens the specified PDF file with the default PDF opener.

This instruction works perfectly locally, but, if I run it from a docker container, this file doesn't get opened in my local machine.

This makes sense, it probably gets opened in the docker container, and I can't see it because I've no way of seeing what's going on in the container (except by looking at the container logs).

My goal is to have the docker container TELL to my local machine to execute that command, in such a way the PDF file gets opened in my local machine, not in the docker container.

How could I achieve such goal?

Body:
Docker for Windows.

I've written a docker image for a python project.

When I start a container based on this image, one of the instructions that gets executed is the following:

os.system(f"start \"\" "path/to/pdf_file.pdf")

which simply opens the specified PDF file with the default PDF opener.

This instruction works perfectly locally, but, if I run it from a docker container, this file doesn't get opened in my local machine.

This makes sense, it probably gets opened in the docker container, and I can't see it because I've no way of seeing what's going on in the container (except by looking at the container logs).

My goal is to have the docker container TELL to my local machine to execute that command, in such a way the PDF file gets opened in my local machine, not in the docker container.

How could I achieve such goal?