问:
Mongodb Failed to look up SRV record
im new using mongodb,im trying to connect using php based on tutorial, im using ubuntu 20, i read mongodb default doesnt have user password and only accept 127.0.0.1. this script runs in same server as mongodb

```<code><?php
require("vendor/autoload.php");

$client = new MongoDB\Client(
    'mongodb+srv://127.0.0.1/test?w=majority'
 );
 $db = $client->test;
</code>```

returns :

```<code>PHP Fatal error:  Uncaught MongoDB\Driver\Exception\InvalidArgumentException: Failed to parse URI options: Failed to look up SRV record "_mongodb._tcp.127.0.0.1": The specified host is unknown. in /opt/wira/test_mongodb/vendor/mongodb/mongodb/src/Client.php:126
Stack trace:
#0 /opt/wira/test_mongodb/vendor/mongodb/mongodb/src/Client.php(126): MongoDB\Driver\Manager->__construct()
#1 /opt/wira/test_mongodb/test.php(5): MongoDB\Client->__construct()
#2 {main}
  thrown in /opt/wira/test_mongodb/vendor/mongodb/mongodb/src/Client.php on line 126
</code>```

Title: Mongodb Failed to look up SRV record

Body:
im new using mongodb,im trying to connect using php based on tutorial, im using ubuntu 20, i read mongodb default doesnt have user password and only accept 127.0.0.1. this script runs in same server as mongodb

<?php
require("vendor/autoload.php");

$client = new MongoDB\Client(
    'mongodb+srv://127.0.0.1/test?w=majority'
 );
 $db = $client->test;

returns :

PHP Fatal error:  Uncaught MongoDB\Driver\Exception\InvalidArgumentException: Failed to parse URI options: Failed to look up SRV record "_mongodb._tcp.127.0.0.1": The specified host is unknown. in /opt/wira/test_mongodb/vendor/mongodb/mongodb/src/Client.php:126
Stack trace:
#0 /opt/wira/test_mongodb/vendor/mongodb/mongodb/src/Client.php(126): MongoDB\Driver\Manager->__construct()
#1 /opt/wira/test_mongodb/test.php(5): MongoDB\Client->__construct()
#2 {main}
  thrown in /opt/wira/test_mongodb/vendor/mongodb/mongodb/src/Client.php on line 126


来源: stackexchange

问:
Open textfile locked by another application: The process cannot access the file because another process has locked a portion of the file
another application creates the text file pobox.lock when a user is logged in there and writes in this file the name of this user. With the Windows editor I can open this file at runtime of the other application and read the user.

But if I try to do that from my .Net code (C#) or even with any other application (Notepad, Notepad++, Word) or with admin rights, it doesn't work and I get the message that the file is locked.

When opening from .Net with the following code.

```<code>    string path = @"C:\<myfolder>\pobox.lock";
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (var sr = new StreamReader(fs))
        {
            string lockEntrie = sr.ReadToEnd();
        }
    }
</code>```

I get this message:

System.IO.IOException: The process cannot access the file because another process has locked
a portion of the file

Is there any other way to read the username from the file? Why is it possible to open the file in the editor?

Best thanks
Markus

ContentLicense: CC BY-SA 4.0

Body:
another application creates the text file pobox.lock when a user is logged in there and writes in this file the name of this user. With the Windows editor I can open this file at runtime of the other application and read the user.

But if I try to do that from my .Net code (C#) or even with any other application (Notepad, Notepad++, Word) or with admin rights, it doesn't work and I get the message that the file is locked.

When opening from .Net with the following code.

    string path = @"C:\<myfolder>\pobox.lock";
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (var sr = new StreamReader(fs))
        {
            string lockEntrie = sr.ReadToEnd();
        }
    }

I get this message:

System.IO.IOException: The process cannot access the file because another process has locked
a portion of the file

Is there any other way to read the username from the file? Why is it possible to open the file in the editor?

Best thanks
Markus


问:
How to add the author's link schema in the Rank math plugin
I can't add the author link in the schema templates section, please help. In addition, I also activated the author archive option, but it does not work. I want to manually insert the code that will insert the link of the author of the article in the schema. please guide me. Thankful

rankmath schema plugin

I tested the following codes but it didn't work
%the_author_posts_link%
%authorlink%


问:
Renv with docker. How to use local renv cache for packages in docker?
I am trying to build docker image for a R project. I created environment with renv for this project to lock state of packages that I used during this project.
How can I build docker image for this project and use the renv cache of my local machine instead of R-cran?
I hope I was clear.

Thank for advance


问:
Could I Test CAN Tranceiver with External Loopback Mode?
Hello I am using STM32H753 over a custom PCB.
I have no any CAN Analyzer except oscilloscope, multimeter and logic analyzer.
We have a problem with CAN BUS communication.
I am suspecting of CAN Tranceiver but we couldn't find the root cause yet.

There are external and internal loopback modes in STM32H7 to test CAN, However these modes also allow us to see the messages what we sent on CAN TX.
I have two different product which has different STM32H753 variant. One is working and the other one is not. Their tranceivers are different but almost same pinout and behavior.

My assumption was if I see my messages on CAN TX then I have to see them CAN H and CAN L.
I wrote test code.
I tried both test code in both device.

On working one, I saw messages on CAN Tx and also see messages with in a suppress way which I thought because of no termination resistor at the end.

On the not-working one, I also saw messages at CAN TX and there is no any move at CAN H or CAN L.

My question is my test was is true or still I could miss something or this test does not imply anyhting ?

```<code>  HAL_Delay(100);
  if(HAL_FDCAN_AddMessageToTxBuffer(&hfdcan1, &TxHeader, TxData_Node1_To_Node2, FDCAN_TX_BUFFER0    ) != HAL_OK)
  {
      Error_Handler();
  }
  /* Send Tx buffer message */
  if(HAL_FDCAN_EnableTxBufferRequest(&hfdcan1, FDCAN_TX_BUFFER0) != HAL_OK)
  {
      Error_Handler();
  }
  while(HAL_FDCAN_IsTxBufferMessagePending(&hfdcan1, FDCAN_TX_BUFFER0) == 1);

  /* Polling for reception complete on buffer index 0 */
  while(HAL_FDCAN_IsRxBufferMessageAvailable(&hfdcan1, FDCAN_RX_BUFFER0) == 0);

  /* Retrieve message from Rx buffer 0. Rec msg from Node 2 */
  if(HAL_FDCAN_GetRxMessage(&hfdcan1, FDCAN_RX_BUFFER0, &RxHeader, RxData_From_Node2) != HAL_OK)
  {
      Error_Handler();
  }

      hfdcan1.Instance = FDCAN1;
      hfdcan1.Init.FrameFormat = FDCAN_FRAME_CLASSIC;
      hfdcan1.Init.Mode = FDCAN_MODE_EXTERNAL_LOOPBACK;
      hfdcan1.Init.AutoRetransmission = DISABLE;
      hfdcan1.Init.TransmitPause = DISABLE;
      hfdcan1.Init.ProtocolException = DISABLE;
      hfdcan1.Init.NominalPrescaler = 1;
      hfdcan1.Init.NominalSyncJumpWidth = 13;
      hfdcan1.Init.NominalTimeSeg1 = 86;
      hfdcan1.Init.NominalTimeSeg2 = 13;
      hfdcan1.Init.DataPrescaler = 2;
      hfdcan1.Init.DataSyncJumpWidth = 12;
      hfdcan1.Init.DataTimeSeg1 = 12;
      hfdcan1.Init.DataTimeSeg2 = 12;
      hfdcan1.Init.MessageRAMOffset = 0;
      hfdcan1.Init.StdFiltersNbr = 1;
      hfdcan1.Init.ExtFiltersNbr = 0 ;
      hfdcan1.Init.RxFifo0ElmtsNbr = 0;
      hfdcan1.Init.RxFifo0ElmtSize = FDCAN_DATA_BYTES_8;
      hfdcan1.Init.RxFifo1ElmtsNbr = 0;
      hfdcan1.Init.RxFifo1ElmtSize = FDCAN_DATA_BYTES_8;
      hfdcan1.Init.RxBuffersNbr = 1;
      hfdcan1.Init.RxBufferSize = FDCAN_DATA_BYTES_8;
      hfdcan1.Init.TxEventsNbr = 0;
      hfdcan1.Init.TxBuffersNbr = 1;
      hfdcan1.Init.TxFifoQueueElmtsNbr = 32;
      hfdcan1.Init.TxFifoQueueMode = FDCAN_TX_FIFO_OPERATION;
      hfdcan1.Init.TxElmtSize = FDCAN_DATA_BYTES_8;
      if (HAL_FDCAN_Init(&hfdcan1) != HAL_OK)
      {
        Error_Handler();
      }
</code>```

Body:
Hello I am using STM32H753 over a custom PCB.
I have no any CAN Analyzer except oscilloscope, multimeter and logic analyzer.
We have a problem with CAN BUS communication.
I am suspecting of CAN Tranceiver but we couldn't find the root cause yet.

There are external and internal loopback modes in STM32H7 to test CAN, However these modes also allow us to see the messages what we sent on CAN TX.
I have two different product which has different STM32H753 variant. One is working and the other one is not. Their tranceivers are different but almost same pinout and behavior.

My assumption was if I see my messages on CAN TX then I have to see them CAN H and CAN L.
I wrote test code.
I tried both test code in both device.

On working one, I saw messages on CAN Tx and also see messages with in a suppress way which I thought because of no termination resistor at the end.

On the not-working one, I also saw messages at CAN TX and there is no any move at CAN H or CAN L.

My question is my test was is true or still I could miss something or this test does not imply anyhting ?

  HAL_Delay(100);
  if(HAL_FDCAN_AddMessageToTxBuffer(&hfdcan1, &TxHeader, TxData_Node1_To_Node2, FDCAN_TX_BUFFER0    ) != HAL_OK)
  {
      Error_Handler();
  }
  /* Send Tx buffer message */
  if(HAL_FDCAN_EnableTxBufferRequest(&hfdcan1, FDCAN_TX_BUFFER0) != HAL_OK)
  {
      Error_Handler();
  }
  while(HAL_FDCAN_IsTxBufferMessagePending(&hfdcan1, FDCAN_TX_BUFFER0) == 1);

  /* Polling for reception complete on buffer index 0 */
  while(HAL_FDCAN_IsRxBufferMessageAvailable(&hfdcan1, FDCAN_RX_BUFFER0) == 0);

  /* Retrieve message from Rx buffer 0. Rec msg from Node 2 */
  if(HAL_FDCAN_GetRxMessage(&hfdcan1, FDCAN_RX_BUFFER0, &RxHeader, RxData_From_Node2) != HAL_OK)
  {
      Error_Handler();
  }

      hfdcan1.Instance = FDCAN1;
      hfdcan1.Init.FrameFormat = FDCAN_FRAME_CLASSIC;
      hfdcan1.Init.Mode = FDCAN_MODE_EXTERNAL_LOOPBACK;
      hfdcan1.Init.AutoRetransmission = DISABLE;
      hfdcan1.Init.TransmitPause = DISABLE;
      hfdcan1.Init.ProtocolException = DISABLE;
      hfdcan1.Init.NominalPrescaler = 1;
      hfdcan1.Init.NominalSyncJumpWidth = 13;
      hfdcan1.Init.NominalTimeSeg1 = 86;
      hfdcan1.Init.NominalTimeSeg2 = 13;
      hfdcan1.Init.DataPrescaler = 2;
      hfdcan1.Init.DataSyncJumpWidth = 12;
      hfdcan1.Init.DataTimeSeg1 = 12;
      hfdcan1.Init.DataTimeSeg2 = 12;
      hfdcan1.Init.MessageRAMOffset = 0;
      hfdcan1.Init.StdFiltersNbr = 1;
      hfdcan1.Init.ExtFiltersNbr = 0 ;
      hfdcan1.Init.RxFifo0ElmtsNbr = 0;
      hfdcan1.Init.RxFifo0ElmtSize = FDCAN_DATA_BYTES_8;
      hfdcan1.Init.RxFifo1ElmtsNbr = 0;
      hfdcan1.Init.RxFifo1ElmtSize = FDCAN_DATA_BYTES_8;
      hfdcan1.Init.RxBuffersNbr = 1;
      hfdcan1.Init.RxBufferSize = FDCAN_DATA_BYTES_8;
      hfdcan1.Init.TxEventsNbr = 0;
      hfdcan1.Init.TxBuffersNbr = 1;
      hfdcan1.Init.TxFifoQueueElmtsNbr = 32;
      hfdcan1.Init.TxFifoQueueMode = FDCAN_TX_FIFO_OPERATION;
      hfdcan1.Init.TxElmtSize = FDCAN_DATA_BYTES_8;
      if (HAL_FDCAN_Init(&hfdcan1) != HAL_OK)
      {
        Error_Handler();
      }


问:
How to test action's dispatching in ngxs?
I try to cover @Action with unit tests and had some difficulties.

Here is an action example:

```<code>@Action(ActionsList.SetId)
public SetId(ctx: StateContext<DbModel>): Observable<string[]> {
    // const availableIds = this.getIds();
    const availableIds = ['ef23fewf', djej3ke1'];

    return this.dbService.getUsers(availableIds)
        .pipe(
            tap(users => {
                const idToSet = users.find(user => user.active)?.id;

                ctx.patchState({
                    activeId: idToSet,
                });

                ctx.dispatch(new ActionsList.SuccessIdSet({ id: idToSet }));
            }),
        );
}
</code>```

And I have problems with testing action dispatching:

```<code>ctx.dispatch(new ActionsList.SuccessIdSet({ id: idToSet }));
</code>```

Here is my current spec file:

```<code>describe('DbState', () => {
  let store: Store;
  let dbService: DbService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        NgxsModule.forRoot([DbState]),
      ],
      providers: [DbService],
    });

    store = TestBed.inject(Store);
    dbService = TestBed.inject(DbService);
  });

  beforeEach(() => {
    spyOn(dbService, 'getUsers').and.returnValue(of([{
      active: true,
      id: 'some-id'
    }]));
    store.dispatch(new ActionsList.SetId());
  });

  it('service method should be called', () => {
    expect(dbService.getUsers).toHaveBeenCalled();
  });

  it('should dispatch SuccessIdSet', () => {
    const dispatchSpy = spyOn(store, 'dispatch').and.callThrough();

    // expect(dispatchSpy).toHaveBeenCalledWith(new ActionsList.SuccessIdSet({ id: 'some-id' }));
  });
});
</code>```

First test works fine, but the second one doesn't work as expected, could you please help me with it?

Body:
I try to cover @Action with unit tests and had some difficulties.

Here is an action example:

@Action(ActionsList.SetId)
public SetId(ctx: StateContext<DbModel>): Observable<string[]> {
    // const availableIds = this.getIds();
    const availableIds = ['ef23fewf', djej3ke1'];

    return this.dbService.getUsers(availableIds)
        .pipe(
            tap(users => {
                const idToSet = users.find(user => user.active)?.id;

                ctx.patchState({
                    activeId: idToSet,
                });

                ctx.dispatch(new ActionsList.SuccessIdSet({ id: idToSet }));
            }),
        );
}

And I have problems with testing action dispatching:

ctx.dispatch(new ActionsList.SuccessIdSet({ id: idToSet }));

Here is my current spec file:

describe('DbState', () => {
  let store: Store;
  let dbService: DbService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        NgxsModule.forRoot([DbState]),
      ],
      providers: [DbService],
    });

    store = TestBed.inject(Store);
    dbService = TestBed.inject(DbService);
  });

  beforeEach(() => {
    spyOn(dbService, 'getUsers').and.returnValue(of([{
      active: true,
      id: 'some-id'
    }]));
    store.dispatch(new ActionsList.SetId());
  });

  it('service method should be called', () => {
    expect(dbService.getUsers).toHaveBeenCalled();
  });

  it('should dispatch SuccessIdSet', () => {
    const dispatchSpy = spyOn(store, 'dispatch').and.callThrough();

    // expect(dispatchSpy).toHaveBeenCalledWith(new ActionsList.SuccessIdSet({ id: 'some-id' }));
  });
});

First test works fine, but the second one doesn't work as expected, could you please help me with it?


问:
How can I convert my columns into rows and vice versa
I have a query wherein I have week, avg_pts, avg_fgm, avg_fga, pct, avg_fg3m as columns. Is there a way wherein I could make weeks 1 to 7 into a column? And the current columns into rows?

```<code>Expected Output:
Stats   Week1   Week2   Week3   Week4   Week5   Week6   Week7
Avg_pts 113.00    ...  ...  ..  ..
avg_fgm 42.00    ....   ...   ...
avg_fga 88.00    ....   ...    ...
pct     0.51     ..   ....   ....
avg_fg3m 11.00   ....   ...    ....
</code>```

Body:
I have a query wherein I have week, avg_pts, avg_fgm, avg_fga, pct, avg_fg3m as columns. Is there a way wherein I could make weeks 1 to 7 into a column? And the current columns into rows?

Expected Output:
Stats   Week1   Week2   Week3   Week4   Week5   Week6   Week7
Avg_pts 113.00    ...  ...  ..  ..
avg_fgm 42.00    ....   ...   ...
avg_fga 88.00    ....   ...    ...
pct     0.51     ..   ....   ....
avg_fg3m 11.00   ....   ...    ....


问:
Matplotlib Obscure Tick Behaviour
I observe some obscure behaviour of the ticks in a matplotlib.pyplot log-log plot.

```<code>#!/usr/bin/python3

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

dtFractions = [1/1, 1/2, 1/4, 1/8]

L2Err   = [4.41669808e-06, 1.10121946e-06, 2.78272254e-07, 8.18570087e-08]
LInfErr = [7.68589519e-05, 2.00625677e-05, 6.05176778e-06, 2.55658820e-06]

InchesX = 7
fig, ax = plt.subplots()

Blue_RGB   = [(0, 84/256, 159/256)]
Petrol_RGB = [(0/256, 152/256, 161/256)]

### ACTUAL PLOTTING: Infty errors ###
ax.scatter(dtFractions, LInfErr, label = r'$e^\infty$', color = Blue_RGB)
ax.plot(dtFractions, LInfErr, color = Blue_RGB[0], linestyle='dashed')
ax.scatter(dtFractions, L2Err, label = r'$e^2$', color = Petrol_RGB)
ax.plot(dtFractions, L2Err, color = Petrol_RGB[0], linestyle='dashed')

ax.loglog(dtFractions, np.multiply(1e-5, np.power(dtFractions, 2) ), linestyle='dotted',
          label = r'$\mathcal{O}\left(\Delta t^2\right)$',
          color = 'black') # Order two line fitted

# Turn on logscale (no native support for logarithmic scatter)
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel(r'$\Delta t^\mathrm{Eff}_S$')

### GRID SECTION ###
ax.grid(axis ='both', which='major', alpha=0.1, linewidth = 1.5, color ='black')
ax.set_axisbelow(True)  # Hide grid behind bars

### LEGEND SECTION ###
ax.legend(loc = "upper left")

### TICKS SECTION ###

plt.tick_params(axis='x', which = 'both', bottom=False)

ax.set_xticks(dtFractions)

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

ax.get_xaxis().set_tick_params(which='minor', size=0)
ax.get_xaxis().set_tick_params(which='minor', width=0)

ax.set_xticklabels([r"$1$", r"$1/2$", r"$1/4$", r"$1/8$"])

### TITLE SECTION ###
plt.title(r"$l^\infty$ Error for CEE: Isentropic Vortex on Uniform Grid")

# Scale while preserving aspect ratio
width, height = fig.get_size_inches()
factor = InchesX / width
fig.set_size_inches(width * factor, height * factor)

plt.tight_layout()  # Title, labels, ... to screen
plt.savefig('Convergence2DComprEulerVortex_PERK.pgf', bbox_inches = 'tight', pad_inches = 0)
plt.show()
</code>```

This produces

Note in particular the strange additional ticks.

If I add one more custom tick, i.e.,

```<code>#!/usr/bin/python3

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

dtFractions = [1/1, 1/2, 1/4, 1/8, 1/16]

L2Err   = [4.41669808e-06, 1.10121946e-06, 2.78272254e-07, 8.18570087e-08, 42]
LInfErr = [7.68589519e-05, 2.00625677e-05, 6.05176778e-06, 2.55658820e-06, 42]

InchesX = 7
fig, ax = plt.subplots()

Blue_RGB   = [(0, 84/256, 159/256)]
Petrol_RGB = [(0/256, 152/256, 161/256)]

### ACTUAL PLOTTING: Infty errors ###
ax.scatter(dtFractions, LInfErr, label = r'$e^\infty$', color = Blue_RGB)
ax.plot(dtFractions, LInfErr, color = Blue_RGB[0], linestyle='dashed')
ax.scatter(dtFractions, L2Err, label = r'$e^2$', color = Petrol_RGB)
ax.plot(dtFractions, L2Err, color = Petrol_RGB[0], linestyle='dashed')

ax.loglog(dtFractions, np.multiply(1e-5, np.power(dtFractions, 2) ), linestyle='dotted',
          label = r'$\mathcal{O}\left(\Delta t^2\right)$',
          color = 'black') # Order two line fitted

# Turn on logscale (no native support for logarithmic scatter)
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel(r'$\Delta t^\mathrm{Eff}_S$')

### GRID SECTION ###
ax.grid(axis ='both', which='major', alpha=0.1, linewidth = 1.5, color ='black')
ax.set_axisbelow(True)  # Hide grid behind bars

### LEGEND SECTION ###
ax.legend(loc = "upper left")

### TICKS SECTION ###

plt.tick_params(axis='x', which = 'both', bottom=False)

ax.set_xticks(dtFractions)

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

ax.get_xaxis().set_tick_params(which='minor', size=0)
ax.get_xaxis().set_tick_params(which='minor', width=0)

ax.set_xticklabels([r"$1$", r"$1/2$", r"$1/4$", r"$1/8$", r"$1/16$"])

### TITLE SECTION ###
plt.title(r"$l^\infty$ Error for CEE: Isentropic Vortex on Uniform Grid")

# Scale while preserving aspect ratio
width, height = fig.get_size_inches()
factor = InchesX / width
fig.set_size_inches(width * factor, height * factor)

plt.tight_layout()  # Title, labels, ... to screen
plt.savefig('Convergence2DComprEulerVortex_PERK.pgf', bbox_inches = 'tight', pad_inches = 0)
plt.show()
</code>```

Then everything works as expected:

Is this a bug? I tried also the second version and then setting xlim to something fitting - the obscure ticks are arising again.

Title: Matplotlib Obscure Tick Behaviour

Body:
I observe some obscure behaviour of the ticks in a matplotlib.pyplot log-log plot.

#!/usr/bin/python3

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

dtFractions = [1/1, 1/2, 1/4, 1/8]

L2Err   = [4.41669808e-06, 1.10121946e-06, 2.78272254e-07, 8.18570087e-08]
LInfErr = [7.68589519e-05, 2.00625677e-05, 6.05176778e-06, 2.55658820e-06]

InchesX = 7
fig, ax = plt.subplots()

Blue_RGB   = [(0, 84/256, 159/256)]
Petrol_RGB = [(0/256, 152/256, 161/256)]

### ACTUAL PLOTTING: Infty errors ###
ax.scatter(dtFractions, LInfErr, label = r'$e^\infty$', color = Blue_RGB)
ax.plot(dtFractions, LInfErr, color = Blue_RGB[0], linestyle='dashed')
ax.scatter(dtFractions, L2Err, label = r'$e^2$', color = Petrol_RGB)
ax.plot(dtFractions, L2Err, color = Petrol_RGB[0], linestyle='dashed')

ax.loglog(dtFractions, np.multiply(1e-5, np.power(dtFractions, 2) ), linestyle='dotted',
          label = r'$\mathcal{O}\left(\Delta t^2\right)$',
          color = 'black') # Order two line fitted

# Turn on logscale (no native support for logarithmic scatter)
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel(r'$\Delta t^\mathrm{Eff}_S$')

### GRID SECTION ###
ax.grid(axis ='both', which='major', alpha=0.1, linewidth = 1.5, color ='black')
ax.set_axisbelow(True)  # Hide grid behind bars

### LEGEND SECTION ###
ax.legend(loc = "upper left")

### TICKS SECTION ###

plt.tick_params(axis='x', which = 'both', bottom=False)

ax.set_xticks(dtFractions)

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

ax.get_xaxis().set_tick_params(which='minor', size=0)
ax.get_xaxis().set_tick_params(which='minor', width=0)

ax.set_xticklabels([r"$1$", r"$1/2$", r"$1/4$", r"$1/8$"])

### TITLE SECTION ###
plt.title(r"$l^\infty$ Error for CEE: Isentropic Vortex on Uniform Grid")

# Scale while preserving aspect ratio
width, height = fig.get_size_inches()
factor = InchesX / width
fig.set_size_inches(width * factor, height * factor)

plt.tight_layout()  # Title, labels, ... to screen
plt.savefig('Convergence2DComprEulerVortex_PERK.pgf', bbox_inches = 'tight', pad_inches = 0)
plt.show()

This produces

Note in particular the strange additional ticks.

If I add one more custom tick, i.e.,

#!/usr/bin/python3

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

dtFractions = [1/1, 1/2, 1/4, 1/8, 1/16]

L2Err   = [4.41669808e-06, 1.10121946e-06, 2.78272254e-07, 8.18570087e-08, 42]
LInfErr = [7.68589519e-05, 2.00625677e-05, 6.05176778e-06, 2.55658820e-06, 42]

InchesX = 7
fig, ax = plt.subplots()

Blue_RGB   = [(0, 84/256, 159/256)]
Petrol_RGB = [(0/256, 152/256, 161/256)]

### ACTUAL PLOTTING: Infty errors ###
ax.scatter(dtFractions, LInfErr, label = r'$e^\infty$', color = Blue_RGB)
ax.plot(dtFractions, LInfErr, color = Blue_RGB[0], linestyle='dashed')
ax.scatter(dtFractions, L2Err, label = r'$e^2$', color = Petrol_RGB)
ax.plot(dtFractions, L2Err, color = Petrol_RGB[0], linestyle='dashed')

ax.loglog(dtFractions, np.multiply(1e-5, np.power(dtFractions, 2) ), linestyle='dotted',
          label = r'$\mathcal{O}\left(\Delta t^2\right)$',
          color = 'black') # Order two line fitted

# Turn on logscale (no native support for logarithmic scatter)
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel(r'$\Delta t^\mathrm{Eff}_S$')

### GRID SECTION ###
ax.grid(axis ='both', which='major', alpha=0.1, linewidth = 1.5, color ='black')
ax.set_axisbelow(True)  # Hide grid behind bars

### LEGEND SECTION ###
ax.legend(loc = "upper left")

### TICKS SECTION ###

plt.tick_params(axis='x', which = 'both', bottom=False)

ax.set_xticks(dtFractions)

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

ax.get_xaxis().set_tick_params(which='minor', size=0)
ax.get_xaxis().set_tick_params(which='minor', width=0)

ax.set_xticklabels([r"$1$", r"$1/2$", r"$1/4$", r"$1/8$", r"$1/16$"])

### TITLE SECTION ###
plt.title(r"$l^\infty$ Error for CEE: Isentropic Vortex on Uniform Grid")

# Scale while preserving aspect ratio
width, height = fig.get_size_inches()
factor = InchesX / width
fig.set_size_inches(width * factor, height * factor)

plt.tight_layout()  # Title, labels, ... to screen
plt.savefig('Convergence2DComprEulerVortex_PERK.pgf', bbox_inches = 'tight', pad_inches = 0)
plt.show()

Then everything works as expected:

Is this a bug? I tried also the second version and then setting xlim to something fitting - the obscure ticks are arising again.


问:
MySQL get MAX using Over Partition on two columns
I'm trying to get a max value of an elements types using Over Partition By. But my query didn't work as well.

This is the input tables (attached file)

And this is my sql query :

```<code>select ccm.id as controle_id, max(ccm.valeur) OVER (PARTITION BY ccm.object_id, ccm.jour) as maxi, max(ccm.minutes) OVER (PARTITION BY ccm.jour, ccm.object_id, ccm.heure) as max_minute, ccm.jour, object_id, ccm.valeur, ccm.heure, ccm.minutes
    from cte_controle_mensuel ccm
</code>```

And this is what I'm expecting.

But when I run the query, I receive this :

How can I fix it

Body:
I'm trying to get a max value of an elements types using Over Partition By. But my query didn't work as well.

This is the input tables (attached file)

And this is my sql query :

select ccm.id as controle_id, max(ccm.valeur) OVER (PARTITION BY ccm.object_id, ccm.jour) as maxi, max(ccm.minutes) OVER (PARTITION BY ccm.jour, ccm.object_id, ccm.heure) as max_minute, ccm.jour, object_id, ccm.valeur, ccm.heure, ccm.minutes
    from cte_controle_mensuel ccm

And this is what I'm expecting.

But when I run the query, I receive this :

How can I fix it


问:
How to move 2D multiple drawn shapes (Squares and Rectanagles) seperately in OpenGl?
I have just started using OpenGl in visual studio.

I used the drawsquare() and drawRoundRect () to draw multiple shapes in seperate void functions which I called seperately in an another function named Display (void return type) which I then called in int main using glutDisplayFunc(Display) to display.

In the Display function I used glutPushmatrix() and glutPopMatrix () keeping the function of 1 shape  in between like this

```<code>glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(50, 50, 50, colors[BALCK]);
glutPopMatrix ();
</code>```
```<code>glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(300, 300, 50, colors[BALCK]);
glutPopMatrix ();
</code>```

The issue is that the when I click the mouse anywhere on the screen(even not on the shapes) both of these shapes start moving together.

Q1) How to move the shapes one by one only when the mouse is clicked and dragged on the specific shape ?

Q2) What should I do so that the shape only moves when it is clicked and dragged and nothing happens when I click anywhere else on the screen.

I used glutPushMatrix() , glutPopMatrix() and glTranslatef () functions which worked fine for moving one shape but I don't know how I can move multiple shapes only when they are clicked and dragged.

```<code>glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(50, 50, 50, colors[BALCK]);
glutPopMatrix ();
</code>```
```<code>glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(300, 300, 50, colors[BALCK]);
glutPopMatrix ();
</code>```

Using this code both of my figures move together not seperately.
Also even if the mouse is not clicked on any of the shapes they both start to move.

Body:
I have just started using OpenGl in visual studio.

I used the drawsquare() and drawRoundRect () to draw multiple shapes in seperate void functions which I called seperately in an another function named Display (void return type) which I then called in int main using glutDisplayFunc(Display) to display.

In the Display function I used glutPushmatrix() and glutPopMatrix () keeping the function of 1 shape  in between like this

glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(50, 50, 50, colors[BALCK]);
glutPopMatrix ();

glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(300, 300, 50, colors[BALCK]);
glutPopMatrix ();

The issue is that the when I click the mouse anywhere on the screen(even not on the shapes) both of these shapes start moving together.

Q1) How to move the shapes one by one only when the mouse is clicked and dragged on the specific shape ?

Q2) What should I do so that the shape only moves when it is clicked and dragged and nothing happens when I click anywhere else on the screen.

I used glutPushMatrix() , glutPopMatrix() and glTranslatef () functions which worked fine for moving one shape but I don't know how I can move multiple shapes only when they are clicked and dragged.

glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(50, 50, 50, colors[BALCK]);
glutPopMatrix ();

glutPushmatrix();
glutTranslatef(x,y,0); // z = 0 because i am making 2D shape
DrawSquare(300, 300, 50, colors[BALCK]);
glutPopMatrix ();

Using this code both of my figures move together not seperately.
Also even if the mouse is not clicked on any of the shapes they both start to move.


问:
Angular 12 - display confirm dialog on browser back button
In Angular 12 i need to display a confirmation message on browser back button.

I'm putting the code in app component.
I do not want a GUARD, because i need something generic that works automagically without have to put a guard on every component :)

If yes -> history.back();

If no -> history.pushState(null, null, null);

The yes button is working.
The no button is behaving like the yes button. It should stay in the page but it is leaving.

Atempt 1:

```<code>window.onpopstate = function (e) {
              const endProgress = confirm('Are you sure you want to go back?');
              if (endProgress) {
                console.log('go back on history');
                window.onpopstate = null;
                history.back();
              } else {
                console.log('stay on same page');
                e.preventDefault();
                history.pushState(null, null, null);
              }
            };
</code>```

Atempt 2 -> displaying a hand made modal, also does not work:
It goes back but triggers again the whole code block displaying the modal again.

```<code>this.router.events
          .pipe(filter((event: NavigationStart) => event.navigationTrigger === 'popstate'))
          .subscribe(() => {
            this.router.navigateByUrl(this.router.url);
            this.location.go(this.router.url);
            console.log('no');
            const ref = this.modalService.open(ConfirmExitModalComponent, { size: 'lg' });
            ref.result.then(
              () => {
                this.location.back();
                console.log('yes');
              },
              () => (err: I2SErrorResponse) => this.messagesService.displayMessages(err)
            );
          });
      }
</code>```

Body:
In Angular 12 i need to display a confirmation message on browser back button.

I'm putting the code in app component.
I do not want a GUARD, because i need something generic that works automagically without have to put a guard on every component :)

If yes -> history.back();

If no -> history.pushState(null, null, null);

The yes button is working.
The no button is behaving like the yes button. It should stay in the page but it is leaving.

Atempt 1:

window.onpopstate = function (e) {
              const endProgress = confirm('Are you sure you want to go back?');
              if (endProgress) {
                console.log('go back on history');
                window.onpopstate = null;
                history.back();
              } else {
                console.log('stay on same page');
                e.preventDefault();
                history.pushState(null, null, null);
              }
            };

Atempt 2 -> displaying a hand made modal, also does not work:
It goes back but triggers again the whole code block displaying the modal again.

this.router.events
          .pipe(filter((event: NavigationStart) => event.navigationTrigger === 'popstate'))
          .subscribe(() => {
            this.router.navigateByUrl(this.router.url);
            this.location.go(this.router.url);
            console.log('no');
            const ref = this.modalService.open(ConfirmExitModalComponent, { size: 'lg' });
            ref.result.then(
              () => {
                this.location.back();
                console.log('yes');
              },
              () => (err: I2SErrorResponse) => this.messagesService.displayMessages(err)
            );
          });
      }


问:
REST API - SOAPUI - POST script generates key ID at the end of the query
I have a bit of a problem here. I was making some API tests using the POST Method in SOAP UI. I put this script to generate a new entry

```<code>{
   "title":"Mark",
   "author":"Hampton",
   "text":"TestRest",
   "created":"${#Project#Timestamp}" - can be a fixed value
}
</code>```

I got a proper response and an entry is created as following

```<code>{
   "title":"Mark",
   "author":"Hampton",
   "text":"TestRest",
   "created":"12/05/2022-15:40",
   "id":6
}
</code>```

The "id" property is generated automatically. I was wondering if there is a way to force the "id" property to be on top. When I did a PATCH method and added a new parameter. The "id" property was above the new parameter

```<code>{
   "title":"Johan",
   "author":"Dudes",
   "text":"Dyke",
   "created":"12/05/2022-15:40",
   "id":6,
   "updated":"12/06/2022-17:07"
}
</code>```

So, how can I do a POST method where the ID is generated automatically at the top, and in the response script, the ID parameter is not at the bottom of a response

Body:
I have a bit of a problem here. I was making some API tests using the POST Method in SOAP UI. I put this script to generate a new entry

{
   "title":"Mark",
   "author":"Hampton",
   "text":"TestRest",
   "created":"${#Project#Timestamp}" - can be a fixed value
}

I got a proper response and an entry is created as following

{
   "title":"Mark",
   "author":"Hampton",
   "text":"TestRest",
   "created":"12/05/2022-15:40",
   "id":6
}

The "id" property is generated automatically. I was wondering if there is a way to force the "id" property to be on top. When I did a PATCH method and added a new parameter. The "id" property was above the new parameter

{
   "title":"Johan",
   "author":"Dudes",
   "text":"Dyke",
   "created":"12/05/2022-15:40",
   "id":6,
   "updated":"12/06/2022-17:07"
}

So, how can I do a POST method where the ID is generated automatically at the top, and in the response script, the ID parameter is not at the bottom of a response


问:
How to change result SQL syntax for age group from colomn to new row
I Tried to grouping age from and found this answer(SQL Group by Age Range)

But the result is as a colomn not a row Like this

I Just want to convert the colomn into a row Like This

The query is:

```<code>SELECT SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') < 18 THEN 1 ELSE 0 END) AS '< 18',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 18 AND 25 THEN 1 ELSE 0 END) AS '18-25 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 26 AND 35 THEN 1 ELSE 0 END) AS '26-35 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 36 AND 45 THEN 1 ELSE 0 END) AS '36-45 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 46 AND 55 THEN 1 ELSE 0 END) AS '46-55 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 56 AND 65 THEN 1 ELSE 0 END) AS '56-65 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 66 AND 200 THEN 1 ELSE 0 END) AS '>66 Tahun'
    FROM user_detail
</code>```

My table for tanggal_lahir:

Body:
I Tried to grouping age from and found this answer(SQL Group by Age Range)

But the result is as a colomn not a row Like this

I Just want to convert the colomn into a row Like This

The query is:

SELECT SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') < 18 THEN 1 ELSE 0 END) AS '< 18',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 18 AND 25 THEN 1 ELSE 0 END) AS '18-25 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 26 AND 35 THEN 1 ELSE 0 END) AS '26-35 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 36 AND 45 THEN 1 ELSE 0 END) AS '36-45 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 46 AND 55 THEN 1 ELSE 0 END) AS '46-55 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 56 AND 65 THEN 1 ELSE 0 END) AS '56-65 Tahun',
    SUM(CASE WHEN DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),user_detail.tanggal_lahir)), '%Y') BETWEEN 66 AND 200 THEN 1 ELSE 0 END) AS '>66 Tahun'
    FROM user_detail

My table for tanggal_lahir:


问:
Sharing content from web page to instagram
Cannot find any opportunity to post content from my page to Instagram directly, without usage of web share api. Is it evet possible to share from my page link, title, img ect. to instagram post/story/direct message?

Or if we anyway should use web share api, can we leave there only instagram related variant but no other ways to share content, like fb, whatsapp ect.?

Have tried to share post on Facebook by adding necessary attributes in url, and used vue-social-sharing npm package, which by the way doesn't contain Instagram as possible option


问:
AvalonDock remove child in LayoutAnchorableGroup
I'm creating LayoutAnchorable dynamically and adding it to a parent. A button fires this code and created layoutAnchrable, listbox and some content in it.

```<code>LayoutAnchorable layoutAnchorable = new LayoutAnchorable
        {
            Content = listBox,
            Title = _selectedSchema.Value,
            ContentId = _selectedSchema.Key,
            IsActive = true,
            IsSelected = true,
            CanFloat = true,
            CanAutoHide = false,
            CanClose = true,
            CanHide = false,
        };

        if(!panelXml.Children.Select(x => x.ContentId).Contains(layoutAnchorable.ContentId))
        {
            panelXml.Children.Add(layoutAnchorable);
        }
        else
        {
            panelXml.Children.Remove(layoutAnchorable);
        }
</code>```

If there is the same layoutAnchorable in Children I want to remove it from the children list.
I traced the code and it works just fine but panelXml.Children.Remove(layoutAnchorable); does not work.

Body:
I'm creating LayoutAnchorable dynamically and adding it to a parent. A button fires this code and created layoutAnchrable, listbox and some content in it.

LayoutAnchorable layoutAnchorable = new LayoutAnchorable
        {
            Content = listBox,
            Title = _selectedSchema.Value,
            ContentId = _selectedSchema.Key,
            IsActive = true,
            IsSelected = true,
            CanFloat = true,
            CanAutoHide = false,
            CanClose = true,
            CanHide = false,
        };

        if(!panelXml.Children.Select(x => x.ContentId).Contains(layoutAnchorable.ContentId))
        {
            panelXml.Children.Add(layoutAnchorable);
        }
        else
        {
            panelXml.Children.Remove(layoutAnchorable);
        }

If there is the same layoutAnchorable in Children I want to remove it from the children list.
I traced the code and it works just fine but panelXml.Children.Remove(layoutAnchorable); does not work.


问:
Javascript desktop to mobile problem
Right Now I am trying to set up a image zoom and the abilty to drag a enlarged image around in a contained box. The code I have for the desktop is show in this fiddle right here

The main problem I have is when i run this js in a mobile enviroment everything works except the ability to move the image around. I am sure my problem is that I am using onmousemove instead of outouchmove, I did on another fiddle right here that used that but still no dice.

So my question is am I not using ontouchmove right or if anyone has any suggestion it would be much helpful

ContentLicense: CC BY-SA 3.0

Title: Javascript desktop to mobile problem


问:
"Jest encountered an unexpected token" expo w/ typescript
I got an error when trying to run a snapshot test.

"Test suite failed to run. Jest encountered an unexpected token. This usually means you are trying to import a file which Jest cannot parse"

I searched SO for duplicate answers but it seems like each error is specific to that OP's case. I am following expo's docs and jest docs.

package.json

```<code>{
  "name": "calorie-tracker-react-native",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "test": "jest"
  },
  "jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)"
    ]
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "~1.17.3",
    "@react-navigation/native": "^6.0.13",
    "@react-navigation/native-stack": "^6.9.1",
    "@reduxjs/toolkit": "^1.8.6",
    "@types/node": "^18.11.10",
    "@types/react-dom": "^18.0.9",
    "expo": "~46.0.16",
    "expo-app-loading": "~2.1.0",
    "expo-checkbox": "~2.2.0",
    "expo-font": "~10.2.0",
    "expo-image-picker": "~13.3.1",
    "expo-status-bar": "~1.4.0",
    "jest": "^26.6.3",
    "jest-expo": "^47.0.1",
    "react": "18.0.0",
    "react-native": "0.69.6",
    "react-native-circular-progress-indicator": "^4.4.0",
    "react-native-popup-menu": "^0.16.1",
    "react-native-progress": "^5.0.0",
    "react-native-reanimated": "^2.12.0",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-svg": "^12.3.0",
    "react-native-vector-icons": "^9.2.0",
    "react-redux": "^8.0.4",
    "react-test-renderer": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@tsconfig/react-native": "^2.0.3",
    "@types/jest": "^29.2.4",
    "@types/react": "^18.0.26",
    "@types/react-native": "^0.70.8",
    "@types/react-test-renderer": "^18.0.0",
    "typescript": "^4.9.4"
  },
  "private": true
}
</code>```

jest.config.js

```<code>module.exports = {
    preset: 'react-native',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
  };
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {},
  "extends": "expo/tsconfig.base"
}

</code>```

Body:
I got an error when trying to run a snapshot test.

"Test suite failed to run. Jest encountered an unexpected token. This usually means you are trying to import a file which Jest cannot parse"

I searched SO for duplicate answers but it seems like each error is specific to that OP's case. I am following expo's docs and jest docs.

package.json

{
  "name": "calorie-tracker-react-native",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "test": "jest"
  },
  "jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)"
    ]
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "~1.17.3",
    "@react-navigation/native": "^6.0.13",
    "@react-navigation/native-stack": "^6.9.1",
    "@reduxjs/toolkit": "^1.8.6",
    "@types/node": "^18.11.10",
    "@types/react-dom": "^18.0.9",
    "expo": "~46.0.16",
    "expo-app-loading": "~2.1.0",
    "expo-checkbox": "~2.2.0",
    "expo-font": "~10.2.0",
    "expo-image-picker": "~13.3.1",
    "expo-status-bar": "~1.4.0",
    "jest": "^26.6.3",
    "jest-expo": "^47.0.1",
    "react": "18.0.0",
    "react-native": "0.69.6",
    "react-native-circular-progress-indicator": "^4.4.0",
    "react-native-popup-menu": "^0.16.1",
    "react-native-progress": "^5.0.0",
    "react-native-reanimated": "^2.12.0",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-svg": "^12.3.0",
    "react-native-vector-icons": "^9.2.0",
    "react-redux": "^8.0.4",
    "react-test-renderer": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@tsconfig/react-native": "^2.0.3",
    "@types/jest": "^29.2.4",
    "@types/react": "^18.0.26",
    "@types/react-native": "^0.70.8",
    "@types/react-test-renderer": "^18.0.0",
    "typescript": "^4.9.4"
  },
  "private": true
}

jest.config.js

module.exports = {
    preset: 'react-native',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
  };

tsconfig.json

{
  "compilerOptions": {},
  "extends": "expo/tsconfig.base"
}


问:
Puppeteer - Extract only the results that contain a certain text
How can I extract / export only the urls that contain the reddit.com domain?

```<code>const puppeteer = require("puppeteer");
const fs = require('fs').promises;

let browser;
(async () => {
  browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox']
  });
  const [page] = await browser.pages();

  await page.goto('https://old.reddit.com/', {
    "waitUntil": "networkidle0"
  });
  const aElems = await page.$$('a.title');
  const urls = [];

  for (let i = 0; i < aElems.length && i < 10; i++) {
    const href = await aElems[i].evaluate(e => e.href);
    const newPage = await browser.newPage();
    await newPage.goto(href, {waitUntil: "networkidle0"});

    const url = await newPage.evaluate(() => document.location.href);
    console.log(url);
    urls.push(url);
  }

  await fs.writeFiexportle('export.json', JSON.stringify(urls));
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;
</code>```

Thank you!

I tried this:

```<code>const href = await aElems[i].evaluate(e => e.href.includes('reddit.com') );
</code>```

but it didn't work :(

Body:
How can I extract / export only the urls that contain the reddit.com domain?

const puppeteer = require("puppeteer");
const fs = require('fs').promises;

let browser;
(async () => {
  browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox']
  });
  const [page] = await browser.pages();

  await page.goto('https://old.reddit.com/', {
    "waitUntil": "networkidle0"
  });
  const aElems = await page.$$('a.title');
  const urls = [];

  for (let i = 0; i < aElems.length && i < 10; i++) {
    const href = await aElems[i].evaluate(e => e.href);
    const newPage = await browser.newPage();
    await newPage.goto(href, {waitUntil: "networkidle0"});

    const url = await newPage.evaluate(() => document.location.href);
    console.log(url);
    urls.push(url);
  }

  await fs.writeFiexportle('export.json', JSON.stringify(urls));
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;

Thank you!

I tried this:

const href = await aElems[i].evaluate(e => e.href.includes('reddit.com') );

but it didn't work :(


问:
how to use LabelEncoder in pipeline? i get an error repeatedly
i don't know how to use LabelEncoder in pipeline! i repeatedly get an error

OK! this is my code:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

bank = pd.read_csv('bankmarketing.csv')

bank.columns = bank.columns.astype('str')
bank.columns = bank.columns.str.strip()

train_set, test_set = train_test_split(bank, test_size = 0.3, random_state = 100)
train_set.shape

```<code>from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import FeatureUnion

class DataFrameSelector(BaseEstimator, TransformerMixin):
    def __init__(self, attribute_names):
        self.attribute_names = attribute_names
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        return X[self.attribute_names].values

df = train_set.copy()
df_label = df['y'].copy()
df = df.drop('y', axis = 1)

df_num_needless = df[['age', 'day', 'compaign', 'previous']].copy()
df_num = df.drop(['age', 'day', 'compaign', 'previous'], axis = 1)
df_num = df[['balance', 'duration', 'pdays']].copy()
df_cat = df[['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'poutcome']].copy()

df_cat1 = df['job']
df_cat2 = df['marital']
df_cat3 = df['education']
df_cat4 = df['default']
df_cat5 = df['housing']
df_cat6 = df['loan']
df_cat7 = df['contact']
df_cat8 = df['month']
df_cat9 = df['poutcome']

num_attrs = list(df_num)

cat_attr1 = list(df_cat1)
cat_attr2 = list(df_cat2)
cat_attr3 = list(df_cat3)
cat_attr4 = list(df_cat4)
cat_attr5 = list(df_cat5)
cat_attr6 = list(df_cat6)
cat_attr7 = list(df_cat7)
cat_attr8 = list(df_cat8)
cat_attr9 = list(df_cat9)

num_pipeline = Pipeline([
    ('selector', DataFrameSelector(num_attrs)),
    ('scaler', StandardScaler())
    ])

*: i got error when i wanted to use LabelEncoder so i had to make different pipeline for categorical data:

cat_pipeline1 = Pipeline([
    ('selector', DataFrameSelector(cat_attr1)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline2 = Pipeline([
    ('selector', DataFrameSelector(cat_attr2)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline3 = Pipeline([
    ('selector', DataFrameSelector(cat_attr3)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline4 = Pipeline([
    ('selector', DataFrameSelector(cat_attr4)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline5 = Pipeline([
    ('selector', DataFrameSelector(cat_attr5)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline6 = Pipeline([
    ('selector', DataFrameSelector(cat_attr6)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline7 = Pipeline([
    ('selector', DataFrameSelector(cat_attr7)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline8 = Pipeline([
    ('selector', DataFrameSelector(cat_attr8)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline9 = Pipeline([
    ('selector', DataFrameSelector(cat_attr9)),
    ('encoder', LabelEncoder())
    ])

*: but now i don't know how can i use these pipelines????

full_pipeline = FeatureUnion(transformer_list = [
    ('num_pipeline', num_pipeline),
    ('cat_pipeline', ????????????)
    ])

bank_prepared_df = pd.DataFrame(full_pipeline.fit_transform(df), columns = ['age', 'job', 'marital', 'education', 'default', 'balance',
                                                            'housing', 'loan', 'contact', 'day', 'month', 'duration',
                                                            'compaign', 'pdays', 'previous', 'poutcome'])
bank_prepared_df.head()

</code>```

Body:
i don't know how to use LabelEncoder in pipeline! i repeatedly get an error

OK! this is my code:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

bank = pd.read_csv('bankmarketing.csv')

bank.columns = bank.columns.astype('str')
bank.columns = bank.columns.str.strip()

train_set, test_set = train_test_split(bank, test_size = 0.3, random_state = 100)
train_set.shape

from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import FeatureUnion

class DataFrameSelector(BaseEstimator, TransformerMixin):
    def __init__(self, attribute_names):
        self.attribute_names = attribute_names
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        return X[self.attribute_names].values

df = train_set.copy()
df_label = df['y'].copy()
df = df.drop('y', axis = 1)

df_num_needless = df[['age', 'day', 'compaign', 'previous']].copy()
df_num = df.drop(['age', 'day', 'compaign', 'previous'], axis = 1)
df_num = df[['balance', 'duration', 'pdays']].copy()
df_cat = df[['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'poutcome']].copy()

df_cat1 = df['job']
df_cat2 = df['marital']
df_cat3 = df['education']
df_cat4 = df['default']
df_cat5 = df['housing']
df_cat6 = df['loan']
df_cat7 = df['contact']
df_cat8 = df['month']
df_cat9 = df['poutcome']

num_attrs = list(df_num)

cat_attr1 = list(df_cat1)
cat_attr2 = list(df_cat2)
cat_attr3 = list(df_cat3)
cat_attr4 = list(df_cat4)
cat_attr5 = list(df_cat5)
cat_attr6 = list(df_cat6)
cat_attr7 = list(df_cat7)
cat_attr8 = list(df_cat8)
cat_attr9 = list(df_cat9)

num_pipeline = Pipeline([
    ('selector', DataFrameSelector(num_attrs)),
    ('scaler', StandardScaler())
    ])

*: i got error when i wanted to use LabelEncoder so i had to make different pipeline for categorical data:

cat_pipeline1 = Pipeline([
    ('selector', DataFrameSelector(cat_attr1)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline2 = Pipeline([
    ('selector', DataFrameSelector(cat_attr2)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline3 = Pipeline([
    ('selector', DataFrameSelector(cat_attr3)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline4 = Pipeline([
    ('selector', DataFrameSelector(cat_attr4)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline5 = Pipeline([
    ('selector', DataFrameSelector(cat_attr5)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline6 = Pipeline([
    ('selector', DataFrameSelector(cat_attr6)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline7 = Pipeline([
    ('selector', DataFrameSelector(cat_attr7)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline8 = Pipeline([
    ('selector', DataFrameSelector(cat_attr8)),
    ('encoder', LabelEncoder())
    ])

cat_pipeline9 = Pipeline([
    ('selector', DataFrameSelector(cat_attr9)),
    ('encoder', LabelEncoder())
    ])

*: but now i don't know how can i use these pipelines????

full_pipeline = FeatureUnion(transformer_list = [
    ('num_pipeline', num_pipeline),
    ('cat_pipeline', ????????????)
    ])

bank_prepared_df = pd.DataFrame(full_pipeline.fit_transform(df), columns = ['age', 'job', 'marital', 'education', 'default', 'balance',
                                                            'housing', 'loan', 'contact', 'day', 'month', 'duration',
                                                            'compaign', 'pdays', 'previous', 'poutcome'])
bank_prepared_df.head()


问:
Getting currently opened tabs from stock browser
Is there a way to get all the URLs from currently opened tabs in Android programmatically? I know there's a way to read browser history but I need a way to detect active tabs and URLs contained. Any ideas?</p>


问:
Measure Symfony's httpClient and Doctrine queries execution time and create Prometheus metrics
there are actually two separate questions under this title

I am trying to figure out how to measure the requests duration made to external services in Symfony application via the httpClient and same for Doctrine queries.
For Doctrine queries I am considering option to create Lifecycle Event Listener and measure pre post timestamps of request but I think they are only for create/update/delete operations but not for get. Also performance is concern with this approach.

Also I am still getting familiar with Prometheus but I would like to post those values as metrics to Prometheus (I would figure out this eventually after I get the data).
I have promphp/prometheus_client_php installed and basic metrics are running fine.

Would be grateful if someone faced similar case to share some opinion.


问:
Error in if (x == "" | x == ".") { : argument is of length zero
I have a questions regarding an error I get. I am new to R so bear with me.

I do understand that the second error is probably an effect of the first error, but I do not understand the first error? Do anyone have any ideas why it occurs?

```<code> #### Correction of snow surface roughness with slope ####
>
> f <- list.files(pattern=paste("ruggedness", i_max, ".asc$", sep=""), full.names=TRUE)
> rugg<- raster(f)
Error in if (x == "" | x == ".") { : argument is of length zero
>
> if (i_max > 1) {
+
+
+   f <- list.files(pattern=paste("slope", i_max, ".asc$", sep=""), full.names=TRUE)
+   slp_coef <- as.matrix(raster(f))
+   slp_coef <- 1- ((slp_coef-30)/30)
+   slp_coef[slp_coef < 0] <- 0
+   slp_coef[slp_coef > 1] <- 1
+   slp_coef <- 1 + (slp_coef * (i_max -1))
+   slp_coef <- round(slp_coef, digits = 0)
+   #write.ascii.grid(data = slp_coef, "coef", header = head, write.header = TRUE, digits = 2,
+   #                hdr.digits = 3 , dec = ".", georef = "corner")
+
+
+   for (i in 1:(i_max -1)) {
+     f <- list.files(pattern=paste("ruggedness", i, ".asc$", sep=""), full.names=TRUE)
+     rugg_i<- raster(f)
+     rugg[which(slp_coef == i )] <- rugg_i[which(slp_coef == i)]
+   }
+ }
Error in h(simpleError(msg, call)) :
  error in evaluating the argument 'x' in selecting a method for function 'as.matrix': argument is of length zero
</code>```

Thank you,
Liza

I am trying to get potential release areas for avalanches by using Rstudio and RSAGA, so everything is helpful!

Body:
I have a questions regarding an error I get. I am new to R so bear with me.

I do understand that the second error is probably an effect of the first error, but I do not understand the first error? Do anyone have any ideas why it occurs?

 #### Correction of snow surface roughness with slope ####
>
> f <- list.files(pattern=paste("ruggedness", i_max, ".asc$", sep=""), full.names=TRUE)
> rugg<- raster(f)
Error in if (x == "" | x == ".") { : argument is of length zero
>
> if (i_max > 1) {
+
+
+   f <- list.files(pattern=paste("slope", i_max, ".asc$", sep=""), full.names=TRUE)
+   slp_coef <- as.matrix(raster(f))
+   slp_coef <- 1- ((slp_coef-30)/30)
+   slp_coef[slp_coef < 0] <- 0
+   slp_coef[slp_coef > 1] <- 1
+   slp_coef <- 1 + (slp_coef * (i_max -1))
+   slp_coef <- round(slp_coef, digits = 0)
+   #write.ascii.grid(data = slp_coef, "coef", header = head, write.header = TRUE, digits = 2,
+   #                hdr.digits = 3 , dec = ".", georef = "corner")
+
+
+   for (i in 1:(i_max -1)) {
+     f <- list.files(pattern=paste("ruggedness", i, ".asc$", sep=""), full.names=TRUE)
+     rugg_i<- raster(f)
+     rugg[which(slp_coef == i )] <- rugg_i[which(slp_coef == i)]
+   }
+ }
Error in h(simpleError(msg, call)) :
  error in evaluating the argument 'x' in selecting a method for function 'as.matrix': argument is of length zero

Thank you,
Liza

I am trying to get potential release areas for avalanches by using Rstudio and RSAGA, so everything is helpful!


问:
select2 textarea field cant able to give input
I would like to give search field in dropdown with multiselect so i went with select2 library but i could not able to give values for the input field.

```<code> dynamicTable = $("#" + gridId).DataTable({
    processing: true,
    serverSide: true,
    filter: true,
    scrollX: true,
    //bFilter: true,
    //dom: "Bfrtip",
    order: [[orderByColumn, "desc"]],
    orderCellsTop: true,
    initComplete: function () {
      var i = 0;
      var api = this.api();
      // For each column
      api
        .columns()
        .eq(0)
        .each(function (colIdx) {
          // Set the header cell to contain the input element
          var cell = $(".filters th").eq(
            $(api.column(colIdx).header()).index()
          );
          if (columnConfig[i].filterRequired) {
            if (columnConfig[i].dropDownFilter) {
              $(cell).html("");
              var select = $(
                '<select id="' +
                  columnConfig[i].colName +
                  'dropDownFilter" class="select2" data-control="select2" style="width:100%;text-dark" multiple="multiple" ><option value=""></option></select>'
              ).on("change", function () {
                var data = $(this).val();

                if (data.length === 0) {
                  data = [""];
                }

                //join array into string with regex or (|)
                var val = data.join("|");

                //search for the option(s) selected
                api
                  .column(colIdx)
                  .search(val ? val : "", true, false)
                  .draw();
              });
              select.append('<option value="Bus">Bus</option>');
              select.append('<option value="Truck">Truck</option>');
              select.append('<option value="Bus">Bus</option>');
              select.append('<option value="Truck">Truck</option>');
              select.append('<option value="Bus">Bus</option>');
              select.append('<option value="Truck">Truck</option>');
              cell.append(select);

              $("#" + columnConfig[i].colName + "dropDownFilter").select2({
                multiple: true,
                closeOnSelect: false,
                placeholder: "Select a " + columnConfig[i].colName,
                //allowClear: true,
              });

              //initially clear select otherwise first option is selected
              $(".select2").val(null).trigger("change");
              dropDownFilterArray.push(
                "#" + columnConfig[i].colName + "dropDownFilter"
              );
            } else {
              var title = $(cell).text();
              $(cell).removeClass("text-white");
              $(cell).html(
                '<input type="text" style="width:100%;text-dark" class="form-control" placeholder="' +
                  title +
                  '" />'
              );
            }
          } else {
            cell.html(
              '<input type="text" style="width:100%;text-dark;" class="form-control hidecolumn" placeholder="' +
                title +
                '" />'
            );
          }
          i++;

          // On every keypress in this input
          $(
            "input[type=text]",
            $(".filters th").eq($(api.column(colIdx).header()).index())
          )
            .off("keyup change")
            .on("keyup change", function (e) {
              e.stopPropagation();
              // Get the search value
              $(this).attr("title", $(this).val());
              var regexr = "{search}"; //$(this).parents('th').find('select').val();
              var cursorPosition = this.selectionStart;
              // Search the column for that value
              api
                .column(colIdx)
                .search(
                  this.value != ""
                    ? regexr.replace("{search}", "" + this.value + "")
                    : "",
                  this.value != "",
                  this.value == ""
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });

          $(dropDownFilterString)
            // "input[type=checkbox]",
            // $(".filters th").eq($(api.column(colIdx).header()).index())
            // .columns(dropDownFilterArray)
            .on("change", function (e) {
              //Get the "text" property from each selected data
              //regex escape the value and store in array
              // var data = $.map($(this).val(), function (value, key) {
              //   return value.text
              //     ? "^" + $.fn.dataTable.util.escapeRegex(value.text) + "$"
              //     : null;
              // });

              // var value = this.$select.val();
              // console.log(value);

              const selected = this.$(" option:selected")
                .toArray()
                .map((opt) => $(opt).val())
                .join("|");
              console.log(selected);
              example.column(2).search(selected, true, false).draw();

              //if no data selected use ""
              if (data.length === 0) {
                data = [""];
              }
              //join array into string with regex or (|)
              var val = data.join("|");

              //search for the option(s) selected
              column.search(val ? val : "", true, false).draw();
            });
        });
      //$("body .dropdown-toggle").dropdown();
      // for (let j = 0; j < dropDownFilterArray.length; j++) {
      //   if (j + 1 == dropDownFilterArray.length)
      //     dropDownFilterString += dropDownFilterArray[j];
      //   else dropDownFilterString += dropDownFilterArray[j] + ",";
      // }
    },
</code>```

Body:
I would like to give search field in dropdown with multiselect so i went with select2 library but i could not able to give values for the input field.

 dynamicTable = $("#" + gridId).DataTable({
    processing: true,
    serverSide: true,
    filter: true,
    scrollX: true,
    //bFilter: true,
    //dom: "Bfrtip",
    order: [[orderByColumn, "desc"]],
    orderCellsTop: true,
    initComplete: function () {
      var i = 0;
      var api = this.api();
      // For each column
      api
        .columns()
        .eq(0)
        .each(function (colIdx) {
          // Set the header cell to contain the input element
          var cell = $(".filters th").eq(
            $(api.column(colIdx).header()).index()
          );
          if (columnConfig[i].filterRequired) {
            if (columnConfig[i].dropDownFilter) {
              $(cell).html("");
              var select = $(
                '<select id="' +
                  columnConfig[i].colName +
                  'dropDownFilter" class="select2" data-control="select2" style="width:100%;text-dark" multiple="multiple" ><option value=""></option></select>'
              ).on("change", function () {
                var data = $(this).val();

                if (data.length === 0) {
                  data = [""];
                }

                //join array into string with regex or (|)
                var val = data.join("|");

                //search for the option(s) selected
                api
                  .column(colIdx)
                  .search(val ? val : "", true, false)
                  .draw();
              });
              select.append('<option value="Bus">Bus</option>');
              select.append('<option value="Truck">Truck</option>');
              select.append('<option value="Bus">Bus</option>');
              select.append('<option value="Truck">Truck</option>');
              select.append('<option value="Bus">Bus</option>');
              select.append('<option value="Truck">Truck</option>');
              cell.append(select);

              $("#" + columnConfig[i].colName + "dropDownFilter").select2({
                multiple: true,
                closeOnSelect: false,
                placeholder: "Select a " + columnConfig[i].colName,
                //allowClear: true,
              });

              //initially clear select otherwise first option is selected
              $(".select2").val(null).trigger("change");
              dropDownFilterArray.push(
                "#" + columnConfig[i].colName + "dropDownFilter"
              );
            } else {
              var title = $(cell).text();
              $(cell).removeClass("text-white");
              $(cell).html(
                '<input type="text" style="width:100%;text-dark" class="form-control" placeholder="' +
                  title +
                  '" />'
              );
            }
          } else {
            cell.html(
              '<input type="text" style="width:100%;text-dark;" class="form-control hidecolumn" placeholder="' +
                title +
                '" />'
            );
          }
          i++;

          // On every keypress in this input
          $(
            "input[type=text]",
            $(".filters th").eq($(api.column(colIdx).header()).index())
          )
            .off("keyup change")
            .on("keyup change", function (e) {
              e.stopPropagation();
              // Get the search value
              $(this).attr("title", $(this).val());
              var regexr = "{search}"; //$(this).parents('th').find('select').val();
              var cursorPosition = this.selectionStart;
              // Search the column for that value
              api
                .column(colIdx)
                .search(
                  this.value != ""
                    ? regexr.replace("{search}", "" + this.value + "")
                    : "",
                  this.value != "",
                  this.value == ""
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });

          $(dropDownFilterString)
            // "input[type=checkbox]",
            // $(".filters th").eq($(api.column(colIdx).header()).index())
            // .columns(dropDownFilterArray)
            .on("change", function (e) {
              //Get the "text" property from each selected data
              //regex escape the value and store in array
              // var data = $.map($(this).val(), function (value, key) {
              //   return value.text
              //     ? "^" + $.fn.dataTable.util.escapeRegex(value.text) + "$"
              //     : null;
              // });

              // var value = this.$select.val();
              // console.log(value);

              const selected = this.$(" option:selected")
                .toArray()
                .map((opt) => $(opt).val())
                .join("|");
              console.log(selected);
              example.column(2).search(selected, true, false).draw();

              //if no data selected use ""
              if (data.length === 0) {
                data = [""];
              }
              //join array into string with regex or (|)
              var val = data.join("|");

              //search for the option(s) selected
              column.search(val ? val : "", true, false).draw();
            });
        });
      //$("body .dropdown-toggle").dropdown();
      // for (let j = 0; j < dropDownFilterArray.length; j++) {
      //   if (j + 1 == dropDownFilterArray.length)
      //     dropDownFilterString += dropDownFilterArray[j];
      //   else dropDownFilterString += dropDownFilterArray[j] + ",";
      // }
    },


问:
How to get an image byte array from an HTML string in C#?
The requirement is to get an image byte from the HTML string. input: HTML string and type(png,jpg) Output: byte[] Any suggestions?

Below added the sample HTML string

This is a paragraph.

This is a paragraph.

This is a paragraph.

```
<p>As I need to pass this byte array to itextSharp for further processing, I need the output as an image byte array.</p>
<p>previously I have used the GetImageFromHTML functionality provided by winnowative. Now we are replacing Winnowative and need an alternative for getting the image bytes.
See the winnowative code below.</p>
```public static byte[] GetWinnovativeImageByte(string htmlString)
        {
            byte[] pdfBytes = null;
            pdfBytes = wImg.GetImageBytesFromHtmlString(htmlString, System.Drawing.Imaging.ImageFormat.Png);//wpc.GetPdfBytesFromHtmlString(htmlString);//, baseURL);
            return pdfBytes;
        }
```

Body:
The requirement is to get an image byte from the HTML string. input: HTML string and type(png,jpg) Output: byte[] Any suggestions?

Below added the sample HTML string

This is a paragraph.

This is a paragraph.

This is a paragraph.

As I need to pass this byte array to itextSharp for further processing, I need the output as an image byte array.

previously I have used the GetImageFromHTML functionality provided by winnowative. Now we are replacing Winnowative and need an alternative for getting the image bytes.
See the winnowative code below.

public static byte[] GetWinnovativeImageByte(string htmlString)
        {
            byte[] pdfBytes = null;
            pdfBytes = wImg.GetImageBytesFromHtmlString(htmlString, System.Drawing.Imaging.ImageFormat.Png);//wpc.GetPdfBytesFromHtmlString(htmlString);//, baseURL);
            return pdfBytes;
        }


问:
Amplify React Login Network Error message appears only in Firefox
We have developed a Neos CMS based website that provides a login mask using React App, AWS Amplify and Cognito. After a successful login, the page is reloaded using

```<code>window.location.reload(false);
</code>```

This works in all browsers except Firefox. A "Network Error" error is briefly displayed there before the reload. The page then reloads after some time and you are also successfully logged in there.

Network error on login in Firefox

Do you have any idea how to fix the "Network error" problem?

I found out that the error only occurs when the page is reloaded after a successful login. Firefox appears to want to reload before the login process is complete. If I remove the page reload, the login works fine in all browsers. However, this is not the solution as we need the page reload.

Body:
We have developed a Neos CMS based website that provides a login mask using React App, AWS Amplify and Cognito. After a successful login, the page is reloaded using

window.location.reload(false);

This works in all browsers except Firefox. A "Network Error" error is briefly displayed there before the reload. The page then reloads after some time and you are also successfully logged in there.

Network error on login in Firefox

Do you have any idea how to fix the "Network error" problem?

I found out that the error only occurs when the page is reloaded after a successful login. Firefox appears to want to reload before the login process is complete. If I remove the page reload, the login works fine in all browsers. However, this is not the solution as we need the page reload.


问:
What is the the purpose of the "scalars.link.ts" file in a React Bundle and why is it so big?

It's all pretty much in the question.
What is the purpose of this file, why is it so big and can I reduce its size?

I have not found any documentation on why this file is generated and how/why/where it's useful to the application.


问:
How can I set TCP connection timeout using Keep alive in Linux?
I have a TCP connection that I want to get fast feedback that the connection is broken.

My device transmits data every second or every couple of seconds (definitely not longer than 4 seconds). There are a few cases that the ethernet connection might get lost and the device doesn't "know" that and it keeps the socket open for many seconds until it is considered broken. If that time was very short I could re-open the socket and start transmitting again.

It takes many seconds until I notice something using send and recv commands.

From another post here I found the following:

```<code>ssize_t set = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&set, sizeof(set)) != 0)
{
    return -1;
}

int keepcnt = 5;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &keepcnt, sizeof(keepcnt)) != 0)
{
    return -1;
}

int keepidle = 5;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle)) != 0)
{
    return -1;
}

int keepintvl = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &keepintvl, sizeof(keepintvl)) != 0)
{
    return -1;
}
</code>```

But it doesn't seem to change anything...

I unplug the cable and it still takes a lot of seconds.

Also if I set the values at 1 the connection should consider broken almost immediately but instead it keeps going even if I have the ethernet cable unplugged for 10 seconds or more.

And it resumes when I plug it in.

Body:
I have a TCP connection that I want to get fast feedback that the connection is broken.

My device transmits data every second or every couple of seconds (definitely not longer than 4 seconds). There are a few cases that the ethernet connection might get lost and the device doesn't "know" that and it keeps the socket open for many seconds until it is considered broken. If that time was very short I could re-open the socket and start transmitting again.

It takes many seconds until I notice something using send and recv commands.

From another post here I found the following:

ssize_t set = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&set, sizeof(set)) != 0)
{
    return -1;
}

int keepcnt = 5;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &keepcnt, sizeof(keepcnt)) != 0)
{
    return -1;
}

int keepidle = 5;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle)) != 0)
{
    return -1;
}

int keepintvl = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &keepintvl, sizeof(keepintvl)) != 0)
{
    return -1;
}

But it doesn't seem to change anything...

I unplug the cable and it still takes a lot of seconds.

Also if I set the values at 1 the connection should consider broken almost immediately but instead it keeps going even if I have the ethernet cable unplugged for 10 seconds or more.

And it resumes when I plug it in.


问:
Doctrine in random ocassions duplicates existing entrys in a OneToMany relation
I have a device that can have multiple states having here a One To many relation.

The problem is that sometimes and totally randomly instead of updating the device info with the new states it creates a new device.

I put logs everywhere in order to see if any error happens but there is no errors and everyday it creates some random new entries and I cannot replicate this error by changing the states values.

DEVICE

```<code>/**
* device
*
* @ORM\Table(name="Device", indexes={@ORM\Index(name="FK_Device_Client",
columns={"client"}), @ORM\Index(name="fk_Device_Instalation1_idx", columns=
{"instalation"})})
* @ORM\Entity
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="tipo", type="integer")
}

abstract class Device
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="bigint", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;
</code>```

CHANGE STATE

```<code>   private $device;

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\OneToMany(targetEntity="InformacionEnviada", mappedBy="changeState")
 */
</code>```

Controller

Now the controller is a bit complicated because there are many cases to consider, so I only put the doctrine calls for better understanding but I notice that some flush method are being called in the same run for the same device so I think something may be wrong here.

```<code>foreach($devices as $device){
   if(Condition){
      $this->em->merge($device);
      IF(Condition){
         $this->em->getConnection()->executeUpdate('UPDATE ChangeState SET date_time_end = ? WHERE device= ? AND date_time_end is null', array($nowString ,  $device->getId()));
        $this->em->flush();
   }

   $this->em->persist($changeState);
   $this->em->merge($device);
   $this->em->flush();
   }

  $this->em->merge($device);
  $this->em->flush();
}
</code>```

This code is working fine and the states are being added to the device, but randomly I get new entries, and I cannot replicate the error, but one of the iterations that got duplicate executed this query and then flushed, so maybe the error is here.

```<code>$this->em->getConnection()->executeUpdate('UPDATE ChangeState SET date_time_end = ? WHERE device= ? AND date_time_end is null', array($nowString ,  $device->getId()));
        $this->em->flush();
</code>```

Can you help me please? I'm so lost here and I cannot figure out the error.

Body:
I have a device that can have multiple states having here a One To many relation.

The problem is that sometimes and totally randomly instead of updating the device info with the new states it creates a new device.

I put logs everywhere in order to see if any error happens but there is no errors and everyday it creates some random new entries and I cannot replicate this error by changing the states values.

DEVICE

/**
* device
*
* @ORM\Table(name="Device", indexes={@ORM\Index(name="FK_Device_Client",
columns={"client"}), @ORM\Index(name="fk_Device_Instalation1_idx", columns=
{"instalation"})})
* @ORM\Entity
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="tipo", type="integer")
}

abstract class Device
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="bigint", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

CHANGE STATE

   private $device;

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\OneToMany(targetEntity="InformacionEnviada", mappedBy="changeState")
 */

Controller

Now the controller is a bit complicated because there are many cases to consider, so I only put the doctrine calls for better understanding but I notice that some flush method are being called in the same run for the same device so I think something may be wrong here.

foreach($devices as $device){
   if(Condition){
      $this->em->merge($device);
      IF(Condition){
         $this->em->getConnection()->executeUpdate('UPDATE ChangeState SET date_time_end = ? WHERE device= ? AND date_time_end is null', array($nowString ,  $device->getId()));
        $this->em->flush();
   }

   $this->em->persist($changeState);
   $this->em->merge($device);
   $this->em->flush();
   }

  $this->em->merge($device);
  $this->em->flush();
}

This code is working fine and the states are being added to the device, but randomly I get new entries, and I cannot replicate the error, but one of the iterations that got duplicate executed this query and then flushed, so maybe the error is here.

$this->em->getConnection()->executeUpdate('UPDATE ChangeState SET date_time_end = ? WHERE device= ? AND date_time_end is null', array($nowString ,  $device->getId()));
        $this->em->flush();

Can you help me please? I'm so lost here and I cannot figure out the error.


问:
How to configure network security for ip address
I am a smart device, and I use http when configuring the network for smart devices,for example: "http://192.168.1.1". Due to some reasons, our devices cannot be upgraded to https for the time being, but Android is forced to use https for communication after 9.0.

I changed the network configuration:

```<code><network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>
</code>```

but This kind of configuration is prohibited on Google play, so I changed it to this:

```<code><network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.1.1</domain>
        <domain includeSubdomains="true">192.168.2.1</domain>
    </domain-config>
</network-security-config>
</code>```

In this way, I can successfully communicate with the device in this LAN, but the IP address of the communication is not fixed. If you change to a different brand of router or a different network segment cannot achieve communication, how should I deal with it，or is there any way to wildcard all ip addresses?

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

Body:
I am a smart device, and I use http when configuring the network for smart devices,for example: "http://192.168.1.1". Due to some reasons, our devices cannot be upgraded to https for the time being, but Android is forced to use https for communication after 9.0.

I changed the network configuration:

<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

but This kind of configuration is prohibited on Google play, so I changed it to this:

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.1.1</domain>
        <domain includeSubdomains="true">192.168.2.1</domain>
    </domain-config>
</network-security-config>

In this way, I can successfully communicate with the device in this LAN, but the IP address of the communication is not fixed. If you change to a different brand of router or a different network segment cannot achieve communication, how should I deal with it，or is there any way to wildcard all ip addresses?


问:
Display data in MVC Kendo Pivot Grid2
`Need some example which can help me to bind data into MVC kendo Pivot Grid2.
I have to display data in Kendo PIvot grid 2 in MVC.

I tried to display data in kendo Pivot Grid2 in MVC. I want to read data from MVC action method and bind to Kendo Grid 2.

```<code><div id="example">
@(Html.Kendo().PivotContainer()
    .Name("container")
    .ConfiguratorPosition("left")
    .Content(@<text>
        @(Html.Kendo().PivotConfiguratorV2()
            .Name("configurator")
            .Sortable(true)
            .Filterable(true))
        @(Html.Kendo().PivotGridV2()
            .Name("pivotgrid")
            .ColumnWidth(200)
            .Height(580)
            .Configurator("#configurator")
            .DataSource(dataSource => dataSource.
                Xmla()
                .Columns(columns => {
                    columns.Add("[Date].[Calendar]").Expand(true);
                    columns.Add("[Product].[Category]");
                })
                .Rows(rows => rows.Add("[Geography].[City]").Expand(true))
                .Measures(measures => measures.Values(new string[]{"[Measures].[Reseller Freight      Cost]"}))
                .Transport(transport => transport
                    .Connection(connection => connection
                        .Catalog("Adventure Works DW 2008R2")
                        .Cube("Adventure Works"))
                    .Read("https://demos.telerik.com/olap/msmdpump.dll")
                )
            )
        )
        @(Html.Kendo().PivotConfiguratorButton()
            .Name("Button")
            .Configurator("configurator")
        )
</text>))
</div>
</code>```

Need to display output as below.
enter image description here

Title: Display data in MVC Kendo Pivot Grid2

Body:
`Need some example which can help me to bind data into MVC kendo Pivot Grid2.
I have to display data in Kendo PIvot grid 2 in MVC.

I tried to display data in kendo Pivot Grid2 in MVC. I want to read data from MVC action method and bind to Kendo Grid 2.

@(Html.Kendo().PivotContainer()
    .Name("container")
    .ConfiguratorPosition("left")
    .Content(@<text>
        @(Html.Kendo().PivotConfiguratorV2()
            .Name("configurator")
            .Sortable(true)
            .Filterable(true))
        @(Html.Kendo().PivotGridV2()
            .Name("pivotgrid")
            .ColumnWidth(200)
            .Height(580)
            .Configurator("#configurator")
            .DataSource(dataSource => dataSource.
                Xmla()
                .Columns(columns => {
                    columns.Add("[Date].[Calendar]").Expand(true);
                    columns.Add("[Product].[Category]");
                })
                .Rows(rows => rows.Add("[Geography].[City]").Expand(true))
                .Measures(measures => measures.Values(new string[]{"[Measures].[Reseller Freight      Cost]"}))
                .Transport(transport => transport
                    .Connection(connection => connection
                        .Catalog("Adventure Works DW 2008R2")
                        .Cube("Adventure Works"))
                    .Read("https://demos.telerik.com/olap/msmdpump.dll")
                )
            )
        )
        @(Html.Kendo().PivotConfiguratorButton()
            .Name("Button")
            .Configurator("configurator")
        )
</text>))

Need to display output as below.
enter image description here


问:
VS, Cmake, add file to folder not associated with a target
My current project is structured as follows

```<code>Project/
  ...
  SubFolder/
    Stuff1/
      CMakeLists.txt
    Stuff2/
      ...
    CMakeLists.txt
    Utils.cmake
</code>```

Where

Project/SubFolder/CMakeLists.txt

```<code>add_subdirectory( Stuff1 )
add_subdirectory( Stuff2 )
...
</code>```

Project/SubFolder/Stuff1/CMakeLists.txt

```<code>add_library( Stuff1 ... )
set_property( TARGET Stuff1 PROPERTY FOLDER "SubFolder" )
</code>```

The Utils.cmake is not a direct source of any target and thus does not show up in my IDE (VS). I could add it to one or all of the Stuffn targets but this is not ideal either.

Can I add this file (using CMake) to the folder of SubFolder without it being a source of a target.

(Utils.cmake is used both by Stuffn targets as well as targets who have them as dependencies )

Body:
My current project is structured as follows

Project/
  ...
  SubFolder/
    Stuff1/
      CMakeLists.txt
    Stuff2/
      ...
    CMakeLists.txt
    Utils.cmake

Where

Project/SubFolder/CMakeLists.txt

add_subdirectory( Stuff1 )
add_subdirectory( Stuff2 )
...

Project/SubFolder/Stuff1/CMakeLists.txt

add_library( Stuff1 ... )
set_property( TARGET Stuff1 PROPERTY FOLDER "SubFolder" )

The Utils.cmake is not a direct source of any target and thus does not show up in my IDE (VS). I could add it to one or all of the Stuffn targets but this is not ideal either.

Can I add this file (using CMake) to the folder of SubFolder without it being a source of a target.

(Utils.cmake is used both by Stuffn targets as well as targets who have them as dependencies )


问:
Openshift - Can defined ConfigMap label values be used inside Deployment.yaml and how?
I have defined a ConfigMap.yaml as below:

```<code>kind: ConfigMap
apiVersion: v1
metadata:
  name: studentmanager-config
  namespace: School
  labels:
    app: studentmanager
data:
  SCHOOL_CITY: ohio
</code>```

and wonder if I can access the value of app which is studentmanager inside my studentmanager application Deployment.yaml. Maybe something like this?

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  replicas: 1
  template:
    metadata:
     labels:
       ......
    spec:
      .....
      containers:
        - name: ${labels.app}
          image: myimage.myrepo.com/${labels.app}:latest
          volumeMounts:
           ....
          env:
            ....
</code>```

Tried by using ${labels.app} or $(labels.app) but none of them seem to work inside deployment yaml.

Body:
I have defined a ConfigMap.yaml as below:

kind: ConfigMap
apiVersion: v1
metadata:
  name: studentmanager-config
  namespace: School
  labels:
    app: studentmanager
data:
  SCHOOL_CITY: ohio

and wonder if I can access the value of app which is studentmanager inside my studentmanager application Deployment.yaml. Maybe something like this?

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  replicas: 1
  template:
    metadata:
     labels:
       ......
    spec:
      .....
      containers:
        - name: ${labels.app}
          image: myimage.myrepo.com/${labels.app}:latest
          volumeMounts:
           ....
          env:
            ....

Tried by using ${labels.app} or $(labels.app) but none of them seem to work inside deployment yaml.


问:
Github Self-hosted Runner on Windows machine - SSL connection failure
I'm trying to set up a self-hosted Github runner on a remote Windows VM, but while following the guide on their webpage, I get to the step "# Create the runner and start the configuration experience" and get the following error:

```<code>--------------------------------------------------------------------------------
 |        ____ _ _   _   _       _          _        _   _                      |
 |       / ___(_) |_| | | |_   _| |__      / \   ___| |_(_) ___  _ __  ___      |
 |      | |  _| | __| |_| | | | | '_ \    / _ \ / __| __| |/ _ \| '_ \/ __|     |
 |      | |_| | | |_|  _  | |_| | |_) |  / ___ \ (__| |_| | (_) | | | \__ \     |
 |       \____|_|\__|_| |_|\__,_|_.__/  /_/   \_\___|\__|_|\___/|_| |_|___/     |
 |                                                                              |
 |                       Self-hosted runner registration                        |
 |                                                                              |
 --------------------------------------------------------------------------------

 # Authentication

 The SSL connection could not be established, see inner exception.
</code>```

I can't see any inner exception, but this is likely related to a certificate error. There are some posts about people mending this on Linux machines by using "$ export GITHUB_ACTIONS_RUNNER_TLS_NO_VERIFY=1", but what would you do on a Windows machine?

Body:
I'm trying to set up a self-hosted Github runner on a remote Windows VM, but while following the guide on their webpage, I get to the step "# Create the runner and start the configuration experience" and get the following error:

--------------------------------------------------------------------------------
 |        ____ _ _   _   _       _          _        _   _                      |
 |       / ___(_) |_| | | |_   _| |__      / \   ___| |_(_) ___  _ __  ___      |
 |      | |  _| | __| |_| | | | | '_ \    / _ \ / __| __| |/ _ \| '_ \/ __|     |
 |      | |_| | | |_|  _  | |_| | |_) |  / ___ \ (__| |_| | (_) | | | \__ \     |
 |       \____|_|\__|_| |_|\__,_|_.__/  /_/   \_\___|\__|_|\___/|_| |_|___/     |
 |                                                                              |
 |                       Self-hosted runner registration                        |
 |                                                                              |
 --------------------------------------------------------------------------------

 # Authentication

 The SSL connection could not be established, see inner exception.

I can't see any inner exception, but this is likely related to a certificate error. There are some posts about people mending this on Linux machines by using "$ export GITHUB_ACTIONS_RUNNER_TLS_NO_VERIFY=1", but what would you do on a Windows machine?


问:
How/where to to find documentId to build suitable JSON request for Yelp?
In this answer to this question BeautifulSoup web scraping for a webpage where information is obtained after clicking a button, Martin's JSON request includes documentIds for each operation (GetBusinessAttributes and GetBizPageProperties). Where does he find these documentIds?

I understand that I need examine the network traffic as @Martin suggested. I spent hours examining the network traffic when visiting https://www.yelp.com/biz/ziggis-coffee-longmont, and I am able to find some documentIds (e.g. the documentId for GetBusinessHealthScoreAlert is "9757b0dd458b4ad4a5922f28cbd77a1d284093c6b0e84a13c95f01c56f776e9d"). However I am unable to locate the documentIds for GetBusinessAttributes or GetBizPageProperties. I am not sure if I am missing something or doing something wrong.


问:
Angular : Issue Reported in Checkmarx
I am facing below issue from checkmarx

```<code><div class="col-md-6">
<label [ngStyle]= "{'font-size':'small'}">{{empName}}[{{empLength}}]</label></div>
</code>```

the issue discription from checkmarx as below:

the apllication's class="emp-card-group"> embeds untrusted data in the generated output with empLength, at line 34 of src\app\routes\emp-management\emp-management.component.html. this untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.

Title: Angular : Issue Reported in Checkmarx

Body:
I am facing below issue from checkmarx

{{empName}}[{{empLength}}]

the issue discription from checkmarx as below:

the apllication's class="emp-card-group"> embeds untrusted data in the generated output with empLength, at line 34 of src\app\routes\emp-management\emp-management.component.html. this untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.