问:
DataFrame to Excel, save to different sheets
I have this code block that creates a subset of a dataframe by grouping. I want to save those subsets to individual excel sheets. From my understanding, the "output.xlsx" is being overwritten because it is being called multiple times after every iteration. What can I do to fix this?

```<code>path = 'output.xlsx'
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
#Per PG Sales Units
for x in pg:
    brand = merged_df[merged_df['product group'] == x]
    for y in months:
        per_month = brand[brand['Month'] == y]
        sum_brandshare = per_month.groupby('new_brand').sum()
        sum_brandshare = sum_brandshare.sort_values('sales_units',ascending=False)
        sum_brandshare = sum_brandshare.reset_index()
        print('For month ', y, 'in ', x)
        display(sum_brandshare)
        top_brands = sum_brandshare['new_brand']
        sales_u = sum_brandshare['sales_units']
        # Plot to Bar Chart
        fig = plt.figure(figsize =(10, 7))
        plt.bar(top_brands, sales_u)
        plt.show()

    sum_brandshare.to_excel(path, sheet_name=x+y, index=False)
    writer.save()
    writer.close()
</code>```

`

Body:
I have this code block that creates a subset of a dataframe by grouping. I want to save those subsets to individual excel sheets. From my understanding, the "output.xlsx" is being overwritten because it is being called multiple times after every iteration. What can I do to fix this?

path = 'output.xlsx'
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
#Per PG Sales Units
for x in pg:
    brand = merged_df[merged_df['product group'] == x]
    for y in months:
        per_month = brand[brand['Month'] == y]
        sum_brandshare = per_month.groupby('new_brand').sum()
        sum_brandshare = sum_brandshare.sort_values('sales_units',ascending=False)
        sum_brandshare = sum_brandshare.reset_index()
        print('For month ', y, 'in ', x)
        display(sum_brandshare)
        top_brands = sum_brandshare['new_brand']
        sales_u = sum_brandshare['sales_units']
        # Plot to Bar Chart
        fig = plt.figure(figsize =(10, 7))
        plt.bar(top_brands, sales_u)
        plt.show()

    sum_brandshare.to_excel(path, sheet_name=x+y, index=False)
    writer.save()
    writer.close()

`


来源: stackexchange

问:
Insert multiple hyperlinks to the same cell using SheetJS
When exporting my data using SheetJS, I need to concatenate multiple hyperlinks to the same cell.

An example I've built manually using Google Sheets:

From what the docs explain, the default way of creating links would be:

```<code>cell = {
    l: { Target: 'https://www.google.com' },
    v: 'Google'
}
</code>```

However, it applies to the whole cell, therefore I can't concatenate multiple hyperlinks.

Another approach would be exporting an HTML table, where I could probably add multiple anchors to the same td, which I'd like to avoid as I'd need to rewrite my whole exporting process.

ContentLicense: CC BY-SA 4.0

Body:
When exporting my data using SheetJS, I need to concatenate multiple hyperlinks to the same cell.

An example I've built manually using Google Sheets:

From what the docs explain, the default way of creating links would be:

cell = {
    l: { Target: 'https://www.google.com' },
    v: 'Google'
}

However, it applies to the whole cell, therefore I can't concatenate multiple hyperlinks.

Another approach would be exporting an HTML table, where I could probably add multiple anchors to the same td, which I'd like to avoid as I'd need to rewrite my whole exporting process.


问:
NodeJS (MERN) where to sanitize and validate
I was just wondering where I should sanitize and validate my incoming data. Mongoose has some validation functions and combined with Validate.js I can do the validation there. But should I also do the sanitization there? Or is it better to do this with the express-validator middleware straight from the request. And should I also do the validation at this point? Or even both?

Or is there another better practice?

I hope you can advise me!

Cheers,

Mik


问:
Intellij - View Git commits before pull
I'm using Intellij new version with GitToolBox plugin

Before pushing to remove repository I must pull first,

But sometimes pulling break compilation, so I want to check the commits before pulling

Is there an option to view git commits before pulling them?

I'm working on a project that isn't stable where multiple users are committing changes before checks

Title: Intellij - View Git commits before pull


问:
Check free iOS bundle id
After going a lot of places setting up my bundle id, now I get :

An App ID with Identifier 'com.myapp.estate' is not available.
Please enter a different string.

com.myapp.estate is just an example here mine is a lot more unique, so how do I check if a selected bundle id on iOS is free before going through all these setups again?

For android we can look for https://play.google.com/store/apps/details?id=com.myapp.estate if it says it doesn't exist it means it's free.

Title: Check free iOS bundle id


问:
IP error when deploying with MongoDB/Mongoose
When I try to deploy my NodeJS Rest API using MongoDB and Mongoose, it gets an error about the IP. When using Heroku, you can use an add-on that generates a static IP but now that it's not free anymore, do you guys have another option? Or maybe something I can do that does not require creating a static IP. Please, if you give me another deploy option, give me a simple one, like Heroku, railway, etc.
Thank you!

I tried Linode, but I don't want to create and use this server stuff because I have no idea how to.


问:
Laravel ajax request returns 419 or 500 error
I am trying to code a chatroom with Laravel 8 and Javascript.

I have this in my layout :

```<code><meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

I have this javascript function that makes the ajax request :

function ajoutMessage(){
    let msg = document.querySelector("#text").value
    if(msg != ""){

        let data = {}
        data["msg"] = msg

        let jSonData = JSON.stringify(data)
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        let  xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function()
        {
                if(this.readyState == 4){
                if(this.status == 201){
                    document.querySelector("#text").value = "";
                }

                }
        }

        xmlhttp.open('POST', 'send');
        xmlhttp.send(jSonData)
    }

}
```
<p>I also have this function in my Controller :</p>
<pre class="lang-php prettyprint-override"><code>public function ajoutMessage(Request $request) {
    if($request->isMethod('POST')){
        $donneesJson = file_get_contents('php//input');
        $donnees = json_decode($donneesJson);

        return response()->json(["message"=>"inserted successfully"], 201);
    }
}
</code>```

Doing this make me an error 500. Can you help for the two cases please ?

With this code I get a 419 error and I do not understand why, so I tried to delete the CSRF verification by excerpting my route from the CSRFVerifiy Middleware:

protected $except = [
   'send'
];
```

I found nothing for explaining the error 500 in /var/log/apache2 error.log file

Body:
I am trying to code a chatroom with Laravel 8 and Javascript.

I have this in my layout :

<meta name="csrf-token" content="{{ csrf_token() }}">

I have this javascript function that makes the ajax request :

function ajoutMessage(){
    let msg = document.querySelector("#text").value
    if(msg != ""){

        let data = {}
        data["msg"] = msg

        let jSonData = JSON.stringify(data)
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        let  xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function()
        {
                if(this.readyState == 4){
                if(this.status == 201){
                    document.querySelector("#text").value = "";
                }

                }
        }

        xmlhttp.open('POST', 'send');
        xmlhttp.send(jSonData)
    }

}

I also have this function in my Controller :

public function ajoutMessage(Request $request) {
    if($request->isMethod('POST')){
        $donneesJson = file_get_contents('php//input');
        $donnees = json_decode($donneesJson);

        return response()->json(["message"=>"inserted successfully"], 201);
    }
}

Doing this make me an error 500. Can you help for the two cases please ?

With this code I get a 419 error and I do not understand why, so I tried to delete the CSRF verification by excerpting my route from the CSRFVerifiy Middleware:

protected $except = [
   'send'
];

I found nothing for explaining the error 500 in /var/log/apache2 error.log file


问:
How to do that a Container follow path of Containers? (AnimatedContainer)
I have a grid of Containers (blue and red containers), and on top of that, a green Container (with StackWidget) which I need move throught red Containers (path)

Is possible to achieve what I need?
I have the grid of containers and a list with path coords

```<code>List<Map<int, int>> path = [
  {2: 0},
  {2: 1},
  {2: 2},
  {2: 3},
  {2: 4},
  {3: 4},
  {4: 4},
  {5: 4},
  {5: 5},
  {5: 6},
  {5: 7},
  //...
</code>```

Body:
I have a grid of Containers (blue and red containers), and on top of that, a green Container (with StackWidget) which I need move throught red Containers (path)

Is possible to achieve what I need?
I have the grid of containers and a list with path coords

List<Map<int, int>> path = [
  {2: 0},
  {2: 1},
  {2: 2},
  {2: 3},
  {2: 4},
  {3: 4},
  {4: 4},
  {5: 4},
  {5: 5},
  {5: 6},
  {5: 7},
  //...


问:
Group revision elements for signed PDFs with PDFBox
Based on my previous question Fill out field for pdf revision when signing with PDFbox I was able to fill out the PDF field with a valid signature:

When looking at a signed document from AdobeSign they managed to group the fields like:

I am not able to analyse the created document von Adobe since they locked it at the end with a password. Is this to make sure nobody is able to edit the forms after the signature (I know that the signature is not valid anymore after somebody did it, but it reduces the risk of a user by accidentally writing into the field.

Update:

setting two signatures works and it will set the form fields in. But only for the Field 2, not the Field 1 from the first signature. see: https://file.io/cvHSBqRzXPyH


问:
Display SIM toolkit Icon, URL
I have developed a small applet to display welcome message, the applet is registered to PROFILE_DOWNLOAD event and its successfully works
the message appears when the SIM registered to network.

```<code>switch (event) {
    case EVENT_PROFILE_DOWNLOAD:
         reg.setEvent(EVENT_EVENT_DOWNLOAD_LOCATION_STATUS);
         break;
    case EVENT_EVENT_DOWNLOAD_LOCATION_STATUS:
    theEnv = EnvelopeHandler.getTheHandler();
    // check location status tag
    if ((Displayed == false) && (theEnv.findTLV(TAG_LOCATION_STATUS, (byte) 1) != TLV_NOT_FOUND)){
       if (theEnv.getValueByte((short) 0) == (byte) 0) {
                proHdlr.initDisplayText((byte) 0x01, DCS_8_BIT_DATA, English_Welcome, (short) 0,(short) Welcome_msg.length);
                proHdlr.send();
                reg.clearEvent(EVENT_EVENT_DOWNLOAD_LOCATION_STATUS);
        }
    }
     break;
</code>```

Is it possible to display icon or clickable URL with displayed message.

Thanks

display message toolkit applet

Title: Display SIM toolkit Icon, URL

Body:
I have developed a small applet to display welcome message, the applet is registered to PROFILE_DOWNLOAD event and its successfully works
the message appears when the SIM registered to network.

switch (event) {
    case EVENT_PROFILE_DOWNLOAD:
         reg.setEvent(EVENT_EVENT_DOWNLOAD_LOCATION_STATUS);
         break;
    case EVENT_EVENT_DOWNLOAD_LOCATION_STATUS:
    theEnv = EnvelopeHandler.getTheHandler();
    // check location status tag
    if ((Displayed == false) && (theEnv.findTLV(TAG_LOCATION_STATUS, (byte) 1) != TLV_NOT_FOUND)){
       if (theEnv.getValueByte((short) 0) == (byte) 0) {
                proHdlr.initDisplayText((byte) 0x01, DCS_8_BIT_DATA, English_Welcome, (short) 0,(short) Welcome_msg.length);
                proHdlr.send();
                reg.clearEvent(EVENT_EVENT_DOWNLOAD_LOCATION_STATUS);
        }
    }
     break;

Is it possible to display icon or clickable URL with displayed message.

Thanks

display message toolkit applet


问:
APN ( apple push notification ) using expo cli not able to access the custom data
i using APN (Apple push notification ) for expo react native app,
i sending push notification using php code from server, with notification i am sending custom data reacordid. , when i am try to use that use recordid, app is getting closed.

Below image is the response of APN

in the above image pancel marked custom data recordid want use in the app, if am using that recordid app getting closed, how to use that recordid variable in app ?

```<code>notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
    setNotification(notification);
    let id = 1;
    let str= null;
    alert("notf:: values:"+JSON.stringify(notification));

    if (Platform.OS === 'android'){
        id = notification.request.content.data.recordid;
    }  if (Platform.OS === 'ios'){{
        // ios platform
        let trigger:any = notification.request.trigger;

    //    id = notification.request.trigger.payload.recordid;//not working
        id = trigger.payload.aps.recordid; // check this

    }
</code>```

Body:
i using APN (Apple push notification ) for expo react native app,
i sending push notification using php code from server, with notification i am sending custom data reacordid. , when i am try to use that use recordid, app is getting closed.

Below image is the response of APN

in the above image pancel marked custom data recordid want use in the app, if am using that recordid app getting closed, how to use that recordid variable in app ?

notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
    setNotification(notification);
    let id = 1;
    let str= null;
    alert("notf:: values:"+JSON.stringify(notification));

    if (Platform.OS === 'android'){
        id = notification.request.content.data.recordid;
    }  if (Platform.OS === 'ios'){{
        // ios platform
        let trigger:any = notification.request.trigger;

    //    id = notification.request.trigger.payload.recordid;//not working
        id = trigger.payload.aps.recordid; // check this

    }


问:
Conforming to Decodable Failing for a struct
I have the following struct:

```<code>struct Category: Codable, Hashable {
    let id: Int
    let name: String
    let image: String
}
</code>```

I also have a Resource struct as shown below:

```<code>struct Resource<T: Codable> {
    let url: URL
    var headers: [String: String] = [:]
    var method: HttpMethod = .get([])
    let modelType: T
}
</code>```

When I try to create an instance of Resource, it fails:

```<code> let resource = Resource(url: URL.allCategories, modelType: Category.self)
</code>```

// Type 'Category.Type' cannot conform to 'Decodable'

UPDATE:

```<code>enum HttpMethod {
    case get([URLQueryItem])
    case post(Data?)
    case delete

    var name: String {
        switch self {
            case .get:
                return "GET"
            case .post:
                return "POST"
            case .delete:
                return "DELETE"
        }
    }
}
</code>```

SOLUTION:

I believe the modelType should be T.Type instead of T. I made the change and now I am not getting any errors.

```<code>struct Resource<T: Codable> {
    let url: URL
    var headers: [String: String] = [:]
    var method: HttpMethod = .get([])
    let modelType: T.Type
}
</code>```

Body:
I have the following struct:

struct Category: Codable, Hashable {
    let id: Int
    let name: String
    let image: String
}

I also have a Resource struct as shown below:

struct Resource<T: Codable> {
    let url: URL
    var headers: [String: String] = [:]
    var method: HttpMethod = .get([])
    let modelType: T
}

When I try to create an instance of Resource, it fails:

 let resource = Resource(url: URL.allCategories, modelType: Category.self)

// Type 'Category.Type' cannot conform to 'Decodable'

UPDATE:

enum HttpMethod {
    case get([URLQueryItem])
    case post(Data?)
    case delete

    var name: String {
        switch self {
            case .get:
                return "GET"
            case .post:
                return "POST"
            case .delete:
                return "DELETE"
        }
    }
}

SOLUTION:

I believe the modelType should be T.Type instead of T. I made the change and now I am not getting any errors.

struct Resource<T: Codable> {
    let url: URL
    var headers: [String: String] = [:]
    var method: HttpMethod = .get([])
    let modelType: T.Type
}


问:
Uploading animated GIF to Imgur API returns "Unable to determine file duration" error
I want to upload an animated GIF file to Imgur through their API but get an error message.

The file is converted from an mp4-file with GifTuna and is 15s duration, 30 FPS, ~70 MB.

I use the following command from the Windows 10 command line:

```<code>curl -X POST -H "Authorization: Bearer [MYTOKEN]" -F "video=@myfile.gif" https://api.imgur.com/3/upload
</code>```

Instead of an http status code 200, it returns the error message:

{"status":400,"success":false,"data":{"error":"Unable to determine file duration","request":"/3/upload","method":"POST"}}

If I upload the original mp4-version, the upload is successful. If I try to upload the animated GIF through Imgurs own postman.com collection I get the same error message as with curl.

It doesn't seem to be a file size issue as the limit for videos is 200MB. Also, trying with a bigger file, say 300 MB, triggers a specific error stating the file is too big.

Any idea how to solve this?

Body:
I want to upload an animated GIF file to Imgur through their API but get an error message.

The file is converted from an mp4-file with GifTuna and is 15s duration, 30 FPS, ~70 MB.

I use the following command from the Windows 10 command line:

curl -X POST -H "Authorization: Bearer [MYTOKEN]" -F "video=@myfile.gif" https://api.imgur.com/3/upload

Instead of an http status code 200, it returns the error message:

{"status":400,"success":false,"data":{"error":"Unable to determine file duration","request":"/3/upload","method":"POST"}}

If I upload the original mp4-version, the upload is successful. If I try to upload the animated GIF through Imgurs own postman.com collection I get the same error message as with curl.

It doesn't seem to be a file size issue as the limit for videos is 200MB. Also, trying with a bigger file, say 300 MB, triggers a specific error stating the file is too big.

Any idea how to solve this?


问:
nextauth extend the profile values strava
I am trying to extend what is returned in the StravaProvider profile() in nextAuth

pages/api/auth/[...nextauth].js

export default NextAuth({
  providers: [
    StravaProvider({
      clientId: process.env.STRAVA_CLIENT_ID,
      clientSecret: process.env.STRAVA_CLIENT_SECRET,
      profile(profile) {
        // LOGS FINE IN CONSOLE
        console.log("profile", profile);

        return {
          id: profile.id,
          image: profile.profile,
          name: `${profile.firstname} ${profile.lastname}`,

          // THE FOLLOWING DOES NOT RETURN
          profile: profile,
        };
      },
    }),
  ],
```
<p>How do I expose the full <code>profile</code> object?. It's only returning the <code>image</code> and <code>name</code>.
In my console log - within my StravaProvider of <code>profile</code> - I can see the whole object, but can't seem to return it?</p>
<p>If I assign <code>profile</code> to the <code>name</code> key this works. I seem to be limited with the keys I can add?</p>
<pre class="lang-js prettyprint-override"><code>StravaProvider{...
profile(profile) {
  return {
    // THE FOLLOWING WORKS
    name: profile,
  };
},
</code>```

The returned session object from my initial example and how I am accessing it is:

```<code>const { data: session } = useSession();

console.log(session);

{
    "user": {
        "name": "JOE BLOGGS",
        "image": "https://dgalywyr863hv.cloudfront.net/pictures/athletes/2909982/3009569/1/large.jpg"
    },
    "expires": "2023-02-03T13:39:01.521Z"
}
</code>```

I realise I can use a callback and modify the session, but I need the entire profile there in the first place from the Provider to do that.

Repo - https://github.com/webknit/NextAuth/

Body:
I am trying to extend what is returned in the StravaProvider profile() in nextAuth

pages/api/auth/[...nextauth].js

export default NextAuth({
  providers: [
    StravaProvider({
      clientId: process.env.STRAVA_CLIENT_ID,
      clientSecret: process.env.STRAVA_CLIENT_SECRET,
      profile(profile) {
        // LOGS FINE IN CONSOLE
        console.log("profile", profile);

        return {
          id: profile.id,
          image: profile.profile,
          name: `${profile.firstname} ${profile.lastname}`,

          // THE FOLLOWING DOES NOT RETURN
          profile: profile,
        };
      },
    }),
  ],

How do I expose the full profile object?. It's only returning the image and name.
In my console log - within my StravaProvider of profile - I can see the whole object, but can't seem to return it?

If I assign profile to the name key this works. I seem to be limited with the keys I can add?

StravaProvider{...
profile(profile) {
  return {
    // THE FOLLOWING WORKS
    name: profile,
  };
},

The returned session object from my initial example and how I am accessing it is:

const { data: session } = useSession();

console.log(session);

{
    "user": {
        "name": "JOE BLOGGS",
        "image": "https://dgalywyr863hv.cloudfront.net/pictures/athletes/2909982/3009569/1/large.jpg"
    },
    "expires": "2023-02-03T13:39:01.521Z"
}

I realise I can use a callback and modify the session, but I need the entire profile there in the first place from the Provider to do that.

Repo - https://github.com/webknit/NextAuth/


问:
Outputting or reading columns in a different order using pandas/python
I have a Python script that reads a CSV file and outputs it to HTML.

I would like to change the order of the columns once written to the HTML file, but I don't know if I should do this on read or write or what function to use, here is my code so far.

```<code>import pandas as pd
import os
import shutil
import glob

#paths
HTMLPATH="C:/NMS4/QUE/HTML/"
QUEPATH="C:/NMS4/QUE/"

#create the directory for holding the HTML files if it doesn't exist

isExist = os.path.exists(HTMLPATH)
if not isExist:
  os.mkdir(HTMLPATH, 0o777)

#convert .txt file to a html file in the HTML folder
#can't convert an empty file so only convert if file size in not 0
for quefile in glob.iglob('C:/NMS4/QUE/*.txt'):
  if os.path.getsize(quefile) != 0:
    csv = pd.read_csv(quefile, header=None, usecols=[0,3,4,15,34,43,44,129], names=['OrderNo','Req Qty','Planned Start','Resource','Op','Part','Desc','Qty Recd'])
    html_table = csv.to_html()
    f = open(quefile + '.html', 'w')
    f.write(html_table)
    f.close()
    shutil.move(quefile + ".HTML", HTMLPATH)
</code>```

Any help, greatly appreciated.

Thanks.

I've been looking at https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html, but can't quite find out how to re-order the columns.

Edit,
Changes to get the solution are,

```<code>import pandas as pd
import os
import shutil
import glob

#paths
HTMLPATH="C:/NMS4/QUE/HTML/"
QUEPATH="C:/NMS4/QUE/"

#create the directory for holding the HTML files if it doesn't exist

isExist = os.path.exists(HTMLPATH)
if not isExist:
  os.mkdir(HTMLPATH, 0o777)

#convert .txt file to a html file in the HTML folder
#python can't convert an empty file so only convert if file size in not 0
for quefile in glob.iglob('C:/NMS4/QUE/*.txt'):
  if os.path.getsize(quefile) != 0:
    csv = pd.read_csv(quefile, header=None, usecols=[0,3,4,15,34,43,44,129], names=['Order No','Req Qty','Planned Start','Resource','Op','Part','Desc','Qty Recd'])
    cols = list(csv.columns)
    a, b, c, d, e, f, g = cols.index('Order No'), cols.index('Req Qty'), cols.index('Planned Start'), cols.index('Resource'), cols.index('Op'), cols.index('Part'), cols.index('Desc')
    cols[a], cols[b], cols[c], cols[d], cols[e], cols[f], cols[g] = cols[a], cols[e], cols[f], cols[g], cols[c], cols[b], cols[d]
    df = csv[cols]
    html_table = df.to_html()
    f = open(quefile + '.html', 'w')
    f.write(html_table)
    f.close()
    shutil.move(quefile + ".HTML", HTMLPATH)
</code>```

Body:
I have a Python script that reads a CSV file and outputs it to HTML.

I would like to change the order of the columns once written to the HTML file, but I don't know if I should do this on read or write or what function to use, here is my code so far.

import pandas as pd
import os
import shutil
import glob

#paths
HTMLPATH="C:/NMS4/QUE/HTML/"
QUEPATH="C:/NMS4/QUE/"

#create the directory for holding the HTML files if it doesn't exist

isExist = os.path.exists(HTMLPATH)
if not isExist:
  os.mkdir(HTMLPATH, 0o777)

#convert .txt file to a html file in the HTML folder
#can't convert an empty file so only convert if file size in not 0
for quefile in glob.iglob('C:/NMS4/QUE/*.txt'):
  if os.path.getsize(quefile) != 0:
    csv = pd.read_csv(quefile, header=None, usecols=[0,3,4,15,34,43,44,129], names=['OrderNo','Req Qty','Planned Start','Resource','Op','Part','Desc','Qty Recd'])
    html_table = csv.to_html()
    f = open(quefile + '.html', 'w')
    f.write(html_table)
    f.close()
    shutil.move(quefile + ".HTML", HTMLPATH)

Any help, greatly appreciated.

Thanks.

I've been looking at https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html, but can't quite find out how to re-order the columns.

Edit,
Changes to get the solution are,

import pandas as pd
import os
import shutil
import glob

#paths
HTMLPATH="C:/NMS4/QUE/HTML/"
QUEPATH="C:/NMS4/QUE/"

#create the directory for holding the HTML files if it doesn't exist

isExist = os.path.exists(HTMLPATH)
if not isExist:
  os.mkdir(HTMLPATH, 0o777)

#convert .txt file to a html file in the HTML folder
#python can't convert an empty file so only convert if file size in not 0
for quefile in glob.iglob('C:/NMS4/QUE/*.txt'):
  if os.path.getsize(quefile) != 0:
    csv = pd.read_csv(quefile, header=None, usecols=[0,3,4,15,34,43,44,129], names=['Order No','Req Qty','Planned Start','Resource','Op','Part','Desc','Qty Recd'])
    cols = list(csv.columns)
    a, b, c, d, e, f, g = cols.index('Order No'), cols.index('Req Qty'), cols.index('Planned Start'), cols.index('Resource'), cols.index('Op'), cols.index('Part'), cols.index('Desc')
    cols[a], cols[b], cols[c], cols[d], cols[e], cols[f], cols[g] = cols[a], cols[e], cols[f], cols[g], cols[c], cols[b], cols[d]
    df = csv[cols]
    html_table = df.to_html()
    f = open(quefile + '.html', 'w')
    f.write(html_table)
    f.close()
    shutil.move(quefile + ".HTML", HTMLPATH)


问:
How to grep a particular string from a log for particular period of time
I want to find a string from log for particular interval of time

```<code>grep -i <string> logfile name
</code>```

This is used to find particular string only

Body:
I want to find a string from log for particular interval of time

grep -i <string> logfile name

This is used to find particular string only


问:
module is not defined after executing vite preview (Vite4 + Vue3)
I'm struggling with configuring a project set with Vite4, Vue3.

App.vue should simply import a module defined in other min.js file,
but it isn't and showing an error "{module name} is not defined".

Glad to be know if there is anything I have missed.

Thank you in advance!

package.json

```<code>{
  "name": "test-project",
  "version": "0.0.3",
  "scripts": {
    "dev": "vite --host --port 3333",
    "start:dev": "vite --port 80 --mode dev",
    "start:prod": "vite --host --port 80 --mode production",
    "build": "vite build",
    "build:dev": "vite build --mode dev",
    "build:prod": "vite build --mode production",
    "serve": "vite preview --open",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
    "format": "prettier .  --write",
    "test:unit": "jest"
  },
  "dependencies": {
    "@babel/preset-env": "^7.16.5",
    "@bundled-es-modules/axios": "^0.21.1",
    "@datadog/browser-rum": "^4.15.0",
    "@j-t-mcc/vue3-chartjs": "^1.2.0",
    "@juggle/resize-observer": "^3.3.1",
    "@popperjs/core": "^2.10.2",
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "@stomp/stompjs": "^6.1.2",
    "chart.js": "^3.7.0",
    "crypto-js": "^4.1.1",
    "element-plus": "^1.2.0-beta.6",
    "esbuild": "^0.14.5",
    "file-saver": "^2.0.5",
    "mitt": "^3.0.0",
    "moment": "^2.29.1",
    "moment-timezone": "^0.5.37",
    "path": "^0.12.7",
    "sockjs-client": "^1.5.2",
    "swiper": "^7.4.1",
    "vite-plugin-html": "^3.2.0",
    "vue": "^3.2.16",
    "vue-chart-3": "^3.0.4",
    "vue-cookie-next": "^1.3.0",
    "vue-router": "^4.0.12",
    "vue-universal-modal": "^1.1.3",
    "vue-zoomer": "^0.4.0-beta.2",
    "vue3-lottie": "^2.1.0",
    "vuex": "^4.0.2",
    "webstomp-client": "^1.2.6",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@types/jest": "^27.0.3",
    "@vitejs/plugin-vue": "^4.0.0",
    "@vue/test-utils": "^2.0.0-rc.17",
    "eslint": "^8.3.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-vue": "^8.1.1",
    "jest": "^26.6.3",
    "prettier": "^2.5.0",
    "sass": "^1.45.1",
    "ts-jest": "^26.5.6",
    "vite": "^4.0.0",
    "vue-jest": "^5.0.0-alpha.10"
  }
}
</code>```

vite.config.js

```<code>import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { splitVendorChunkPlugin } from "vite";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [splitVendorChunkPlugin(), vue()],
})
</code>```

index.html (nothing should have been changed from default settings...)

```<code><!DOCTYPE html>
<html lang="en">
  <head>
     <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
</code>```

main.js

```<code>import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import '../src/assets/js/no-working-logic.min.js'; <- this is problem
import 'element-plus/dist/index.css';

createApp(App).mount('#app')
</code>```

App.vue (partial)

```<code><script>
import {onMounted, ref} from 'vue';

export default {
    setup() {
      const password = ref("");
      onMounted(() => {
        try {
          const passwordId = document.getElementById('password');

          const passwordRandom = new KeypadSuit(pinRandom, {

            --- some random logic here ---
            // new Keypadsuit <- this Keypadsuit is defined in no-working-logic.min.js
        } catch (e) {
          alert(e)
        }
      });
      return {
        password
      }
    }
  }
</script>

<template>
  <el-form-item prop="password">
    <el-input
      id="password"
      type="password"
      placeholder="비밀번호"
      v-model="password"
      maxlength="4"
    >
    </el-input>
  </el-form-item>
</template>
</code>```

the problem is(as described on App.vue logic),

no-working-logic.min.js works well on other environments except these.

I have tried with some plugins avaliable on Vite and rollupOptions,

but it was not enough to declare and solve this error.

Should any other conditions/ additional codes be shared, please let me know! Thanks!

Body:
I'm struggling with configuring a project set with Vite4, Vue3.

App.vue should simply import a module defined in other min.js file,
but it isn't and showing an error "{module name} is not defined".

Glad to be know if there is anything I have missed.

Thank you in advance!

package.json

{
  "name": "test-project",
  "version": "0.0.3",
  "scripts": {
    "dev": "vite --host --port 3333",
    "start:dev": "vite --port 80 --mode dev",
    "start:prod": "vite --host --port 80 --mode production",
    "build": "vite build",
    "build:dev": "vite build --mode dev",
    "build:prod": "vite build --mode production",
    "serve": "vite preview --open",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
    "format": "prettier .  --write",
    "test:unit": "jest"
  },
  "dependencies": {
    "@babel/preset-env": "^7.16.5",
    "@bundled-es-modules/axios": "^0.21.1",
    "@datadog/browser-rum": "^4.15.0",
    "@j-t-mcc/vue3-chartjs": "^1.2.0",
    "@juggle/resize-observer": "^3.3.1",
    "@popperjs/core": "^2.10.2",
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "@stomp/stompjs": "^6.1.2",
    "chart.js": "^3.7.0",
    "crypto-js": "^4.1.1",
    "element-plus": "^1.2.0-beta.6",
    "esbuild": "^0.14.5",
    "file-saver": "^2.0.5",
    "mitt": "^3.0.0",
    "moment": "^2.29.1",
    "moment-timezone": "^0.5.37",
    "path": "^0.12.7",
    "sockjs-client": "^1.5.2",
    "swiper": "^7.4.1",
    "vite-plugin-html": "^3.2.0",
    "vue": "^3.2.16",
    "vue-chart-3": "^3.0.4",
    "vue-cookie-next": "^1.3.0",
    "vue-router": "^4.0.12",
    "vue-universal-modal": "^1.1.3",
    "vue-zoomer": "^0.4.0-beta.2",
    "vue3-lottie": "^2.1.0",
    "vuex": "^4.0.2",
    "webstomp-client": "^1.2.6",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@types/jest": "^27.0.3",
    "@vitejs/plugin-vue": "^4.0.0",
    "@vue/test-utils": "^2.0.0-rc.17",
    "eslint": "^8.3.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-vue": "^8.1.1",
    "jest": "^26.6.3",
    "prettier": "^2.5.0",
    "sass": "^1.45.1",
    "ts-jest": "^26.5.6",
    "vite": "^4.0.0",
    "vue-jest": "^5.0.0-alpha.10"
  }
}

vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { splitVendorChunkPlugin } from "vite";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [splitVendorChunkPlugin(), vue()],
})

index.html (nothing should have been changed from default settings...)

<!DOCTYPE html>

     <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue</title>

main.js

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import '../src/assets/js/no-working-logic.min.js'; <- this is problem
import 'element-plus/dist/index.css';

createApp(App).mount('#app')

App.vue (partial)

<template>
  <el-form-item prop="password">
    <el-input
      id="password"
      type="password"
      placeholder="비밀번호"
      v-model="password"
      maxlength="4"
    >
    </el-input>
  </el-form-item>
</template>

the problem is(as described on App.vue logic),

no-working-logic.min.js works well on other environments except these.

I have tried with some plugins avaliable on Vite and rollupOptions,

but it was not enough to declare and solve this error.

Should any other conditions/ additional codes be shared, please let me know! Thanks!


问:
Efficient way to loop through large amount of files, convert them to webp and save the timestamp
I have a folder with about 750'000 images. Some images will change over time and new images will also be added every now and then. The folder-structure is about 4-5 levels deep with a maximum of 70'000 images per one single folder.

I now want to write a script that can do the following:

Loop through all the files

Check if the file is new (has not yet been converted) or changed since the last conversion

Convert the file from jpg or png to webp if above rules apply

My current solution is a python script that writes the conversion-times into a sqlite database. It works, but is really slow. I also thought about doing it in PowerShell due to better performance (I assume) but had no efficient way of storing the conversion-times.

What language would you recommend? Is there another way to convert jpg to webp without having to exernally call the command cwebp from within my script?


问:
Function operation order in C++
I'm pretty new coding C++, but still practicing it.

I have the following code of main.cpp file:

```<code>#include "additionalFile.h"
#include <iostream>

int getValueFromUser() {
    std::cout << "Enter an integer: ";
    int input{};
    std::cin >> input;

    return input;
}

void printDouble(int value) {
    std::cout << value << " doubled is: " << value * 2 << "\n";
}

int main() {
    printDouble(getValueFromUser());
    addNumber(inputFirstNumber(), inputSecondNumber());

    return 0;
}
</code>```

The following code of additionalFile.cpp file:

```<code>#include <iostream>

int inputFirstNumber() {
    std::cout << "Enter first integer: \n";
    int num;
    std::cin >> num;

    return num;
}

int inputSecondNumber() {
    std::cout << "Enter second integer: \n";
    int num;
    std::cin >> num;

    return num;
}

void addNumber(int x, int y) {
    std::cout << "Your result is " << x + y << "\n";
}
</code>```

And code for additionalFile.h file:

```<code>#pragma once
int inputFirstNumber(); int inputSecondNumber(); void addNumber(int x, int y);
</code>```

The question is: Why, when i run the program and it runs addNumber() function, does it ask me for the second digit to input, and then for the first one? The order looks misordered.

Thank you in advance!

```<code>addNumber(inputFirstNumber(), inputSecondNumber());
</code>```

In this line i've exchanged parameters vice versa, and it asked me to input digits in proper order. But i want to get the basic clue of the issue.

Title: Function operation order in C++

Body:
I'm pretty new coding C++, but still practicing it.

I have the following code of main.cpp file:

#include "additionalFile.h"
#include <iostream>

int getValueFromUser() {
    std::cout << "Enter an integer: ";
    int input{};
    std::cin >> input;

    return input;
}

void printDouble(int value) {
    std::cout << value << " doubled is: " << value * 2 << "\n";
}

int main() {
    printDouble(getValueFromUser());
    addNumber(inputFirstNumber(), inputSecondNumber());

    return 0;
}

The following code of additionalFile.cpp file:

#include <iostream>

int inputFirstNumber() {
    std::cout << "Enter first integer: \n";
    int num;
    std::cin >> num;

    return num;
}

int inputSecondNumber() {
    std::cout << "Enter second integer: \n";
    int num;
    std::cin >> num;

    return num;
}

void addNumber(int x, int y) {
    std::cout << "Your result is " << x + y << "\n";
}

And code for additionalFile.h file:

#pragma once
int inputFirstNumber(); int inputSecondNumber(); void addNumber(int x, int y);

The question is: Why, when i run the program and it runs addNumber() function, does it ask me for the second digit to input, and then for the first one? The order looks misordered.

Thank you in advance!

addNumber(inputFirstNumber(), inputSecondNumber());

In this line i've exchanged parameters vice versa, and it asked me to input digits in proper order. But i want to get the basic clue of the issue.


问:
Unexpected exception formatting exception. Falling back to standard exception using gensim
I try to understand Word2vec with a very simple example

import gensim
texts = [
    "This is a sentence.",
    "This is another sentence.",
    "This is also a sentence."
]

texts_split = [text.split() for text in texts]

model = gensim.models.Word2Vec(texts_split, min_count=1, vector_size=100)

word_vectors = model.wv['sentence']

print(word_vectors)
```

Can you explain me why I get the Error: "Unexpected exception formatting exception. Falling back to standard exception"

I can not explain myself where the problem is coming from?

Body:
I try to understand Word2vec with a very simple example

import gensim
texts = [
    "This is a sentence.",
    "This is another sentence.",
    "This is also a sentence."
]

texts_split = [text.split() for text in texts]

model = gensim.models.Word2Vec(texts_split, min_count=1, vector_size=100)

word_vectors = model.wv['sentence']

print(word_vectors)

Can you explain me why I get the Error: "Unexpected exception formatting exception. Falling back to standard exception"

I can not explain myself where the problem is coming from?


问:
Unable to create iceberg table using Trino
I am trying to create iceberg table using trino but ddl is not executing stating that sort_order not find .below sample ddl

```<code>Create table <tableschema>.test ( C1 datetime,
C2 double ,
C3 double
)
With ( format='parquet',
       Location='S3a:// location of file',
        Partitioning=ARRAY['day(C1)'],
        Sort_order=ARRAY['C2','C3']
)
</code>```

DDL not executing when I am defining the sort_order for table . Without sort_order table getting created

Can you please help with this is anything I need to modify in DDL . I am using trino-jdbc380.jar for driver to connect

Body:
I am trying to create iceberg table using trino but ddl is not executing stating that sort_order not find .below sample ddl

Create table <tableschema>.test ( C1 datetime,
C2 double ,
C3 double
)
With ( format='parquet',
       Location='S3a:// location of file',
        Partitioning=ARRAY['day(C1)'],
        Sort_order=ARRAY['C2','C3']
)

DDL not executing when I am defining the sort_order for table . Without sort_order table getting created

Can you please help with this is anything I need to modify in DDL . I am using trino-jdbc380.jar for driver to connect


问:
How to terminate app after each test Appium UIAutomator2
I've been using older version of Appium and appium-java-client and recently I've been trying to upgrade to new versions. For closing the app after each android test I used mobileDriver.quit() but it's not working in the new version. I've read the documentation and found a command mobileDriver.executeScript("mobile: terminateApp", ImmutableMap.of("appId", "app.id")) but it won't work either. Has anyone been able to achieve this?
Thanks in advance.


问:
React and multilingual site: good pratices / SEO
I have a site done with React. On this site, two languages are available: 'en' and 'fr'. Here is how I implement it:

When the user comes on my site for the first time, I determine the language from its browser and I redirect it to www.mysite.com/fr or www.mysite.com/en.

The user is also free to change the language or directly access to the URL containing the language (example: www.mysite.com/fr).

Each time the language change, I store it in the local storage. This way, the user can comeback to www.mysite.com and I will redirect him to the correct URL containing the language (example: www.mysite.com/fr).

I don't specify 'lang' attribute on 'html' tag in my 'index.html' but when I know the language, I use Javascript to add this attribute dynamically.

I defined two 'hreflang' in the 'index.html'.

I already noticed two small problems with this implementation:

When I analyze my site with https://validator.w3.org/, I've got a warning telling me that 'lang' attribute is missing. I guess, this validator doesn't execute the Javascript. Can I considered it as a false positive ?

The browser extension 'Google Translate' seems to consider www.mysite.com/fr as an English page. I guess the extension doesn't wait enough to see the dynamic update of 'lang' attribute.

Is there is a way to avoid these problems ? Do you see other problems in my implementation ?


问:
using only one parametr from ax.table {bbox} for height (depends from length of text) of rows in matplotlib
I have a problem in formating pdf report.
One value in my record list is a big text, that need to be wrap and the size of row must cover all text. I've tried by using bbox option from: https://matplotlib.org/stable/api/transformations.html#matplotlib.transforms.Bbox ,but I need only one- the last 4th parameter, which will be change dynamically from the length of text. I'm not sure how to sapare it from previous ones..and finally is it correct road to establish the height of table

Thanks for every kind of help!

the whole code looks that (it genereted raport, but I can't publish it):

```<code>            wrapError = ('\n' + ' ').join(wrapError)
            ErorrsInTable = {'clas':[clas],'path':[path],'translate':[translate], 'full content':[wrapError], 'row of Error':[rowError], 'column of Error':[columnError]}#'wrapError' set the length of row
            df = pd.DataFrame(ErorrsInTable)
            fig, ax = plt.subplots(figsize=(26,0.01*len(wrapError)))#size of window
            plt.subplots_adjust(left = 0.1, top = 0.95)
            tytul=plt.title('Report of errors', fontweight="bold")
            ax.axis('auto')
            ax.axis('off')
            the_table = ax.table(cellText=df.values, cellLoc='center', rowLoc='center',  colLabels=df.columns, loc='upper center', bbox=[0,0,0,0.01*len(wrapError)],  edges='closed')#here is the problematic bbox
            the_table.auto_set_font_size(False)
            the_table.set_fontsize(8)
            the_table.auto_set_column_width(col=list(range(len(df.columns))))
            the_table.scale(0,0.01*len(wrapError))
            cellDict = the_table.get_celld()
     ...
            pp = PdfPages(str(path)+ "\errorReports.pdf")
            print ("report was created")
            pp.savefig(fig)
            pp.close()```
```

Body:
I have a problem in formating pdf report.
One value in my record list is a big text, that need to be wrap and the size of row must cover all text. I've tried by using bbox option from: https://matplotlib.org/stable/api/transformations.html#matplotlib.transforms.Bbox ,but I need only one- the last 4th parameter, which will be change dynamically from the length of text. I'm not sure how to sapare it from previous ones..and finally is it correct road to establish the height of table

Thanks for every kind of help!

the whole code looks that (it genereted raport, but I can't publish it):

            wrapError = ('\n' + ' ').join(wrapError)
            ErorrsInTable = {'clas':[clas],'path':[path],'translate':[translate], 'full content':[wrapError], 'row of Error':[rowError], 'column of Error':[columnError]}#'wrapError' set the length of row
            df = pd.DataFrame(ErorrsInTable)
            fig, ax = plt.subplots(figsize=(26,0.01*len(wrapError)))#size of window
            plt.subplots_adjust(left = 0.1, top = 0.95)
            tytul=plt.title('Report of errors', fontweight="bold")
            ax.axis('auto')
            ax.axis('off')
            the_table = ax.table(cellText=df.values, cellLoc='center', rowLoc='center',  colLabels=df.columns, loc='upper center', bbox=[0,0,0,0.01*len(wrapError)],  edges='closed')#here is the problematic bbox
            the_table.auto_set_font_size(False)
            the_table.set_fontsize(8)
            the_table.auto_set_column_width(col=list(range(len(df.columns))))
            the_table.scale(0,0.01*len(wrapError))
            cellDict = the_table.get_celld()
     ...
            pp = PdfPages(str(path)+ "\errorReports.pdf")
            print ("report was created")
            pp.savefig(fig)
            pp.close()```


问:
JDA Discord using modals (slash commands) working only on debug mode
im using first time discord modals (slash commands) on JDA. When I export the bot and turn it on, the commands appear under / (slash commands) they do not work, it shows "The application is not responding"

```<code>JDA jda = JDABuilder.createDefault(token)
                .setActivity(Activity.listening("TEST"))
                .addEventListeners(new TestCommand())
                .build().awaitReady();

        Guild guild = jda.getGuildById("SERVER_ID");

        if (guild != null){
            guild.upsertCommand("test", "test command").queue();
        }
</code>```

TestCommand

```<code>@Override
    public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {

        if (event.getName().equals("test")){

            TextInput test_name = TextInput.create("test-name", "Name", TextInputStyle.SHORT)
                    .setPlaceholder("test text")
                    .setMinLength(1)
                    .setRequired(true)
                    .build();

            TextInput message = TextInput.create("test-message","Message", TextInputStyle.PARAGRAPH)
                    .setMinLength(10)
                    .setMaxLength(100)
                    .setRequired(true)
                    .setValue("test text.")
                    .build();

            Modal modal = Modal.create("test-modal", "test text")
                    .addActionRows(ActionRow.of(name), ActionRow.of(message))
                    .build();

            event.replyModal(modal).queue();
</code>```

If turn it on IntelliJ debug mode and enable the bot without exporting, the slash commands / work normally.

Body:
im using first time discord modals (slash commands) on JDA. When I export the bot and turn it on, the commands appear under / (slash commands) they do not work, it shows "The application is not responding"

JDA jda = JDABuilder.createDefault(token)
                .setActivity(Activity.listening("TEST"))
                .addEventListeners(new TestCommand())
                .build().awaitReady();

        Guild guild = jda.getGuildById("SERVER_ID");

        if (guild != null){
            guild.upsertCommand("test", "test command").queue();
        }

TestCommand

@Override
    public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {

        if (event.getName().equals("test")){

            TextInput test_name = TextInput.create("test-name", "Name", TextInputStyle.SHORT)
                    .setPlaceholder("test text")
                    .setMinLength(1)
                    .setRequired(true)
                    .build();

            TextInput message = TextInput.create("test-message","Message", TextInputStyle.PARAGRAPH)
                    .setMinLength(10)
                    .setMaxLength(100)
                    .setRequired(true)
                    .setValue("test text.")
                    .build();

            Modal modal = Modal.create("test-modal", "test text")
                    .addActionRows(ActionRow.of(name), ActionRow.of(message))
                    .build();

            event.replyModal(modal).queue();

If turn it on IntelliJ debug mode and enable the bot without exporting, the slash commands / work normally.


问:
How to implement dynamic certificate generation in Java, similar to Golang's tls.Config.GetCertificate
like Go:

func main() {
ln, _ := net.Listen("tcp",":443")
ln = tls.NewListener(ln, &tls.Config{
    GetCertificate: func (info *clientHelloInfo) (Certificate, error) {
        // from db or dynamic generate a certificate use "info.ServerName"
        cert := generateX509Certificate(info.ServerName)
        return cert, nil
    }
})
}
```

In Go I can implement that the first time a domain is accessed (or even a concurrent request) only one goroutine is responsible for generating the certificate, and then when that is done, all connections are immediately successful.

No idea. Since Spring is called through Netty, but don't know how to modify the Netty behavior of Spring.

Body:
like Go:

func main() {
ln, _ := net.Listen("tcp",":443")
ln = tls.NewListener(ln, &tls.Config{
    GetCertificate: func (info *clientHelloInfo) (Certificate, error) {
        // from db or dynamic generate a certificate use "info.ServerName"
        cert := generateX509Certificate(info.ServerName)
        return cert, nil
    }
})
}

In Go I can implement that the first time a domain is accessed (or even a concurrent request) only one goroutine is responsible for generating the certificate, and then when that is done, all connections are immediately successful.

No idea. Since Spring is called through Netty, but don't know how to modify the Netty behavior of Spring.


问:
How to send Jenkins build notification to MS Teams
I have written a Jenkins pipeline job to build and push images, and wanted to get the build notification with build details, tags, and committers in MS-Teams; but I am not able to send notification to the MS-Teams.

Below is what I have tried:

```<code>stage('MSTEAMS') {
            steps {
                office365ConnectorSend webhookUrl: "https://orosoft.webhook.office.com/webhookb////xxxxxxxxxxxxx",
                message: "The Build has been completed, here is the image URL>>> 123456.dkr.ecr.ap-south-1.amazonaws.com/${REPO}:${TAG}",
                status: "Success",
                color: "00ff00"
            }
        }
</code>```

Body:
I have written a Jenkins pipeline job to build and push images, and wanted to get the build notification with build details, tags, and committers in MS-Teams; but I am not able to send notification to the MS-Teams.

Below is what I have tried:

stage('MSTEAMS') {
            steps {
                office365ConnectorSend webhookUrl: "https://orosoft.webhook.office.com/webhookb////xxxxxxxxxxxxx",
                message: "The Build has been completed, here is the image URL>>> 123456.dkr.ecr.ap-south-1.amazonaws.com/${REPO}:${TAG}",
                status: "Success",
                color: "00ff00"
            }
        }


问:
Selected table row in TableView border leaks
I have an interesting challenge. I have a JavaFX 8 TableView which seems to leak vertical borders of table cells in a selected row into the next or previous row. I have searched around and can't seem to find anyone who has come across the same. Not sure the image I uploaded actually displays, but it is a very thin line extending from a table cell's vertical border, but not all table rows exhibit this behavior.

I have applied the following CSS:

```<code>.table-row-cell:selected {
    -fx-background-color: -fx-focus-color;
    -fx-text-background-color: white;
}
.table-row-cell:selected-row {
    -fx-background-color: -fx-focus-color;
    -fx-text-background-color: white;
}
</code>```

Body:
I have an interesting challenge. I have a JavaFX 8 TableView which seems to leak vertical borders of table cells in a selected row into the next or previous row. I have searched around and can't seem to find anyone who has come across the same. Not sure the image I uploaded actually displays, but it is a very thin line extending from a table cell's vertical border, but not all table rows exhibit this behavior.

I have applied the following CSS:

.table-row-cell:selected {
    -fx-background-color: -fx-focus-color;
    -fx-text-background-color: white;
}
.table-row-cell:selected-row {
    -fx-background-color: -fx-focus-color;
    -fx-text-background-color: white;
}


问:
Asp.net core 6 Set the CurrentCulture for the first request
I am trying to set the value of CultureInfo.CurrentCulture for the first as follow:

In the Configure method of the startup class

```<code>             string defCulture =
            configuration.GetSection("Defaults").GetSection("DefalutLang").Value.Trim();
            var requestCulture = new CultureInfo(defCulture);

            app.UseRequestLocalization();
            CultureInfo.DefaultThreadCurrentCulture = requestCulture;
            CultureInfo.DefaultThreadCurrentUICulture = requestCulture;
            CultureInfo.CurrentCulture = requestCulture;
            CultureInfo.CurrentUICulture = requestCulture;
            app.UseRouting();
</code>```

And in the configure services:

```<code>    string defCulture = configuration.GetSection("Defaults").GetSection("DefalutLang").Value.Trim();
        var cultures = CultureHelper.GetArrOfCultureInfo(configuration);
        services.Configure<RequestLocalizationOptions>(ops =>
        {
            ops.SupportedCultures = cultures;
            ops.SupportedUICultures = cultures;
            ops.DefaultRequestCulture = new RequestCulture(defCulture);
            ops.RequestCultureProviders.Insert(0, new RouteSegmentRequestCultureProvider(cultures));
        });
</code>```

But the CurrentCulture in the View is not the one I have configured in the startup class
The view:

```<code>@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options

@inject IOptions<RequestLocalizationOptions> LocOps

@{

    var requestCulture = CultureInfo.CurrentCulture;
}
</code>```

Body:
I am trying to set the value of CultureInfo.CurrentCulture for the first as follow:

In the Configure method of the startup class

             string defCulture =
            configuration.GetSection("Defaults").GetSection("DefalutLang").Value.Trim();
            var requestCulture = new CultureInfo(defCulture);

            app.UseRequestLocalization();
            CultureInfo.DefaultThreadCurrentCulture = requestCulture;
            CultureInfo.DefaultThreadCurrentUICulture = requestCulture;
            CultureInfo.CurrentCulture = requestCulture;
            CultureInfo.CurrentUICulture = requestCulture;
            app.UseRouting();

And in the configure services:

    string defCulture = configuration.GetSection("Defaults").GetSection("DefalutLang").Value.Trim();
        var cultures = CultureHelper.GetArrOfCultureInfo(configuration);
        services.Configure<RequestLocalizationOptions>(ops =>
        {
            ops.SupportedCultures = cultures;
            ops.SupportedUICultures = cultures;
            ops.DefaultRequestCulture = new RequestCulture(defCulture);
            ops.RequestCultureProviders.Insert(0, new RouteSegmentRequestCultureProvider(cultures));
        });

But the CurrentCulture in the View is not the one I have configured in the startup class
The view:

@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options

@inject IOptions<RequestLocalizationOptions> LocOps

@{

    var requestCulture = CultureInfo.CurrentCulture;
}


问:
stm32f7 https connection using with mbedtls
my connnection is return -0x0050 on ssl_tls step.

```<code>  < Read from server:../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:8270: => read<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:4311: => read record<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2536: => fetch input<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2696: in_left: 0, nb_want: 5<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2720: in_left: 0, nb_want: 5<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2722: ssl->f_recv(_timeout)() returned -80 (-0x0050)<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:4973: mbedtls_ssl_fetch_input() returned -80 (-0x0050)<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:4344: ssl_get_next_record() returned -80 (-0x0050)<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:8335: mbedtls_ssl_read_record() returned -80 (-0x0050)<\n>

</code>```

I tried to connect google.

I tried change heap size. I tried connect to other website etc.

Body:
my connnection is return -0x0050 on ssl_tls step.

  < Read from server:../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:8270: => read<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:4311: => read record<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2536: => fetch input<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2696: in_left: 0, nb_want: 5<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2720: in_left: 0, nb_want: 5<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:2722: ssl->f_recv(_timeout)() returned -80 (-0x0050)<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:4973: mbedtls_ssl_fetch_input() returned -80 (-0x0050)<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:4344: ssl_get_next_record() returned -80 (-0x0050)<\n>
../Middlewares/Third_Party/mbedTLS/library/ssl_tls.c:8335: mbedtls_ssl_read_record() returned -80 (-0x0050)<\n>

I tried to connect google.

I tried change heap size. I tried connect to other website etc.


问:
When using `docker compose` how can you show each build step's intermeddiate cached container id?
It's common for docker build steps to fail. The "new" dockerx builder hides critical info for ... some reason. This makes it much more difficult to run the container where it failed and debug. Is there an easy way to enable viewing those intermediate id's?

You can use something like:

DOCKER_BUILDKIT=0 docker compose build my-service

To use the old way, but does buildkit/buildx support just viewing those ids?


问:
Property 'whileInView' does not exist on type 'IntrinsicAttributes
I have a motion component with the framer-motion property useInView in a .tsx file but I'm getting an error:

Property 'whileInView' does not exist on type 'IntrinsicAttributes &
SVGMotionProps & RefAttributes'

Here's a stripped down version of my component:

```<code>const LogoIcon = () => {
  //Animation Variants
  const logoAnimation = {
    initial: {
      pathLength: -1,
    },
    animate: {
      pathLength: 1,
    },
  };

  return (
    <div>
      <Svg viewBox="0 0 140 158">
        <motion.path
          variants={logoAnimation}
          initial="initial"
          whileInView="animate"
          vectorEffect="non-scaling-stroke"
          d="..."
        />
      </Svg>
    </div>
  );
};

const Svg = styled.svg`
  max-width: 200px;
  width: 100%;
  height: auto;
  path {
    fill: none;
    stroke: ${({ theme }) => theme.colors.gray["700"]};
    stroke-miterlimit: 10;
    stroke-width: 1;
  }
`;

export default LogoIcon;
</code>```

I've used whileInView in .js files before and never had this error.

I may be wrong but I get the feeling I need to set proptypes for useInView, though I'm not sure how to set them for this property.

Any help would be appreciated.

Body:
I have a motion component with the framer-motion property useInView in a .tsx file but I'm getting an error:

Property 'whileInView' does not exist on type 'IntrinsicAttributes &
SVGMotionProps & RefAttributes'

Here's a stripped down version of my component:

const LogoIcon = () => {
  //Animation Variants
  const logoAnimation = {
    initial: {
      pathLength: -1,
    },
    animate: {
      pathLength: 1,
    },
  };

  return (

      <Svg viewBox="0 0 140 158">
        <motion.path
          variants={logoAnimation}
          initial="initial"
          whileInView="animate"
          vectorEffect="non-scaling-stroke"
          d="..."
        />
      </Svg>

  );
};

const Svg = styled.svg`
  max-width: 200px;
  width: 100%;
  height: auto;
  path {
    fill: none;
    stroke: ${({ theme }) => theme.colors.gray["700"]};
    stroke-miterlimit: 10;
    stroke-width: 1;
  }
`;

export default LogoIcon;

I've used whileInView in .js files before and never had this error.

I may be wrong but I get the feeling I need to set proptypes for useInView, though I'm not sure how to set them for this property.

Any help would be appreciated.


问:
Call a subprocess to process and kill after two minutes python
I try call exe and if it is over two minutes kill the process but it is not work</p>
```<code>def call_autoit(path_exe, setting='', state=''):
    if setting or state:
        logging.info("start autoit '%s' with argument set setting '%s' to '%s'" % (path_exe,setting, state))
    else:
        logging.info("start autoit  '%s'" % path_exe)
    os.chdir(pathAutoit)

    try:
        args = [path_exe, setting, state]
        process = subprocess.run(args, stdout=subprocess.PIPE, shell=True, timeout=100)
        logging.info("'%s' set to '%s'" % (setting, state))
    except subprocess.TimeoutExpired:
        # Kill the process if the timeout is reached
        process.kill()
        logging.error("Timed out while trying to call '%s'" % path_exe)
    except IOError as e:
        logging.error(" error '%s'" % e.strerror)
        exit(1)
</code>```

Body:
I try call exe and if it is over two minutes kill the process but it is not work

def call_autoit(path_exe, setting='', state=''):
    if setting or state:
        logging.info("start autoit '%s' with argument set setting '%s' to '%s'" % (path_exe,setting, state))
    else:
        logging.info("start autoit  '%s'" % path_exe)
    os.chdir(pathAutoit)

    try:
        args = [path_exe, setting, state]
        process = subprocess.run(args, stdout=subprocess.PIPE, shell=True, timeout=100)
        logging.info("'%s' set to '%s'" % (setting, state))
    except subprocess.TimeoutExpired:
        # Kill the process if the timeout is reached
        process.kill()
        logging.error("Timed out while trying to call '%s'" % path_exe)
    except IOError as e:
        logging.error(" error '%s'" % e.strerror)
        exit(1)


问:
AssignedAccess not working in Powershell on Windows 11
I'm trying to use 'Set-AssignedAccess' on windows 11, but whenever I try the command, it fails. Based on how simple online instructions make it sound, I'm guessing I'm just doing it wrong. I'm using the first result for PowerShell, and have tried normal and admin versions.

I tried to use 'Set-AssignedAccess' in PowerShell, but it cast an error that the command wasn't found. I've also run the 'Import-Module' for AssignedAccess in PowerShell with no success.

I've checked around for a while and I haven't found a resource that displays a resolution to this issue. I'm not too familiar with PowerShell, so if there was something I should've included that I didn't, I'm sorry about that.


问:
Module parse failed: Unexpected character '' when importing video file
Making a video player in NextJS using TS. I imported a video file from my src/assets folder and this is the error I am getting.

error - ./src/assets/video.mp4 Module parse failed: Unexpected
character '' (1:0) You may need an appropriate loader to handle this
file type, currently no loaders are configured to process this file.
See https://webpack.js.org/concepts#loaders (Source code omitted for
this binary file)

I researched a bit and found out that the webpack is the issue here. Some of the solutions in Stack Overflow suggests that I should add a custom.d.ts file in my project and add the following:

```<code>declare module "*.mp4" {
  const src: string;
  export default src;
}
</code>```

which omits the error caused when importing video files, but the error I am facing is in compile time. Another solution is to add loaders to webpack.config.js. But which webpack.config.js file? I only have one in my node_modules folder, and it is in boxicon. I don't have much experience in changing these types of settings, which might cause big issues. So, how to work around this issue?

Body:
Making a video player in NextJS using TS. I imported a video file from my src/assets folder and this is the error I am getting.

error - ./src/assets/video.mp4 Module parse failed: Unexpected
character '' (1:0) You may need an appropriate loader to handle this
file type, currently no loaders are configured to process this file.
See https://webpack.js.org/concepts#loaders (Source code omitted for
this binary file)

I researched a bit and found out that the webpack is the issue here. Some of the solutions in Stack Overflow suggests that I should add a custom.d.ts file in my project and add the following:

declare module "*.mp4" {
  const src: string;
  export default src;
}

which omits the error caused when importing video files, but the error I am facing is in compile time. Another solution is to add loaders to webpack.config.js. But which webpack.config.js file? I only have one in my node_modules folder, and it is in boxicon. I don't have much experience in changing these types of settings, which might cause big issues. So, how to work around this issue?


问:
How can I completely remove a hazelcast map from a Hazelcast cluster running externally from my applications?
I am working on a project to externalize some of our maps with an external cluster using the client/server topology provided by Hazelcast. We are using version 5.2. I want to build an endpoint or use some api provided by Hazelcast to allow me to completely remove the map in the external cluster. I don't see anywhere in the Hazelcast Management Center where you can delete maps or any API that allows me to do this.
I don't want to just evict entries I want to remove them and completely get rid of the map. I also don't want to bring the cluster down.

I have tried getting the map from the instance and calling destroy with my local external cluster and that also doesn't seem to work.

externalHazelcastInstance.getMap("mapOfStuff").destroy();

It will evict the entries but the map is still there.

I have found that I can enable the REST api with my NetworkConfig but there doesn't seem to be a solution there either.


问:
problem font in ICEpdf viewer when i m transform pdf document in image
When i do this in java

```<code>
BufferedImage image = (BufferedImage) _document.getPageImage( 0, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, _rotation, _scale );
</code>```

The ' (apostrophe) in the pdf document become a seven white in a black circle

I'm in 6.2 version of icepdf and i cant upgrade to icepdf 7.0.0 version because our software is not ready to jdk11 yet

But i see the font in my pdf document and it seems to me you support theses fonts already:

Hekvetica: Type: Type1, Encodage: ANSI, Police ArialMT, True Type

Hekvetica-Bold: Type: Type1, Encodage: ANSI, Police Arial-BoldMT, TrueType

Times-Bold: Type: Type1, Encodage: ANSI, Police TimesNewRomanPS-BoldMT, True Type

Times-Roman: Type: Type1, Encodage: ANSI, Police TimesNewRomanPSMT, True

It's standard fonts no ?

Thank you for your help

Regards

Didier Maurel

i try to install version 7.0.0
solve this problem

Body:
When i do this in java

BufferedImage image = (BufferedImage) _document.getPageImage( 0, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, _rotation, _scale );

The ' (apostrophe) in the pdf document become a seven white in a black circle

I'm in 6.2 version of icepdf and i cant upgrade to icepdf 7.0.0 version because our software is not ready to jdk11 yet

But i see the font in my pdf document and it seems to me you support theses fonts already:

Hekvetica: Type: Type1, Encodage: ANSI, Police ArialMT, True Type

Hekvetica-Bold: Type: Type1, Encodage: ANSI, Police Arial-BoldMT, TrueType

Times-Bold: Type: Type1, Encodage: ANSI, Police TimesNewRomanPS-BoldMT, True Type

Times-Roman: Type: Type1, Encodage: ANSI, Police TimesNewRomanPSMT, True

It's standard fonts no ?

Thank you for your help

Regards

Didier Maurel

i try to install version 7.0.0
solve this problem


问:
Angular custom loader doesn't work properly
I am trying to fix a bug that is caused by ngx translate language change. Changing language from default to English for the first time doesn't cause any issues, the loader works fine, but after changing from English to Georgian loader doesn't stop loading.
After changing language for the first time I also noticed that request is not made for some reason and as a result in interceptor, finalize method is not ecxecuted

loader.component.html

```<code><div class="progress-bar-container">
      <div class="progress-bar" [ngClass]="{'in-progress': !show, 'fill': show}"></div>
</div>
</code>```

loader.component.ts

```<code>export class ProgressBarComponent {

  show = true;

  constructor(private progressBarService: ProgressBarService) {

    this.progressBarService.progressBarSub()

      .subscribe(status => {

        this.show = status;

      })

  }

}

</code>```

app.component.ts

```<code>export class AppComponent {
  title = 'app';

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private progressBarService: ProgressBarService,
    private prevRoute: PreviousRouteService,
    private locationStrategy: LocationStrategy,
    private translate: TranslateService) {
    translate.addLangs(['en', 'ka']);

    this.activatedRoute.queryParams
      .subscribe(p => {
        const { lang } = p;
        if (!this.checkLang(lang) && lang.match(/en|ka|EN|KA/)) {
          let oldLang = this.translate.currentLang
          if (!oldLang) {
            this.translate.use(lang.toLowerCase());
            sessionStorage.setItem('lang', lang.toLowerCase());
          } else {
            const qParams = { ...p };
            qParams['lang'] = oldLang;
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { ...qParams }, replaceUrl: true })
              .catch(err => console.log(err))
          }
        } else {
          this.translate.setDefaultLang('ka');
          sessionStorage.setItem('lang', 'ka');
        }
      })

    this.router.events
      .subscribe(event => {
        if (event instanceof NavigationStart) {
          if (event.url.includes('result')) {
            history.pushState(null, null, location.href);

            this.locationStrategy.onPopState((l: LocationChangeEvent) => {
              history.pushState(null, null, location.href);
            });
          }

          if (this.prevRoute.prevPath == undefined) {
            this.prevRoute.previousRoutePath.next(event.url);
          }
          this.progressBarService.progressBarProcess(false);
        }
      })
  }

  private checkLang(lang) {
    return lang === undefined || lang === "undefined" || lang === null || lang.length <= 0;
  }
}
</code>```

header.component.ts where I have dropdown flags for changing languages on click.
here after change language method is called I tried to log result of activatedroute.subscribe and after each call subscribe method returns result increased by one compared to previous call. I have no idea what causes that as well.

```<code>this.translate.onDefaultLangChange
      .subscribe(defaultLang => {
        this.currentLang = defaultLang.lang;
        this.languageFlags = this.filterFlags();
      })

    this.translate.onLangChange
      .subscribe(lang => {
        this.currentLang = lang.lang;
        this.languageFlags = this.filterFlags();
      })
  }

  showPopOver() {
    setTimeout(() => {
      this.popoverVisible = !this.popoverVisible;
    }, 0)
  }

  toggleLanguageDropdown() {
    this.languageDropdown = !this.languageDropdown;
  }

  changeLanguage(lang: string) {
    this.languageDropdown = false;
    this.translate.use(lang)
      .subscribe(() => {
        this.languageFlags = this.langs;
        this.currentLang = this.translate.currentLang
        this.languageFlags = this.filterFlags();
        window.sessionStorage.setItem('lang', lang);
        this.activatedRoute.queryParams
          .subscribe(r => {
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { lang: lang, status: r['status'] }, replaceUrl: true })
              .catch(err => console.log(err))
          });
      })
  }

  private filterFlags(): string[] {
    return this.languageFlags.filter(el => el !== this.currentLang)
  }

</code>```

Interceptor

```<code>constructor(private progressBarService: ProgressBarService) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.progressBarService.progressBarProcess(false);

    const token = window.sessionStorage.getItem('auth_token');

    const lang = window.sessionStorage.getItem('lang') ?? 'ka';

    const newReq = token

      ? req.clone({ headers: req.headers.set("Authorization", `Bearer ${token}`).set("Accept-Language", lang) })

      : req.clone({ headers: req.headers.set("Accept-Language", lang) });

    return next.handle(newReq)

      .pipe(

        catchError((error) => {

          if (error.status === 301) {

            window.location.reload();

          }

          return throwError(error);

        }),

        finalize(() => {

          this.progressBarService.progressBarProcess(true);

        }));

  }

</code>```

Body:
I am trying to fix a bug that is caused by ngx translate language change. Changing language from default to English for the first time doesn't cause any issues, the loader works fine, but after changing from English to Georgian loader doesn't stop loading.
After changing language for the first time I also noticed that request is not made for some reason and as a result in interceptor, finalize method is not ecxecuted

loader.component.html

loader.component.ts

export class ProgressBarComponent {

  show = true;

  constructor(private progressBarService: ProgressBarService) {

    this.progressBarService.progressBarSub()

      .subscribe(status => {

        this.show = status;

      })

  }

}

app.component.ts

export class AppComponent {
  title = 'app';

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private progressBarService: ProgressBarService,
    private prevRoute: PreviousRouteService,
    private locationStrategy: LocationStrategy,
    private translate: TranslateService) {
    translate.addLangs(['en', 'ka']);

    this.activatedRoute.queryParams
      .subscribe(p => {
        const { lang } = p;
        if (!this.checkLang(lang) && lang.match(/en|ka|EN|KA/)) {
          let oldLang = this.translate.currentLang
          if (!oldLang) {
            this.translate.use(lang.toLowerCase());
            sessionStorage.setItem('lang', lang.toLowerCase());
          } else {
            const qParams = { ...p };
            qParams['lang'] = oldLang;
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { ...qParams }, replaceUrl: true })
              .catch(err => console.log(err))
          }
        } else {
          this.translate.setDefaultLang('ka');
          sessionStorage.setItem('lang', 'ka');
        }
      })

    this.router.events
      .subscribe(event => {
        if (event instanceof NavigationStart) {
          if (event.url.includes('result')) {
            history.pushState(null, null, location.href);

            this.locationStrategy.onPopState((l: LocationChangeEvent) => {
              history.pushState(null, null, location.href);
            });
          }

          if (this.prevRoute.prevPath == undefined) {
            this.prevRoute.previousRoutePath.next(event.url);
          }
          this.progressBarService.progressBarProcess(false);
        }
      })
  }

  private checkLang(lang) {
    return lang === undefined || lang === "undefined" || lang === null || lang.length <= 0;
  }
}

header.component.ts where I have dropdown flags for changing languages on click.
here after change language method is called I tried to log result of activatedroute.subscribe and after each call subscribe method returns result increased by one compared to previous call. I have no idea what causes that as well.

this.translate.onDefaultLangChange
      .subscribe(defaultLang => {
        this.currentLang = defaultLang.lang;
        this.languageFlags = this.filterFlags();
      })

    this.translate.onLangChange
      .subscribe(lang => {
        this.currentLang = lang.lang;
        this.languageFlags = this.filterFlags();
      })
  }

  showPopOver() {
    setTimeout(() => {
      this.popoverVisible = !this.popoverVisible;
    }, 0)
  }

  toggleLanguageDropdown() {
    this.languageDropdown = !this.languageDropdown;
  }

  changeLanguage(lang: string) {
    this.languageDropdown = false;
    this.translate.use(lang)
      .subscribe(() => {
        this.languageFlags = this.langs;
        this.currentLang = this.translate.currentLang
        this.languageFlags = this.filterFlags();
        window.sessionStorage.setItem('lang', lang);
        this.activatedRoute.queryParams
          .subscribe(r => {
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { lang: lang, status: r['status'] }, replaceUrl: true })
              .catch(err => console.log(err))
          });
      })
  }

  private filterFlags(): string[] {
    return this.languageFlags.filter(el => el !== this.currentLang)
  }

Interceptor

constructor(private progressBarService: ProgressBarService) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.progressBarService.progressBarProcess(false);

    const token = window.sessionStorage.getItem('auth_token');

    const lang = window.sessionStorage.getItem('lang') ?? 'ka';

    const newReq = token

      ? req.clone({ headers: req.headers.set("Authorization", `Bearer ${token}`).set("Accept-Language", lang) })

      : req.clone({ headers: req.headers.set("Accept-Language", lang) });

    return next.handle(newReq)

      .pipe(

        catchError((error) => {

          if (error.status === 301) {

            window.location.reload();

          }

          return throwError(error);

        }),

        finalize(() => {

          this.progressBarService.progressBarProcess(true);

        }));

  }


问:
appium-java Unknown HttpClient factory apache when initializing driver
I'm  trying to migrate from appium-java client 7.0 to 8.3 - After updating to 8.3 version I get an error when initializing appium driver (for iOS)

```<code>java.lang.IllegalArgumentException: Unknown HttpClient factory apache
at org.openqa.selenium.remote.http.HttpClient$Factory.create(HttpClient.java:57)
at org.openqa.selenium.remote.http.HttpClient$Factory.createDefault(HttpClient.java:73)
at io.appium.java_client.remote.AppiumCommandExecutor.<init>(AppiumCommandExecutor.java:108)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:92)
at io.appium.java_client.ios.IOSDriver.<init>(IOSDriver.java:106)
</code>```

Command to start appium server is build smth like this

```<code>command = nodePath + "  " + appiumMainJS + " ";
command = command + " -a " + hostName + " -p " + availablePort + " ";
command = command + " -cp " + (availablePort + 1000) + " -bp " + (availablePort + 2000);
command = command + " --chromedriver-port " + (availablePort + 3000);
command = command + " " + appiumArgs;
</code>```

Capabilities

```<code>capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, OS_VERIOSN);
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
capabilities.setCapability("appium:keychainPath", KEYCHAIN_PATH);
capabilities.setCapability("appium:keychainPassword", KEYCHAIN_PASSWORD);
capabilities.setCapability("appium:xcodeOrgId", XCODE_ORG_ID);
capabilities.setCapability("appium:xcodeSigningId", XCODE_SIGNING_ID);
capabilities.setCapability("appium:deviceName", DEVICE_NAME);
capabilities.setCapability("appium:showXcodeLog", true);
capabilities.setCapability("appium:noReset", false);
capabilities.setCapability("appium:simpleIsVisibleCheck", false);
capabilities.setCapability(MobileCapabilityType.UDID, DEVICE_ID);
capabilities.setCapability("appium:newCommandTimeout", "2000000");
capabilities.setCapability("appium:launchTimeout", "120000");
capabilities.setCapability("appium:shouldUseSingletonTestManager", false);
capabilities.setCapability("appium:wdaConnectionTimeout", 15*60*1000);
capabilities.setCapability("appium:sendKeyStrategy", "setValue");
capabilities.setCapability("appium:session-override", true);
capabilities.setCapability("appium:webkitResponseTimeout", 20000);
capabilities.setCapability("appium:useJSONSource", true);
capabilities.setCapability("appium:sendKeyStrategy", "grouped");
capabilities.setCapability("appium:commandTimeouts", "1000000");
capabilities.setCapability("appium:webDriverAgentUrl", customWdaUrl);
capabilities.setCapability("appium:webDriverAgentUrl", WDA_SERVER_URL);
capabilities.setCapability(IOSMobileCapabilityType.WDA_LOCAL_PORT, wdaPort);
</code>```

Driver is initialized like this

```<code>IOSDriver iosDriver = new IOSDriver(url, capabilities);
</code>```

What could be the issue here?

Body:
I'm  trying to migrate from appium-java client 7.0 to 8.3 - After updating to 8.3 version I get an error when initializing appium driver (for iOS)

java.lang.IllegalArgumentException: Unknown HttpClient factory apache
at org.openqa.selenium.remote.http.HttpClient$Factory.create(HttpClient.java:57)
at org.openqa.selenium.remote.http.HttpClient$Factory.createDefault(HttpClient.java:73)
at io.appium.java_client.remote.AppiumCommandExecutor.<init>(AppiumCommandExecutor.java:108)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:92)
at io.appium.java_client.ios.IOSDriver.<init>(IOSDriver.java:106)

Command to start appium server is build smth like this

command = nodePath + "  " + appiumMainJS + " ";
command = command + " -a " + hostName + " -p " + availablePort + " ";
command = command + " -cp " + (availablePort + 1000) + " -bp " + (availablePort + 2000);
command = command + " --chromedriver-port " + (availablePort + 3000);
command = command + " " + appiumArgs;

Capabilities

capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, OS_VERIOSN);
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
capabilities.setCapability("appium:keychainPath", KEYCHAIN_PATH);
capabilities.setCapability("appium:keychainPassword", KEYCHAIN_PASSWORD);
capabilities.setCapability("appium:xcodeOrgId", XCODE_ORG_ID);
capabilities.setCapability("appium:xcodeSigningId", XCODE_SIGNING_ID);
capabilities.setCapability("appium:deviceName", DEVICE_NAME);
capabilities.setCapability("appium:showXcodeLog", true);
capabilities.setCapability("appium:noReset", false);
capabilities.setCapability("appium:simpleIsVisibleCheck", false);
capabilities.setCapability(MobileCapabilityType.UDID, DEVICE_ID);
capabilities.setCapability("appium:newCommandTimeout", "2000000");
capabilities.setCapability("appium:launchTimeout", "120000");
capabilities.setCapability("appium:shouldUseSingletonTestManager", false);
capabilities.setCapability("appium:wdaConnectionTimeout", 15*60*1000);
capabilities.setCapability("appium:sendKeyStrategy", "setValue");
capabilities.setCapability("appium:session-override", true);
capabilities.setCapability("appium:webkitResponseTimeout", 20000);
capabilities.setCapability("appium:useJSONSource", true);
capabilities.setCapability("appium:sendKeyStrategy", "grouped");
capabilities.setCapability("appium:commandTimeouts", "1000000");
capabilities.setCapability("appium:webDriverAgentUrl", customWdaUrl);
capabilities.setCapability("appium:webDriverAgentUrl", WDA_SERVER_URL);
capabilities.setCapability(IOSMobileCapabilityType.WDA_LOCAL_PORT, wdaPort);

Driver is initialized like this

IOSDriver iosDriver = new IOSDriver(url, capabilities);

What could be the issue here?


问:
Flutter + firestore app : how to update a document once when many users listen (StreamBuilder) to the same Document?
I have a Flutter mobile application, where several people can read the same firestore document in real time using StreamBuilder (obviously one person can leave the room).
At the same time, to switch from one screen to another, I have a 30 second counter (I use the package https://pub.dev/packages/flutter_countdown_timer).
When the counter reaches 0, I update a field in the firestore document (increment the field by 1) and I go to another screen.

What is the best solution to guarantee that the document update will be done by a single user (single instance of the app) and to prevent a false operation (do two increments for example)


问:
I have a null when using a relative path when reading a FileInputStream
I am trying to read a .properties file from a class that is in a different folder than this .properties. Firstly, I have used another class with a main (testLogin.java) to see if the paths I use are correct and success!

I used an absolute path to read this file and it hasn't given me any problems, in the same way I've tried using a relative one and everything is correct.

Absolute path: "C:\User\Documents\project-web\src\main\config\local\application.properties"

Relative path: "src/main/config/local/application.properties"

I don't know if this error can occur because the file .properties is in a folder (src/main/config/development/application.properties) and not in a package as it is said in this post
https://softwareengineering.stackexchange.com/questions/238208/properties-files-in-regular-src-folder-okay

In the class that I want to implement this function (login.java) I use the absolute path to test and it works for me. I compile, run tomcat and everything is correct. However when implementing the relative, I don't :(, compile, run tomcat and get null. Do you know what this could be? I'm using Servlets and Maven for the build. My code:

login.java

```<code>public void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
   Properties properties = new Properties();

//Using relative path
   try(InputStream is = new FileInputStream("src/main/config/local/application.properties")){ //null when i test after the deploy of the .war in tomcat. But if I execute into a main class it works. It´s strange because only with tomcat it doesn´t works
       properties.load(is);
       System.out.println(properties.getProperty("enviroment"));
   }catch(FileNotFoundException e){
       e.printstackTrace();
   }catch(IOException e){
       e.printstackTrace();
   }

//Using absolute path
   try(InputStream is = new FileInputStream("C:\\Usuario\\Documents\\project-web\\src\\main\\config\\local\\application.properties")){ //OK
       properties.load(is);
       System.out.println(properties.getProperty("enviroment")); //localhost
   }catch(FileNotFoundException e){
       e.printstackTrace();
   }catch(IOException e){
       e.printstackTrace();
   }
}

</code>```

Structure of my project:

Error when i try go in after deploy with mvn tomcat7:run

Body:
I am trying to read a .properties file from a class that is in a different folder than this .properties. Firstly, I have used another class with a main (testLogin.java) to see if the paths I use are correct and success!

I used an absolute path to read this file and it hasn't given me any problems, in the same way I've tried using a relative one and everything is correct.

Absolute path: "C:\User\Documents\project-web\src\main\config\local\application.properties"

Relative path: "src/main/config/local/application.properties"

I don't know if this error can occur because the file .properties is in a folder (src/main/config/development/application.properties) and not in a package as it is said in this post
https://softwareengineering.stackexchange.com/questions/238208/properties-files-in-regular-src-folder-okay

In the class that I want to implement this function (login.java) I use the absolute path to test and it works for me. I compile, run tomcat and everything is correct. However when implementing the relative, I don't :(, compile, run tomcat and get null. Do you know what this could be? I'm using Servlets and Maven for the build. My code:

login.java

public void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
   Properties properties = new Properties();

//Using relative path
   try(InputStream is = new FileInputStream("src/main/config/local/application.properties")){ //null when i test after the deploy of the .war in tomcat. But if I execute into a main class it works. It´s strange because only with tomcat it doesn´t works
       properties.load(is);
       System.out.println(properties.getProperty("enviroment"));
   }catch(FileNotFoundException e){
       e.printstackTrace();
   }catch(IOException e){
       e.printstackTrace();
   }

//Using absolute path
   try(InputStream is = new FileInputStream("C:\\Usuario\\Documents\\project-web\\src\\main\\config\\local\\application.properties")){ //OK
       properties.load(is);
       System.out.println(properties.getProperty("enviroment")); //localhost
   }catch(FileNotFoundException e){
       e.printstackTrace();
   }catch(IOException e){
       e.printstackTrace();
   }
}

Structure of my project:

Error when i try go in after deploy with mvn tomcat7:run


问:
In python, how to transfer file in bytes with GRPC in a right way?
For some reason, I want to transfer file (not in stream) with grpc in python. The protobuf and python code are as follows

protobuf

```<code>syntax = "proto3";

import "google/protobuf/empty.proto";
package xxxx;

service gRPCComServeFunc {
  rpc sendToClient(FileRequest) returns (google.protobuf.Empty) {}
}

message FileRequest {
  FileInfo info = 1;
  bytes chunk = 2;
}

message FileInfo {
  int32 sender = 1;
  int32 state = 2;
  string timestamp = 3;
}

</code>```

python

```<code>def get_file_content(path_file):
    with open(path_file, 'rb') as f:
        content = f.read()
    return content

def pack_file_request(state, chunk):
    request = gRPC_comm_manager_pb2.FileRequest(
        info=gRPC_comm_manager_pb2.FileInfo(
            sender=0,
            state=state,
            timestamp=""),
        chunk=chunk
    )
    return request

...
chunk = get_file_content(path_file)
request = pack_file_request(state, chunk)
stub.sendToClient(request)

</code>```

First, the server reports error as follows

```<code>...
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
        status = StatusCode.CANCELLED
        details = "Received RST_STREAM with error code 8"
        debug_error_string = "UNKNOWN:Error received from peer 0.0.0.0:50078 {created_time:"2023-01-04T22:02:11.242643217+08:00", grpc_status:1, grpc_message:"Received RST_STREAM with error code 8"}"
</code>```

It looks like the message is sent successfully, but refused by the remote client at 0.0.0.0:50078.

So I guess it's caused by the file chunk, and this time I send the message without chunk as follows

```<code>def pack_file_request(state, chunk):
    request = gRPC_comm_manager_pb2.FileRequest(
        info=gRPC_comm_manager_pb2.FileInfo(
            sender=0,
            state=state,
            timestamp=""),
    )
    return request
</code>```

And it works. Therefore I guess I cannot directly read the file and pass it to grpc services in python.

So how should I read the file and pass it to the parameter chunk in grpc service sendToClient?

Body:
For some reason, I want to transfer file (not in stream) with grpc in python. The protobuf and python code are as follows

protobuf

syntax = "proto3";

import "google/protobuf/empty.proto";
package xxxx;

service gRPCComServeFunc {
  rpc sendToClient(FileRequest) returns (google.protobuf.Empty) {}
}

message FileRequest {
  FileInfo info = 1;
  bytes chunk = 2;
}

message FileInfo {
  int32 sender = 1;
  int32 state = 2;
  string timestamp = 3;
}

python

def get_file_content(path_file):
    with open(path_file, 'rb') as f:
        content = f.read()
    return content

def pack_file_request(state, chunk):
    request = gRPC_comm_manager_pb2.FileRequest(
        info=gRPC_comm_manager_pb2.FileInfo(
            sender=0,
            state=state,
            timestamp=""),
        chunk=chunk
    )
    return request

...
chunk = get_file_content(path_file)
request = pack_file_request(state, chunk)
stub.sendToClient(request)

First, the server reports error as follows

...
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
        status = StatusCode.CANCELLED
        details = "Received RST_STREAM with error code 8"
        debug_error_string = "UNKNOWN:Error received from peer 0.0.0.0:50078 {created_time:"2023-01-04T22:02:11.242643217+08:00", grpc_status:1, grpc_message:"Received RST_STREAM with error code 8"}"

It looks like the message is sent successfully, but refused by the remote client at 0.0.0.0:50078.

So I guess it's caused by the file chunk, and this time I send the message without chunk as follows

def pack_file_request(state, chunk):
    request = gRPC_comm_manager_pb2.FileRequest(
        info=gRPC_comm_manager_pb2.FileInfo(
            sender=0,
            state=state,
            timestamp=""),
    )
    return request

And it works. Therefore I guess I cannot directly read the file and pass it to grpc services in python.

So how should I read the file and pass it to the parameter chunk in grpc service sendToClient?


问:
Conditional statement in HOCON configuration files
I need to write a production.conf file for my play framework and scala application.
I have few requirements like
if <some_condition>, then username = <something_from_env>
else username = <something_else_from_env>.

I am currently using jinja2 template, which support this kind of statements. Is there a way to do the same with Play in hocon format?


问:
How to retrieve google calendar events in Android TV app
I'm currently working on Android TV app, I need to retrieve google calendar events and show it in the TV app UI. I used the ContentResolver and calendar events URI  "Uri.parse("content://com.android.calendar/events")" to get the events, but unable to retrieve the events and its showing as an empty list from the cursor. The same code is working fine in Android mobile app, because it is retrieving the events from the calendar app, that was not available in the Android TV.</p>


问:
Hi Everyone, I have a Applicant__c object and How should I display the duplicate records for existing records? (ref: Concept of Internal Deduping).)
I have a Applicant__c object and fields are: Name, Phone, Pan, email Id. I have duplicate rule & matching rule Pan Exact match. How should I display the duplicate records for existing records? (ref: Concept of Internal Deduping).)

Object: Applicant__C
fields: Name, Pan__c, Phone__C, Email__C
Duplicate rule: ApplicantDuplicacyRule (Pan Exact match)

I want to display the duplicate records having same pan with help of Lightning aura & DataCloud Duplicate rule.
I dont want SOQL way of approach beacuse in future duplicate rule parameters can have more than one.

I expecting full lenght code of Aura component, controller, helper & APex code also


问:
Excel Power Query custom data connector
Is it currently possible to build a custom data connector for EXCEL Power Query? If yes, where can i find more info?

I'm seeing all these custom connectors for Power BI, but NOT for EXCEL Power Query.

If it's not possible, I would really appreciate an official link where that's mentioned.

Thanks.

Title: Excel Power Query custom data connector