问:
NestJs: Imported service can not be found when running custom commands from Nest Commander
I have a module called WebscraperModule with a service called WebscaperService. Within the WebscraperService I am importing another service GeoCodingService from another module GeoCodingModule.
From the GeoCodingModule I am exporting the GeoCodingService and importing it into the WebscraperModule. I believe I have imported everything correctly and the import paths when clicked all take to the correct Modules/Services. However, when I call the  WebscaperService with my custom commands created using the Nest Commander package I get the error Error: Cannot find module 'src/@geoCoding/services/geoCoding.service'. When running
npm run start:dev I get no errors, so I'm thinking I've not set up the Commander package properly. How can I can fix this?

Command module

```<code>@Module({
    providers: [ WebscraperCommand ],
    imports:   [ WebscraperModule ],
    exports:   [ WebscraperCommand ]
})
export class CommandsModule {}
</code>```

Webscraper.command.ts

```<code>import { WebscraperService } from 'src/@webScraper/services/webscraper.service';

  @Command({ name: 'basic', description: 'A parameter parse' })
  export class WebscraperCommand extends CommandRunner {

    constructor(private readonly webscraperService: WebscraperService) {
        super();
    };

    async run() : Promise<void> {
      console.log("run")
        this.callMainScrapper();
    };

    @Option({
      flags: '-msc',
      description: 'Call the main scraper',
    })

    callMainScrapper(){
     console.log("run");
     this.webscraperService.mainScraper();
    };

  };
</code>```

GeoCoding Module

```<code>@Global()
  @Module({
    imports: [ HttpModule, ConfigModule.forRoot({ isGlobal: true }) ],
    providers: [ GeoCodingService ],
    exports: [ GeoCodingService ]
    })

export class GeoCodingModule {}

</code>```

GeoCoding Service

```<code>@Injectable()
export class GeoCodingService {

    constructor(
      private readonly _httpService: HttpService,
      private readonly _configService: ConfigService
      ) {};

    public coordinates : object = {};

    private _logger = new Logger('GeoCodingService');
    private _apiKey : string = this._configService.get('API_KEY');

    public async getGeoCoding(address: string): Promise<void> {

        const result : unknown = address.match(/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i);

        const url : string = `https://api.tomtom.com/search/2/geocode/${result[0].toUpperCase()}&limit=1.json?key=${this._apiKey}`;

        let res : object = {};

        try {

          this._httpService.get(url).then(response => {

            if (response.data.results[0].position === undefined) {

              res = {};

            } else {

              res = response.data.results[0].position;

            };

            this.coordinates = res;

          });

        } catch (error: any) {

          this._logger.error(error.message, error.stack);

        };
    };
};
</code>```

Webscraper module

```<code>  @Global()
  @Module({
    imports: [ GeoCodingModule, HttpModule, ConfigModule.forRoot({
      isGlobal: true
    }), ],
    exports: [ WebscraperService],
    providers: [WebscraperService, WebscraperCommand],
    })

export class WebscraperModule {};
</code>```

Webscraper service

```<code>import { GeoCodingService } from 'src/@geoCoding/services/geoCoding.service';
//This is the line in question

export class WebscraperService {

  constructor(
    private _geoCodingService: GeoCodingService,
    private readonly _httpService: HttpService,
    private readonly _configService: ConfigService
    ) {};

 private async _getDataFromPage() : Promise<void> {

      for (const anchorLink of this._anchors) {

        const response : any = await fetch(anchorLink);

        const body : any = await response.text();

        this._setPropertyType(anchorLink);

        this._setProps(body);

        const slice: Array<string> = this._addressData.slice(0, -2);

        const addressToString = slice.toString()

        //getGeoCoding is called here
        this._geoCodingService.getGeoCoding(addressToString)

        const property : PropertyInterface = {
          address: addressToString,
          telephone: this._telephoneNumber,
          website: this._websiteLink,
          canLeaveDogsUnattended: this._dogsUnattended,
          maxDogs: this._numberOfDogs,
          extraCharge: this._charge,
          coordinates: this._coordinates,
          type: this._type
        };

      properties.push(property);

      console.log(property, "property")

      await this._sleep(1000);

      };

    };

}
</code>```

Body:
I have a module called WebscraperModule with a service called WebscaperService. Within the WebscraperService I am importing another service GeoCodingService from another module GeoCodingModule.
From the GeoCodingModule I am exporting the GeoCodingService and importing it into the WebscraperModule. I believe I have imported everything correctly and the import paths when clicked all take to the correct Modules/Services. However, when I call the  WebscaperService with my custom commands created using the Nest Commander package I get the error Error: Cannot find module 'src/@geoCoding/services/geoCoding.service'. When running
npm run start:dev I get no errors, so I'm thinking I've not set up the Commander package properly. How can I can fix this?

Command module

@Module({
    providers: [ WebscraperCommand ],
    imports:   [ WebscraperModule ],
    exports:   [ WebscraperCommand ]
})
export class CommandsModule {}

Webscraper.command.ts

import { WebscraperService } from 'src/@webScraper/services/webscraper.service';

  @Command({ name: 'basic', description: 'A parameter parse' })
  export class WebscraperCommand extends CommandRunner {

    constructor(private readonly webscraperService: WebscraperService) {
        super();
    };

    async run() : Promise<void> {
      console.log("run")
        this.callMainScrapper();
    };

    @Option({
      flags: '-msc',
      description: 'Call the main scraper',
    })

    callMainScrapper(){
     console.log("run");
     this.webscraperService.mainScraper();
    };

  };

GeoCoding Module

@Global()
  @Module({
    imports: [ HttpModule, ConfigModule.forRoot({ isGlobal: true }) ],
    providers: [ GeoCodingService ],
    exports: [ GeoCodingService ]
    })

export class GeoCodingModule {}

GeoCoding Service

@Injectable()
export class GeoCodingService {

    constructor(
      private readonly _httpService: HttpService,
      private readonly _configService: ConfigService
      ) {};

    public coordinates : object = {};

    private _logger = new Logger('GeoCodingService');
    private _apiKey : string = this._configService.get('API_KEY');

    public async getGeoCoding(address: string): Promise<void> {

        const result : unknown = address.match(/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i);

        const url : string = `https://api.tomtom.com/search/2/geocode/${result[0].toUpperCase()}&limit=1.json?key=${this._apiKey}`;

        let res : object = {};

        try {

          this._httpService.get(url).then(response => {

            if (response.data.results[0].position === undefined) {

              res = {};

            } else {

              res = response.data.results[0].position;

            };

            this.coordinates = res;

          });

        } catch (error: any) {

          this._logger.error(error.message, error.stack);

        };
    };
};

Webscraper module

  @Global()
  @Module({
    imports: [ GeoCodingModule, HttpModule, ConfigModule.forRoot({
      isGlobal: true
    }), ],
    exports: [ WebscraperService],
    providers: [WebscraperService, WebscraperCommand],
    })

export class WebscraperModule {};

Webscraper service

import { GeoCodingService } from 'src/@geoCoding/services/geoCoding.service';
//This is the line in question

export class WebscraperService {

  constructor(
    private _geoCodingService: GeoCodingService,
    private readonly _httpService: HttpService,
    private readonly _configService: ConfigService
    ) {};

 private async _getDataFromPage() : Promise<void> {

      for (const anchorLink of this._anchors) {

        const response : any = await fetch(anchorLink);

        const body : any = await response.text();

        this._setPropertyType(anchorLink);

        this._setProps(body);

        const slice: Array<string> = this._addressData.slice(0, -2);

        const addressToString = slice.toString()

        //getGeoCoding is called here
        this._geoCodingService.getGeoCoding(addressToString)

        const property : PropertyInterface = {
          address: addressToString,
          telephone: this._telephoneNumber,
          website: this._websiteLink,
          canLeaveDogsUnattended: this._dogsUnattended,
          maxDogs: this._numberOfDogs,
          extraCharge: this._charge,
          coordinates: this._coordinates,
          type: this._type
        };

      properties.push(property);

      console.log(property, "property")

      await this._sleep(1000);

      };

    };

}


来源: stackexchange

问:
How to plot sentiment score changes over time in pandas?
I have a Pandas dataframe with tweets from Oct 1, 2022 to today.  I used the VADER sentiment analysis method on each tweet, and the sentiment scores were added to new columns.
DATASET

Now, I want  to visualize this in some kind of line chart so that I could analyze how the averaged sentiment scores per month changed over the year. As a result, the dates must be on the x-axis, and the averaged negative, positive, and compound scores (three different lines) must be on the y-axis.

Python knowledge is still limited. I'd appreciate it if anyone could give me some advice on how to proceed!

ContentLicense: CC BY-SA 4.0


问:
Starting two services, but the second one fails to start because the first one is taking too long
In my /opt/entrypoint.sh file, I am trying to start the following services:

```<code> 1. mosquitto.service
 2. notus-scanner
 3. postgresql@14-main
 4. redis-server@openvas.service
 5. ospd-openvas
 6. gvmd
 7. gsad
</code>```

However, it seems that the gvmd service fails to start because postresql@14-main is still starting, at least according to this screenshot:

I tried adding sleep 10 after each line of starting a service, but that still doesn't help.

To my understanding, After= is supposed to mean that, after these services have started, it will start the current service (gvmd in my case).

I'm basically just trying to start the gvmd service after postgresql@14-main has successfully started, but not sure what's the best way to do this other than repeatedly trying to run systemctl start gvmd until it works properly.

Body:
In my /opt/entrypoint.sh file, I am trying to start the following services:

 1. mosquitto.service
 2. notus-scanner
 3. postgresql@14-main
 4. redis-server@openvas.service
 5. ospd-openvas
 6. gvmd
 7. gsad

However, it seems that the gvmd service fails to start because postresql@14-main is still starting, at least according to this screenshot:

I tried adding sleep 10 after each line of starting a service, but that still doesn't help.

To my understanding, After= is supposed to mean that, after these services have started, it will start the current service (gvmd in my case).

I'm basically just trying to start the gvmd service after postgresql@14-main has successfully started, but not sure what's the best way to do this other than repeatedly trying to run systemctl start gvmd until it works properly.


问:
Running Get-SPWeb in powershell command for sharepoint
I'm trying to run the following code against sharepoint.

```<code>Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web URL, List Name
$WebURL ="https://sharepoint.sharepoint.com/sites/Sharepoint"

#get the list object
$web = Get-SPWeb $WebURL

# Check if web has Unique permission - Root webs always uses Unique permission
if ( ($web.HasUniqueRoleAssignments) -and ($web.IsRootWeb -eq $false ) )
 {
      #Reset broken inheritance
      $web.ResetRoleInheritance()
      Write-host "Broken Inheritance Reset on web:" $web.URL
 }
</code>```

When I try to run this command I get: Get-SPWeb : The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.

When I try to add the snapin, Add-PSSnapin Microsoft.Sharepoint.Powershell I get: Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 5.

I've tried installing the snap-in and I've tried using Sharepoint Online Management Shell, I've tried ISE and that doesn't appear to work either.  Am I just missing something?

Body:
I'm trying to run the following code against sharepoint.

Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web URL, List Name
$WebURL ="https://sharepoint.sharepoint.com/sites/Sharepoint"

#get the list object
$web = Get-SPWeb $WebURL

# Check if web has Unique permission - Root webs always uses Unique permission
if ( ($web.HasUniqueRoleAssignments) -and ($web.IsRootWeb -eq $false ) )
 {
      #Reset broken inheritance
      $web.ResetRoleInheritance()
      Write-host "Broken Inheritance Reset on web:" $web.URL
 }

When I try to run this command I get: Get-SPWeb : The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.

When I try to add the snapin, Add-PSSnapin Microsoft.Sharepoint.Powershell I get: Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 5.

I've tried installing the snap-in and I've tried using Sharepoint Online Management Shell, I've tried ISE and that doesn't appear to work either.  Am I just missing something?


问:
setFullScreenIntent on Android 13 not shown over lock screen
I am trying to use setFullScreenIntent to show my alarm screen when the lock screen is on:

```<code>// I am using AlarmManager to send notification at a specific time:
 setAlarmClock(AlarmManager.AlarmClockInfo(info.cld.timeInMillis, null), pendingIntent)

// FullscreenIntent to open activity on lock screen
val fullScreenIntent = Intent(context, MainActivity::class.java)
val fullPendingIntent = PendingIntent.getActivity(
            context, FULL_PENDING_ID, fullScreenIntent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
val builder = NotificationCompat
            .Builder(context, context.getString(R.string.notification_channel_id))
            .setDefaults(0)
            .setSmallIcon(R.drawable.logo)
            .setSilent(true)
            .setLargeIcon(bm)
            .setAutoCancel(false)
            .setContentIntent(tapPendingIntent)
            .setFullScreenIntent(fullPendingIntent, true)
            .setCategory(NotificationCompat.CATEGORY_ALARM)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentTitle(context.getString(R.string.label_alarm_notification))
            .setColor(ContextCompat.getColor(context, R.color.blue))
            .setOngoing(true)
    mgr.notify(NOTIFICATION_ID, builder.build())

// On MainActivity, I added some flags:
    fun setupShowOverLockedScreen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
            setTurnScreenOn(true)
            val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
            keyguardManager.requestDismissKeyguard(this, null)
        } else {
            window.addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
            )
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
// I added those permissions as well
    <uses-permission android:name="android.permission.SET_ALARM" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

</code>```

It's working fine on Android 12 or below. However, when I tested the Android 13 phone, it stopped working. From the log, I can see the notification was fired, but the activity was not shown on the lock screen.
Does anyone have a solution for it?

Body:
I am trying to use setFullScreenIntent to show my alarm screen when the lock screen is on:

// I am using AlarmManager to send notification at a specific time:
 setAlarmClock(AlarmManager.AlarmClockInfo(info.cld.timeInMillis, null), pendingIntent)

// FullscreenIntent to open activity on lock screen
val fullScreenIntent = Intent(context, MainActivity::class.java)
val fullPendingIntent = PendingIntent.getActivity(
            context, FULL_PENDING_ID, fullScreenIntent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
val builder = NotificationCompat
            .Builder(context, context.getString(R.string.notification_channel_id))
            .setDefaults(0)
            .setSmallIcon(R.drawable.logo)
            .setSilent(true)
            .setLargeIcon(bm)
            .setAutoCancel(false)
            .setContentIntent(tapPendingIntent)
            .setFullScreenIntent(fullPendingIntent, true)
            .setCategory(NotificationCompat.CATEGORY_ALARM)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentTitle(context.getString(R.string.label_alarm_notification))
            .setColor(ContextCompat.getColor(context, R.color.blue))
            .setOngoing(true)
    mgr.notify(NOTIFICATION_ID, builder.build())

// On MainActivity, I added some flags:
    fun setupShowOverLockedScreen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
            setTurnScreenOn(true)
            val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
            keyguardManager.requestDismissKeyguard(this, null)
        } else {
            window.addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
            )
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
// I added those permissions as well
    <uses-permission android:name="android.permission.SET_ALARM" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

It's working fine on Android 12 or below. However, when I tested the Android 13 phone, it stopped working. From the log, I can see the notification was fired, but the activity was not shown on the lock screen.
Does anyone have a solution for it?


问:
docker login not responding
My docker login is not responding . It is stuck as shown below

```<code>$ sudo docker login ghcr.io -u user --password-stdin
</code>```

We have disabled egress in our environment except for few ports which includes 443/80 .

Does docker login uses other port than 443/80 ?

Just to add we are running docker in a compute engine instance on GCP environment

Title: docker login not responding

Body:
My docker login is not responding . It is stuck as shown below

$ sudo docker login ghcr.io -u user --password-stdin

We have disabled egress in our environment except for few ports which includes 443/80 .

Does docker login uses other port than 443/80 ?

Just to add we are running docker in a compute engine instance on GCP environment


问:
Converting onnx model to sklearn
I Originally trained the model with sklearn, which was then converted to onnx. I now want to get the Sklearn model back. The only related thing I can find online is converting onnx to tf-lite.
Thanks in advance!</p>

Title: Converting onnx model to sklearn


问:
Save and resuse deeplearning model in Keras/Tensoflow
Hi,
I test a deeplearning model for image segmentation with the library Segmentation Model based on Keras (Tensorflow) framework.

```<code>import segmentation_models as sm
model = sm.Unet(
        backbone_name   = BACKBONE,
        encoder_weights = "imagenet", # poids prédéfini après entrainement sur les images du dataset ImageNet
        input_shape     = (512,512,3),
        activation      = "sigmoid"
)
from tensorflow.keras.optimizers import Adam

optimizer = Adam(learning_rate=5e-4)
loss = sm.losses.dice_loss
metric = sm.metrics.iou_score

model.compile(
    optimizer = optimizer,
    loss      = loss,
    metrics   = [metric],
)
...
**It works not so bad. So I saved it like this : **
...
model.save("RetinaNeuroneCounter.h5")
</code>```

Now I would like tu resuse this model with a new data set.
I'm working with GoogleColab.
I follow these steps :
1-Data importation

```<code>!wget -O RetinaNeurons.zip https://mycore.core-cloud.net/index.php/s/k1vLbyRF5tTf189/download
!unzip -qq RetinaNeurons.zip
!rm -f RetinaNeurons.zip
</code>```

**2-model importation **

```<code>!wget -O RetinaNeuroneCounter.h5 https://mycore.core-cloud.net/index.php/s/VnbPHdf6T8ylU1e/download
!rm -f RetinaNeuroneCounter.h5
</code>```

**3-I reload my model to test on new data **

```<code>import tensorflow.keras as keras
from keras.models import load_model
model = load_model("./drive/MyDrive/RetinaNeurons/RetinaNeuroneCounter.h5")
</code>```

--> Error

```<code>---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-8-9fe7242d9e02> in <module>
      1 import tensorflow.keras as keras
      2 from keras.models import load_model
----> 3 model = load_model("./drive/MyDrive/RetinaNeurons/RetinaNeuroneCounter.h5")
      4 #model = keras.models.load_model('RetinaNeuroneCounter.h5')
      5 #saved_models = 'D:\VGigot\TRAVAUX\Traitement Image CSGA\Elodie Masson - Elise Léger-Charnay\IA-DeepLearning-RetinaNeurons'

1 frames

/usr/local/lib/python3.8/dist-packages/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    707       obj = module_objects.get(object_name)
    708       if obj is None:
--> 709         raise ValueError(
    710             f'Unknown {printable_module_name}: {object_name}. Please ensure '
    711             'this object is passed to the `custom_objects` argument. See '

ValueError: Unknown loss function: dice_loss. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.
</code>```

I don't understand, Dice_loss is one the usable loss function :
segmentation_models.losses.DiceLoss(beta=1, class_weights=None, class_indexes=None, per_image=False, smooth=1e-05)
Returns:

A callable dice_loss instance. Can be used in model.compile(...) function` or combined with other losses.

Any idea how to code to reuse a model in a new notebook ?
Thanks.

Body:
Hi,
I test a deeplearning model for image segmentation with the library Segmentation Model based on Keras (Tensorflow) framework.

import segmentation_models as sm
model = sm.Unet(
        backbone_name   = BACKBONE,
        encoder_weights = "imagenet", # poids prédéfini après entrainement sur les images du dataset ImageNet
        input_shape     = (512,512,3),
        activation      = "sigmoid"
)
from tensorflow.keras.optimizers import Adam

optimizer = Adam(learning_rate=5e-4)
loss = sm.losses.dice_loss
metric = sm.metrics.iou_score

model.compile(
    optimizer = optimizer,
    loss      = loss,
    metrics   = [metric],
)
...
**It works not so bad. So I saved it like this : **
...
model.save("RetinaNeuroneCounter.h5")

Now I would like tu resuse this model with a new data set.
I'm working with GoogleColab.
I follow these steps :
1-Data importation

!wget -O RetinaNeurons.zip https://mycore.core-cloud.net/index.php/s/k1vLbyRF5tTf189/download
!unzip -qq RetinaNeurons.zip
!rm -f RetinaNeurons.zip

**2-model importation **

!wget -O RetinaNeuroneCounter.h5 https://mycore.core-cloud.net/index.php/s/VnbPHdf6T8ylU1e/download
!rm -f RetinaNeuroneCounter.h5

**3-I reload my model to test on new data **

import tensorflow.keras as keras
from keras.models import load_model
model = load_model("./drive/MyDrive/RetinaNeurons/RetinaNeuroneCounter.h5")

--> Error

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-8-9fe7242d9e02> in <module>
      1 import tensorflow.keras as keras
      2 from keras.models import load_model
----> 3 model = load_model("./drive/MyDrive/RetinaNeurons/RetinaNeuroneCounter.h5")
      4 #model = keras.models.load_model('RetinaNeuroneCounter.h5')
      5 #saved_models = 'D:\VGigot\TRAVAUX\Traitement Image CSGA\Elodie Masson - Elise Léger-Charnay\IA-DeepLearning-RetinaNeurons'

1 frames

/usr/local/lib/python3.8/dist-packages/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    707       obj = module_objects.get(object_name)
    708       if obj is None:
--> 709         raise ValueError(
    710             f'Unknown {printable_module_name}: {object_name}. Please ensure '
    711             'this object is passed to the `custom_objects` argument. See '

ValueError: Unknown loss function: dice_loss. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.

I don't understand, Dice_loss is one the usable loss function :
segmentation_models.losses.DiceLoss(beta=1, class_weights=None, class_indexes=None, per_image=False, smooth=1e-05)
Returns:

A callable dice_loss instance. Can be used in model.compile(...) function` or combined with other losses.

Any idea how to code to reuse a model in a new notebook ?
Thanks.


问:
"ERROR: connect ECONNREFUSED 127.0.0.1:5432" when using PostgresSQL + Node v12.22.9 + systemd service
I followed these instructions to create an SQL API that interacts via HTTPS with a leaflet map.
HERE

It worked fine for a month or so but recently I get the ECONNREFUSED error in the server log as the PostgreSQL database seems to be refusing connection.

When I ssh in and run “sudo service postgresql restart” in the terminal the problem stops for a few hours at least. It seems like maybe the service is failing to automatically restart. But in the .serivce file it still says “Restart=always”.

As far a potential causes go I don’t know but several days before the issue began I was made to install Webroot on several macs that connect to the database.

I did some research into the issue and found a similar problem here: HERE

One of the potential solutions suggested involves replacing “localhost” with a specific “127.0.0.1” .

Taking the example server-side script from the instructions: http://132.72.155.230:3838/js/setting-up-an-sql-api.html

I think perhaps I should change the following line:

let db = pgp("postgres://readonlyuser:whatever2@localhost:5432/gisdb");

To:
let db = pgp("postgres://readonlyuser:whatever2@127.0.0.1:5432/gisdb");

Is this likely to work in my case? Or have I got the wrong end of the stick? Any suggestions welcome.

Perhaps I should update my version of node?

Apologies if the question is badly formulated I don’t post here very much.

"sudo service postgresql restart" does temporarily solve the problem.

Within ubuntu I tried “ $ sudo reboot” but the problem persists.


问:
WebCrypto: How can one use `deriveKey` with a key which came from `deriveKey`?
I would like to create a "master key" from a password using PBKDF2, and then create various application-specific keys using HKDF from that "master key". However, when I try to use SubtleCrypto.deriveKey with a usage of deriveKey, it throws an opaque error:

Error: Data provided to an operation does not meet requirements

For the moment, I have worked around this by exporting the "master key" and then re-importing it with the appropriate key usage, but this requires marking my "super key" as exportable, which should not be necessary. Using deriveBits has the same issue.

I will accept an answer which either demonstrates how to use SubtleCrypto.deriveKey on a key itself created using SubtleCrypto.deriveKey, or else confirms that this is a flaw in the WebCrypto API and that what I am trying to do is not possible (ideally with a reference to the WebCrypto spec).

I'm sure there will be questions about why I want to do this:

The goal is to have multiple applications be unlocked by a single password.

If the key for any one of these applications is leaked, it should not impact the security of the other applications.

Once a user has entered their password, the "master key" will be kept around for the next N minutes to allow multiple application-specific keys to be derived, but I don't want to keep around the original password for any length of time.

I have tried many possibilities for the derivedKeyType argument to deriveKey, but all seem to result in an error.


问:
Produce Discrete fourier transform of multiple time series within one csv file
I have a csv with multiple time series and although I can create all DFTs in a single plot. I want to separate out all the plots.DFT of all time series

I created the DFT of all time series as a single plot overlapped on each other. The code I am trying is this-

    uni_1 = []
    for item in time_series:
      if item not in uni_1:

        uni_1.append(item)

    for u in uni_1[0:50]:

    small_df= df[df["time_series"]==u]

    # convert into x and y

          x = list(range(len(small_df.index)))
          y = (small_df.Quantity).tolist()

    # apply fast fourier transform and take absolute values
        f=abs(np.fft.fft(y))

    # get the list of frequencies
        num=np.size(x)
        freq = [i / num for i in list(range(num))]

    # get the list of spectrums
    spectrum = f.real*f.real+f.imag*f.imag
    nspectrum = spectrum/spectrum[0]
# plot nspectrum per frequency, with a semilog scale on nspectrum
    plt.semilogy(freq,nspectrum)
```

I want to separate out the plots for better visibility.

Body:
I have a csv with multiple time series and although I can create all DFTs in a single plot. I want to separate out all the plots.DFT of all time series

I created the DFT of all time series as a single plot overlapped on each other. The code I am trying is this-

    uni_1 = []
    for item in time_series:
      if item not in uni_1:

        uni_1.append(item)

    for u in uni_1[0:50]:

    small_df= df[df["time_series"]==u]

    # convert into x and y

          x = list(range(len(small_df.index)))
          y = (small_df.Quantity).tolist()

    # apply fast fourier transform and take absolute values
        f=abs(np.fft.fft(y))

    # get the list of frequencies
        num=np.size(x)
        freq = [i / num for i in list(range(num))]

    # get the list of spectrums
    spectrum = f.real*f.real+f.imag*f.imag
    nspectrum = spectrum/spectrum[0]
# plot nspectrum per frequency, with a semilog scale on nspectrum
    plt.semilogy(freq,nspectrum)

I want to separate out the plots for better visibility.


问:
Find poetry installation used by PyCharm
I am trying to set up a Poetry virtual environment in PyCharm. I am doing the following:

Press Ctrl+Alt+S to open the Project Settings

Go to Project -> Python Interpreter

Click on Add Intepreter -> Add Local Interpreter...

Select Poetry Environment

Select Poetry Environment

Make sure Python 3.11 is selected as the Base Environment

Click OK

This gives the following error:

RuntimeError: The lock file is not compatible with the current version of Poetry.

I already installed poetry 1.3.2. I can confirm this from powershell:

```<code>PS C:\src\my-project> poetry --version
Poetry (version 1.3.2)
</code>```

I think I have another version of poetry installed somewhere and PyCharm is picking it up. How do I find this instance of poetry? Where do I look for it?

Body:
I am trying to set up a Poetry virtual environment in PyCharm. I am doing the following:

Press Ctrl+Alt+S to open the Project Settings

Go to Project -> Python Interpreter

Click on Add Intepreter -> Add Local Interpreter...

Select Poetry Environment

Select Poetry Environment

Make sure Python 3.11 is selected as the Base Environment

Click OK

This gives the following error:

RuntimeError: The lock file is not compatible with the current version of Poetry.

I already installed poetry 1.3.2. I can confirm this from powershell:

PS C:\src\my-project> poetry --version
Poetry (version 1.3.2)

I think I have another version of poetry installed somewhere and PyCharm is picking it up. How do I find this instance of poetry? Where do I look for it?


问:
How do we style a component with multiple components Wrapped in a React Fragment without introducing new wrappers , when we upgrade to Material UI 5
I have a React component with multiple components wrapped in a Fragment. When I upgraded to Material UI V5 using codemod, it automatically added a div to wrap the components in Styled Component. and My styles are breaking because there is an extra 'div', how can we avoid this issue and not introduce an extra div , but keep the styles like before.

Old code

```<code><>
            {key === '1' && <Box className={classes.item1}>content</Box>}
            {key === '2' && <Box className={classes.item2}>content</Box>}
</>
</code>```

After upgrade using codemod - npx @mui/codemod v5.0.0/jss-to-styled src

```<code>// TODO jss-to-styled codemod: The Fragment root was replaced by div. Change the tag if needed.

    const Root = styled('div')((
        {
            theme
        }
    ) => {
    return {
    [`& .${classes.item1}`]: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-end',
                paddingRight: theme.spacing(1)
            }
    }

    <Root>
                {key === '1' && <Box className={classes.item1}>content</Box>}
                {key === '2' && <Box className={classes.item2}>content</Box>}
    </Root>
</code>```

Body:
I have a React component with multiple components wrapped in a Fragment. When I upgraded to Material UI V5 using codemod, it automatically added a div to wrap the components in Styled Component. and My styles are breaking because there is an extra 'div', how can we avoid this issue and not introduce an extra div , but keep the styles like before.

Old code

<>
            {key === '1' && <Box className={classes.item1}>content</Box>}
            {key === '2' && <Box className={classes.item2}>content</Box>}
</>

After upgrade using codemod - npx @mui/codemod v5.0.0/jss-to-styled src

// TODO jss-to-styled codemod: The Fragment root was replaced by div. Change the tag if needed.

    const Root = styled('div')((
        {
            theme
        }
    ) => {
    return {
    [`& .${classes.item1}`]: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-end',
                paddingRight: theme.spacing(1)
            }
    }

    <Root>
                {key === '1' && <Box className={classes.item1}>content</Box>}
                {key === '2' && <Box className={classes.item2}>content</Box>}
    </Root>


问:
How could I limit memory and cpu usage in Docker globally
I'm using Docker with Ubuntu in a development environment, but I noticed that docker can use all the resources of the host machine, is there any way I can limit this without having to configure each of the containers?

I tried to configure the docker daemon.json example:

{
  "cpus": 1,
  "memory": "4096m"
}
```


问:
Getting Error 401 unauthorized when connecting to SharePoint 2016 server in C#
I am creating a simple console application that connect to SharePoint Server 2016. However, I receiver error 401 unauthorized when it gets to context.ExecuteQuery. I have no issues connecting to SharePoint Online. The issue is perculiar to SharePoint Onpremise. Below is my code

```<code>string siteUrl = "http://abc.mysharepoint.local/sites/mysite";
string userName = "myname@domain.com";
string pwd = "mypassword";
string domain = "domain.com";

using (ClientContext ctx = new ClientContext(siteUrl))
{
    try
    {
        ctx.AuthenticationMode = ClientAuthenticationMode.Default;
        ctx.Credentials = new System.Net.NetworkCredential(userName, pwd, domain);

        ctx.Load(ctx.Web, w => w.Title, w => w.Description);
        ctx.ExecuteQuery();
        Console.WriteLine(ctx.Web.Title);
    }
    catch (Exception ex)
    {

        Console.WriteLine($"{ex.Message} ");
    }
}
</code>```

Please what could be the possible cause and how to resolve it. I have full admin right to the site and can access the site from the browser. I have the IP to the server configured on my computer host file.

I have checked the SharePoint Server and can confirm I have access and everything looks okay. I also tried with the credentials of a service account but am still getting same 401 unauthorized error though I have full admin access to the site.

Body:
I am creating a simple console application that connect to SharePoint Server 2016. However, I receiver error 401 unauthorized when it gets to context.ExecuteQuery. I have no issues connecting to SharePoint Online. The issue is perculiar to SharePoint Onpremise. Below is my code

string siteUrl = "http://abc.mysharepoint.local/sites/mysite";
string userName = "myname@domain.com";
string pwd = "mypassword";
string domain = "domain.com";

using (ClientContext ctx = new ClientContext(siteUrl))
{
    try
    {
        ctx.AuthenticationMode = ClientAuthenticationMode.Default;
        ctx.Credentials = new System.Net.NetworkCredential(userName, pwd, domain);

        ctx.Load(ctx.Web, w => w.Title, w => w.Description);
        ctx.ExecuteQuery();
        Console.WriteLine(ctx.Web.Title);
    }
    catch (Exception ex)
    {

        Console.WriteLine($"{ex.Message} ");
    }
}

Please what could be the possible cause and how to resolve it. I have full admin right to the site and can access the site from the browser. I have the IP to the server configured on my computer host file.

I have checked the SharePoint Server and can confirm I have access and everything looks okay. I also tried with the credentials of a service account but am still getting same 401 unauthorized error though I have full admin access to the site.


问:
How to make plotly code into a function? So as not to continuously repeat code for each new graph
I have the following plotly code (below) which I have tried to turn into a function. I want to create 20 plots from 20 different dataframes (all the same structure), without repeating this plotly code each time.

For each new plot, I want to change the data source (data_frame = nema), and the name of each new plot (I want plots called fig1, fig2, fig3, fig4 etc.)

I know how to do this in R GGPLOT (https://thomasadventure.blog/posts/turning-your-ggplot2-code-into-a-function/), and I am hoping there is a similar solution in Python.

```<code>def nemaheatmap():
    fig1 = px.scatter(data_frame = nema, x = "Longitude", y = "Latitude",
                 hover_name="Q0",
                 color="Q0",
                 color_continuous_scale= 'hot_r')
    fig1.update_xaxes(zeroline=False)
    fig1.update_yaxes(zeroline=False)
    fig1.update_layout (title = 'Q0 values',
                        plot_bgcolor = 'rgb(173,216,230)',
                        xaxis_showgrid=False,
                        yaxis_showgrid=False)
    pio.renderers.default = 'browser'
    fig1.show()

nemaheatmap()
</code>```

Body:
I have the following plotly code (below) which I have tried to turn into a function. I want to create 20 plots from 20 different dataframes (all the same structure), without repeating this plotly code each time.

For each new plot, I want to change the data source (data_frame = nema), and the name of each new plot (I want plots called fig1, fig2, fig3, fig4 etc.)

I know how to do this in R GGPLOT (https://thomasadventure.blog/posts/turning-your-ggplot2-code-into-a-function/), and I am hoping there is a similar solution in Python.

def nemaheatmap():
    fig1 = px.scatter(data_frame = nema, x = "Longitude", y = "Latitude",
                 hover_name="Q0",
                 color="Q0",
                 color_continuous_scale= 'hot_r')
    fig1.update_xaxes(zeroline=False)
    fig1.update_yaxes(zeroline=False)
    fig1.update_layout (title = 'Q0 values',
                        plot_bgcolor = 'rgb(173,216,230)',
                        xaxis_showgrid=False,
                        yaxis_showgrid=False)
    pio.renderers.default = 'browser'
    fig1.show()

nemaheatmap()


问:
How Can I Visualise ETM(Embedded-Topic-Model) via Python3.0?
I'm trying to visualise ETM(Embedded Topic Model) in Python like picture below. But I can't find any code for Python.

How can I do?

example image: https://i.stack.imgur.com/ESKSE.png

(Stackoverflow says I can't upload image since I have under 10 reputation;;)

image source: "Topic Modeling in Embedding Space" (Adji B. Dieng et al.)

I just want to see the distances of topics or words using that picture.

I used ETM code from here (pypi.org/project/embedded-topic-model). And my data has 2 dimentionality with 34rows(topics) and 30columns(words)

My code

```<code>  import torch
  from embedded_topic_model.utils import preprocessing
  from embedded_topic_model.utils import embedding
  from embedded_topic_model.models.etm import ETM

  # Vocabulary: 'all_n' is list of all words
  vocabulary, dataset, _ = preprocessing.create_etm_datasets(all_n,
                                  min_df=15)

  # ???
  embeddings_mapping = embedding.create_word2vec_embedding_from_dataset(all_n,
                                          min_count=15,
                                          embedding_file_path='./w2v',
                                          debug_mode=True)

  # Train
  etm_train = ETM(vocabulary,
                   embeddings=embeddings_mapping,
                   num_topics=36,
                   epochs=100,
                   train_embeddings=False,
                   debug_mode=True
                   )
  etm_train.fit(dataset)

  topics = etm_train.get_topics(30)
  etm_train.get_most_similar_words(['stack'])
  etm_tensor = etm_train.get_document_topic_dist()
</code>```

Body:
I'm trying to visualise ETM(Embedded Topic Model) in Python like picture below. But I can't find any code for Python.

How can I do?

example image: https://i.stack.imgur.com/ESKSE.png

(Stackoverflow says I can't upload image since I have under 10 reputation;;)

image source: "Topic Modeling in Embedding Space" (Adji B. Dieng et al.)

I just want to see the distances of topics or words using that picture.

I used ETM code from here (pypi.org/project/embedded-topic-model). And my data has 2 dimentionality with 34rows(topics) and 30columns(words)

My code

  import torch
  from embedded_topic_model.utils import preprocessing
  from embedded_topic_model.utils import embedding
  from embedded_topic_model.models.etm import ETM

  # Vocabulary: 'all_n' is list of all words
  vocabulary, dataset, _ = preprocessing.create_etm_datasets(all_n,
                                  min_df=15)

  # ???
  embeddings_mapping = embedding.create_word2vec_embedding_from_dataset(all_n,
                                          min_count=15,
                                          embedding_file_path='./w2v',
                                          debug_mode=True)

  # Train
  etm_train = ETM(vocabulary,
                   embeddings=embeddings_mapping,
                   num_topics=36,
                   epochs=100,
                   train_embeddings=False,
                   debug_mode=True
                   )
  etm_train.fit(dataset)

  topics = etm_train.get_topics(30)
  etm_train.get_most_similar_words(['stack'])
  etm_tensor = etm_train.get_document_topic_dist()


问:
How do you use the Django timezone.override(utc) to create datetimes with tzinfo?
I can use timezone.now() to get a UTC timestamp in Django.
I can use timezone.make_aware(datetime(2012,1,1)) to add UTC as the TZ for the datetime.

Last one is cumbersome and a lot of extra typing.

Meanwhile I find these docs:  https://docs.djangoproject.com/en/4.1/topics/i18n/timezones/

But activating the TZ doesn't seem to affect datetime creation (still no tzinfo included)

I also found these docs inside python:

```<code>>>> from django.utils import timezone
>>> help(timezone)
Help on module django.utils.timezone in django.utils:

NAME
    django.utils.timezone - Timezone-related classes and functions.

CLASSES
    contextlib.ContextDecorator(builtins.object)
        override

    class override(contextlib.ContextDecorator)
     |  override(timezone)
     |
     |  Temporarily set the time zone for the current thread.
     |
     |  This is a context manager that uses django.utils.timezone.activate()
     |  to set the timezone on entry and restores the previously active timezone
     |  on exit.
     |
     |  The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
     |  time zone name, or ``None``. If it is ``None``, Django enables the default
     |  time zone.
     |
     |  Method resolution order:
     |      override
     |      contextlib.ContextDecorator
     |      builtins.object
     |
     |  Methods defined here:
     |
     |  __enter__(self)
     |
     |  __exit__(self, exc_type, exc_value, traceback)
     |
     |  __init__(self, timezone)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from contextlib.ContextDecorator:
     |
     |  __call__(self, func)
     |      Call self as a function.
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from contextlib.ContextDecorator:
</code>```

I'm wanting to do something like:

```<code>from datetime import datetime
from django.utils import timezone

>>> with timezone.override(None):
...   datetime.now()
...
datetime.datetime(2023, 1, 12, 16, 56, 3, 679319). #WTF is the timezone info?
>>>
</code>```

Am I stuck with writing a wrapper class to apply the tzinfo or is there a pythonic way to do this?

Body:
I can use timezone.now() to get a UTC timestamp in Django.
I can use timezone.make_aware(datetime(2012,1,1)) to add UTC as the TZ for the datetime.

Last one is cumbersome and a lot of extra typing.

Meanwhile I find these docs:  https://docs.djangoproject.com/en/4.1/topics/i18n/timezones/

But activating the TZ doesn't seem to affect datetime creation (still no tzinfo included)

I also found these docs inside python:

>>> from django.utils import timezone
>>> help(timezone)
Help on module django.utils.timezone in django.utils:

NAME
    django.utils.timezone - Timezone-related classes and functions.

CLASSES
    contextlib.ContextDecorator(builtins.object)
        override

    class override(contextlib.ContextDecorator)
     |  override(timezone)
     |
     |  Temporarily set the time zone for the current thread.
     |
     |  This is a context manager that uses django.utils.timezone.activate()
     |  to set the timezone on entry and restores the previously active timezone
     |  on exit.
     |
     |  The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
     |  time zone name, or ``None``. If it is ``None``, Django enables the default
     |  time zone.
     |
     |  Method resolution order:
     |      override
     |      contextlib.ContextDecorator
     |      builtins.object
     |
     |  Methods defined here:
     |
     |  __enter__(self)
     |
     |  __exit__(self, exc_type, exc_value, traceback)
     |
     |  __init__(self, timezone)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from contextlib.ContextDecorator:
     |
     |  __call__(self, func)
     |      Call self as a function.
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from contextlib.ContextDecorator:

I'm wanting to do something like:

from datetime import datetime
from django.utils import timezone

>>> with timezone.override(None):
...   datetime.now()
...
datetime.datetime(2023, 1, 12, 16, 56, 3, 679319). #WTF is the timezone info?
>>>

Am I stuck with writing a wrapper class to apply the tzinfo or is there a pythonic way to do this?


问:
Are the ec2 T family instances objectively "worse" than the other ones?
I wonder why the documentation seems to allude that the T instances should not be used in production. I am most concerned about advertised CPU performance and network availability.

Regardless of the cost and the credits thing, is there any reason to believe that the CPU performance of the T family ec2 instances is worse than other instance types with the same amount of cores and frequency?

Does the T instance have "access" to it's full non-baseline CPU performance as fast as other types? Or is there some kind of delay?

Can the performance of my instance be impacted by other customers putting more load on their instances?

Are latency spikes more likely to happen than with other types of instances?


问:
Locking a Fold in vscode
I use folding constantly but it seems to be missing one key feature. There are some parts of my code that are rather long that I'm constantly having to scroll past. Having formatting on save often unfolds sections that I rarely if ever want unfolded. Is there a way to lock certain folds so that it takes more than the standard actions to unfold?

For instance, when working in html, I have json scripts for google meta information that are long. They are mostly boilerplate but each page needs several custom changes. I want to fold and lock this so that it only unfolds when I specifically want to make changes to that script. Is there a way to accomplish this?

I've searched help files and website tips but haven't found any references.

Title: Locking a Fold in vscode


问:
Question about Multiselect using Javascript and Tableau
Good day

I have a problem with JavaScript and Multiselect, my example is in the next link: https://tableaujs.kiradata.com/

This is my code to generate the multiselect in HTML

```<code>                 <div>
                <label class="checkbox-container">Skinallergies
                    <input type="checkbox" name="problemsFilter" value="Skinallergies" onchange="changeHandler()">
                    <span class="checkmark"></span>
                  </label>
                  <label class="checkbox-container">respiratoryissues
                    <input type="checkbox" name="problemsFilter" value="respiratoryissues" onchange="changeHandler()">
                    <span class="checkmark"></span>
                  </label>
                  <label class="checkbox-container">pancreatitis
                    <input type="checkbox" name="problemsFilter" value="pancreatitis" onchange="changeHandler()">
                    <span class="checkmark"></span>
                  </label>
                  <label class="checkbox-container">obesity
                    <input type="checkbox" name="problemsFilter" value="obesity" onchange="changeHandler()">
                    <span class="checkmark"></span>
                  </label>
            </div>
</code>```

And this is the code that I use to get the Array and try to work it in Tableau is:

```<code>function changeHandler(){
const selectedOptions = Array.from(document.querySelectorAll('input[name="problemsFilter"]:checked'))
  .map(input => input.value);
console.log(selectedOptions);
var sheet = viz.getWorkbook().getActiveSheet();
    for(var i = 0; i < selectedOptions.length; i++){
        filterList = selectedOptions[i];
        sheet.applyFilterAsync("Problems", filterList, tableau.FilterUpdateType.REPLACE);
    }

}
</code>```

In the console.log I can get the Array but in the Dashboard doesnt work it

Someone work it with Arrays in Tableau Javascript?

Body:
Good day

I have a problem with JavaScript and Multiselect, my example is in the next link: https://tableaujs.kiradata.com/

This is my code to generate the multiselect in HTML

                Skinallergies
                    <input type="checkbox" name="problemsFilter" value="Skinallergies" onchange="changeHandler()">

                  respiratoryissues
                    <input type="checkbox" name="problemsFilter" value="respiratoryissues" onchange="changeHandler()">

                  pancreatitis
                    <input type="checkbox" name="problemsFilter" value="pancreatitis" onchange="changeHandler()">

                  obesity
                    <input type="checkbox" name="problemsFilter" value="obesity" onchange="changeHandler()">

And this is the code that I use to get the Array and try to work it in Tableau is:

function changeHandler(){
const selectedOptions = Array.from(document.querySelectorAll('input[name="problemsFilter"]:checked'))
  .map(input => input.value);
console.log(selectedOptions);
var sheet = viz.getWorkbook().getActiveSheet();
    for(var i = 0; i < selectedOptions.length; i++){
        filterList = selectedOptions[i];
        sheet.applyFilterAsync("Problems", filterList, tableau.FilterUpdateType.REPLACE);
    }

}

In the console.log I can get the Array but in the Dashboard doesnt work it

Someone work it with Arrays in Tableau Javascript?


问:
How to I register locales in a Flatpak application?
I have created a gtk app
https://github.com/mijorus/webapp-manager from the Builder template

and put a bunch of .po files in the /po folder.

Using flatpak-builder I can see them compiling

```<code>Installing po/sk/LC_MESSAGES/webapp-manager.mo to /app/share/locale/sk/LC_MESSAGES
</code>```

But the app is always showing up in in English.

How can I fix that?

Body:
I have created a gtk app
https://github.com/mijorus/webapp-manager from the Builder template

and put a bunch of .po files in the /po folder.

Using flatpak-builder I can see them compiling

Installing po/sk/LC_MESSAGES/webapp-manager.mo to /app/share/locale/sk/LC_MESSAGES

But the app is always showing up in in English.

How can I fix that?


问:
Custom rendered input for django-formtools wizard field
New to Django.  I've created some bootstrap card UI widgets that function as radio buttons and this works ok in plain old html, but I'm trying to integrate it into a Django wizard.

How would I go about telling the form the data field is associated with?

I just have a bunch of widgets included for each option like this

```<code>                <div class="col-6">
                    {% include "./domain_type_widget.html" with radio_group="domain_type" title="People" description="For a URL with your name" left="name" mid="people" type_id="name" checked=True %}
                </div>
                <div class="col-6">
                    {% include "./domain_type_widget.html" with radio_group="domain_type" title="Event" description="For events" left="eventname" mid="event" type_id="event" %}
                </div>
</code>```

And domain_type_widget.html looks like so

```<code><label class="card m-1 {% if checked %}selected_type{% endif %}" id="{{ type_id }}_card">
<div class="card-body" onclick="selectDomainType({{type_id}})">
    <div class="row">
        <div class="col-sm-12 col-md-10">
            <h5 class="card-title">{{ title }}</h5>
            <p class="card-text">{{ description }}</p>
            {%  if left %}
                <p class="domain-example" class="domain-example">
                    <span class="left">{{ left }}</span>
                    <span>.</span>
                    <span class="mid">{{ mid }}</span>
                    <span>.</span>
                    <span class="right">site.com</span>
                </p>
            {% endif %}
        </div>
        <div class="col-sm-12 col-md-2 d-flex align-items-center justify-content-center">
            <input type="radio" class="radio" name="{{ radio_group }}" id="{{ type_id }}" {% if checked %}checked{% endif %} onchange="selectDomainType(this)">
        </div>
    </div>
</div>
</code>```

Body:
New to Django.  I've created some bootstrap card UI widgets that function as radio buttons and this works ok in plain old html, but I'm trying to integrate it into a Django wizard.

How would I go about telling the form the data field is associated with?

I just have a bunch of widgets included for each option like this

                    {% include "./domain_type_widget.html" with radio_group="domain_type" title="People" description="For a URL with your name" left="name" mid="people" type_id="name" checked=True %}

                    {% include "./domain_type_widget.html" with radio_group="domain_type" title="Event" description="For events" left="eventname" mid="event" type_id="event" %}

And domain_type_widget.html looks like so

{{ title }}

{{ description }}

            {%  if left %}

                    {{ left }}
                    .
                    {{ mid }}
                    .
                    site.com

            {% endif %}

            <input type="radio" class="radio" name="{{ radio_group }}" id="{{ type_id }}" {% if checked %}checked{% endif %} onchange="selectDomainType(this)">


问:
Saving ID from CSV and associate to a response from tRestClient
I just started my adventure with Talend Open Studio,

I am having trouble figuring out how to solve a problem I am encountering.

I have a tFileInputDelimited as input with a two-column schema (name and id), on which I am iterating with tFlowToIterate, saving these two variables together using tFixedFlowInput in order to use the name variable as a query parameter on tRestClient, and then extracting the response with tExtractJSONField.

I would like to keep the id variable to associate it with each response, but since the id variable is not a valid parameter for the query, I am looking for a way to add it during my mapping in tExtractJSONField.

Any help will be appreciated

Find a solution to save variable and add to the corresponding response


问:
CLOB TO BLOB and parse to APEX table
So i have a procedure using SOAP function
and i want to parse the data into the table...but when i run the script it cameback with
enter image description here
here is my procedure script i'm still new using apex...

```<code>create or replace procedure       "GET_SUPL"
(p_wsdl IN VARCHAR2,
p_version IN VARCHAR2,
p_username IN VARCHAR2,
p_password IN VARCHAR2,
p_wallet_path IN VARCHAR2 default null,
p_wallet_pwd IN VARCHAR2 default null,
p_rpt_path IN VARCHAR2,
p_rpt_name IN VARCHAR2,
r_out_id OUT NUMBER,
l_output OUT BLOB)
IS
l_envelope   CLOB;
l_result     XMLTYPE;
l_base64     CLOB;
\--        l_output     CLOB;
v_out_id     NUMBER;
v_sqlerrm    VARCHAR2 (4000);
v_name varchar2(100);
begin
/\*
insert into TG_OUTPUT_EXTERNAL_RPT (RPT_NAME, START_DATE_DOWNLOAD, STATUS_DOWNLOAD)
values (p_rpt_name, sysdate, 'P')
returning OUT_ID
into v_out_id;
\*/

        /* 20190219/Aan/Case dimana saat insert gagal return ID. */

       -- COMMIT;

       -- r_out_id := v_out_id;

        /* 20190205/Aan/ORA-06502: PL/SQL: numeric or value error: invalid LOB locator specified: ORA-22275 */
        DBMS_LOB.createtemporary (l_envelope, TRUE);
        DBMS_LOB.createtemporary (l_base64, TRUE);

\--        DBMS_LOB.createtemporary (l_output, TRUE);

        l_envelope :=
            '
           <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:pub="http://xmlns.oracle.com/oxp/service/PublicReportService">

\<soap:Header/\>
\<soap:Body\>
\<pub:runReport\>
\<pub:reportRequest\>
\<pub:attributeFormat\>csv\</pub:attributeFormat\>
\<!-- Flatten XML should always be false when we have XML type of output to display the XML tags as mentioned in BIP Data Model and display XML structure in as expected format --\>
\<pub:flattenXML\>false\</pub:flattenXML\>
\<pub:parameterNameValues\>

            </pub:parameterNameValues>
            <pub:reportAbsolutePath>/Custom/-------/--------------</pub:reportAbsolutePath>
            <!-- Setting sizeOfDataChunkDownload to -1 will return the output to the calling client -->
            <pub:sizeOfDataChunkDownload>-1</pub:sizeOfDataChunkDownload>
         </pub:reportRequest>
      </pub:runReport>

\</soap:Body\>
\</soap:Envelope\>
';

        l_result :=
            APEX_WEB_SERVICE.make_request (
                p_url                => XXXXXX,
                p_version            => '1.2',
                p_envelope           => l_envelope,
                p_username           => 'XXXXXXX',
                p_password           => 'XXXXXXX',
                p_transfer_timeout   => 720,
                p_wallet_path        => null,
                p_wallet_pwd         => null);

        l_base64 :=
            APEX_WEB_SERVICE.parse_xml_clob (
                p_xml   => l_result,
                p_xpath   =>
                    ' //ns2:runReportResponse/ns2:runReportReturn/ns2:reportBytes/text()',
                p_ns    =>
                    ' xmlns:ns2="http://xmlns.oracle.com/oxp/service/PublicReportService"');

        l_output :=
                APEX_WEB_SERVICE.clobbase642blob (
                    REPLACE (REPLACE (l_base64, CHR (10), NULL),
                             CHR (13),
                             NULL));

         dbms_lob.createtemporary(  l_output,true );
        COMMIT;

        DBMS_LOB.freetemporary (l_envelope);
        DBMS_LOB.freetemporary (l_base64);

select  col001
from table(
APEX_DATA_PARSER.parse(
p_content         => l_output,
p_file_name       => 'test.csv') ) ;

\--            dbms_output.put_line(col001);
\--        DBMS_LOB.freetemporary (l_output);
DBMS_LOB.freetemporary (l_envelope);
DBMS_LOB.freetemporary (l_base64);
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (SQLERRM);

            v_sqlerrm := SUBSTR (SQLERRM, 1, 4000);
            COMMIT;

        INSERT INTO TEST_SUPL values(v_name);

            COMMIT;

end;
</code>```

This is my current procedure that i create, and i'm stuck figuring this out

I hope i can get a better version of this script or maybe a solution for my problem

Title: CLOB TO BLOB and parse to APEX table

Body:
So i have a procedure using SOAP function
and i want to parse the data into the table...but when i run the script it cameback with
enter image description here
here is my procedure script i'm still new using apex...

create or replace procedure       "GET_SUPL"
(p_wsdl IN VARCHAR2,
p_version IN VARCHAR2,
p_username IN VARCHAR2,
p_password IN VARCHAR2,
p_wallet_path IN VARCHAR2 default null,
p_wallet_pwd IN VARCHAR2 default null,
p_rpt_path IN VARCHAR2,
p_rpt_name IN VARCHAR2,
r_out_id OUT NUMBER,
l_output OUT BLOB)
IS
l_envelope   CLOB;
l_result     XMLTYPE;
l_base64     CLOB;
\--        l_output     CLOB;
v_out_id     NUMBER;
v_sqlerrm    VARCHAR2 (4000);
v_name varchar2(100);
begin
/\*
insert into TG_OUTPUT_EXTERNAL_RPT (RPT_NAME, START_DATE_DOWNLOAD, STATUS_DOWNLOAD)
values (p_rpt_name, sysdate, 'P')
returning OUT_ID
into v_out_id;
\*/

        /* 20190219/Aan/Case dimana saat insert gagal return ID. */

       -- COMMIT;

       -- r_out_id := v_out_id;

        /* 20190205/Aan/ORA-06502: PL/SQL: numeric or value error: invalid LOB locator specified: ORA-22275 */
        DBMS_LOB.createtemporary (l_envelope, TRUE);
        DBMS_LOB.createtemporary (l_base64, TRUE);

\--        DBMS_LOB.createtemporary (l_output, TRUE);

        l_envelope :=
            '
           <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:pub="http://xmlns.oracle.com/oxp/service/PublicReportService">

\<soap:Header/\>
\<soap:Body\>
\<pub:runReport\>
\<pub:reportRequest\>
\<pub:attributeFormat\>csv\</pub:attributeFormat\>
\
            <pub:sizeOfDataChunkDownload>-1</pub:sizeOfDataChunkDownload>
         </pub:reportRequest>
      </pub:runReport>

\</soap:Body\>
\</soap:Envelope\>
';

        l_result :=
            APEX_WEB_SERVICE.make_request (
                p_url                => XXXXXX,
                p_version            => '1.2',
                p_envelope           => l_envelope,
                p_username           => 'XXXXXXX',
                p_password           => 'XXXXXXX',
                p_transfer_timeout   => 720,
                p_wallet_path        => null,
                p_wallet_pwd         => null);

        l_base64 :=
            APEX_WEB_SERVICE.parse_xml_clob (
                p_xml   => l_result,
                p_xpath   =>
                    ' //ns2:runReportResponse/ns2:runReportReturn/ns2:reportBytes/text()',
                p_ns    =>
                    ' xmlns:ns2="http://xmlns.oracle.com/oxp/service/PublicReportService"');

        l_output :=
                APEX_WEB_SERVICE.clobbase642blob (
                    REPLACE (REPLACE (l_base64, CHR (10), NULL),
                             CHR (13),
                             NULL));

         dbms_lob.createtemporary(  l_output,true );
        COMMIT;

        DBMS_LOB.freetemporary (l_envelope);
        DBMS_LOB.freetemporary (l_base64);

select  col001
from table(
APEX_DATA_PARSER.parse(
p_content         => l_output,
p_file_name       => 'test.csv') ) ;

\--            dbms_output.put_line(col001);
\--        DBMS_LOB.freetemporary (l_output);
DBMS_LOB.freetemporary (l_envelope);
DBMS_LOB.freetemporary (l_base64);
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (SQLERRM);

            v_sqlerrm := SUBSTR (SQLERRM, 1, 4000);
            COMMIT;

        INSERT INTO TEST_SUPL values(v_name);

            COMMIT;

end;

This is my current procedure that i create, and i'm stuck figuring this out

I hope i can get a better version of this script or maybe a solution for my problem


问:
Some tool to debug CSS unexpected style?
I'm developing a big website and I'm in trouble often with styles.
In this case, I have a 40px div height (from CSS class), but the computed value ends to 20px.

Is there a tool or something that can let me know why the height of this div is 20px instead 40px?

I don't want to figure out why it is 20px, I'm looking for a tool or a concrete way to reach why the final result is 20px instead 40px (maybe flex, maybe I don't know what rule in this case).

This is just a generic example, I'm bored of fighting against so many CSS rules and a huge web style hierarchy.

Thanks in advance.


问:
I'd like to connect a droplist to a button and have it change its effect for each choice on the list

Hello there!

I've been trying to learn some html lately and I have a very funny idea, which might seem a bit too simple to the most of you, but made me struggle nevertheless.

I basically have a droplist ( tag) of dog foods and want to make a different picture pop up, depending on the user's choice, when they press a "Submit" button I will put below.

I couldn't find anything anywhere, maybe I just couldn't ask the question correctly.

Any help is greatly appreciated!

I did not try anything, as I am 100% certain I don't know how to do it.

Thanks again!


问:
How to compress image converted to a Bitmap , using glide
I am implementing an android app ( in java) in which am sending images taken with the camera , that will be sent over the internet through Apis . The problem is , it takes some more few seconds to be loaded on the backend side  and i want the process to be faster . So i want  to convert images into Bitmap and compress it using Glide . How can i figure it out it ? How can i take the image from the external storage using Glide . Here 's what i've done</p>
```<code> Bitmap bitmap = BitmapFactory.decodeFile(creanceDetteList.get(i).getEncodedImagePath());
                //Convert bitmap to byteArray
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream .toByteArray();
                //Then convert to base64
                String encodedImage= Base64.encodeToString(byteArray, Base64.DEFAULT);
</code>```

Body:
I am implementing an android app ( in java) in which am sending images taken with the camera , that will be sent over the internet through Apis . The problem is , it takes some more few seconds to be loaded on the backend side  and i want the process to be faster . So i want  to convert images into Bitmap and compress it using Glide . How can i figure it out it ? How can i take the image from the external storage using Glide . Here 's what i've done

 Bitmap bitmap = BitmapFactory.decodeFile(creanceDetteList.get(i).getEncodedImagePath());
                //Convert bitmap to byteArray
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream .toByteArray();
                //Then convert to base64
                String encodedImage= Base64.encodeToString(byteArray, Base64.DEFAULT);


问:
Does a remote storage exist for common user accounts (like google/apple) rather than needing my own database?
I want to create a website and use a remote database or something similar to allow for cross-device data access for users. So they log on via a computer and see their data, or a phone and see the same data, etc. However, I don't want to start up a business model where I'm incurring costs for a database and charging users a monthly fee or something like that.

Instead, I would like the user themselves to log in via a common account they may have like a google or apple account, and have their own database or storage area through that account that I could use via an API of some sort (ofcourse so long as the user is willing). The closest thing I found was something very specific. It was for google extensions: something called Chrome.storage. This accomplished just what I wanted, except that it only works for extensions and google extensions don't exist on phones. So if I went this route, my website (or actually extension in this case) couldn't save and store data through a phone, which is unacceptable for me.

So I'm back to square one. Basically, my question is: does a common user account like a google or apple or other account also offer a remote storage API that I could use in my website to store and retrieve user data rather than having to setup and use my own remote database?


问:
Cannot read properties of undefined (reading 'bind') in class
I am currently in the process of learning Java Script, and am having an issue with using the .bind(this) method.

I have created a class called App() which will run my app.  As a first step I am trying to create a variable in the class to store the latitude and longitude using the navigator.geolocation API.

When I define the variables in the method _getCurrentLocal() it works fine.  When I try to define the latitude and longitude in the class, I get an error stating: "script.js:16 Uncaught TypeError: Cannot read properties of undefined (reading 'bind')", followed by: "script.js:31 Uncaught TypeError: Cannot set properties of undefined (setting 'latitude')"

My code is as follows:

```<code>class App {
  constructor() {
    this._getCurrentLocal().bind(this);
    this.latitude;
    this.longitude;
  }

  _getCurrentLocal() {
    //guard clause
    if (!navigator.geolocation) {
      console.log('no geo location');
      return;
    }
    //get geolocation
    navigator.geolocation.getCurrentPosition(
      function (position) {
        // const { latitude, longitude } = position.coords;
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        console.log('lat ', latitude, ' long ', longitude);
      },
      function () {
        prompt('Could not get your location');
      }
    );
  }
}
</code>```

Any help would be greatly appreciated!

Body:
I am currently in the process of learning Java Script, and am having an issue with using the .bind(this) method.

I have created a class called App() which will run my app.  As a first step I am trying to create a variable in the class to store the latitude and longitude using the navigator.geolocation API.

When I define the variables in the method _getCurrentLocal() it works fine.  When I try to define the latitude and longitude in the class, I get an error stating: "script.js:16 Uncaught TypeError: Cannot read properties of undefined (reading 'bind')", followed by: "script.js:31 Uncaught TypeError: Cannot set properties of undefined (setting 'latitude')"

My code is as follows:

class App {
  constructor() {
    this._getCurrentLocal().bind(this);
    this.latitude;
    this.longitude;
  }

  _getCurrentLocal() {
    //guard clause
    if (!navigator.geolocation) {
      console.log('no geo location');
      return;
    }
    //get geolocation
    navigator.geolocation.getCurrentPosition(
      function (position) {
        // const { latitude, longitude } = position.coords;
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        console.log('lat ', latitude, ' long ', longitude);
      },
      function () {
        prompt('Could not get your location');
      }
    );
  }
}

Any help would be greatly appreciated!


问:
How to write a request in php to get a token
```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://online.moysklad.ru/api/remap/1.2/security/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Authorization: Basic <Credentials>';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
</code>```

Getting a new token

Request for a new token.  As in other requests, in the Authorization header, the login:password pair is specified encoded in the RFC2045-MIME version of the Base64 standard.  When a new access token is generated, the previously generated user tokens will be revoked.

Where and how can I specify my login and password?

Thanks.

Body:
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://online.moysklad.ru/api/remap/1.2/security/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Authorization: Basic <Credentials>';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

Getting a new token

Request for a new token.  As in other requests, in the Authorization header, the login:password pair is specified encoded in the RFC2045-MIME version of the Base64 standard.  When a new access token is generated, the previously generated user tokens will be revoked.

Where and how can I specify my login and password?

Thanks.


问:
Webpack 5 babel-loader tsx error "TypeError: loaderUtils.getOptions is not a function"
I am getting the following error with my Webpack 5 config that needs to handle ts and tsx files. There's /ReactScripts with our react tsx/ts files, then all ts files in /Content I am quite new to Webpack and I just can't seem to find any other question that resolves this issue. I'm not sure I even have the best build for this, but I'm trying to make it work. ALL packages are up to date as far as I can tell!:

Error:

ERROR in ./ReactScripts/AppRoot.tsx Module build failed (from ./node_modules/babel-loader/lib/index.js): TypeError: loaderUtils.getOptions is not a function

webpack.config.ts:

```<code>const path = require("path");
const webpack = require("webpack");
const TerserPlugin = require("terser-webpack-plugin");

function vendorBundle( bundle ) {
    if ( bundle ) {
        return {
            splitChunks: {
                cacheGroups: {
                    commons: {
                        test: /[\\/]node_modules[\\/]/,
                        name: "vendor",
                        chunks: "initial"
                    }
                }
            },
            sideEffects: false,
            minimizer: [
                new TerserPlugin(),
            ],
        };
    }
    else {
        return {};
    }
}

function WebpackConfiguration(WebpackOptions, mode)
{
    return {
        watchOptions: {
            poll: true,
            ignored: "/node_modules",
        },
        context: __dirname,
        mode: mode,
        stats: { modules: false, errorDetails: true },
        resolve: {
            extensions: [".ts", ".js", ".tsx"],
            fallback: {
                fs: false,
                "http": require.resolve("stream-http"),
                "https": require.resolve("https-browserify"),
                "buffer": require.resolve("buffer"),
                "url": require.resolve("url"),
                "crypto": require.resolve("crypto-browserify") ,
                "util": require.resolve("util"),
                "stream": require.resolve("stream-browserify"),
            }
        },
        entry: {
            // common ts and js files
            initial: path.resolve(__dirname, "./TEST_ENTRY/initial.entry.ts"),
            slickgrid: path.resolve(__dirname, "./TEST_ENTRY/slickgrid.entry.ts"),
            jquery: path.resolve(__dirname, "./TEST_ENTRY/jquery.entry.ts"),
            scriptsadmin: path.resolve(__dirname, "./TEST_ENTRY/scriptsadmin.entry.ts"),
            main: [path.resolve(__dirname, "./TEST_ENTRY/tscore.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/jqx.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/tswidgets.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/managers.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/thirdparty.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/main.entry.ts")],
            lbcomponents: path.resolve(__dirname, "./Scripts/LBComponents/dist/lb-components.min.js"),
            ie7: path.resolve(__dirname, "./TEST_ENTRY/ie7.entry.ts"),

            // react js and jsx files
            reactAppRoot: path.resolve(__dirname, "./ReactScripts/AppRoot.tsx"),
        },
        output: {
            path:  WebpackOptions.BuildDirectory,
            filename: "[name].bundle.js"
        },
        plugins: [
            new webpack.ProvidePlugin({
                Buffer: ["buffer", "Buffer"],
            }),
            new webpack.ProvidePlugin({
                process: "process/browser",
            }),
            new webpack.ProvidePlugin({
              $: "jquery",
              jQuery: "jquery"
            }),
        ],
        performance: {
            hints: false
        },
        module: {
            rules: [
                // ts/x files
                {
                    test: /\.ts(x)$/,
                    include: [
                        path.resolve(__dirname, "Content"),
                        path.resolve(__dirname, "ReactScripts"),
                    ],
                    exclude: /node_modules/,
                    use: [
                        'babel-loader',
                        {
                            loader: "ts-loader",
                            options: {
                                transpileOnly: true,
                                experimentalWatchApi: true
                            }
                        }
                    ],
                },
                // images
                {
                    test: /\.(gif|png|svg)(\?[\s\S]+)?$/,
                    type: "asset",
                },
                // handles mjs files from node_modules
                {
                    test: /\.mjs$/,
                    include: /node_modules/,
                    type: "javascript/auto",
                    resolve: {
                        fullySpecified: false
                    }
                },
            ]
        },

        // build source maps for us to use in dev
        devtool: "eval-cheap-module-source-map",

        // builds vendor bundle (npm) and optimizes
        optimization: vendorBundle( WebpackOptions.VendorBundle ),
    }
}

module.exports = WebpackConfiguration;
</code>```

tsconfig.json:

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "preserve",
    "module": "commonjs",
    "sourceMap": true,
    "declaration": true,
    "declarationDir": "./TEST/types",
    "declarationMap": true,
    "lib": [ "es2015", "es6", "dom" ]
  },
  "env": {
    "browser":  true
  },
  "exclude": [
    "node_modules",
    "Scripts/LBComponents"
  ]
}
</code>```

.babelrc:

```<code>{
  "ignore": [ "node-modules/**" ],
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": "commonjs",
        "useBuiltIns": "usage",
        "corejs": "2"
        //,"debug": true,
        //"targets": {
        //  "browsers": [ "IE >= 11" ]
        //}
      }
    ],
    [
      "@babel/preset-react"
    ]
  ],
  "plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true,
        "modules": false
      }
    ],
    [
      "@babel/plugin-proposal-private-methods",
      {
        "loose": true
      }
    ],
    [
      "@babel/plugin-proposal-private-property-in-object",
      {
        "loose": true
      }
    ],
    [
      "@babel/plugin-transform-runtime"
    ]
  ]
}
</code>```

Layout.cshtml:

@System.Web.Optimization.Scripts.Render("~/TEST/initial.bundle.js") and the like, one line for each bundle above

Body:
I am getting the following error with my Webpack 5 config that needs to handle ts and tsx files. There's /ReactScripts with our react tsx/ts files, then all ts files in /Content I am quite new to Webpack and I just can't seem to find any other question that resolves this issue. I'm not sure I even have the best build for this, but I'm trying to make it work. ALL packages are up to date as far as I can tell!:

Error:

ERROR in ./ReactScripts/AppRoot.tsx Module build failed (from ./node_modules/babel-loader/lib/index.js): TypeError: loaderUtils.getOptions is not a function

webpack.config.ts:

const path = require("path");
const webpack = require("webpack");
const TerserPlugin = require("terser-webpack-plugin");

function vendorBundle( bundle ) {
    if ( bundle ) {
        return {
            splitChunks: {
                cacheGroups: {
                    commons: {
                        test: /[\\/]node_modules[\\/]/,
                        name: "vendor",
                        chunks: "initial"
                    }
                }
            },
            sideEffects: false,
            minimizer: [
                new TerserPlugin(),
            ],
        };
    }
    else {
        return {};
    }
}

function WebpackConfiguration(WebpackOptions, mode)
{
    return {
        watchOptions: {
            poll: true,
            ignored: "/node_modules",
        },
        context: __dirname,
        mode: mode,
        stats: { modules: false, errorDetails: true },
        resolve: {
            extensions: [".ts", ".js", ".tsx"],
            fallback: {
                fs: false,
                "http": require.resolve("stream-http"),
                "https": require.resolve("https-browserify"),
                "buffer": require.resolve("buffer"),
                "url": require.resolve("url"),
                "crypto": require.resolve("crypto-browserify") ,
                "util": require.resolve("util"),
                "stream": require.resolve("stream-browserify"),
            }
        },
        entry: {
            // common ts and js files
            initial: path.resolve(__dirname, "./TEST_ENTRY/initial.entry.ts"),
            slickgrid: path.resolve(__dirname, "./TEST_ENTRY/slickgrid.entry.ts"),
            jquery: path.resolve(__dirname, "./TEST_ENTRY/jquery.entry.ts"),
            scriptsadmin: path.resolve(__dirname, "./TEST_ENTRY/scriptsadmin.entry.ts"),
            main: [path.resolve(__dirname, "./TEST_ENTRY/tscore.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/jqx.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/tswidgets.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/managers.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/thirdparty.entry.ts"), path.resolve(__dirname, "./TEST_ENTRY/main.entry.ts")],
            lbcomponents: path.resolve(__dirname, "./Scripts/LBComponents/dist/lb-components.min.js"),
            ie7: path.resolve(__dirname, "./TEST_ENTRY/ie7.entry.ts"),

            // react js and jsx files
            reactAppRoot: path.resolve(__dirname, "./ReactScripts/AppRoot.tsx"),
        },
        output: {
            path:  WebpackOptions.BuildDirectory,
            filename: "[name].bundle.js"
        },
        plugins: [
            new webpack.ProvidePlugin({
                Buffer: ["buffer", "Buffer"],
            }),
            new webpack.ProvidePlugin({
                process: "process/browser",
            }),
            new webpack.ProvidePlugin({
              $: "jquery",
              jQuery: "jquery"
            }),
        ],
        performance: {
            hints: false
        },
        module: {
            rules: [
                // ts/x files
                {
                    test: /\.ts(x)$/,
                    include: [
                        path.resolve(__dirname, "Content"),
                        path.resolve(__dirname, "ReactScripts"),
                    ],
                    exclude: /node_modules/,
                    use: [
                        'babel-loader',
                        {
                            loader: "ts-loader",
                            options: {
                                transpileOnly: true,
                                experimentalWatchApi: true
                            }
                        }
                    ],
                },
                // images
                {
                    test: /\.(gif|png|svg)(\?[\s\S]+)?$/,
                    type: "asset",
                },
                // handles mjs files from node_modules
                {
                    test: /\.mjs$/,
                    include: /node_modules/,
                    type: "javascript/auto",
                    resolve: {
                        fullySpecified: false
                    }
                },
            ]
        },

        // build source maps for us to use in dev
        devtool: "eval-cheap-module-source-map",

        // builds vendor bundle (npm) and optimizes
        optimization: vendorBundle( WebpackOptions.VendorBundle ),
    }
}

module.exports = WebpackConfiguration;

tsconfig.json:

{
  "compileOnSave": true,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "preserve",
    "module": "commonjs",
    "sourceMap": true,
    "declaration": true,
    "declarationDir": "./TEST/types",
    "declarationMap": true,
    "lib": [ "es2015", "es6", "dom" ]
  },
  "env": {
    "browser":  true
  },
  "exclude": [
    "node_modules",
    "Scripts/LBComponents"
  ]
}

.babelrc:

{
  "ignore": [ "node-modules/**" ],
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": "commonjs",
        "useBuiltIns": "usage",
        "corejs": "2"
        //,"debug": true,
        //"targets": {
        //  "browsers": [ "IE >= 11" ]
        //}
      }
    ],
    [
      "@babel/preset-react"
    ]
  ],
  "plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true,
        "modules": false
      }
    ],
    [
      "@babel/plugin-proposal-private-methods",
      {
        "loose": true
      }
    ],
    [
      "@babel/plugin-proposal-private-property-in-object",
      {
        "loose": true
      }
    ],
    [
      "@babel/plugin-transform-runtime"
    ]
  ]
}

Layout.cshtml:

@System.Web.Optimization.Scripts.Render("~/TEST/initial.bundle.js") and the like, one line for each bundle above


问:
Unable to delete docker image
I am getting the following error when I execute docker image rm -f command and I am not able to delete the docker images from my system even after using force option.Please help to resolve it.Even prune command is also giving the same error.

```<code>Error: error reading image "5325e37426255f971e691f20b068b47d71dd3be62bd8bf22c5f6d23964bd4a44" as image: error locating item named "manifest" for image with ID "5325e37426255f971e691f20b068b47d71dd3be62bd8bf22c5f6d23964bd4a44": file does not exist
</code>```

Title: Unable to delete docker image

Body:
I am getting the following error when I execute docker image rm -f command and I am not able to delete the docker images from my system even after using force option.Please help to resolve it.Even prune command is also giving the same error.

Error: error reading image "5325e37426255f971e691f20b068b47d71dd3be62bd8bf22c5f6d23964bd4a44" as image: error locating item named "manifest" for image with ID "5325e37426255f971e691f20b068b47d71dd3be62bd8bf22c5f6d23964bd4a44": file does not exist


问:
VSCode - Externally open local file in attached remote container
I have an existing docker container that I am opening up in VSCode through the "Dev Containers: Attach to Running Container..." command.  I have a volume mounted that I can access fine through the VSCode Explorer pane (/Users/me/dev-workspace/web/ is mounted to /code/).  When I try to open a file within that mount (say /Users/me/dev-workspace/web/README.md, also at /code/README.md in the container) externally, such as double clicking in Finder or selecting "Open in VisualStudio Code" in GitHub Desktop, it opens in a separate instance of VSCode.  Is there a way to have the local file open in the instance of VSCode with the attached container when opened externally?

I've tried adding mounts into devcontainers.json, but couldn't get it to apply to an attached container (existing container)


问:
Web scraping, getting access to content that is dynamically generated after site is opened
I'm using python to webscrape windspeed data from windy.com
(example link: https://www.windy.com/57.261/21.709?56.919,21.706,8,m:fgBagLl)

This part in particular

Doing an inspect page reveals that is scrapable
the table in question

But I ran into 2 problems, the resulting payload says that it comes from a mobile source, even though I tried specifying the source of the call as a desktop.

Second, the text I retrieved contains no information of the wind data table, even though it is available.

By using the following python code, I was hoping to retrieve it

```<code>from requests_html import HTMLSession
from bs4 import BeautifulSoup

session = HTMLSession()
session.headers['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,     like Gecko) Chrome/78.0.3904.97 Safari/537.36'
url= 'https://www.windy.com/57.261/21.709?56.922,21.706,8,m:fgBagLl'
response = session.get(url, headers=session.headers).text
soup= BeautifulSoup(response, 'lxml')
print(soup.prettify())`
</code>```

Body:
I'm using python to webscrape windspeed data from windy.com
(example link: https://www.windy.com/57.261/21.709?56.919,21.706,8,m:fgBagLl)

This part in particular

Doing an inspect page reveals that is scrapable
the table in question

But I ran into 2 problems, the resulting payload says that it comes from a mobile source, even though I tried specifying the source of the call as a desktop.

Second, the text I retrieved contains no information of the wind data table, even though it is available.

By using the following python code, I was hoping to retrieve it

from requests_html import HTMLSession
from bs4 import BeautifulSoup

session = HTMLSession()
session.headers['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,     like Gecko) Chrome/78.0.3904.97 Safari/537.36'
url= 'https://www.windy.com/57.261/21.709?56.922,21.706,8,m:fgBagLl'
response = session.get(url, headers=session.headers).text
soup= BeautifulSoup(response, 'lxml')
print(soup.prettify())`


问:
Can I safely replace usesCleartextTraffic in my Manifest?
I am trying to use hCaptcha library on my project. However, it seems that hCaptcha library comes with a usesCleartextTraffic tag defined on the Manifest which is already defined by another library. When I add hCaptcha and try to run the project I get the following error:

```<code>Attribute application@usesCleartextTraffic value=(true) from [com.theoremreach:theoremreach:3.5.1] AndroidManifest.xml:15:9-44
is also present at [com.github.hcaptcha:hcaptcha-android-sdk:3.3.6] AndroidManifest.xml:11:9-45 value=(false).
Suggestion: add 'tools:replace="android:usesCleartextTraffic"' to <application> element at AndroidManifest.xml:17:5-132:19 to override.
</code>```

Great, there is a suggestion. Now by adding the following to my application tag on the Manifest, I can avoid any errors and run my application:

```<code>tools:replace="android:usesCleartextTraffic"
android:usesCleartextTraffic="true"
</code>```

My question is, replacing this value with true will not influenciate the hCaptcha Manifest false value for usesCleartextTraffic?

What would be the correct way to solve this error, without affecting each library security?

Body:
I am trying to use hCaptcha library on my project. However, it seems that hCaptcha library comes with a usesCleartextTraffic tag defined on the Manifest which is already defined by another library. When I add hCaptcha and try to run the project I get the following error:

Attribute application@usesCleartextTraffic value=(true) from [com.theoremreach:theoremreach:3.5.1] AndroidManifest.xml:15:9-44
is also present at [com.github.hcaptcha:hcaptcha-android-sdk:3.3.6] AndroidManifest.xml:11:9-45 value=(false).
Suggestion: add 'tools:replace="android:usesCleartextTraffic"' to <application> element at AndroidManifest.xml:17:5-132:19 to override.

Great, there is a suggestion. Now by adding the following to my application tag on the Manifest, I can avoid any errors and run my application:

tools:replace="android:usesCleartextTraffic"
android:usesCleartextTraffic="true"

My question is, replacing this value with true will not influenciate the hCaptcha Manifest false value for usesCleartextTraffic?

What would be the correct way to solve this error, without affecting each library security?