问:
How to put silhouette (or k-means ) cluster tree into pheatmap row cluster tree?
I recently did some work on how to put silhouette (or k-means ) cluster tree  into pheatmap row cluster tree.

But there is something wrong with my ideas.

Firstly, I want to get the better or best cluster groups by function fviz_nbclust. But it doesn't mean I must use the clusters. I may choose k=5 here.

Then I get the clusters and numbers in each group:

```<code>cluster size ave.sil.width
 1       1    6          0.44
 2       2   11          0.44
 3       3    6          0.59
 4       4    5          0.33
 5       5    4          0.56
##
</code>```

And then,I want to put this cluster result into pheatmap with the same cluster trees.

However, in the end, the same clusters with different cluster tree leaves:

```<code>**> table(newOrder$Cluster)
3  2  4  1  5
7  8 12  3  2**
</code>```

So I don't know how to keep the two results the same. I mean,use the first cluster result instead of the second one.

I looked up very many materials but I didn't have any ideas to solve my problem.

Could somebody give me some help? I'd be very thankful.

Here is my code:

```<code>dataa<-mtcars
fviz_nbclust(dataa, pam, method = "silhouette")+ theme_classic()
##
pam.res3 <- pam(dataa, k =5,  metric = "euclidean", stand = FALSE)

fviz_silhouette(pam.res3, palette = "jco", ggtheme = theme_classic())

##
# cluster size ave.sil.width
# 1       1    6          0.44
# 2       2   11          0.44
# 3       3    6          0.59
# 4       4    5          0.33
# 5       5    4          0.56

# order for rows
Rowv  <- dataa %>% scale %>% dist %>% hclust %>% as.dendrogram %>%
  set("branches_k_color", k = 5) %>% set("branches_lwd", 1.2) %>%
  ladderize
# Order for columns: We must transpose the data
Colv  <- data %>% scale %>% t %>% dist %>% hclust %>% as.dendrogram %>%
  set("branches_k_color", k = 2, value = c("orange", "blue")) %>%
  set("branches_lwd", 1.2) %>%
  ladderize

pheatmap(dataa,
         clustering_distance_rows = "euclidean",
         clustering_method = "complete",
         cluster_rows = T,
         cutree_rows = 5
         )
pp<-pheatmap(scale(dataa), Rowv = Rowv, Colv = Colv,
         clustering_distance_rows = "euclidean",
         clustering_method = "complete",
         cluster_rows = T,
         cutree_rows = 5
)

result = dataa[pp$tree_row$order,]

########
row_cluster <- cutree(pp$tree_row,k=5)
## order
newOrder <- dataa[pp$tree_row$order,]
newOrder[,ncol(newOrder)+1]=row_cluster[match(rownames(newOrder),names(row_cluster))]
colnames(newOrder)[ncol(newOrder)]="Cluster"
newOrder$Cluster<-factor(newOrder$Cluster,levels = unique(newOrder$Cluster))
table(newOrder$Cluster)

> table(newOrder$Cluster)
3  2  4  1  5
7  8 12  3  2
</code>```

Body:
I recently did some work on how to put silhouette (or k-means ) cluster tree  into pheatmap row cluster tree.

But there is something wrong with my ideas.

Firstly, I want to get the better or best cluster groups by function fviz_nbclust. But it doesn't mean I must use the clusters. I may choose k=5 here.

Then I get the clusters and numbers in each group:

cluster size ave.sil.width
 1       1    6          0.44
 2       2   11          0.44
 3       3    6          0.59
 4       4    5          0.33
 5       5    4          0.56
##

And then,I want to put this cluster result into pheatmap with the same cluster trees.

However, in the end, the same clusters with different cluster tree leaves:

**> table(newOrder$Cluster)
3  2  4  1  5
7  8 12  3  2**

So I don't know how to keep the two results the same. I mean,use the first cluster result instead of the second one.

I looked up very many materials but I didn't have any ideas to solve my problem.

Could somebody give me some help? I'd be very thankful.

Here is my code:

dataa<-mtcars
fviz_nbclust(dataa, pam, method = "silhouette")+ theme_classic()
##
pam.res3 <- pam(dataa, k =5,  metric = "euclidean", stand = FALSE)

fviz_silhouette(pam.res3, palette = "jco", ggtheme = theme_classic())

##
# cluster size ave.sil.width
# 1       1    6          0.44
# 2       2   11          0.44
# 3       3    6          0.59
# 4       4    5          0.33
# 5       5    4          0.56

# order for rows
Rowv  <- dataa %>% scale %>% dist %>% hclust %>% as.dendrogram %>%
  set("branches_k_color", k = 5) %>% set("branches_lwd", 1.2) %>%
  ladderize
# Order for columns: We must transpose the data
Colv  <- data %>% scale %>% t %>% dist %>% hclust %>% as.dendrogram %>%
  set("branches_k_color", k = 2, value = c("orange", "blue")) %>%
  set("branches_lwd", 1.2) %>%
  ladderize

pheatmap(dataa,
         clustering_distance_rows = "euclidean",
         clustering_method = "complete",
         cluster_rows = T,
         cutree_rows = 5
         )
pp<-pheatmap(scale(dataa), Rowv = Rowv, Colv = Colv,
         clustering_distance_rows = "euclidean",
         clustering_method = "complete",
         cluster_rows = T,
         cutree_rows = 5
)

result = dataa[pp$tree_row$order,]

########
row_cluster <- cutree(pp$tree_row,k=5)
## order
newOrder <- dataa[pp$tree_row$order,]
newOrder[,ncol(newOrder)+1]=row_cluster[match(rownames(newOrder),names(row_cluster))]
colnames(newOrder)[ncol(newOrder)]="Cluster"
newOrder$Cluster<-factor(newOrder$Cluster,levels = unique(newOrder$Cluster))
table(newOrder$Cluster)

> table(newOrder$Cluster)
3  2  4  1  5
7  8 12  3  2


来源: stackexchange

问:
How to guess/find types for strict usage of Typescript
I wish to use Typescript in strict mode in my projects and I have the following problem.
I don't seem to always be able to find the type to specify.

Let me give an example.
Let's say I am using a third party library and assuming it has types definition.

```<code>import {foo} from "someLibrary"

foo((a, b) => {}); //foo function has a callback parameter

</code>```

How am I suppose to get the type of a and b (stating that it is not explicitly written in the doc) ?

Wanted result :

```<code>foo((a: typeOfA, b: typeOfB) => {});
</code>```

For a more concrete example, let's take findOne of mongoose :

```<code>Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});
</code>```

How am I suppose to get the type of err and adventure ?

If this post is not clear enough, don't hesitate to ask for edit.

Thank you

ContentLicense: CC BY-SA 4.0

Body:
I wish to use Typescript in strict mode in my projects and I have the following problem.
I don't seem to always be able to find the type to specify.

Let me give an example.
Let's say I am using a third party library and assuming it has types definition.

import {foo} from "someLibrary"

foo((a, b) => {}); //foo function has a callback parameter

How am I suppose to get the type of a and b (stating that it is not explicitly written in the doc) ?

Wanted result :

foo((a: typeOfA, b: typeOfB) => {});

For a more concrete example, let's take findOne of mongoose :

Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});

How am I suppose to get the type of err and adventure ?

If this post is not clear enough, don't hesitate to ask for edit.

Thank you


问:
link 2 subdomains in Firebase one for web and the other for dynamic links
So I have already configured 2 sub domains in Firebase hosting and I have a Flutter web version app it's running on these domains but I also want to use dynamic links and I linked one of these sub domains to it and to my Flutter app but whenever I generate a dynamic link it navigates me to the web version

This is my firebase.json file

```<code>{
  "hosting": {
    "public": "build/web",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      },
      { "source": "/**", "dynamicLinks": true },

      {
        "source": "/links/**",
        "dynamicLinks": true
      }
    ]
  }
}
</code>```

EDIT:
I tried to move the last part /links/ before the destination part but when generating the long url in the app I get the same error page wasn't found

this is my code :

```<code>  FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

  Future<String> builDynamicLinks(String? id, {bool isFamily = false}) async {
    final DynamicLinkParameters parameters = DynamicLinkParameters(
      // The Dynamic Link URI domain. You can view created URIs on your Firebase console
      uriPrefix: 'https://links.nanny-finder.app/links',

      // The deep Link passed to your application which you can use to affect change
      link: Uri.parse(
          'https://links.nanny-finder.app/links/${isFamily ? "families" : "nannies"}?id=$id'),

      // Android application details needed for opening correct app on device/Play Store
      androidParameters: AndroidParameters(
          packageName: 'com.mickaelrobin.nannyfinderuae',
          fallbackUrl: playStore),

      // iOS application details needed for opening correct app on device/App Store
      iosParameters: IOSParameters(
          bundleId: 'com.mickaelrobin.nannyfinderuae', fallbackUrl: appStore),
    );

    final Uri uri = await dynamicLinks.buildLink(parameters);
    print(uri);
    return uri.toString();
  }
</code>```

and this is firebase console

Body:
So I have already configured 2 sub domains in Firebase hosting and I have a Flutter web version app it's running on these domains but I also want to use dynamic links and I linked one of these sub domains to it and to my Flutter app but whenever I generate a dynamic link it navigates me to the web version

This is my firebase.json file

{
  "hosting": {
    "public": "build/web",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      },
      { "source": "/**", "dynamicLinks": true },

      {
        "source": "/links/**",
        "dynamicLinks": true
      }
    ]
  }
}

EDIT:
I tried to move the last part /links/ before the destination part but when generating the long url in the app I get the same error page wasn't found

this is my code :

  FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

  Future<String> builDynamicLinks(String? id, {bool isFamily = false}) async {
    final DynamicLinkParameters parameters = DynamicLinkParameters(
      // The Dynamic Link URI domain. You can view created URIs on your Firebase console
      uriPrefix: 'https://links.nanny-finder.app/links',

      // The deep Link passed to your application which you can use to affect change
      link: Uri.parse(
          'https://links.nanny-finder.app/links/${isFamily ? "families" : "nannies"}?id=$id'),

      // Android application details needed for opening correct app on device/Play Store
      androidParameters: AndroidParameters(
          packageName: 'com.mickaelrobin.nannyfinderuae',
          fallbackUrl: playStore),

      // iOS application details needed for opening correct app on device/App Store
      iosParameters: IOSParameters(
          bundleId: 'com.mickaelrobin.nannyfinderuae', fallbackUrl: appStore),
    );

    final Uri uri = await dynamicLinks.buildLink(parameters);
    print(uri);
    return uri.toString();
  }

and this is firebase console


问:
How to set default value for Dry::Validation::Contract
I have the following contract and I would like to somehow set apikey to default to whatever is set in ENV.fetch('MY_ENV') so that users don't have to pass apikey param to every contract. I'd like it be injected automatically somehow if possible.

require 'dry-validation'

class BaseContract < Dry::Validation::Contract
  params do
    required(:apikey).value(:string)
  end

  rule(:apikey) do
    key.failure("must provide 'apikey'. Please set 'TICKETMASTER_API_KEY' in your environment")
  end
end

class Event < BaseContract
  params do
    required(:id).value(:string)
  end
end

event = Event.new
event.call(id: '123') # <= I'd like :apikey to be automatically set here
```

Is it possible?

Body:
I have the following contract and I would like to somehow set apikey to default to whatever is set in ENV.fetch('MY_ENV') so that users don't have to pass apikey param to every contract. I'd like it be injected automatically somehow if possible.

require 'dry-validation'

class BaseContract < Dry::Validation::Contract
  params do
    required(:apikey).value(:string)
  end

  rule(:apikey) do
    key.failure("must provide 'apikey'. Please set 'TICKETMASTER_API_KEY' in your environment")
  end
end

class Event < BaseContract
  params do
    required(:id).value(:string)
  end
end

event = Event.new
event.call(id: '123') # <= I'd like :apikey to be automatically set here

Is it possible?


问:
php-fpm usage high very high cpu wordpress aws
I am using PHP 7.4 and it was working well for weeks. Suddenly each PHP-FPM child started taking too much memory. In initial weeks each PHP-FPM child used to take 40% cpu now few children are taking 90%cpu. Can anybody guide on this?

i allowed max 5 children process but nothing


问:
boxplot scatterplot from r to python
I am trying to port some code from R to python, but I am encountering some difficulties with plotting.

The simplest example I can give is the following:

```<code>library(ggplot2)
df1=data.frame(a_class=letters[1:10], vals=sample(10, replace=TRUE))

ggplot(df1, aes(x=0, y=vals))+
  geom_boxplot()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+
  geom_jitter(aes(shape=a_class, color=a_class), height = 0)+
  scale_shape_manual(values = 1:nrow(df1))
</code>```

This code produces this image (it may be slightly different each time since sample is random).

How can I achieve this in seaborn or matplotlib?
I tried:

```<code>df1 = pd.DataFrame({"a_class": list("abcdefghij"), "vals": [1,2,3,4,5,6,7,8,9,10]})
sns.boxplot(x=0, y="vals", data=df1)
sns.stripplot(x=0, y="vals", data=df1, jitter=True, hue="a_class", palette="Set1")
</code>```

But I get the following error:

```<code>AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_5696\451374326.py in <module>
      1 df1 = pd.DataFrame({"a_class": list("abcdefghij"), "vals": [1,2,3,4,5,6,7,8,9,10]})
      2
----> 3 sns.boxplot(x=0, y="vals", data=df1)
      4 sns.stripplot(x=0, y="vals", data=df1, jitter=True, hue="a_class", palette="Set1")

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\_decorators.py in inner_f(*args, **kwargs)
     44             )
     45         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46         return f(**kwargs)
     47     return inner_f
     48

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth, whis, ax, **kwargs)
   2241 ):
   2242
-> 2243     plotter = _BoxPlotter(x, y, hue, data, order, hue_order,
   2244                           orient, color, palette, saturation,
   2245                           width, dodge, fliersize, linewidth)

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\categorical.py in __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth)
    404                  width, dodge, fliersize, linewidth):
    405
--> 406         self.establish_variables(x, y, hue, data, orient, order, hue_order)
    407         self.establish_colors(color, palette, saturation)
    408

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\categorical.py in establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
    154
    155             # Figure out the plotting orientation
--> 156             orient = infer_orient(
    157                 x, y, orient, require_numeric=self.require_numeric
    158             )

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\_core.py in infer_orient(x, y, orient, require_numeric)
   1309     """
   1310
-> 1311     x_type = None if x is None else variable_type(x)
   1312     y_type = None if y is None else variable_type(y)
   1313

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\_core.py in variable_type(vector, boolean_type)
   1227
   1228     # Special-case all-na data, which is always "numeric"
-> 1229     if pd.isna(vector).all():
   1230         return "numeric"
   1231

AttributeError: 'bool' object has no attribute 'all'
</code>```

Title: boxplot scatterplot from r to python

Body:
I am trying to port some code from R to python, but I am encountering some difficulties with plotting.

The simplest example I can give is the following:

library(ggplot2)
df1=data.frame(a_class=letters[1:10], vals=sample(10, replace=TRUE))

ggplot(df1, aes(x=0, y=vals))+
  geom_boxplot()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+
  geom_jitter(aes(shape=a_class, color=a_class), height = 0)+
  scale_shape_manual(values = 1:nrow(df1))

This code produces this image (it may be slightly different each time since sample is random).

How can I achieve this in seaborn or matplotlib?
I tried:

df1 = pd.DataFrame({"a_class": list("abcdefghij"), "vals": [1,2,3,4,5,6,7,8,9,10]})
sns.boxplot(x=0, y="vals", data=df1)
sns.stripplot(x=0, y="vals", data=df1, jitter=True, hue="a_class", palette="Set1")

But I get the following error:

AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_5696\451374326.py in <module>
      1 df1 = pd.DataFrame({"a_class": list("abcdefghij"), "vals": [1,2,3,4,5,6,7,8,9,10]})
      2
----> 3 sns.boxplot(x=0, y="vals", data=df1)
      4 sns.stripplot(x=0, y="vals", data=df1, jitter=True, hue="a_class", palette="Set1")

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\_decorators.py in inner_f(*args, **kwargs)
     44             )
     45         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46         return f(**kwargs)
     47     return inner_f
     48

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth, whis, ax, **kwargs)
   2241 ):
   2242
-> 2243     plotter = _BoxPlotter(x, y, hue, data, order, hue_order,
   2244                           orient, color, palette, saturation,
   2245                           width, dodge, fliersize, linewidth)

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\categorical.py in __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth)
    404                  width, dodge, fliersize, linewidth):
    405
--> 406         self.establish_variables(x, y, hue, data, orient, order, hue_order)
    407         self.establish_colors(color, palette, saturation)
    408

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\categorical.py in establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
    154
    155             # Figure out the plotting orientation
--> 156             orient = infer_orient(
    157                 x, y, orient, require_numeric=self.require_numeric
    158             )

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\_core.py in infer_orient(x, y, orient, require_numeric)
   1309     """
   1310
-> 1311     x_type = None if x is None else variable_type(x)
   1312     y_type = None if y is None else variable_type(y)
   1313

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\_core.py in variable_type(vector, boolean_type)
   1227
   1228     # Special-case all-na data, which is always "numeric"
-> 1229     if pd.isna(vector).all():
   1230         return "numeric"
   1231

AttributeError: 'bool' object has no attribute 'all'


问:
Flutter Platform Channel to Android Kotlin can't find implementation of method
I'm programming a Flutter project that uses the azure Speech SDK services. Because I can't use the Speech SDK directly with dart, I'm using a Flutter Platform Channel to run Android native Kotlin Code for the implementation of the azure services. At first I programmed everything directly into the Android MainActivity.kt file like described in this guide and that worked fine, but because I plan to use multiple azure services and multiple platform channels that would become very confusing. So I tried to create different classes in different Kotlin files (code of one class below). The problem is now that the Platform Channel doesn't find the implementation.

Every time I call the the azureTTS method, this error is returned:

```<code>E/flutter ( 6695): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method speak on channel azure_speech) E/flutter ( 6695): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:294:7) E/flutter ( 6695): <asynchronous suspension> E/flutter ( 6695): #1      AzureSpeech.azureTTS (package:test/services/azure/speech/speech.dart:21:7) E/flutter ( 6695): <asynchronous suspension>
</code>```

Implementation on dart side:

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

class AzureSpeech {

  final MethodChannel azureSpeechChannel = const MethodChannel("azure_speech");

  void azureTTS({required String text}) async {
    var arguments = {
      "text": text,
      "voiceName": "en-US-JennyNeural",
    };

    try {
      await azureSpeechChannel.invokeMethod("speak", arguments);
    } on PlatformException catch (e) {
      print("Failed to start azure TTS: '${e.message}'.");
    }
  }
}
</code>```

Implementation on Android native side:

```<code>package com.example.test.azure

import android.app.Activity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.ExecutionException

class Speech: FlutterPlugin, Activity(), MethodChannel.MethodCallHandler {
    private lateinit var azureSpeechChannel : MethodChannel

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        azureSpeechChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "azure_speech")
        azureSpeechChannel.setMethodCallHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        azureSpeechChannel.setMethodCallHandler(null)
    }

     override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "speak") {
            speak(text = call.argument<String>("text")!!, voice = call.argument<String>("voiceName")!!)
            result.success(true)
        }
        else{
            result.notImplemented()
        }
    }

    fun speak(text: String, voice: String) {
        //speak method
    }
}
</code>```

I tried adding a Activity in the AndroidManifest.xml file as following, but I don't know if that's what I have to do or how to do it correctly.

```<code><activity android:name=".azure.Speech"/>
</code>```

Do I have to add anything to the Manifest.xml or the pubspec.yaml file?

Body:
I'm programming a Flutter project that uses the azure Speech SDK services. Because I can't use the Speech SDK directly with dart, I'm using a Flutter Platform Channel to run Android native Kotlin Code for the implementation of the azure services. At first I programmed everything directly into the Android MainActivity.kt file like described in this guide and that worked fine, but because I plan to use multiple azure services and multiple platform channels that would become very confusing. So I tried to create different classes in different Kotlin files (code of one class below). The problem is now that the Platform Channel doesn't find the implementation.

Every time I call the the azureTTS method, this error is returned:

E/flutter ( 6695): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method speak on channel azure_speech) E/flutter ( 6695): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:294:7) E/flutter ( 6695): <asynchronous suspension> E/flutter ( 6695): #1      AzureSpeech.azureTTS (package:test/services/azure/speech/speech.dart:21:7) E/flutter ( 6695): <asynchronous suspension>

Implementation on dart side:

import 'package:flutter/services.dart';

class AzureSpeech {

  final MethodChannel azureSpeechChannel = const MethodChannel("azure_speech");

  void azureTTS({required String text}) async {
    var arguments = {
      "text": text,
      "voiceName": "en-US-JennyNeural",
    };

    try {
      await azureSpeechChannel.invokeMethod("speak", arguments);
    } on PlatformException catch (e) {
      print("Failed to start azure TTS: '${e.message}'.");
    }
  }
}

Implementation on Android native side:

package com.example.test.azure

import android.app.Activity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.ExecutionException

class Speech: FlutterPlugin, Activity(), MethodChannel.MethodCallHandler {
    private lateinit var azureSpeechChannel : MethodChannel

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        azureSpeechChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "azure_speech")
        azureSpeechChannel.setMethodCallHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        azureSpeechChannel.setMethodCallHandler(null)
    }

     override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "speak") {
            speak(text = call.argument<String>("text")!!, voice = call.argument<String>("voiceName")!!)
            result.success(true)
        }
        else{
            result.notImplemented()
        }
    }

    fun speak(text: String, voice: String) {
        //speak method
    }
}

I tried adding a Activity in the AndroidManifest.xml file as following, but I don't know if that's what I have to do or how to do it correctly.

<activity android:name=".azure.Speech"/>

Do I have to add anything to the Manifest.xml or the pubspec.yaml file?


问:
Telegram bot unban command
This is my code to unban a user by replying to a message previously left by the user in the bot. But I also want to implement the /unban id command to be able to unban a user by their id. But I don't know how to do it. Please, help.

@bot.message_handler(commands=["unban"], func=Filters.is_answer)
def unblock(message):
    user_id = (
        Message.select()
        .where(Message.id == message.reply_to_message.message_id)
        .get()
        .from_
    )
    try:
        Block.select().where(Block.user_id == user_id).get().delete_instance()
        bot.send_message(user_id, "you have been unbanned"),
    except Block.DoesNotExist:
        pass

    bot.send_message(
        message.chat.id, ("{user_id} has been unbanned").format(user_id=user_id)
    )
```

I thought to just read the entire contents of the /unban command through message.text, but I didn’t see any errors, but the command stopped working

Title: Telegram bot unban command

Body:
This is my code to unban a user by replying to a message previously left by the user in the bot. But I also want to implement the /unban id command to be able to unban a user by their id. But I don't know how to do it. Please, help.

@bot.message_handler(commands=["unban"], func=Filters.is_answer)
def unblock(message):
    user_id = (
        Message.select()
        .where(Message.id == message.reply_to_message.message_id)
        .get()
        .from_
    )
    try:
        Block.select().where(Block.user_id == user_id).get().delete_instance()
        bot.send_message(user_id, "you have been unbanned"),
    except Block.DoesNotExist:
        pass

    bot.send_message(
        message.chat.id, ("{user_id} has been unbanned").format(user_id=user_id)
    )

I thought to just read the entire contents of the /unban command through message.text, but I didn’t see any errors, but the command stopped working


问:
Run sql query through SQL agent job across all Databases
I am trying to run the following query across all databases in one instance through SQL agent job(except master db), which is basically used for index optimization

I have created the agent job but runs through only one database. Help is appreciated. I have attached Agent job, how I have created

```<code>USE [DBNAME]

SET NOCOUNT ON

DECLARE @Objectid INT, @Indexid INT,
        @schemaname VARCHAR(100), @tablename VARCHAR(300),
        @ixname VARCHAR(500),
        @avg_fragment float, @command VARCHAR(4000)

DECLARE AWS_Cusrsor CURSOR FOR
    SELECT
        A.object_id, A.index_id,
        QUOTENAME(SS.NAME) AS schemaname,
        QUOTENAME(OBJECT_NAME(B.object_id, B.database_id)) AS tablename,
        QUOTENAME(A.name) AS ixname,
        B.avg_fragmentation_in_percent AS avg_fragment
    FROM
        sys.indexes A
    INNER JOIN
        sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS B ON A.object_id = B.object_id
                                                                                AND A.index_id = B.index_id
    INNER JOIN
        sys.OBJECTS OS ON A.object_id = OS.object_id
    INNER JOIN
        sys.schemas SS ON OS.schema_id = SS.schema_id
    WHERE
        B.avg_fragmentation_in_percent > 30
        AND A.index_id > 0
        AND A.IS_DISABLED <> 1
    ORDER BY
        tablename,ixname

OPEN AWS_Cusrsor

FETCH NEXT FROM AWS_Cusrsor INTO @Objectid, @Indexid, @schemaname, @tablename, @ixname, @avg_fragment

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @avg_fragment >= 30.0
    BEGIN
        SET @command = N'ALTER INDEX '+@ixname+N' ON '+@schemaname+N'.'+ @tablename+N' REBUILD '+N' WITH (ONLINE = ON)';
        SET @command = N'ALTER INDEX '+@ixname+N' ON '+@schemaname+N'.'+ @tablename+N' REORGANIZE';
    END

    EXEC(@command)

    FETCH NEXT FROM AWS_Cusrsor INTO @Objectid, @Indexid, @schemaname, @tablename, @ixname, @avg_fragment
END

CLOSE AWS_Cusrsor
DEALLOCATE AWS_Cusrsor
</code>```

Body:
I am trying to run the following query across all databases in one instance through SQL agent job(except master db), which is basically used for index optimization

I have created the agent job but runs through only one database. Help is appreciated. I have attached Agent job, how I have created

USE [DBNAME]

SET NOCOUNT ON

DECLARE @Objectid INT, @Indexid INT,
        @schemaname VARCHAR(100), @tablename VARCHAR(300),
        @ixname VARCHAR(500),
        @avg_fragment float, @command VARCHAR(4000)

DECLARE AWS_Cusrsor CURSOR FOR
    SELECT
        A.object_id, A.index_id,
        QUOTENAME(SS.NAME) AS schemaname,
        QUOTENAME(OBJECT_NAME(B.object_id, B.database_id)) AS tablename,
        QUOTENAME(A.name) AS ixname,
        B.avg_fragmentation_in_percent AS avg_fragment
    FROM
        sys.indexes A
    INNER JOIN
        sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS B ON A.object_id = B.object_id
                                                                                AND A.index_id = B.index_id
    INNER JOIN
        sys.OBJECTS OS ON A.object_id = OS.object_id
    INNER JOIN
        sys.schemas SS ON OS.schema_id = SS.schema_id
    WHERE
        B.avg_fragmentation_in_percent > 30
        AND A.index_id > 0
        AND A.IS_DISABLED <> 1
    ORDER BY
        tablename,ixname

OPEN AWS_Cusrsor

FETCH NEXT FROM AWS_Cusrsor INTO @Objectid, @Indexid, @schemaname, @tablename, @ixname, @avg_fragment

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @avg_fragment >= 30.0
    BEGIN
        SET @command = N'ALTER INDEX '+@ixname+N' ON '+@schemaname+N'.'+ @tablename+N' REBUILD '+N' WITH (ONLINE = ON)';
        SET @command = N'ALTER INDEX '+@ixname+N' ON '+@schemaname+N'.'+ @tablename+N' REORGANIZE';
    END

    EXEC(@command)

    FETCH NEXT FROM AWS_Cusrsor INTO @Objectid, @Indexid, @schemaname, @tablename, @ixname, @avg_fragment
END

CLOSE AWS_Cusrsor
DEALLOCATE AWS_Cusrsor


问:
Flutter getApplicationDocumentsDirectory() returns a path different from Device file explorer
My getApplicationDocumentsDirectory() is returning me

/data/user/0/com.my.applicationname/app_flutter

While when using the device file explorer(and using "copy path" option),this directory comes up as

/data/data/com.my.applicationname/app_flutter

This is causing issues as when I try to play a file stored using above path prefix(using the uri as Uri.file(fileNameFromAbovePrefix), the file is not being found(whereas if I manually copy the path from device explorer and paste in Uri.file, it works).

My path_provider pluting version is ^2.0.1

So how do I get the path that actually works with uri(in a reliable way across all android devices)?


问:
stripe successUrl function get status paid
I use

```<code>stripe.redirectToCheckout
</code>```

After pay its just redirect user to successes page.

But how to add user to DB with status - paid ?

Body:
I use

stripe.redirectToCheckout

After pay its just redirect user to successes page.

But how to add user to DB with status - paid ?


问:
Error This MySqlConnection is already in use thrown with EFCore
I get a "This MySqlConnection is already in use" error on this part of my code:

```<code>public async Task<IEnumerable<Track>> FindByArtistIdAsync(string artistId)
{
    var tracks = await FullCollection
        .Where(t => t.Artists.Select(a => a.ArtistId).Contains(artistId))
        .ToListAsync();
    return tracks;
}
</code>```

The FullCollection is defined like this: public IQueryable<Track> FullCollection => _context.Tracks.Include(t => t.Artists);

With protected DatabaseContext _context;.
And in the DatabaseContext class: public DbSet<Track> Tracks { get; set; }

The complete error message looks like this:

fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'DatabaseContext'.
      System.InvalidOperationException: This MySqlConnection is already in use. See https://fl.vu/mysql-conn-reuse
         at MySqlConnector.Core.ServerSession.StartQuerying(ICancellableCommand command) in /_/src/MySqlConnector/Core/ServerSession.cs:line 283
         at MySqlConnector.Core.CommandExecutor.ExecuteReaderAsync(IReadOnlyList`1 commands, ICommandPayloadCreator payloadCreator, CommandBehavior behavior, Activity activity, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/Core/CommandExecutor.cs:line 51
         at MySqlConnector.MySqlCommand.ExecuteReaderAsync(CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlCommand.cs:line 344
```
</blockquote>
<p>The Track class has an attribute that stores a List of Artist.</p>
<p>I tried reformulating the query like this:</p>
```var tracks = new List<Track>();
foreach (var track in FullCollection)
{
    foreach (var artist in track.Artists)
    {
        if (artist.ArtistId == artistId) {
            tracks.Add(track);
        }
    }
}
```

I read that it might help to use .ToList() instead of .ToListAsync().
But that didnt help.

Body:
I get a "This MySqlConnection is already in use" error on this part of my code:

public async Task<IEnumerable<Track>> FindByArtistIdAsync(string artistId)
{
    var tracks = await FullCollection
        .Where(t => t.Artists.Select(a => a.ArtistId).Contains(artistId))
        .ToListAsync();
    return tracks;
}

The FullCollection is defined like this: public IQueryable<Track> FullCollection => _context.Tracks.Include(t => t.Artists);

With protected DatabaseContext _context;.
And in the DatabaseContext class: public DbSet<Track> Tracks { get; set; }

The complete error message looks like this:

fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'DatabaseContext'.
      System.InvalidOperationException: This MySqlConnection is already in use. See https://fl.vu/mysql-conn-reuse
         at MySqlConnector.Core.ServerSession.StartQuerying(ICancellableCommand command) in /_/src/MySqlConnector/Core/ServerSession.cs:line 283
         at MySqlConnector.Core.CommandExecutor.ExecuteReaderAsync(IReadOnlyList`1 commands, ICommandPayloadCreator payloadCreator, CommandBehavior behavior, Activity activity, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/Core/CommandExecutor.cs:line 51
         at MySqlConnector.MySqlCommand.ExecuteReaderAsync(CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlCommand.cs:line 344

The Track class has an attribute that stores a List of Artist.

I tried reformulating the query like this:

var tracks = new List<Track>();
foreach (var track in FullCollection)
{
    foreach (var artist in track.Artists)
    {
        if (artist.ArtistId == artistId) {
            tracks.Add(track);
        }
    }
}

I read that it might help to use .ToList() instead of .ToListAsync().
But that didnt help.


问:
Getting frequent D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: failed to connect to <server-ip> from <client-ip>
Getting frequent D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: failed to connect to / (port 8443) from / (port 50810) after 60000ms: isConnected failed: ETIMEDOUT (Connection timed out)

I am getting frequent(one in 10 times average) D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException from my servers and I have set all timeouts(read, write, connect) to 60seconds but I get this exception in 8-10 seconds and there are no hits on my server for these requests.

Some of the previously closed issues(#6486) discuss IPv4 vs IPv6 issues at the client and/or server-side but my server supports only IPv4 and I made the client(android device) use IPv4 only still I am receiving this.

Can someone please help here,

Deps used -

```<code>implementation 'com.squareup.retrofit2:retrofit:2.7.1'
implementation "com.squareup.retrofit2:converter-moshi:2.6.2"
implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.7.1'
implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'
</code>```

Body:
Getting frequent D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: failed to connect to / (port 8443) from / (port 50810) after 60000ms: isConnected failed: ETIMEDOUT (Connection timed out)

I am getting frequent(one in 10 times average) D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException from my servers and I have set all timeouts(read, write, connect) to 60seconds but I get this exception in 8-10 seconds and there are no hits on my server for these requests.

Some of the previously closed issues(#6486) discuss IPv4 vs IPv6 issues at the client and/or server-side but my server supports only IPv4 and I made the client(android device) use IPv4 only still I am receiving this.

Can someone please help here,

Deps used -

implementation 'com.squareup.retrofit2:retrofit:2.7.1'
implementation "com.squareup.retrofit2:converter-moshi:2.6.2"
implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.7.1'
implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'


问:
Text to audio engine is omitting first word
Why is it that pyttsx3 engine fails to read the first character or word and how can I fix it.

When I supply text it always reads from the second word


问:
multiple animations (timeline) in react-spring
I have a component with 2 Boxes and a shadow:

First Box is outside the view: topBox
Second Box is inside the view at the bottom: middleBox
Third is the shadow of the Box on the bottom (a png): Shadow

If i start the animation (or if the component loads) i want to have the following animation:

Step 1

middleBox move up 50px

shadow grows (from scale(0.8) to scale(1))

Step 2

topBox moves down 50px into the view

Step 3

(this animation should look like the two boxes smash into each other, like if if they would crash. like two balls hitting each other and go back to origin.)

middleBox moves up 20px and back down 20px

topBox moves down 20px and back up 20px

Shadow scales 1.1 and back to 1

Step 4

topBox moves back outside the view

So i created useSprings for all steps and i tried to update state when the first animation finished based on this update the other animation. i also tried with useChain to have the animations together. But nothing seems to work.

so i would have state

```<code>const [isAnimationMove, setAnimationMove] = useState(true)
const [isAnimationHit, setIsAnimationHit] = useState(false)
</code>```

and then change the state after the second animation finishes to trigger the new animations

```<code>const topBoxMoveDown = useSpring({
    from: { transform: 'translate(-20%, 100%)' },
    transform: 'translate(-10%, 60%)',
    onRest: () => {
        setAnimationMove(false);
        setIsAnimationHit(true);
    }
</code>```

and render the different animation on the element

```<code> <BoxFromTop
     animationStyle={
        isAnimationMove ? topBoxMoveDown :
        isAnimationHit ? topBoxHit : null } />
</code>```

which is

```<code>const topBoxHit = useSpring({
    from: { transform: 'translate(-10%, 60%) rotate(0)' },
    transform: 'translate(-10%, 55%) rotate(10deg)',
    reset: true,
});
</code>```

However it works kind of as long as i would not use transform again in the topHitBox but i think my question is more about the concept in general:

How do i animate different states and have control over what starts when and what follows what. I mean i just be a simple animation with multiple steps but i can not get my head around how this works with react-spring. Am i using the wrong library? is there a better one to use for this? or did i just use the wrong approach?

Body:
I have a component with 2 Boxes and a shadow:

First Box is outside the view: topBox
Second Box is inside the view at the bottom: middleBox
Third is the shadow of the Box on the bottom (a png): Shadow

If i start the animation (or if the component loads) i want to have the following animation:

Step 1

middleBox move up 50px

shadow grows (from scale(0.8) to scale(1))

Step 2

topBox moves down 50px into the view

Step 3

(this animation should look like the two boxes smash into each other, like if if they would crash. like two balls hitting each other and go back to origin.)

middleBox moves up 20px and back down 20px

topBox moves down 20px and back up 20px

Shadow scales 1.1 and back to 1

Step 4

topBox moves back outside the view

So i created useSprings for all steps and i tried to update state when the first animation finished based on this update the other animation. i also tried with useChain to have the animations together. But nothing seems to work.

so i would have state

const [isAnimationMove, setAnimationMove] = useState(true)
const [isAnimationHit, setIsAnimationHit] = useState(false)

and then change the state after the second animation finishes to trigger the new animations

const topBoxMoveDown = useSpring({
    from: { transform: 'translate(-20%, 100%)' },
    transform: 'translate(-10%, 60%)',
    onRest: () => {
        setAnimationMove(false);
        setIsAnimationHit(true);
    }

and render the different animation on the element

 <BoxFromTop
     animationStyle={
        isAnimationMove ? topBoxMoveDown :
        isAnimationHit ? topBoxHit : null } />

which is

const topBoxHit = useSpring({
    from: { transform: 'translate(-10%, 60%) rotate(0)' },
    transform: 'translate(-10%, 55%) rotate(10deg)',
    reset: true,
});

However it works kind of as long as i would not use transform again in the topHitBox but i think my question is more about the concept in general:

How do i animate different states and have control over what starts when and what follows what. I mean i just be a simple animation with multiple steps but i can not get my head around how this works with react-spring. Am i using the wrong library? is there a better one to use for this? or did i just use the wrong approach?


问:
how to withot reload page call api.services.js externl file
```<code>api.service.js

const shop = localStorage.getItem('shopid');
async getProduct() {
    return axios.get(API_URL+'/product/all?installation_id='+shop, { headers: authHeader() })
    .then((res) => res.data);

  }
</code>```

AppTopbar.vue

```<code>            <Dropdown v-model="selected" :options="storesLists" @change="onChange" optionLabel="name" :filter="true"  />

  onChange(event) {
        console.log(event.value);
         localStorage.setItem('shopid',event.value);

         }
</code>```

here AppTopbar is common for all vue files(ex.products.vue,bill.vue).
if i change dropdown it set to localStorage then get data like id wise(axios.get(API_URL+'/product/all?installation_id='+shop).

its working fine but i only reload then get record.

how to withot reload page call api.services.js externl file.

Body:
api.service.js

const shop = localStorage.getItem('shopid');
async getProduct() {
    return axios.get(API_URL+'/product/all?installation_id='+shop, { headers: authHeader() })
    .then((res) => res.data);

  }

AppTopbar.vue

            <Dropdown v-model="selected" :options="storesLists" @change="onChange" optionLabel="name" :filter="true"  />

  onChange(event) {
        console.log(event.value);
         localStorage.setItem('shopid',event.value);

         }

here AppTopbar is common for all vue files(ex.products.vue,bill.vue).
if i change dropdown it set to localStorage then get data like id wise(axios.get(API_URL+'/product/all?installation_id='+shop).

its working fine but i only reload then get record.

how to withot reload page call api.services.js externl file.


问:
Is there a way to add a JLabel from a class to another CardLayout?
I'm doing a project for school and my goal here is to design a gallery on Swing. One of the features is the possibility to add new images to my gallery and display the new picture. I created a card where you can add your picture by browsing the file explorer on your computer and then it will copy and add the file to the folder of the app. For the moment this part works fine, but when I go back to my GalleryPage CardLayout the image is not displayed (because I don't know how to add it directly). What I'm trying to do is add this new image to the bottomPanel of my GalleryPage java class from newImg [JLabel] on my NewImage java class. Is there a way to do that? I've been browsing the Internet to find an answer but I can't find a solution.

Here is my code:

Gallery.java

public class Gallery extends JPanel {
    private GalleryPage panelGalleryPage;
    private NewImage newImage;
    protected static CardLayout cardGal;

    public Gallery() {
        super();
        setLayout(new CardLayout());
        cardGal = (CardLayout) this.getLayout();
        panelGalleryPage = new GalleryPage();
        newImage = new NewImage();
        add(panelGalleryPage, "GalleryPage");
        add(newImage, "NewImage");
    }
}
```
<p><strong>GalleryPage.java</strong></p>
<pre class="lang-java prettyprint-override"><code>public class GalleryPage extends JPanel {

    // preparing my grid of images by sorting the filepath of each image.
    File directory = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images");

    int fileCount = directory.list().length;
    private JButton addImg, delImg;
    private JLabel title;
    private JLabel[] cache = new JLabel[fileCount];
    private ImageIcon[] imgGrid = new ImageIcon[fileCount];
    private ImageIcon imgTitle, imgAdd, imgDel;
    private JSplitPane splitPanel;
    private JPanel bottomPanel, topPanel;
    private List<String> results;

    public GalleryPage() {
        super();
        setBackground(PowerOn.userInterface.DARK_GREY);
        initComponents();
    }

    public void initComponents() {

        // create a split pane
        splitPanel = new JSplitPane();

        topPanel = new JPanel(); // top component
        bottomPanel = new JPanel(); // bottom component

        // configure splitPanel
        splitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
        splitPanel.setDividerLocation(100);
        splitPanel.setDividerSize(0);
        splitPanel.setTopComponent(topPanel);
        splitPanel.setBottomComponent(bottomPanel);

        // create title
        imgTitle = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/images.png");
        imgTitle.setImage(imgTitle.getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT));
        title = new JLabel(imgTitle);

        // create add Button
        imgAdd = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/add.png");
        imgAdd.setImage(imgAdd.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
        addImg = new JButton(imgAdd);
        addImg.setPreferredSize(new Dimension(60, 40));

        // add Actionlisteneer to addImg Button
        addImg.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                Gallery.cardGal.show(PowerOn.gallery, "NewImage");
            }
        });

        // create delete Button
        imgDel = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/trash.png");
        imgDel.setImage(imgDel.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
        delImg = new JButton(imgDel);
        delImg.setPreferredSize(new Dimension(60, 40));

        // Add title and buttons to the topPanel
        topPanel.add(title);
        topPanel.add(addImg);
        topPanel.add(delImg);

        // add the splitPanel to the frame
        this.add(splitPanel);

        // set top and bottom panel Background
        topPanel.setBackground(PowerOn.userInterface.DARK_GREY);
        bottomPanel.setBackground(PowerOn.userInterface.DARK_GREY);

        // set a GridLayout for the bottomPanel
        this.setLayout(new GridLayout());
        GridLayout layout = new GridLayout(0, 3, 10, 10);
        bottomPanel.setLayout(layout);

        // creating an array of file
        results = new ArrayList<String>();
        File[] files = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images").listFiles();

        // retrieving the name of each images
        for (File file : files) {
            if (file.isFile()) {
                results.add(file.getName());
            }
        }

        // create an array of images
        for (int i = 0; i < fileCount; i++) {
            imgGrid[i] = new ImageIcon(files[i].toString());
        }

        // loop to sale and add the images to the bottomPanel
        for (int i = 0; i < files.length; i++) {
            // scaling the images
            imgGrid[i].setImage(imgGrid[i].getImage().getScaledInstance(120, 120,
                    Image.SCALE_SMOOTH));

            // add the images to the grid
            cache[i] = new JLabel(imgGrid[i]);
            bottomPanel.add(cache[i]);
        }
    }
}
</code>```

NewImage.java

public class NewImage extends JPanel {
    private JLabel title, newImg;
    private ImageIcon cacheImg;
    private JPanel display;
    private JButton choose, back;
    private JFileChooser file;
    private File selectedFile;
    private Gallery addNew;

    public NewImage() {
        super();
        setBackground(PowerOn.userInterface.DARK_GREY);
        initComponents();
    }

    public void initComponents() {

        // configure title JLabel
        title = new JLabel("Choose a new image to add (jpg or png only)");
        title.setHorizontalAlignment(title.CENTER);

        // configurin choose JButton + Actionlistener
        choose = new JButton("Explore");
        file = new JFileChooser();
        choose.setPreferredSize(new Dimension(60, 60));
        choose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                int result = file.showOpenDialog(display);
                if (result == JFileChooser.APPROVE_OPTION) {
                    selectedFile = file.getSelectedFile();

                    // check the type of the file only jpg and png accepted
                    String check = selectedFile.getAbsolutePath()
                            .substring(selectedFile.getAbsolutePath().length() - 3);
                    System.out.println(check);

                    // if the fil is ok add the file to the gallery directory
                    if (check.equals("png") || check.equals("jpg")) {

                        // retrieving the name of the file and copy on the galery folder
                        try {
                            String[] parts = selectedFile.getAbsolutePath().split(Pattern.quote(File.separator));
                            String dest = "oop_2022/src/main/java/com/phone/common/png/Galery_images/"
                                    + parts[parts.length - 1];
                            copyFile(selectedFile, new File(dest));
                            cacheImg = new ImageIcon(dest);
                            cacheImg.setImage(cacheImg.getImage().getScaledInstance(120, 120, Image.SCALE_DEFAULT));
                            newImg = new JLabel(cacheImg);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        JOptionPane.showMessageDialog(null, "Your image as been succesfully uploaded");
                    }

                    // if the file is not a png or a jpg display an error message
                    else {
                        JOptionPane.showMessageDialog(null, "You must choose a png or jpg file");
                    }
                }
            }
        });

        // configuring back JButton + Actionlistener
        back = new JButton("Return to home page");
        back.setPreferredSize(new Dimension(60, 60));
        back.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                Gallery.cardGal.show(PowerOn.gallery, "GalleryPage");
            }
        });

        // configure layout of panel
        this.setLayout(new GridLayout());

        // add panels
        display = new JPanel();
        display.setLayout(new GridLayout(0, 1));
        this.add(display);
        display.add(title);
        display.add(choose);
        display.add(back);
    }

    public static void copyFile(File from, File to) throws IOException {
        Files.copy(from.toPath(), new FileOutputStream(to));
    }
}
```

What I want is that the image I added is directly displayed without running the code again when I go back to my gallery page.

my gallery page

Body:
I'm doing a project for school and my goal here is to design a gallery on Swing. One of the features is the possibility to add new images to my gallery and display the new picture. I created a card where you can add your picture by browsing the file explorer on your computer and then it will copy and add the file to the folder of the app. For the moment this part works fine, but when I go back to my GalleryPage CardLayout the image is not displayed (because I don't know how to add it directly). What I'm trying to do is add this new image to the bottomPanel of my GalleryPage java class from newImg [JLabel] on my NewImage java class. Is there a way to do that? I've been browsing the Internet to find an answer but I can't find a solution.

Here is my code:

Gallery.java

public class Gallery extends JPanel {
    private GalleryPage panelGalleryPage;
    private NewImage newImage;
    protected static CardLayout cardGal;

    public Gallery() {
        super();
        setLayout(new CardLayout());
        cardGal = (CardLayout) this.getLayout();
        panelGalleryPage = new GalleryPage();
        newImage = new NewImage();
        add(panelGalleryPage, "GalleryPage");
        add(newImage, "NewImage");
    }
}

GalleryPage.java

public class GalleryPage extends JPanel {

    // preparing my grid of images by sorting the filepath of each image.
    File directory = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images");

    int fileCount = directory.list().length;
    private JButton addImg, delImg;
    private JLabel title;
    private JLabel[] cache = new JLabel[fileCount];
    private ImageIcon[] imgGrid = new ImageIcon[fileCount];
    private ImageIcon imgTitle, imgAdd, imgDel;
    private JSplitPane splitPanel;
    private JPanel bottomPanel, topPanel;
    private List<String> results;

    public GalleryPage() {
        super();
        setBackground(PowerOn.userInterface.DARK_GREY);
        initComponents();
    }

    public void initComponents() {

        // create a split pane
        splitPanel = new JSplitPane();

        topPanel = new JPanel(); // top component
        bottomPanel = new JPanel(); // bottom component

        // configure splitPanel
        splitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
        splitPanel.setDividerLocation(100);
        splitPanel.setDividerSize(0);
        splitPanel.setTopComponent(topPanel);
        splitPanel.setBottomComponent(bottomPanel);

        // create title
        imgTitle = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/images.png");
        imgTitle.setImage(imgTitle.getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT));
        title = new JLabel(imgTitle);

        // create add Button
        imgAdd = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/add.png");
        imgAdd.setImage(imgAdd.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
        addImg = new JButton(imgAdd);
        addImg.setPreferredSize(new Dimension(60, 40));

        // add Actionlisteneer to addImg Button
        addImg.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                Gallery.cardGal.show(PowerOn.gallery, "NewImage");
            }
        });

        // create delete Button
        imgDel = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/trash.png");
        imgDel.setImage(imgDel.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
        delImg = new JButton(imgDel);
        delImg.setPreferredSize(new Dimension(60, 40));

        // Add title and buttons to the topPanel
        topPanel.add(title);
        topPanel.add(addImg);
        topPanel.add(delImg);

        // add the splitPanel to the frame
        this.add(splitPanel);

        // set top and bottom panel Background
        topPanel.setBackground(PowerOn.userInterface.DARK_GREY);
        bottomPanel.setBackground(PowerOn.userInterface.DARK_GREY);

        // set a GridLayout for the bottomPanel
        this.setLayout(new GridLayout());
        GridLayout layout = new GridLayout(0, 3, 10, 10);
        bottomPanel.setLayout(layout);

        // creating an array of file
        results = new ArrayList<String>();
        File[] files = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images").listFiles();

        // retrieving the name of each images
        for (File file : files) {
            if (file.isFile()) {
                results.add(file.getName());
            }
        }

        // create an array of images
        for (int i = 0; i < fileCount; i++) {
            imgGrid[i] = new ImageIcon(files[i].toString());
        }

        // loop to sale and add the images to the bottomPanel
        for (int i = 0; i < files.length; i++) {
            // scaling the images
            imgGrid[i].setImage(imgGrid[i].getImage().getScaledInstance(120, 120,
                    Image.SCALE_SMOOTH));

            // add the images to the grid
            cache[i] = new JLabel(imgGrid[i]);
            bottomPanel.add(cache[i]);
        }
    }
}

NewImage.java

public class NewImage extends JPanel {
    private JLabel title, newImg;
    private ImageIcon cacheImg;
    private JPanel display;
    private JButton choose, back;
    private JFileChooser file;
    private File selectedFile;
    private Gallery addNew;

    public NewImage() {
        super();
        setBackground(PowerOn.userInterface.DARK_GREY);
        initComponents();
    }

    public void initComponents() {

        // configure title JLabel
        title = new JLabel("Choose a new image to add (jpg or png only)");
        title.setHorizontalAlignment(title.CENTER);

        // configurin choose JButton + Actionlistener
        choose = new JButton("Explore");
        file = new JFileChooser();
        choose.setPreferredSize(new Dimension(60, 60));
        choose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                int result = file.showOpenDialog(display);
                if (result == JFileChooser.APPROVE_OPTION) {
                    selectedFile = file.getSelectedFile();

                    // check the type of the file only jpg and png accepted
                    String check = selectedFile.getAbsolutePath()
                            .substring(selectedFile.getAbsolutePath().length() - 3);
                    System.out.println(check);

                    // if the fil is ok add the file to the gallery directory
                    if (check.equals("png") || check.equals("jpg")) {

                        // retrieving the name of the file and copy on the galery folder
                        try {
                            String[] parts = selectedFile.getAbsolutePath().split(Pattern.quote(File.separator));
                            String dest = "oop_2022/src/main/java/com/phone/common/png/Galery_images/"
                                    + parts[parts.length - 1];
                            copyFile(selectedFile, new File(dest));
                            cacheImg = new ImageIcon(dest);
                            cacheImg.setImage(cacheImg.getImage().getScaledInstance(120, 120, Image.SCALE_DEFAULT));
                            newImg = new JLabel(cacheImg);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        JOptionPane.showMessageDialog(null, "Your image as been succesfully uploaded");
                    }

                    // if the file is not a png or a jpg display an error message
                    else {
                        JOptionPane.showMessageDialog(null, "You must choose a png or jpg file");
                    }
                }
            }
        });

        // configuring back JButton + Actionlistener
        back = new JButton("Return to home page");
        back.setPreferredSize(new Dimension(60, 60));
        back.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                Gallery.cardGal.show(PowerOn.gallery, "GalleryPage");
            }
        });

        // configure layout of panel
        this.setLayout(new GridLayout());

        // add panels
        display = new JPanel();
        display.setLayout(new GridLayout(0, 1));
        this.add(display);
        display.add(title);
        display.add(choose);
        display.add(back);
    }

    public static void copyFile(File from, File to) throws IOException {
        Files.copy(from.toPath(), new FileOutputStream(to));
    }
}

What I want is that the image I added is directly displayed without running the code again when I go back to my gallery page.

my gallery page


问:
How to Get Tracking Parameters of a Campaign In LinkedIn
I want to get dynamic tracking parameters associated with campaigns.
I have tried the api as per documentation https://api.linkedin.com/rest/adTrackingParameters/(adEntity:(sponsoredCampaign:urn%3Ali%3AsponsoredCampaign%3A166564776))

But I get below error.

```<code>    "message": "Tracking Parameters resource does not exist for the ad entity provided: urn:li:sponsoredCampaign:166564776",
    "status": 404
}
</code>```

Body:
I want to get dynamic tracking parameters associated with campaigns.
I have tried the api as per documentation https://api.linkedin.com/rest/adTrackingParameters/(adEntity:(sponsoredCampaign:urn%3Ali%3AsponsoredCampaign%3A166564776))

But I get below error.

    "message": "Tracking Parameters resource does not exist for the ad entity provided: urn:li:sponsoredCampaign:166564776",
    "status": 404
}


问:
Sorting 16 and 32 bits instructions of STM in Python using endianness
[Update of my old post]

I am using Python to read a hex file containing a STM32 code, translated to a one-line binary, and then re-written in a file with only one instruction per line.

That last part is the problem, because my code is not working properly : some 32-bits instructions are interpreted as a 16-bits instruction, causing the code to not properly divide the instructions.

Here is the code i use :

```<code>import json

def function(filepath):
    STMfile = open(filepath)  # Read the file containing the data
    STMfileLines = STMfile.readlines()
    data_STMfile = ""
    for STMfileLine in STMfileLines:
        data_STMfile += STMfileLine[12:-3]  # Taking only the data of each line
    data_binary = ""
    for c in data_STMfile:
        data_binary += str(bin(int(c, 16))[2:].zfill(4))  # Converting each hex character in binary of 4 bits
    instruction_file = open("./instructions_file.txt", "w")
    i = 0
    while i < len(data_binary)-15:
        tmp = data_binary[i:i+32]
        if tmp[24:27] == '111' and tmp[27:29] != '00':  # 32-bits condition
            instruction_file.write(tmp[24:] + tmp[16:24] + tmp[8:16] + tmp[:8] + '\n')
            i += 32
        else:
            tmp = data_binary[i:i+16]
            instruction_file.write(tmp[8:] + tmp[:8] + '\n')
            i += 16

if __name__ == '__main__':
    function("./clignoter_led.srec")
</code>```

The file 'clignoter_led.srec' is :

```<code>S3250800000000400120650100081D0200081D0200081D0200081D0200081D0200080000000040
S325080000200000000000000000000000001D0200081D020008000000001D0200081D02000816
S325080000401D0200081D0200081D0200081D0200081D0200081D0200081D0200081D0200085A
S325080000601D0200081D0200081D0200081D0200081D0200081D0200081D0200081D0200083A
S325080000801D0200081D0200081D0200081D0200081D0200081D0200081D0200081D0200081A
S325080000a01D0200081D0200081D0200081D0200081D0200081D0200081D0200081D020008FA
S325080000c01D0200081D0200081D0200081D0200081D0200081D0200081D0200081D020008DA
S325080000e01D0200081D0200081D0200081D0200081D0200081D0200081D0200081D020008BA
S325080001001D0200081D0200081D0200081D0200081D0200081D0200081D0200081D02000899
S325080001201D02000810B5054C237833B9044B13B10448AFF300800123237010BD04000020C4
S32508000140000000006802000808B5034B1BB103490348AFF3008008BD0000000008000020A2
S325080001606802000823488546AFF3008022482349234A002302E0D458C4500433C4188C423E
S32508000180F9D3204A204C002301E013600432A242FBD300F045F800F01EF81C484FF0010178
S325080001a00268114301601A484FF48061026811430160704717484FF02001026811430160D8
S325080001c0704714486FF0200102681140016070470138FDD17047FFF7E0FFFFF7EBFF0E48E2
S325080001e00068FFF7F5FFFFF7ECFF0B480068FFF7EFFFF2E7004001200000002004000020A1
S325080002008802000804000020200000201C380240000002401400024000000020FEE70000A7
S3250800022070B500260C4D0D4C641BA410A64209D100F01AF800260A4D0A4C641BA410A642CE
S3250800024005D170BD55F8043B98470136EEE755F8043B98470136F2E7800200088002000887
S325080002608002000884020008F8B500BFF8BC08BC9E467047F8B500BFF8BC08BC9E4670475A
S3250800028049010008250100083C55050000000000000000000000000000000000000000003A
S325080002a0000000000000000000000000000000000000000000000000000000000000000030
S325080002c0000000000000000000000000000000000000000000000000000000000000000010
S325080002e00000000000000000000000000000000000000000000000000000000000000000F0
S325080003002846A4EB0E0440EA03409EE7C1F120078B4022FA07FC4CEA030C25FA07FA4FEA6D
S325080003201C49BAFBF9F820FA07F309FB18AA8D401FFA8CFE1D4300FA01F308FB0EF02C0CD3
S3250800034044EA0A44A04202FA01F20BD91CEB040408F1FF3A80F08880A04240F28580A8F1F3
S3250800036002086444241AB4FBF9F009FB104400FB0EFEADB245EA0444A64508D91CEB0404D7
S3250800038000F1FF356CD2A6456AD90238644440EA0840A0FB0295A4EB0E04AC42C846AE46A7
S325080003a056D353D0002E69D0B3EB080264EB0E0422FA01F304FA07F71F43CC40C6E90074D6
S325080003c0002147E70CFA02FCC2F1200125FA01F34FEA1C4720FA01F195400D43B3FBF7F172
S325080003e007FB11331FFA8CFE280C40EA034001FB0EF3834204FA02F408D91CEB000001F1D5
S70500000000FA
</code>```

As explained in my old post, an instruction is 32-bits if it starts with '111' but they must not be followed by '00' (therefore an instruction starting with '11100' is a 16-bits, and the instructions starting by '11101', '11110', '11111' are 32-bits instructions, all other starts are 16-bits ones).

When I run this function with the above file, the resulting file (instructions_file.txt) contains these lines :

```<code>(198) 11110000000000001101001111111011
(199) 11110000000000001111100001000101
(200) 1111100000011110
(201) 11110000010011110100100000011100
</code>```

Here, the third line is supposed to be a 32-bits instruction, and so the 4th should be 16-bits, yet my code didn't recognize the third line as a 16-bits instruction.

I've verified every index, they are correct.

I've tried different hex file (they are directly downloaded from STM32CubeProgrammer), they all have this problem.

Body:
[Update of my old post]

I am using Python to read a hex file containing a STM32 code, translated to a one-line binary, and then re-written in a file with only one instruction per line.

That last part is the problem, because my code is not working properly : some 32-bits instructions are interpreted as a 16-bits instruction, causing the code to not properly divide the instructions.

Here is the code i use :

import json

def function(filepath):
    STMfile = open(filepath)  # Read the file containing the data
    STMfileLines = STMfile.readlines()
    data_STMfile = ""
    for STMfileLine in STMfileLines:
        data_STMfile += STMfileLine[12:-3]  # Taking only the data of each line
    data_binary = ""
    for c in data_STMfile:
        data_binary += str(bin(int(c, 16))[2:].zfill(4))  # Converting each hex character in binary of 4 bits
    instruction_file = open("./instructions_file.txt", "w")
    i = 0
    while i < len(data_binary)-15:
        tmp = data_binary[i:i+32]
        if tmp[24:27] == '111' and tmp[27:29] != '00':  # 32-bits condition
            instruction_file.write(tmp[24:] + tmp[16:24] + tmp[8:16] + tmp[:8] + '\n')
            i += 32
        else:
            tmp = data_binary[i:i+16]
            instruction_file.write(tmp[8:] + tmp[:8] + '\n')
            i += 16

if __name__ == '__main__':
    function("./clignoter_led.srec")

The file 'clignoter_led.srec' is :

S3250800000000400120650100081D0200081D0200081D0200081D0200081D0200080000000040
S325080000200000000000000000000000001D0200081D020008000000001D0200081D02000816
S325080000401D0200081D0200081D0200081D0200081D0200081D0200081D0200081D0200085A
S325080000601D0200081D0200081D0200081D0200081D0200081D0200081D0200081D0200083A
S325080000801D0200081D0200081D0200081D0200081D0200081D0200081D0200081D0200081A
S325080000a01D0200081D0200081D0200081D0200081D0200081D0200081D0200081D020008FA
S325080000c01D0200081D0200081D0200081D0200081D0200081D0200081D0200081D020008DA
S325080000e01D0200081D0200081D0200081D0200081D0200081D0200081D0200081D020008BA
S325080001001D0200081D0200081D0200081D0200081D0200081D0200081D0200081D02000899
S325080001201D02000810B5054C237833B9044B13B10448AFF300800123237010BD04000020C4
S32508000140000000006802000808B5034B1BB103490348AFF3008008BD0000000008000020A2
S325080001606802000823488546AFF3008022482349234A002302E0D458C4500433C4188C423E
S32508000180F9D3204A204C002301E013600432A242FBD300F045F800F01EF81C484FF0010178
S325080001a00268114301601A484FF48061026811430160704717484FF02001026811430160D8
S325080001c0704714486FF0200102681140016070470138FDD17047FFF7E0FFFFF7EBFF0E48E2
S325080001e00068FFF7F5FFFFF7ECFF0B480068FFF7EFFFF2E7004001200000002004000020A1
S325080002008802000804000020200000201C380240000002401400024000000020FEE70000A7
S3250800022070B500260C4D0D4C641BA410A64209D100F01AF800260A4D0A4C641BA410A642CE
S3250800024005D170BD55F8043B98470136EEE755F8043B98470136F2E7800200088002000887
S325080002608002000884020008F8B500BFF8BC08BC9E467047F8B500BFF8BC08BC9E4670475A
S3250800028049010008250100083C55050000000000000000000000000000000000000000003A
S325080002a0000000000000000000000000000000000000000000000000000000000000000030
S325080002c0000000000000000000000000000000000000000000000000000000000000000010
S325080002e00000000000000000000000000000000000000000000000000000000000000000F0
S325080003002846A4EB0E0440EA03409EE7C1F120078B4022FA07FC4CEA030C25FA07FA4FEA6D
S325080003201C49BAFBF9F820FA07F309FB18AA8D401FFA8CFE1D4300FA01F308FB0EF02C0CD3
S3250800034044EA0A44A04202FA01F20BD91CEB040408F1FF3A80F08880A04240F28580A8F1F3
S3250800036002086444241AB4FBF9F009FB104400FB0EFEADB245EA0444A64508D91CEB0404D7
S3250800038000F1FF356CD2A6456AD90238644440EA0840A0FB0295A4EB0E04AC42C846AE46A7
S325080003a056D353D0002E69D0B3EB080264EB0E0422FA01F304FA07F71F43CC40C6E90074D6
S325080003c0002147E70CFA02FCC2F1200125FA01F34FEA1C4720FA01F195400D43B3FBF7F172
S325080003e007FB11331FFA8CFE280C40EA034001FB0EF3834204FA02F408D91CEB000001F1D5
S70500000000FA

As explained in my old post, an instruction is 32-bits if it starts with '111' but they must not be followed by '00' (therefore an instruction starting with '11100' is a 16-bits, and the instructions starting by '11101', '11110', '11111' are 32-bits instructions, all other starts are 16-bits ones).

When I run this function with the above file, the resulting file (instructions_file.txt) contains these lines :

(198) 11110000000000001101001111111011
(199) 11110000000000001111100001000101
(200) 1111100000011110
(201) 11110000010011110100100000011100

Here, the third line is supposed to be a 32-bits instruction, and so the 4th should be 16-bits, yet my code didn't recognize the third line as a 16-bits instruction.

I've verified every index, they are correct.

I've tried different hex file (they are directly downloaded from STM32CubeProgrammer), they all have this problem.


问:
Portainer Docker Webserver add a volume problem
I created a container with a webserver and the path in the container is '/usr/sbin/httpd' '-D' 'FOREGROUND'

I have a volume that i want to add to this container but if i put a path like /usr/sbin/httpd/test it return me the error:
"lstat /var/lib/docker/overlay2/51da1d63f52da3173be283864f9d20e1202f2e6fefee1442f4e41133edc36cc3/merged/usr/sbin/httpd/test: not a directory"

If i use an other path, i can't reach it from the webservice

How can i have the file reachable from the webservice that are static and not volatile?


问:
linq circular query reference c# on Category and Parent Category
The category table have a circular reference to have an unlimited hierarchy structure.
Herewith is the structure im trying to achieve.
How do I write a query in linq C# to achieve the following structure ?

```<code>Automotive - vehicle hire
           - Vehicle Sales
Tyre's And Shocks - Tyres  - dunlop
                           - continental
                  - Shocks - Gabriel
                           - No Name
</code>```

```<code>var category = _context.Category.Where(c.ParentCategoryId == 11).ToList();
</code>```

Table Structure :

CategoryID
ParentCategoryID
CategoryName

1
null
Automotive

2
1
Vehicle Hire

3
1
Vehicle Sales

4
1
Spares  or  Accessories

5
1
Automotive Associations

6
1
Financial Institutions

7
1
Health Care

8
1
Panelbeaters

9
1
Auto Glass

10
1
Mags  or  Rims

11
1
Tyre's And Shocks

12
11
Tyres

13
11
Shocks

14
11
Exhausts

15
11
Suspension Springs

16
12
Dunlop

17
12
Continental

18
13
Gabriel

19
13
No Name

Body:
The category table have a circular reference to have an unlimited hierarchy structure.
Herewith is the structure im trying to achieve.
How do I write a query in linq C# to achieve the following structure ?

Automotive - vehicle hire
           - Vehicle Sales
Tyre's And Shocks - Tyres  - dunlop
                           - continental
                  - Shocks - Gabriel
                           - No Name

var category = _context.Category.Where(c.ParentCategoryId == 11).ToList();

Table Structure :

CategoryID
ParentCategoryID
CategoryName

1
null
Automotive

2
1
Vehicle Hire

3
1
Vehicle Sales

4
1
Spares  or  Accessories

5
1
Automotive Associations

6
1
Financial Institutions

7
1
Health Care

8
1
Panelbeaters

9
1
Auto Glass

10
1
Mags  or  Rims

11
1
Tyre's And Shocks

12
11
Tyres

13
11
Shocks

14
11
Exhausts

15
11
Suspension Springs

16
12
Dunlop

17
12
Continental

18
13
Gabriel

19
13
No Name


问:
No columns generated in datagridview if empty query in EF Core
```<code>Stops_BindingSource = new BindingSource();
dgvStops.DataSource = Stops_BindingSource;
Trips_Context.Tripstops.Load();

long Id = (long)dgvTrips.CurrentRow.Cells["Id"].Value;
Stops_BindingSource.DataSource = Trips_Context.Tripstops.Local.ToBindingList().Where(x => x.Tripid == Id);
</code>```

If the query returns records then dgvStops has columns created, if empty, then no columns (or new record row) is created.  Do I need to add something

Body:
Stops_BindingSource = new BindingSource();
dgvStops.DataSource = Stops_BindingSource;
Trips_Context.Tripstops.Load();

long Id = (long)dgvTrips.CurrentRow.Cells["Id"].Value;
Stops_BindingSource.DataSource = Trips_Context.Tripstops.Local.ToBindingList().Where(x => x.Tripid == Id);

If the query returns records then dgvStops has columns created, if empty, then no columns (or new record row) is created.  Do I need to add something


问:
Can I Use The Mean of Binary Coded Variable on Mann-Whitney U Test?
I have a question regarding using a binary-coded dependent variable on the Mann-Whitney U test.
I have a test with 15 questions from 3 different categories in my study. The answers are forced answers and have one correct answer. I coded the answers as binary values with 1 being correct and 0 being incorrect.
Therefore, for 3 different categories, the participants have a mean score between 0 and 1 representing their success (I took the mean because I have many participants who did not answer the whole test).
Does it make sense to put a mean of binary coded value as a dependent variable on a nonparametric test or it sounds weird and I should apply something else like chi-square or logistic regression?</p>


问:
how to login and get a authorization token
I'm using the site's data, but it often changes the authorization token.
How do I automatically register to receive this token

I am by no means an expert in scraping, so this is all I came up with.

```<code>login <- "keyiyaf191@octovie.com"
pass <- "Qaz123123"
url <- "https://my.exness.com/accounts/sign-in"

library(rvest)
session <- html_session(url)
form <- html_form(session)
</code>```

Can someone help me with this?

Body:
I'm using the site's data, but it often changes the authorization token.
How do I automatically register to receive this token

I am by no means an expert in scraping, so this is all I came up with.

login <- "keyiyaf191@octovie.com"
pass <- "Qaz123123"
url <- "https://my.exness.com/accounts/sign-in"

library(rvest)
session <- html_session(url)
form <- html_form(session)

Can someone help me with this?


问:
Trying to highlight focused GridView item in showCupertinoModalBottomSheet
I have a ModalBottomSheet containing a GridView of cards with FocusNode which I would like to navigate using Keyboard or RemoteControl and highlighting the selected card.

The navigation between focusnodes working fine in my code but the color of all cards is always the same even when isFocused == true.

Here is the code I've been trying to make work:

```<code>
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

      onGenerateRoute: (RouteSettings settings) {
        switch (settings.name) {
          case '/':
            return MaterialWithModalsPageRoute(
                builder: (_) => MyHomePage(title: 'Flutter Demo Home Page'),
                settings: settings);
        }
        return MaterialPageRoute(
          builder: (context) => Scaffold(
            body: CupertinoScaffold(
              body: Builder(
                builder: (context) => CupertinoPageScaffold(
                  child: Center(
                    child: Container(),
                  ),
                ),
              ),
            ),
          ),
          settings: settings,
        );
      },
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool? isFocused = false;
  late List<FocusNode> fnList;

  @override
  void initState() {
  super.initState();
  fnList= List.generate(7, (int index) => FocusNode());
  _firstFocus();
}

void _firstFocus(){
  for(int i=0;i<7;i++){
    //print("Listener added on focus number $i");
    fnList[i].addListener((){
      if (fnList[i].hasFocus != isFocused) {
        setState(() {
          print("SET STATE isFocused from $isFocused");
          isFocused = fnList[i].hasFocus;
          print("To $isFocused");
        });
      }
    });
  }
}

  @override
  void dispose() async {
    super.dispose();
    for(int i=0;i<=7;i++){
    fnList[i].dispose();
    }
  }

  _changeFocus(FocusNode node){
    node.requestFocus();
  }

  Color iconColor = Colors.blue;
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        body: CupertinoPageScaffold(
          navigationBar: CupertinoNavigationBar(
            transitionBetweenRoutes: false,
            middle: const Text('Modal Presentation'),
            trailing: GestureDetector(
              child: const Icon(Icons.arrow_forward),
              onTap: () => Navigator.of(context).pushNamed('ss'),
            ),
          ),
          child: SizedBox.expand(
            child: SafeArea(
              bottom: false,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[

                  section('STYLES'),

                  RawKeyboardListener(
                              focusNode: FocusNode(),
                    child: ListTile(
                      title: const Text('Cupertino Modal fit'),
                      onTap: () => showCupertinoModalBottomSheet(
                        expand: false,
                        context: context,
                        backgroundColor: Colors.transparent,
                        builder: (context) => GridView.builder(
                          primary: true,
                              physics: const BouncingScrollPhysics(),
                              shrinkWrap: true,
                              gridDelegate:
                              const SliverGridDelegateWithMaxCrossAxisExtent(
                                maxCrossAxisExtent: 200,
                                childAspectRatio: 6/5,
                                crossAxisSpacing: 7,
                                mainAxisSpacing: 7
                              ),
                              scrollDirection: Axis.vertical,
                              itemCount: 7,
                              itemBuilder: (BuildContext context, int index) =>
                              Focus(
                                focusNode: fnList[index] ,
                                autofocus: (index==0)?true:false,
                                  onKey:(node, event) {
                                    if (event.isKeyPressed(LogicalKeyboardKey.arrowRight)) {
                                      _changeFocus(fnList[index+1]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    } else if (event.isKeyPressed(LogicalKeyboardKey.arrowLeft)) {
                                        _changeFocus(fnList[index-1]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    }
                                    else if (event.isKeyPressed(LogicalKeyboardKey.arrowUp)) {
                                        _changeFocus(fnList[index-5]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    }
                                    else if (event.isKeyPressed(LogicalKeyboardKey.arrowDown)) {
                                        _changeFocus(fnList[index+5]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    }
                                    else if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
                                      print(index);
                                      print("---------------------------------------------------");
                                    }
                                    return KeyEventResult.handled;
                                  },
                                    onFocusChange: (hasFocus)
                                    {
                                    if(hasFocus)
                                        {
                                          iconColor = Colors.red;
                                          }
                                    else{
                                            iconColor = Colors.blue;
                                        }
                                        setState((){});
                                      },
                                child: Padding(
                                  padding:  const EdgeInsets.all(16.0),
                                  child: Container(
                                    height: 100,
                                    width: 100,
                                    color: iconColor,
                                  ),
                                ),
                              ),
                                            ),
                    ),),
                  ),

                  const SizedBox(
                    height: 60,
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget section(String title) {
    return const Padding(
      padding: EdgeInsets.fromLTRB(16, 20, 16, 8),

    );
  }
}
</code>```

Body:
I have a ModalBottomSheet containing a GridView of cards with FocusNode which I would like to navigate using Keyboard or RemoteControl and highlighting the selected card.

The navigation between focusnodes working fine in my code but the color of all cards is always the same even when isFocused == true.

Here is the code I've been trying to make work:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

      onGenerateRoute: (RouteSettings settings) {
        switch (settings.name) {
          case '/':
            return MaterialWithModalsPageRoute(
                builder: (_) => MyHomePage(title: 'Flutter Demo Home Page'),
                settings: settings);
        }
        return MaterialPageRoute(
          builder: (context) => Scaffold(
            body: CupertinoScaffold(
              body: Builder(
                builder: (context) => CupertinoPageScaffold(
                  child: Center(
                    child: Container(),
                  ),
                ),
              ),
            ),
          ),
          settings: settings,
        );
      },
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool? isFocused = false;
  late List<FocusNode> fnList;

  @override
  void initState() {
  super.initState();
  fnList= List.generate(7, (int index) => FocusNode());
  _firstFocus();
}

void _firstFocus(){
  for(int i=0;i<7;i++){
    //print("Listener added on focus number $i");
    fnList[i].addListener((){
      if (fnList[i].hasFocus != isFocused) {
        setState(() {
          print("SET STATE isFocused from $isFocused");
          isFocused = fnList[i].hasFocus;
          print("To $isFocused");
        });
      }
    });
  }
}

  @override
  void dispose() async {
    super.dispose();
    for(int i=0;i<=7;i++){
    fnList[i].dispose();
    }
  }

  _changeFocus(FocusNode node){
    node.requestFocus();
  }

  Color iconColor = Colors.blue;
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        body: CupertinoPageScaffold(
          navigationBar: CupertinoNavigationBar(
            transitionBetweenRoutes: false,
            middle: const Text('Modal Presentation'),
            trailing: GestureDetector(
              child: const Icon(Icons.arrow_forward),
              onTap: () => Navigator.of(context).pushNamed('ss'),
            ),
          ),
          child: SizedBox.expand(
            child: SafeArea(
              bottom: false,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[

                  section('STYLES'),

                  RawKeyboardListener(
                              focusNode: FocusNode(),
                    child: ListTile(
                      title: const Text('Cupertino Modal fit'),
                      onTap: () => showCupertinoModalBottomSheet(
                        expand: false,
                        context: context,
                        backgroundColor: Colors.transparent,
                        builder: (context) => GridView.builder(
                          primary: true,
                              physics: const BouncingScrollPhysics(),
                              shrinkWrap: true,
                              gridDelegate:
                              const SliverGridDelegateWithMaxCrossAxisExtent(
                                maxCrossAxisExtent: 200,
                                childAspectRatio: 6/5,
                                crossAxisSpacing: 7,
                                mainAxisSpacing: 7
                              ),
                              scrollDirection: Axis.vertical,
                              itemCount: 7,
                              itemBuilder: (BuildContext context, int index) =>
                              Focus(
                                focusNode: fnList[index] ,
                                autofocus: (index==0)?true:false,
                                  onKey:(node, event) {
                                    if (event.isKeyPressed(LogicalKeyboardKey.arrowRight)) {
                                      _changeFocus(fnList[index+1]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    } else if (event.isKeyPressed(LogicalKeyboardKey.arrowLeft)) {
                                        _changeFocus(fnList[index-1]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    }
                                    else if (event.isKeyPressed(LogicalKeyboardKey.arrowUp)) {
                                        _changeFocus(fnList[index-5]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    }
                                    else if (event.isKeyPressed(LogicalKeyboardKey.arrowDown)) {
                                        _changeFocus(fnList[index+5]);
                                      print(fnList);
                                      //print(isFocused);
                                      print("---------------------------------------------------");
                                    }
                                    else if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
                                      print(index);
                                      print("---------------------------------------------------");
                                    }
                                    return KeyEventResult.handled;
                                  },
                                    onFocusChange: (hasFocus)
                                    {
                                    if(hasFocus)
                                        {
                                          iconColor = Colors.red;
                                          }
                                    else{
                                            iconColor = Colors.blue;
                                        }
                                        setState((){});
                                      },
                                child: Padding(
                                  padding:  const EdgeInsets.all(16.0),
                                  child: Container(
                                    height: 100,
                                    width: 100,
                                    color: iconColor,
                                  ),
                                ),
                              ),
                                            ),
                    ),),
                  ),

                  const SizedBox(
                    height: 60,
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget section(String title) {
    return const Padding(
      padding: EdgeInsets.fromLTRB(16, 20, 16, 8),

    );
  }
}