问:
How to access a linux terminal's scrolled text file/buffer directly?
linux terminals display output on a (configurable) scrolling window.  User configuration allows control of both the scrolling and the size of the window (in number of rows and columns).

The fact that we can scroll back to areas that went off screen, then select that text for cut+paste, means that there is an accessible buffer where that content can be reached directly and specifically.

Is there a process, using linux/bash built-ins or utilites, which would permit the user to access specific segments of that content buffer (which are otherwise accessible via mouse selection) from within a bash script (preferrably directly ... and, if not, possibly via prompted mouse interraction) ?

If unable to do that selectively, is there a way, again from within a bash script, to get a snapshot of that full 2000-line buffer and save it to a script-defined file, where it could then be manipulated ?


来源: stackexchange

问:
Problem with running Socket IO through gunicorn on Fly.io
I am trying to host my flask website on fly.io. My website uses the flask_socketio library and needs a 2 ended connection with the client and server, so this is the gunicorn command I use in the Profile:

```<code>    web: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 main:app
</code>```

This causes the following error in my fly.io log

```<code>    TypeError: Cannot convert greenlet.greenlet to gevent._gevent_c_greenlet_primitives.SwitchOutGreenletWithLoop
</code>```

I have searched stack overflow and found this person having a practically identical problem using Hikaru. Unfortunatly no one gave him an answer and he solved the problem on his own by updating python and re-installing gunicorn.
I tried this, without any positive outcome.
Python: 3.10.9

```<code>gevent==22.10.2
gevent-websocket==0.10.1
greenlet==2.0.1
gunicorn==20.1.0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to host my flask website on fly.io. My website uses the flask_socketio library and needs a 2 ended connection with the client and server, so this is the gunicorn command I use in the Profile:

    web: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 main:app

This causes the following error in my fly.io log

    TypeError: Cannot convert greenlet.greenlet to gevent._gevent_c_greenlet_primitives.SwitchOutGreenletWithLoop

I have searched stack overflow and found this person having a practically identical problem using Hikaru. Unfortunatly no one gave him an answer and he solved the problem on his own by updating python and re-installing gunicorn.
I tried this, without any positive outcome.
Python: 3.10.9

gevent==22.10.2
gevent-websocket==0.10.1
greenlet==2.0.1
gunicorn==20.1.0


问:
matplotlib event handling not working with inline backend
I want to know if matplotlib event handling even work with inline backend?

I am trying to plot an interactive plot with mouse click event but it is not working with matplotlib inline backend. But it works with qt backend.


问:
Google chat app is not responding for image attachment
I am trying to save attachment uploaded by google chat app.
I am handling two cases if user messages anything to google chat app, it will pop up a card with widgets which is perfectly fine but I am handling if user uploads attachment it will save into google drive but the code is not working. Can someone please help?
I am new in coding.</p>
```<code>function getByteStream(dataRef) {
 var blob = "";
 var driveFileName = "";
 var url = "https://chat.googleapis.com/v1/media/"+ dataRef +"?alt=media"

 var service = getOAuth2Service();
 var response = UrlFetchApp.fetch(url, {
   headers: {
     'Authorization': 'Bearer ' + service.getAccessToken(),
   },
   'muteHttpExceptions': true,
 });

 if(response.getResponseCode() != 200){
   return "Failed to get file content with error code: " + response.getResponseCode();
 }
 blob = response.getBlob();
 driveFileName = DriveApp.createFile(blob);
 return "The uploaded contents have been saved in a Google Drive file: "+ driveFileName;
}

function onMessage(event) {
if (event.message.attachment) {
var attachmentName = event.message.attachment[0].name;
var attachment = getByteStream(attachmentName);
console.log(attachment);
} else {
return {
"cards_v2": [{
"card_id": "addContact",
"card": {
"header": {
"title": "Hello" +" " + event.user.displayName + "!",
"subtitle": "Log your feedback!",
"imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
"imageType": "CIRCLE"
},
              "sections": [
                {
                  "widgets": [
                    {
                      "buttonList": {
                        "buttons": [
                          {
                            "text": "Start here",
                            "onClick": {
                              "action": {
                                "function": "openDialog",
                                "interaction": "OPEN_DIALOG"
                                }
                              }
                            }
                          ]
                        },
                            "horizontalAlignment": "CENTER"
                        }
                      ]
                      }
                     ]
                      }
                      }]
                      };
                      }
 }

</code>```

Body:
I am trying to save attachment uploaded by google chat app.
I am handling two cases if user messages anything to google chat app, it will pop up a card with widgets which is perfectly fine but I am handling if user uploads attachment it will save into google drive but the code is not working. Can someone please help?
I am new in coding.

function getByteStream(dataRef) {
 var blob = "";
 var driveFileName = "";
 var url = "https://chat.googleapis.com/v1/media/"+ dataRef +"?alt=media"

 var service = getOAuth2Service();
 var response = UrlFetchApp.fetch(url, {
   headers: {
     'Authorization': 'Bearer ' + service.getAccessToken(),
   },
   'muteHttpExceptions': true,
 });

 if(response.getResponseCode() != 200){
   return "Failed to get file content with error code: " + response.getResponseCode();
 }
 blob = response.getBlob();
 driveFileName = DriveApp.createFile(blob);
 return "The uploaded contents have been saved in a Google Drive file: "+ driveFileName;
}

function onMessage(event) {
if (event.message.attachment) {
var attachmentName = event.message.attachment[0].name;
var attachment = getByteStream(attachmentName);
console.log(attachment);
} else {
return {
"cards_v2": [{
"card_id": "addContact",
"card": {
"header": {
"title": "Hello" +" " + event.user.displayName + "!",
"subtitle": "Log your feedback!",
"imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
"imageType": "CIRCLE"
},
              "sections": [
                {
                  "widgets": [
                    {
                      "buttonList": {
                        "buttons": [
                          {
                            "text": "Start here",
                            "onClick": {
                              "action": {
                                "function": "openDialog",
                                "interaction": "OPEN_DIALOG"
                                }
                              }
                            }
                          ]
                        },
                            "horizontalAlignment": "CENTER"
                        }
                      ]
                      }
                     ]
                      }
                      }]
                      };
                      }
 }


问:
how to show all child data from groupBy laravel.?
how to show all child data on group by laravel eloquent.?

i have try to using

```<code>Model::groupBy('something')->get()
</code>```

but it just return one row from the same group...

Model::groupBy('something')->get()

Body:
how to show all child data on group by laravel eloquent.?

i have try to using

Model::groupBy('something')->get()

but it just return one row from the same group...

Model::groupBy('something')->get()


问:
How to check whether file name contains a specific character with Pathlib
Since it looks like Pathlib is the future, I'm trying to refactor some of my code to change from from previous use of os to Pathlib. I'm stuck with the following problem. Since I work with a Mac, sometimes the folders contain hidden files preceded by a period (.DS_Store or names from deleted files preceded by ._). That gets me into a lot of problems when I loop through files in a directory that have certain extension. To avoid this problem using os.walk, I do the following:

```<code>for root, dirs, files in os.walk(DIR_NAME):

    # iterate all files
    for file in files:
        if file.endswith(ext):
            if file.startswith("."):
                 continue
            do something with the file

</code>```

I know we have the .stem and .suffix method to manipulate file names with Pathlib, but I don't see how they can help with this problem. The .startswith seems more intuitive but alas it does not seem to be available in Pathlib. So, the question is, how would one go about doing this in Pathlib?

Body:
Since it looks like Pathlib is the future, I'm trying to refactor some of my code to change from from previous use of os to Pathlib. I'm stuck with the following problem. Since I work with a Mac, sometimes the folders contain hidden files preceded by a period (.DS_Store or names from deleted files preceded by ._). That gets me into a lot of problems when I loop through files in a directory that have certain extension. To avoid this problem using os.walk, I do the following:

for root, dirs, files in os.walk(DIR_NAME):

    # iterate all files
    for file in files:
        if file.endswith(ext):
            if file.startswith("."):
                 continue
            do something with the file

I know we have the .stem and .suffix method to manipulate file names with Pathlib, but I don't see how they can help with this problem. The .startswith seems more intuitive but alas it does not seem to be available in Pathlib. So, the question is, how would one go about doing this in Pathlib?


问:
How can I overlay text on image in ReactJS/NextJS application?
I am having some trouble getting the css styles to apply as intended. I'm writing this application in ReactJS/NextJS. I am trying to create a component that shows an image with text positioned on top of image. I expect the CSS styles that I'm applying to work, because I've already tested the styles through w3schools. I'm attaching screenshot of what I've done in w3schools, what I'm currently doing in my code, and how everything looks in my localhost:3000. The div with imageContainer1, has a background-image applied to it in the css file, but the image is not appearing on screen. The image that does appear is from the second div with inline styling (which I copied from somewhere, can't remember). The thing is that when I remove the inline styles and move the styles inside the style tags or in the css file, the styles no longer want to apply as they did inline. It's quite confusing how the styling is inconsistent when I move it.

Alas, the goal is to show an image, at full width of the viewport, with text positioned on top of the image. I appreciate any pointers.

```<code>import styles from './HomeContent.module.css'

const Home = () => {

return (
  <div className={styles.container}>
    <div className={styles.imageContainer1}></div>
    <p className={styles.text}>
        text
    </p>
 </div>

  )
}
export default Home

.imageContainer1 {
  background-image: url(../public/redtesla.jpg);
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  max-width: max-content;
  /* position: relative;
  text-align: center;
  background-color: blue; */
}
.container {
  height: 100%;
  margin: 0;
}

.text{
  position: 'absolute';
  top: '25%';
  left: '10%';
  color: "red";
}
</code>```

Body:
I am having some trouble getting the css styles to apply as intended. I'm writing this application in ReactJS/NextJS. I am trying to create a component that shows an image with text positioned on top of image. I expect the CSS styles that I'm applying to work, because I've already tested the styles through w3schools. I'm attaching screenshot of what I've done in w3schools, what I'm currently doing in my code, and how everything looks in my localhost:3000. The div with imageContainer1, has a background-image applied to it in the css file, but the image is not appearing on screen. The image that does appear is from the second div with inline styling (which I copied from somewhere, can't remember). The thing is that when I remove the inline styles and move the styles inside the style tags or in the css file, the styles no longer want to apply as they did inline. It's quite confusing how the styling is inconsistent when I move it.

Alas, the goal is to show an image, at full width of the viewport, with text positioned on top of the image. I appreciate any pointers.

import styles from './HomeContent.module.css'

const Home = () => {

return (

        text

  )
}
export default Home

.imageContainer1 {
  background-image: url(../public/redtesla.jpg);
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  max-width: max-content;
  /* position: relative;
  text-align: center;
  background-color: blue; */
}
.container {
  height: 100%;
  margin: 0;
}

.text{
  position: 'absolute';
  top: '25%';
  left: '10%';
  color: "red";
}


问:
How to save the number of child paragraph in Django Model?
im beginner in django. Here im trying to save number like as MS word headings 1,2,3 levels.

This model would save each paragraph items with numbers
For example if there is no uplevel, numbers should be 1, 2, 3 else 1.1, 1.2 or 1.1.1, 1.1.2

But i can't do this. Please help me.

models

```<code>class Document (models.Model):
    drafttype=models.ForeignKey(DraftType, on_delete=models.CASCADE,verbose_name='GroupItem')
    draft=models.CharField(max_length=500)
    number=models.CharField(max_length=500)
    uplevel=models.ForeignKey('self', on_delete=models.CASCADE, related_name='+')

    def __str__(self):
       return self.title
    def get_absolute_url(self):
       return reverse('doc-detail', args=[str(self.id)])
    def get_update_url(self):
       return '/doc/update/{}'.format(self.id)
    def get_delete_url(self):
       return '/doc/del/{}'.format(self.id)
    def save(self):
    **Problem in here**
       if self.uplevel:
           counter=Document.objects.filter(uplevel=self.uplevel)
           # increasing by 1 , should be 1.1, or 1.1.1
           self.number=counter.number+'.'+counter.count()
       else:
           # getting last number and next one should be 2 or 3
          counter=Document.objects.all().order_by('number').last()
          self.number=counter.number+1
</code>```

Im tried separated model as like below. But i think this is not solution

Models

```<code>    class Buleg (Authors):
        norm=models.ForeignKey(Norm, on_delete=models.CASCADE, verbose_name='Төсөл')
        text = models.TextField(verbose_name='Бүлэг')

    class Heseg (Authors):
        norm=models.ForeignKey(Buleg, on_delete=models.CASCADE, verbose_name='Бүлэг')
        text = models.TextField(verbose_name='Хэсэг')

    class Zaalt (Authors):
        norm=models.ForeignKey(Heseg, on_delete=models.CASCADE, verbose_name='Хэсэг')
        text = models.TextField(verbose_name='Заалт')
</code>```

Body:
im beginner in django. Here im trying to save number like as MS word headings 1,2,3 levels.

This model would save each paragraph items with numbers
For example if there is no uplevel, numbers should be 1, 2, 3 else 1.1, 1.2 or 1.1.1, 1.1.2

But i can't do this. Please help me.

models

class Document (models.Model):
    drafttype=models.ForeignKey(DraftType, on_delete=models.CASCADE,verbose_name='GroupItem')
    draft=models.CharField(max_length=500)
    number=models.CharField(max_length=500)
    uplevel=models.ForeignKey('self', on_delete=models.CASCADE, related_name='+')

    def __str__(self):
       return self.title
    def get_absolute_url(self):
       return reverse('doc-detail', args=[str(self.id)])
    def get_update_url(self):
       return '/doc/update/{}'.format(self.id)
    def get_delete_url(self):
       return '/doc/del/{}'.format(self.id)
    def save(self):
    **Problem in here**
       if self.uplevel:
           counter=Document.objects.filter(uplevel=self.uplevel)
           # increasing by 1 , should be 1.1, or 1.1.1
           self.number=counter.number+'.'+counter.count()
       else:
           # getting last number and next one should be 2 or 3
          counter=Document.objects.all().order_by('number').last()
          self.number=counter.number+1

Im tried separated model as like below. But i think this is not solution

Models

    class Buleg (Authors):
        norm=models.ForeignKey(Norm, on_delete=models.CASCADE, verbose_name='Төсөл')
        text = models.TextField(verbose_name='Бүлэг')

    class Heseg (Authors):
        norm=models.ForeignKey(Buleg, on_delete=models.CASCADE, verbose_name='Бүлэг')
        text = models.TextField(verbose_name='Хэсэг')

    class Zaalt (Authors):
        norm=models.ForeignKey(Heseg, on_delete=models.CASCADE, verbose_name='Хэсэг')
        text = models.TextField(verbose_name='Заалт')


问:
How can I log in to two different systems at the same time in the browser without implementing regular SSO？
What I want is: I have two B/S systems,let's say A: demo.a.com, B: sample.b.com,  I need to when log in A system, at the same time log in B system (The two systems have same user account and password). So I can click a link from web page in A and seamlessly redirect to B, without login again.

I know SSO can achieve this,but it's too heavy for me. The B system is using http basic authentication. I think there should be a lightweight method.

I used the spring boot to test, but failed

```<code> @GetMapping("/gob")
    public void redirectWC(HttpServletRequest request, HttpServletResponse response) {
        //return "redirect:"+siteBurl;
        try {
            String authString = "user1:pwd";
            byte[] authEncBytes = Base64Utils.encode(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            response.setHeader("Authorization", "Basic "+authStringEnc);
//          response.sendRedirect("");
//          response.setStatus(response.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", siteBurl);
            RequestDispatcher dispatcher  = request.getRequestDispatcher(siteBurl);
            dispatcher.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Please help, thanks in advance.

Body:
What I want is: I have two B/S systems,let's say A: demo.a.com, B: sample.b.com,  I need to when log in A system, at the same time log in B system (The two systems have same user account and password). So I can click a link from web page in A and seamlessly redirect to B, without login again.

I know SSO can achieve this,but it's too heavy for me. The B system is using http basic authentication. I think there should be a lightweight method.

I used the spring boot to test, but failed

 @GetMapping("/gob")
    public void redirectWC(HttpServletRequest request, HttpServletResponse response) {
        //return "redirect:"+siteBurl;
        try {
            String authString = "user1:pwd";
            byte[] authEncBytes = Base64Utils.encode(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            response.setHeader("Authorization", "Basic "+authStringEnc);
//          response.sendRedirect("");
//          response.setStatus(response.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", siteBurl);
            RequestDispatcher dispatcher  = request.getRequestDispatcher(siteBurl);
            dispatcher.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Please help, thanks in advance.


问:
Token failed : 401 Forbidden Error connecting to Sharepoint using pnpframework
I am writing a web app that I would like to have access to Sharepoint Document Libraries from a particular site using the currently logged on user credentials. I have looked at a number of articles that suggest using the PnP Framework and using a certificate instead of the client/secret ids.

I have tried both, the code of which is below:

```<code>string siteCollectionURL = "https://mycompanyname.sharepoint.com/sites/staffportal";

        var authManager = new AuthenticationManager(ApplicationId, "C:\\pathtopfxfile\certifcatefx.pfx", "certificatepassword", "https://mycompany.sharepoint.com/sites/staffportal");
        using (var clientContext = authManager.GetACSAppOnlyContext(siteCollectionURL,ApplicationId,ClientSecretId))
        {
            clientContext.Load(clientContext.Web, p => p.Title);
            clientContext.ExecuteQuery();
            return Ok(clientContext.Web.Title);
        }
</code>```

Unfortunately  on the ExecuteQuery line I am consistently getting the 401 error, indicating that I am not authorized.

I registered the app in Azure -> Enterprise applications:

I have checked the following articles:

How to use the PnP Framework in a c# application

Secure Authentication of SharePoint with PnP Framework with C#(Code)

And tried the code snippets, but I cannot seem to find anything that suggests using the currently logged in user to the Web app.(see screen shot) - the user is a global administrator

Below is the error:

Any suggestions would be much appreciated.

Regards,
Darren

UPDATE TO ARTICLE

jimas13's link is what pointed me in the right direction. The tweaks I mentioned in the comment I have posted below for anyone wanting to write an MVC C# web app. This does require that the app needs to be registered and needs a self-signed certificate setup.

The two Async lines need to be written as follows:

```<code>public static async Task<AuthenticationResult> GetToken(IConfidentialClientApplication app, string[] scopes)
    {

            return await app.AcquireTokenForClient(scopes).ExecuteAsync();
    }

    public static async Task<Web> GetClientContext(string Uri,AuthenticationResult authResult)
    {
        using (var clientContext = ContextHelper.GetClientContext(Uri, authResult.AccessToken))
        {
            Web web = clientContext.Web;
            clientContext.Load(web);
            await clientContext.ExecuteQueryAsync();
            return web;
        }
    }
</code>```

The rest of the code is here:

```<code> public IActionResult Index()
    {
        AuthenticationConfiguration.AuthenticationConfiguration config = AuthenticationConfiguration.AuthenticationConfiguration.ReadFromJsonFile("appsettings.json");
        string siteURL = config.SiteUrl;
        string[] scopes = new string[] { config.Scope };
        CertificateDescription certificate = config.Certificate;
        ICertificateLoader certificateLoader = new DefaultCertificateLoader();
        certificateLoader.LoadIfNeeded(certificate);

        IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
            .WithCertificate(certificate.Certificate)
            .WithTenantId(config.Tenant)
            .WithAuthority(config.Authority)
            .Build();

       AuthenticationResult result = GetToken(app, scopes).Result;
        Web WebSite = GetClientContext(siteURL, result).Result;

        return Ok(WebSite.Title);
    }
</code>```

The .SiteUrl and .Scope were added to the AuthenticationConfiguration.cs file as a property and then also added to the appsettings.json file.

Body:
I am writing a web app that I would like to have access to Sharepoint Document Libraries from a particular site using the currently logged on user credentials. I have looked at a number of articles that suggest using the PnP Framework and using a certificate instead of the client/secret ids.

I have tried both, the code of which is below:

string siteCollectionURL = "https://mycompanyname.sharepoint.com/sites/staffportal";

        var authManager = new AuthenticationManager(ApplicationId, "C:\\pathtopfxfile\certifcatefx.pfx", "certificatepassword", "https://mycompany.sharepoint.com/sites/staffportal");
        using (var clientContext = authManager.GetACSAppOnlyContext(siteCollectionURL,ApplicationId,ClientSecretId))
        {
            clientContext.Load(clientContext.Web, p => p.Title);
            clientContext.ExecuteQuery();
            return Ok(clientContext.Web.Title);
        }

Unfortunately  on the ExecuteQuery line I am consistently getting the 401 error, indicating that I am not authorized.

I registered the app in Azure -> Enterprise applications:

I have checked the following articles:

How to use the PnP Framework in a c# application

Secure Authentication of SharePoint with PnP Framework with C#(Code)

And tried the code snippets, but I cannot seem to find anything that suggests using the currently logged in user to the Web app.(see screen shot) - the user is a global administrator

Below is the error:

Any suggestions would be much appreciated.

Regards,
Darren

UPDATE TO ARTICLE

jimas13's link is what pointed me in the right direction. The tweaks I mentioned in the comment I have posted below for anyone wanting to write an MVC C# web app. This does require that the app needs to be registered and needs a self-signed certificate setup.

The two Async lines need to be written as follows:

public static async Task<AuthenticationResult> GetToken(IConfidentialClientApplication app, string[] scopes)
    {

            return await app.AcquireTokenForClient(scopes).ExecuteAsync();
    }

    public static async Task<Web> GetClientContext(string Uri,AuthenticationResult authResult)
    {
        using (var clientContext = ContextHelper.GetClientContext(Uri, authResult.AccessToken))
        {
            Web web = clientContext.Web;
            clientContext.Load(web);
            await clientContext.ExecuteQueryAsync();
            return web;
        }
    }

The rest of the code is here:

 public IActionResult Index()
    {
        AuthenticationConfiguration.AuthenticationConfiguration config = AuthenticationConfiguration.AuthenticationConfiguration.ReadFromJsonFile("appsettings.json");
        string siteURL = config.SiteUrl;
        string[] scopes = new string[] { config.Scope };
        CertificateDescription certificate = config.Certificate;
        ICertificateLoader certificateLoader = new DefaultCertificateLoader();
        certificateLoader.LoadIfNeeded(certificate);

        IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
            .WithCertificate(certificate.Certificate)
            .WithTenantId(config.Tenant)
            .WithAuthority(config.Authority)
            .Build();

       AuthenticationResult result = GetToken(app, scopes).Result;
        Web WebSite = GetClientContext(siteURL, result).Result;

        return Ok(WebSite.Title);
    }

The .SiteUrl and .Scope were added to the AuthenticationConfiguration.cs file as a property and then also added to the appsettings.json file.


问:
Salesforce business hours calculation on start and end date
I am trying to calculate difference between to dates in formula field on start and end date. I am not getting accurate value.

I should calculate hours in weekdays that is Monday to Friday and 9 AM to 6 PM EST  between given dates

below is my formula:

```<code>ROUND( 9 * (
( 5 * FLOOR( ( DATEVALUE( End_Date_Time__c ) - DATE( 1900, 1, 8) ) / 7) +
MIN(5,
MOD( DATEVALUE( End_Date_Time__c ) - DATE( 1900, 1, 8), 7) +
MIN( 1, 24 / 9 * ( MOD( End_Date_Time__c - DATETIMEVALUE( '1900-01-08 14:00:00' ), 1 ) ) )
)
)
-
( 5 * FLOOR( ( DATEVALUE( Start_Date_Time__c ) - DATE( 1900, 1, 8) ) / 7) +
MIN( 5,
MOD( DATEVALUE( Start_Date_Time__c ) - DATE( 1996, 1, 1), 7 ) +
MIN( 1, 24 / 9 * ( MOD( Start_Date_Time__c - DATETIMEVALUE( '1900-01-08 14:00:00' ), 1) ) )
)
)
),
0 )
</code>```

In some scenarios I am  getting expected results but in most not correct values.

Body:
I am trying to calculate difference between to dates in formula field on start and end date. I am not getting accurate value.

I should calculate hours in weekdays that is Monday to Friday and 9 AM to 6 PM EST  between given dates

below is my formula:

ROUND( 9 * (
( 5 * FLOOR( ( DATEVALUE( End_Date_Time__c ) - DATE( 1900, 1, 8) ) / 7) +
MIN(5,
MOD( DATEVALUE( End_Date_Time__c ) - DATE( 1900, 1, 8), 7) +
MIN( 1, 24 / 9 * ( MOD( End_Date_Time__c - DATETIMEVALUE( '1900-01-08 14:00:00' ), 1 ) ) )
)
)
-
( 5 * FLOOR( ( DATEVALUE( Start_Date_Time__c ) - DATE( 1900, 1, 8) ) / 7) +
MIN( 5,
MOD( DATEVALUE( Start_Date_Time__c ) - DATE( 1996, 1, 1), 7 ) +
MIN( 1, 24 / 9 * ( MOD( Start_Date_Time__c - DATETIMEVALUE( '1900-01-08 14:00:00' ), 1) ) )
)
)
),
0 )

In some scenarios I am  getting expected results but in most not correct values.


问:
Drools Version 8.32.0
Does the latest version of Drools have a higher memory limitation than previous versions? I cannot find this memory limitatoin noted anywhere. Is there any version which dynamically increases memory?

Tried to look into increasing memory

Title: Drools Version 8.32.0


问:
How can I Align this Menu to the Center (Bootstrap 5.3-Alpha)
I am having a problem aligning the dropdown menu to the center. I can align it to the left and right (.dropdown-menu-start, .dropdown-menu-end) but just can’t manage to align it to the center (.dropdown-menu-start).

I’ve tried:

```<code><div class="dropdown-center">
   <li class="dropdown me-3">
      <a href="#" class="d-flex align-items-center text-decoration-none dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
      <img src="imgsrc.png" alt="" width="32" height="32" class="rounded-circle me-2" style="border: 1px solid #808080">
      <strong>Guest</strong>
      </a>
      <ul class="dropdown-menu text-small shadow">
         <li><a class="dropdown-item" href="/auth/login">Login</a></li>
         <li><a href="/auth/registration" class="dropdown-item" style="cursor:pointer">Signup</a></li>
         <li><a class="dropdown-item" href="#"Settings</a></li>
         <li><a class="dropdown-item" href="#">Theme </a></li>
      </ul>
   </li>
</div>
</code>```

That is what is in the documentation, with a few different classes.

https://getbootstrap.com/docs/5.3/components/dropdowns/#centered

Body:
I am having a problem aligning the dropdown menu to the center. I can align it to the left and right (.dropdown-menu-start, .dropdown-menu-end) but just can’t manage to align it to the center (.dropdown-menu-start).

I’ve tried:

      Guest

Login

Signup

<a class="dropdown-item" href="#"Settings

Theme

That is what is in the documentation, with a few different classes.

https://getbootstrap.com/docs/5.3/components/dropdowns/#centered


问:
ng test hangs after successful tests in Github Actions
I added a step in my Github Actions workflow to run my Angular tests using the command ng test. The tests run and pass successfully but it never moves onto the next step in my workflow.

What have I tried:

Adding the argument watch=false in the step so that "ng test" isn't watching for file changes.

Setting singleRun to true in karma.conf.js

Nothing's worked so far and I'm not seeing any other resources that can help me solve this issue.

Here is a snippet of the step in my build-push.yml file:

```<code>- name: Run tests
  run: npm test -- --watch=false --browsers=ChromeHeadless
</code>```

Here is a snippet of my karma.conf.js file:

```<code>reporters          : ['progress', 'kjhtml'],
port               : 9876,
colors             : true,
logLevel           : config.LOG_INFO,
autoWatch          : true,
browsers           : ['Chrome'],
singleRun          : false,
restartOnFileChange: true,
</code>```

The above image is a screenshot of the workflow running in Github Actions. I expected "Post Set up Node" to run but it just hangs on the tests

Any help is greatly appreciated as I've been stuck on this for quite some time now. Thank you all!

Body:
I added a step in my Github Actions workflow to run my Angular tests using the command ng test. The tests run and pass successfully but it never moves onto the next step in my workflow.

What have I tried:

Adding the argument watch=false in the step so that "ng test" isn't watching for file changes.

Setting singleRun to true in karma.conf.js

Nothing's worked so far and I'm not seeing any other resources that can help me solve this issue.

Here is a snippet of the step in my build-push.yml file:

- name: Run tests
  run: npm test -- --watch=false --browsers=ChromeHeadless

Here is a snippet of my karma.conf.js file:

reporters          : ['progress', 'kjhtml'],
port               : 9876,
colors             : true,
logLevel           : config.LOG_INFO,
autoWatch          : true,
browsers           : ['Chrome'],
singleRun          : false,
restartOnFileChange: true,

The above image is a screenshot of the workflow running in Github Actions. I expected "Post Set up Node" to run but it just hangs on the tests

Any help is greatly appreciated as I've been stuck on this for quite some time now. Thank you all!


问:
Lxml error and cffi error when attempting to download the yfinance package
I am fairly new to python and really learning still. I would like to utilize the yfinance package however when I attempt to download I receive two types of errors one saying:
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> cffi

another saying:
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> lxml

how can I correct this error? I attempted downloading using pip, I am running it on a Mac and have downloaded I believe all of the required packages for yfinance.

```<code>1 error generated.
  Compile failed: command '/usr/bin/clang' failed with exit code 1
  creating var
  creating var/folders
  creating var/folders/3l
  creating var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn
  creating var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T
  cc -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/usr/include/libxml2 -c /var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T/xmlXPathInitguxzb5ln.c -o var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T/xmlXPathInitguxzb5ln.o
  cc var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T/xmlXPathInitguxzb5ln.o -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -lxml2 -o a.out
  error: command '/usr/bin/clang' failed with exit code 1
  [end of output]
</code>```

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for lxml
Running setup.py clean for lxml
Failed to build lxml
Installing collected packages: lxml
Running setup.py install for lxml ... error
error: subprocess-exited-with-error

× Running setup.py install for lxml did not run successfully.
│ exit code: 1
╰─> [116 lines of output]

Body:
I am fairly new to python and really learning still. I would like to utilize the yfinance package however when I attempt to download I receive two types of errors one saying:
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> cffi

another saying:
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> lxml

how can I correct this error? I attempted downloading using pip, I am running it on a Mac and have downloaded I believe all of the required packages for yfinance.

1 error generated.
  Compile failed: command '/usr/bin/clang' failed with exit code 1
  creating var
  creating var/folders
  creating var/folders/3l
  creating var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn
  creating var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T
  cc -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/usr/include/libxml2 -c /var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T/xmlXPathInitguxzb5ln.c -o var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T/xmlXPathInitguxzb5ln.o
  cc var/folders/3l/c0m9ys6s67b_1l7xrwjc_psh0000gn/T/xmlXPathInitguxzb5ln.o -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -lxml2 -o a.out
  error: command '/usr/bin/clang' failed with exit code 1
  [end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for lxml
Running setup.py clean for lxml
Failed to build lxml
Installing collected packages: lxml
Running setup.py install for lxml ... error
error: subprocess-exited-with-error

× Running setup.py install for lxml did not run successfully.
│ exit code: 1
╰─> [116 lines of output]


问:
Where can vscode view the default colors for parts that you don't define
I sometimes wonder what vscode's default widget color is. For example: when I use a github theme, I find that it only defines one part of the color internally, so where is the other part defined, and how do I view it.

For example, when I look at the color scheme of the topic by Developer : generator color theme... command, the undefined part is always shown in the form of comments(e.g "activityBar.activeBackground": null,). How can I see the color of this annotated section?


问:
In Knockout how do you go about nesting custom components when using an html binding?
I'm a bit new to knockout. I'm trying to get a custom component to dynamically load another custom component. I have a variable called location_board that contains html and that html has a custom component in it. . When I use the data-bind="html: location_board" it put the line for the  in the dom but it doesn't run the custom component to fill out that node. Note: If I add the npc-widget directly to the template it works. It just doesn't work when it is added though the html binding. From my research I think this means I need to applyBindings on it? I'm not sure how to go about that in this situation though.

Any help is apricated.

Here is my full code for the custom component.

import {Database} from './database.js'
let database = new Database();
import {ResourceManager} from "./resource-manager.js";
let resourceManager = new ResourceManager();
let locationRegister = {
    fog_forest: {
        name: "The Ghostly Woodland",
        image: "url('img/foggy_forest.jpeg')",
        description: `
Place holder
        `,
        location_board: `
<npc-widget id="john-npc" params="id: 1, tree: 'shopkeep', speed: 50"></npc-widget>

In

`
    }
};

ko.components.register('location-widget', {
    viewModel: function (params) {
        let self = this;
        self.function = function () {
            console.log("Functions!")
        }

        for(let k in locationRegister[params.id]) {
            console.log(k)
            this[k] = locationRegister[params.id][k];
        }
        console.log(this.name)
        //return { controlsDescendantBindings: true };
    },
    template:
        `

`
});```


问:
How to change settings in phone via Android Studio SDK?

It is necessary that when you click on the button in the application, the phone turns on this slider. How can this be done in Java? Application made in Android Studio

I imagine this as a macro that goes into the settings of my phone and switches the slider. I think this is the easiest thing to do


问:
Certain non-latin characters are displaying out of order
EDIT: got it by some dedicated searching. unicode-bidi: plaintext on the font's i style block does it. Very nice to be able to scope it so tightly; hopefully this won't muck with localization like a broader solution might.

Kind of hard to explain, but I'm using a webfont that leverages unicode glyphs to display its own characters.

The following code is displaying the shield between the 0 and the +

```<code><span class="text-stat ng-star-inserted" style="">
  <i class="game-icon game-icon-shield"></i>
  0+
</span>
</code>```

But this code displays everything in the right order (Seemingly any a-zA-Z makes it work correctly)

```<code><span class="text-stat ng-star-inserted" style="">
  <i class="game-icon game-icon-shield"></i>
  a0+
</span>
</code>```

Looking at the CSS provided for the webfont, I see this:

```<code>.game-icon-shield:before {
    content: "ﱗ";
}
.game-icon:before {
    font-family: "game-icons" !important;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    font-style: normal;
    font-variant: normal;
    font-weight: normal !important;
    text-decoration: none;
    text-transform: none;
    line-height: inherit;
}
</code>```

It seems like the character ﱗintrinsically places itself after a subsequent zero, for some reason? ﱗ0 typing that out, I placed the ﱗ before the zero but it moved itself over. ﱗa0 works fine.

I'm trying to enforce code-order for this portion of my page but I don't see a way to do that with css. direction: ltr has no effect.

Body:
EDIT: got it by some dedicated searching. unicode-bidi: plaintext on the font's i style block does it. Very nice to be able to scope it so tightly; hopefully this won't muck with localization like a broader solution might.

Kind of hard to explain, but I'm using a webfont that leverages unicode glyphs to display its own characters.

The following code is displaying the shield between the 0 and the +

  0+

But this code displays everything in the right order (Seemingly any a-zA-Z makes it work correctly)

  a0+

Looking at the CSS provided for the webfont, I see this:

.game-icon-shield:before {
    content: "ﱗ";
}
.game-icon:before {
    font-family: "game-icons" !important;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    font-style: normal;
    font-variant: normal;
    font-weight: normal !important;
    text-decoration: none;
    text-transform: none;
    line-height: inherit;
}

It seems like the character ﱗintrinsically places itself after a subsequent zero, for some reason? ﱗ0 typing that out, I placed the ﱗ before the zero but it moved itself over. ﱗa0 works fine.

I'm trying to enforce code-order for this portion of my page but I don't see a way to do that with css. direction: ltr has no effect.


问:
Sveltekit won't load component SCSS correctly when executed

Problem Background:

I have a tauri app set up in Linux (Pop OS), with sveltekit with vite as the frontend framework, and typescript and SCSS being the languages I code for scripts and styles.

Vite is also hot reloadable.

There's an app.scss for overall styles and components scoped scss defined in each components using the


问:
when i am running registration form after submitting form data it show like this?
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''userdetails'('sno','uname','gender','email','password','mobileno','address')...'</p>


问:
Enable or disable buttons after all widget entries are complete in tkinter
I am making a simple GUI in tkinter to test entry validations. Most of this code appears to work, except getting the calculate button to show up enabled in green as soon as the entries are complete.
What I'm trying to achieve is that once all the entries are complete and radiobuttons are selected, the calculate button is then enabled and is visibly "available". Once the calculate button has been used the submit button is then enabled. When both buttons have been used the form resets.
I need to have both buttons in the application. Button1 (calculate) should perform some calculations AND do error checking on entry widgets. Button 2 needs to submit the data from the form to a file, but only if the validation checks were correct and the calculation has been made. I'm fairly new to python, and despite a lot of researching I cannot quite get it to work.
I think the answer in this post might help me, but I'm not completely sure how to incorporate it How to disable the following button in Tkinter? .

I tried using .bind or .trace respectively with the variables for each widget, because I'd seen some examples using that method, but I got errors. I've tried various ways of enabling or disabling the buttons using .config, but essentially as a new coder I'm just having trouble even finding out what method or tool I should be using, or how to write the functions to operate as I need them.

```<code>import tkinter as tk
from tkinter import *
from tkinter import messagebox
from pathlib import Path

ws = Tk()
ws.title('Validation test')
ws.geometry('400x300')
ws.config(bg='#04B2D9')
#attempts to set the button to enabled once radiobutton is chosen
def enable_calc():
    global a
    a = var.get()
    if a == 1:
        butt1.config(state=NORMAL, bg="lightgreen")
    elif a == 2:
        butt1.config(state=NORMAL, bg="lightgreen")

#calculation associated with butt1, called in validation function
def calculate(*args):
    global b
    choice = var.get()
    if choice == 1:
        a = 10
    if choice == 2:
        a = 15
    b = a * 4
    calc.config(text=f"the amount is {b} ")
    butt2.config(state=NORMAL, bg="lightgreen")
    butt1.config(state=DISABLED, bg="lightgrey")

#attempts to validate the name entry
def validation(*args):
    global select, name_check
    select = var.get()
    name_check = name_var.get()
    msg = ''
    butt2.config(state=DISABLED, bg="lightgrey")
#attempts to call the calculation if radiobutton selected
    if select ==1:
        calculate()
    elif select ==2:
        calculate()
    else:
        messagebox.showwarning("Please enter all fields ")
        butt2.config(state=DISABLED, bg="lightgrey")
        butt1.config(state=DISABLED, bg="lightgrey")
#checks name entry for input
    if len(name_check) == 0:
        msg = 'name can\'t be empty'
    else:
        try:
            if any(ch.isdigit() for ch in name_check):
                msg = 'Name can\'t contain numbers'
            elif len(name_check) <= 2:
                msg = 'name is too short.'
            elif len(name_check) > 100:
                msg = 'name is too long.'
            else:
                msg = 'Success!'
                butt2.config(state=NORMAL, bg="lightgreen")
        except Exception as ep:
            messagebox.showerror('error', ep)
    messagebox.showinfo('message', msg)
#writes the file (should be only if calculate was successful) and clears the widgets
def submit():
    file_sent = ""
    try:
        filepath = Path("C:/Temp/text_example.txt")
        filepath.parent.mkdir(parents=True, exist_ok=True)
        with filepath.open("a", encoding ="utf-8") as f:
            f.write(f"\n Name : {name_check}")
            f.close()
        file_sent = f" Success! {name_check}, your application has been submitted"
    except Exception as ep:
        messagebox.showerror('error', ep)
    messagebox.showinfo('message', file_sent)
    name_tf.delete(0,END)
    butt2.config(state=DISABLED, bg="lightgrey")
    var.set(0)
#plotting components
frame = tk.LabelFrame(ws, padx=10,pady=10)
frame.pack(pady=20)

first_name = tk.Label( frame, text='Enter Name')
first_name.grid(row=0, column=1)

calc = tk.Label(frame)
calc.grid(row=5, column=1)

name_var = StringVar()

name_tf = tk.Entry(frame, textvariable=name_var,
    font = ('sans-sherif', 14))
name_tf.grid(row=1, column=1)

var = IntVar()
var.set(0)
var.trace('w', enable_calc)

opt1 = tk.Radiobutton(frame,pady=10,padx=20,
    variable=var, value=1).grid(row=2, column=1)
opt2 = tk.Radiobutton(frame, pady=10,padx=20,
    variable=var, value=2).grid(row=2, column=2)

butt1 = tk.Button(frame,text='Calculate', pady=10,padx=20)
butt1.grid(row=3, columnspan=2)
butt1.bind('<Button-1>', validation)

butt2 = tk.Button(frame, text='Submit', pady=10,
                  padx=25,command=submit)
butt2.grid(row=4, columnspan=2)

ws.mainloop()
</code>```

Body:
I am making a simple GUI in tkinter to test entry validations. Most of this code appears to work, except getting the calculate button to show up enabled in green as soon as the entries are complete.
What I'm trying to achieve is that once all the entries are complete and radiobuttons are selected, the calculate button is then enabled and is visibly "available". Once the calculate button has been used the submit button is then enabled. When both buttons have been used the form resets.
I need to have both buttons in the application. Button1 (calculate) should perform some calculations AND do error checking on entry widgets. Button 2 needs to submit the data from the form to a file, but only if the validation checks were correct and the calculation has been made. I'm fairly new to python, and despite a lot of researching I cannot quite get it to work.
I think the answer in this post might help me, but I'm not completely sure how to incorporate it How to disable the following button in Tkinter? .

I tried using .bind or .trace respectively with the variables for each widget, because I'd seen some examples using that method, but I got errors. I've tried various ways of enabling or disabling the buttons using .config, but essentially as a new coder I'm just having trouble even finding out what method or tool I should be using, or how to write the functions to operate as I need them.

import tkinter as tk
from tkinter import *
from tkinter import messagebox
from pathlib import Path

ws = Tk()
ws.title('Validation test')
ws.geometry('400x300')
ws.config(bg='#04B2D9')
#attempts to set the button to enabled once radiobutton is chosen
def enable_calc():
    global a
    a = var.get()
    if a == 1:
        butt1.config(state=NORMAL, bg="lightgreen")
    elif a == 2:
        butt1.config(state=NORMAL, bg="lightgreen")

#calculation associated with butt1, called in validation function
def calculate(*args):
    global b
    choice = var.get()
    if choice == 1:
        a = 10
    if choice == 2:
        a = 15
    b = a * 4
    calc.config(text=f"the amount is {b} ")
    butt2.config(state=NORMAL, bg="lightgreen")
    butt1.config(state=DISABLED, bg="lightgrey")

#attempts to validate the name entry
def validation(*args):
    global select, name_check
    select = var.get()
    name_check = name_var.get()
    msg = ''
    butt2.config(state=DISABLED, bg="lightgrey")
#attempts to call the calculation if radiobutton selected
    if select ==1:
        calculate()
    elif select ==2:
        calculate()
    else:
        messagebox.showwarning("Please enter all fields ")
        butt2.config(state=DISABLED, bg="lightgrey")
        butt1.config(state=DISABLED, bg="lightgrey")
#checks name entry for input
    if len(name_check) == 0:
        msg = 'name can\'t be empty'
    else:
        try:
            if any(ch.isdigit() for ch in name_check):
                msg = 'Name can\'t contain numbers'
            elif len(name_check) <= 2:
                msg = 'name is too short.'
            elif len(name_check) > 100:
                msg = 'name is too long.'
            else:
                msg = 'Success!'
                butt2.config(state=NORMAL, bg="lightgreen")
        except Exception as ep:
            messagebox.showerror('error', ep)
    messagebox.showinfo('message', msg)
#writes the file (should be only if calculate was successful) and clears the widgets
def submit():
    file_sent = ""
    try:
        filepath = Path("C:/Temp/text_example.txt")
        filepath.parent.mkdir(parents=True, exist_ok=True)
        with filepath.open("a", encoding ="utf-8") as f:
            f.write(f"\n Name : {name_check}")
            f.close()
        file_sent = f" Success! {name_check}, your application has been submitted"
    except Exception as ep:
        messagebox.showerror('error', ep)
    messagebox.showinfo('message', file_sent)
    name_tf.delete(0,END)
    butt2.config(state=DISABLED, bg="lightgrey")
    var.set(0)
#plotting components
frame = tk.LabelFrame(ws, padx=10,pady=10)
frame.pack(pady=20)

first_name = tk.Label( frame, text='Enter Name')
first_name.grid(row=0, column=1)

calc = tk.Label(frame)
calc.grid(row=5, column=1)

name_var = StringVar()

name_tf = tk.Entry(frame, textvariable=name_var,
    font = ('sans-sherif', 14))
name_tf.grid(row=1, column=1)

var = IntVar()
var.set(0)
var.trace('w', enable_calc)

opt1 = tk.Radiobutton(frame,pady=10,padx=20,
    variable=var, value=1).grid(row=2, column=1)
opt2 = tk.Radiobutton(frame, pady=10,padx=20,
    variable=var, value=2).grid(row=2, column=2)

butt1 = tk.Button(frame,text='Calculate', pady=10,padx=20)
butt1.grid(row=3, columnspan=2)
butt1.bind('<Button-1>', validation)

butt2 = tk.Button(frame, text='Submit', pady=10,
                  padx=25,command=submit)
butt2.grid(row=4, columnspan=2)

ws.mainloop()


问:
Docker-compose start scaled services sequentially, so instance port maps to host ports in order?
I have built a web scraping service with Selenium docker container, running several instances via docker-compose.
Every now and then I want to see the content of screen for debugging purpose.
So I exposed the vnc port (5900) of Selenium instance, to be mapped to a range of ports on the host machine like this:

```<code>version: "3"
services:
  app:
    image: mylocalapp
  sel:
    image: selenium/standalone-chrome
    ports:
      - "10001-10010:5900"
</code>```

Then I can have required number of selenium instances (up to 10 in the above example) via command:

```<code>docker-compose up -d --scale sel=5
</code>```

I can successfully connect to instance port 5900 from a VNC client, on host ports 10000-10009.
But the problems with this approach is that, there is no easy way to tell which port is mapped to each container.

I can docker ps to check which port is mapped to which instance, but the order is often confusing because sel instances initialise in a random order.
(sel_1 is 10004, sel_2 is 10001... etc)

It'd be a lot easier for me to manage, if all sel instance initialise in sequential order, so sel_1 is 10001, sel_2 is 10002... etc.

Is there a way to start sel instances sequentially, so that sel_2 waits for sel_1, then sel_3, sel_4... ?

Body:
I have built a web scraping service with Selenium docker container, running several instances via docker-compose.
Every now and then I want to see the content of screen for debugging purpose.
So I exposed the vnc port (5900) of Selenium instance, to be mapped to a range of ports on the host machine like this:

version: "3"
services:
  app:
    image: mylocalapp
  sel:
    image: selenium/standalone-chrome
    ports:
      - "10001-10010:5900"

Then I can have required number of selenium instances (up to 10 in the above example) via command:

docker-compose up -d --scale sel=5

I can successfully connect to instance port 5900 from a VNC client, on host ports 10000-10009.
But the problems with this approach is that, there is no easy way to tell which port is mapped to each container.

I can docker ps to check which port is mapped to which instance, but the order is often confusing because sel instances initialise in a random order.
(sel_1 is 10004, sel_2 is 10001... etc)

It'd be a lot easier for me to manage, if all sel instance initialise in sequential order, so sel_1 is 10001, sel_2 is 10002... etc.

Is there a way to start sel instances sequentially, so that sel_2 waits for sel_1, then sel_3, sel_4... ?


问:
Expo Go `expo-auth-session` `useAuthRequest()` after login redirects to NotFound page
To implement Google OAuth, I followed the docs:

```<code>// Inside app.json
{
    name: 'my-app',
    slug: 'my-app',
    scheme: 'ori-app'
...
}
</code>```
```<code>// Inside a React component
import * as Google from 'expo-auth-session/providers/google';

  const [request, response, prompt] = Google.useAuthRequest({
    expoClientId: Constants.manifest?.extra?.googleExpoClientId as
      | string
      | undefined,
    androidClientId: Constants.manifest?.extra?.googleAndroidClientId as
      | string
      | undefined,
    // TODO: iOS
    scopes: [
      'openid',
      'https://www.googleapis.com/auth/userinfo.email',
      'https://www.googleapis.com/auth/userinfo.profile',
    ],
  });
</code>```
```<code>// In the Credentials page on the Google Developer Console
https://auth.expo.io/@<my_expo_username>/my-app
</code>```

Authentication completes successfully, an an access token is obtained but the page is redirects to is unknown and it shows a catch-all NotFound page.

Body:
To implement Google OAuth, I followed the docs:

// Inside app.json
{
    name: 'my-app',
    slug: 'my-app',
    scheme: 'ori-app'
...
}

// Inside a React component
import * as Google from 'expo-auth-session/providers/google';

  const [request, response, prompt] = Google.useAuthRequest({
    expoClientId: Constants.manifest?.extra?.googleExpoClientId as
      | string
      | undefined,
    androidClientId: Constants.manifest?.extra?.googleAndroidClientId as
      | string
      | undefined,
    // TODO: iOS
    scopes: [
      'openid',
      'https://www.googleapis.com/auth/userinfo.email',
      'https://www.googleapis.com/auth/userinfo.profile',
    ],
  });

// In the Credentials page on the Google Developer Console
https://auth.expo.io/@<my_expo_username>/my-app

Authentication completes successfully, an an access token is obtained but the page is redirects to is unknown and it shows a catch-all NotFound page.


问:
apt install mysql-server cause error raise error "Error: Unable to shut down server with process id 2636"
full error:

```<code>mysqld will log errors to /var/log/mysql/error.log
mysqld is running as pid 2636
Error: Unable to shut down server with process id 2636
dpkg: error processing package mysql-server-8.0 (--configure):
 installed mysql-server-8.0 package post-installation script subprocess returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-8.0; however:
  Package mysql-server-8.0 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mysql-server-8.0
 mysql-server
</code>```

/var/log/mysql/error.log cannot see any error

```<code>2023-01-08T02:46:57.117825Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/tmp' in the path is accessible to all OS users. Consider choosing a different directory.
2023-01-08T02:46:57.145582Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2023-01-08T02:46:57.145655Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.31-0ubuntu0.20.04.2'  socket: '/tmp/tmp.ezuexXT3Qd/mysqld.sock'  port: 0  (Ubuntu).
2023-01-08T02:46:57.167030Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user <via user signal>. Shutting down mysqld (Version: 8.0.31-0ubuntu0.20.04.2).
2023-01-08T02:46:58.725865Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.31-0ubuntu0.20.04.2)  (Ubuntu).
2023-01-08T03:31:56.594254Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.31-0ubuntu0.20.04.2) starting as process 1793
2023-01-08T03:31:56.610912Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-01-08T03:31:56.809605Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-01-08T03:31:57.059550Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-01-08T03:31:57.059643Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-01-08T03:31:57.063734Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/tmp' in the path is accessible to all OS users. Consider choosing a different directory.
2023-01-08T03:31:57.113564Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.31-0ubuntu0.20.04.2'  socket: '/tmp/tmp.tYo8ProTui/mysqld.sock'  port: 0  (Ubuntu).
2023-01-08T03:31:57.113591Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2023-01-08T03:31:57.137926Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user <via user signal>. Shutting down mysqld (Version: 8.0.31-0ubuntu0.20.04.2).
2023-01-08T03:31:58.700360Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.31-0ubuntu0.20.04.2)  (Ubuntu).
2023-01-08T03:39:47.849526Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.31-0ubuntu0.20.04.2) starting as process 2634
2023-01-08T03:39:47.866070Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-01-08T03:39:48.076542Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-01-08T03:39:48.354685Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-01-08T03:39:48.354750Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-01-08T03:39:48.358399Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/tmp' in the path is accessible to all OS users. Consider choosing a different directory.
2023-01-08T03:39:48.387186Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2023-01-08T03:39:48.387337Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.31-0ubuntu0.20.04.2'  socket: '/tmp/tmp.gyZtp1Z5Ho/mysqld.sock'  port: 0  (Ubuntu).
2023-01-08T03:39:48.414986Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user <via user signal>. Shutting down mysqld (Version: 8.0.31-0ubuntu0.20.04.2).
2023-01-08T03:39:50.009890Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.31-0ubuntu0.20.04.2)  (Ubuntu).
</code>```

and I cannot remove mysql-server with apt remove mysql-server, same error like above

Body:
full error:

mysqld will log errors to /var/log/mysql/error.log
mysqld is running as pid 2636
Error: Unable to shut down server with process id 2636
dpkg: error processing package mysql-server-8.0 (--configure):
 installed mysql-server-8.0 package post-installation script subprocess returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-8.0; however:
  Package mysql-server-8.0 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mysql-server-8.0
 mysql-server

/var/log/mysql/error.log cannot see any error

2023-01-08T02:46:57.117825Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/tmp' in the path is accessible to all OS users. Consider choosing a different directory.
2023-01-08T02:46:57.145582Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2023-01-08T02:46:57.145655Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.31-0ubuntu0.20.04.2'  socket: '/tmp/tmp.ezuexXT3Qd/mysqld.sock'  port: 0  (Ubuntu).
2023-01-08T02:46:57.167030Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user <via user signal>. Shutting down mysqld (Version: 8.0.31-0ubuntu0.20.04.2).
2023-01-08T02:46:58.725865Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.31-0ubuntu0.20.04.2)  (Ubuntu).
2023-01-08T03:31:56.594254Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.31-0ubuntu0.20.04.2) starting as process 1793
2023-01-08T03:31:56.610912Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-01-08T03:31:56.809605Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-01-08T03:31:57.059550Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-01-08T03:31:57.059643Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-01-08T03:31:57.063734Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/tmp' in the path is accessible to all OS users. Consider choosing a different directory.
2023-01-08T03:31:57.113564Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.31-0ubuntu0.20.04.2'  socket: '/tmp/tmp.tYo8ProTui/mysqld.sock'  port: 0  (Ubuntu).
2023-01-08T03:31:57.113591Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2023-01-08T03:31:57.137926Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user <via user signal>. Shutting down mysqld (Version: 8.0.31-0ubuntu0.20.04.2).
2023-01-08T03:31:58.700360Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.31-0ubuntu0.20.04.2)  (Ubuntu).
2023-01-08T03:39:47.849526Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.31-0ubuntu0.20.04.2) starting as process 2634
2023-01-08T03:39:47.866070Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-01-08T03:39:48.076542Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-01-08T03:39:48.354685Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-01-08T03:39:48.354750Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-01-08T03:39:48.358399Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/tmp' in the path is accessible to all OS users. Consider choosing a different directory.
2023-01-08T03:39:48.387186Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2023-01-08T03:39:48.387337Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.31-0ubuntu0.20.04.2'  socket: '/tmp/tmp.gyZtp1Z5Ho/mysqld.sock'  port: 0  (Ubuntu).
2023-01-08T03:39:48.414986Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user <via user signal>. Shutting down mysqld (Version: 8.0.31-0ubuntu0.20.04.2).
2023-01-08T03:39:50.009890Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.31-0ubuntu0.20.04.2)  (Ubuntu).

and I cannot remove mysql-server with apt remove mysql-server, same error like above


问:
How do I display the latitude and longitude of zip code points in Tableau
I have addresses with Zip codes in a source. When I add the [Zip Code] string field to a new worksheet in Tableau it displays them as a map, which I love. However, I want to get it to also display the latitude and longitude in the Text or Tooltip. Or I suppose get the Point info for these points. That way I can build BUFFERs around those Points, the way I can't seem to with just a [Zip Code] string.</p>


问:
Get Relationship Field Value Inside on Repeater going to Another Posts
```<code><?php

$related_articles = get_posts(array(
    'post_type' => 'book',
    'meta_query' => array(
        array(
            'key' => 'related_articles', // name of custom field
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));

if( have_rows('related_articles_repeater') ): // i added this line im not sure about this
    while( have_rows('related_articles_repeater') ) : the_row();

    if( $related_articles ):
        foreach( $related_articles as $article ):

        // Do something to display the articles. Each article is a WP_Post object.
        // Example:

        echo $article->post_title;  // The post title
        echo $article->post_excerpt;  // The excerpt
        echo get_the_post_thumbnail( $article->ID );  // The thumbnail

        endforeach;
    endif;

endwhile;
endif;

?>
</code>```

Hi guys! Whats wrong did i make? the code work well without repeater. I Wanted to work it with repeater so that i coded but is not working thougt.......................

Body:
<?php

$related_articles = get_posts(array(
    'post_type' => 'book',
    'meta_query' => array(
        array(
            'key' => 'related_articles', // name of custom field
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));

if( have_rows('related_articles_repeater') ): // i added this line im not sure about this
    while( have_rows('related_articles_repeater') ) : the_row();

    if( $related_articles ):
        foreach( $related_articles as $article ):

        // Do something to display the articles. Each article is a WP_Post object.
        // Example:

        echo $article->post_title;  // The post title
        echo $article->post_excerpt;  // The excerpt
        echo get_the_post_thumbnail( $article->ID );  // The thumbnail

        endforeach;
    endif;

endwhile;
endif;

?>

Hi guys! Whats wrong did i make? the code work well without repeater. I Wanted to work it with repeater so that i coded but is not working thougt.......................


问:
correct websocket architecture for django chat app
I am building the chat functionality on my app with django-channels and redis, and I am new to websocket.

after collecting enough infomation, here's my sketch of the application.

basically there are two types of chat:

team chat

user chat

they are all integrited into one chat friends view.

for team chat, such a team with pk=8, the user connects to

let route = `ws://${window.location.host}/ws/team/${team.pk}/`
```
<p>to send and receive messages. and if the user is not in the team, the connection will be rejected.</p>
<p>this means <strong>if you joined to team8, team12, team13... you be connected to ws8, ws12, ws13...</strong></p>
<hr />
<p>for user app, establish ws connection between two user: for example, ws1 is used for user1 to receive message, which if user2 want to send message to user1, user2 must connect to the socket.</p>
<p>this means <strong>if you have <code>n</code> contacts, it will be <code>n</code> ws connections</strong>.</p>
<hr />
<p>the chat consumer only applies in chat view, and I have a <strong>notification</strong> app uses ws and is implemented throughout the application. user1 connect to note1 to receive system infomation.</p>
<p>this means <strong>if <code>n</code> user is online, <code>n</code> note socket connections will be established.</strong></p>
<hr />
<p>soon I noticed the performance and number limit issue, which per browser only allow those for particular domain:</p>
```IE 6
chrome 256
firefox 200
safari(macos) 1273
```
<p>and the larger the amount of connections, the more pressue there will be for server.</p>
<hr />
<p>my app's target user works in office, therefore the messages are important and should be saved in the database.</p>
<pre class="lang-py prettyprint-override"><code>class ChatDatabaseMixin:
    @staticmethod
    @database_sync_to_async
    def newText(read, text, style, sender_pk, receiver_pk):
        msg = Message(
            sender=User.objects.get(pk=sender_pk).chatProfile,
            receiver=User.objects.get(pk=receiver_pk).chatProfile,
            text=text,
            style=style,
            read=read,
        )
        msg.save()
        return msg

    @staticmethod
    @database_sync_to_async
    def newAudio(read, binary, sender_pk, receiver_pk):
        msg = Message(
            sender=User.objects.get(pk=sender_pk).chatProfile,
            receiver=User.objects.get(pk=receiver_pk).chatProfile,
            audio=binary,
            read=read,
        )
        msg.save()
        return msg

    @staticmethod
    @database_sync_to_async
    def talkAble(sender_pk: int, receiver_pk: int):
        return Relation.talkAble(sender_pk, receiver_pk)
</code>```

it is complicated since user and team both support sending varies media:

class ChatConsumer(ChatDatabaseMixin, AsyncJsonWebsocketConsumer):
    @staticmethod
    def send_online(sender_pk, receiver_pk):
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            __class__.rn(receiver_pk),
            {
                'type': 'online_status',
                'message': 'online',
                'user': sender_pk,
            }
        )

    async def online_status(self, event):
        # print(f"{event['user']} online to {self.room_name}")
        await self.send(text_data=json.dumps({
            'type': 'online',
            'message': event['message'],
            'user': event['user'],
        }))

    async def receive(self, text_data=None, bytes_data=None):
        sender_pk = int(self.scope["user"].pk)
        receiver_pk = int(self.room_name)
        async def receive(self, text_data=None, bytes_data=None):
        sender_pk = int(self.scope["user"].pk)
        receiver_pk = int(self.room_name)
        talkable = await ChatConsumer.talkAble(sender_pk, receiver_pk)
        if not talkable['status']:
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'info_message',
                    'to': sender_pk,
                    'e': talkable['e'],
                }
            )
            return
        try:
            e = talkable['e']
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'info_message',
                    'to': sender_pk,
                    'e': e,
                }
            )
        except KeyError:
            pass
        if bytes_data:
            if len(bytes_data) > 1000000:
                await self.channel_layer.group_send(
                    self.room_group_name,
                    {
                        'type': 'info_message',
                        'to': sender_pk,
                        'e': 'sorry the audio is too long, please limit it by 30seconds',
                    }
                )
                return
            # audio
            read = await ChatConsumer.toreadReceiveBool(self)
            msg = await ChatConsumer.newAudio(
                read,
                bytes_data,
                sender_pk,
                receiver_pk,
            )

            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'audio_message',
                    'pk': msg.pk,
                    'audio': bytes_data,
                    'sender': sender_pk,
                    'receiver': receiver_pk,
                    'read': read,
                }
            )
        else:
            # text
            text_data_json = json.loads(text_data)
            if text_data_json['type'] == 'text':
                message = text_data_json['message']
                style = None
                try:
                    style = text_data_json['style']
                except KeyError:
                    pass
                '''
                sender: self.scope["user"].pk
                receiver: self.room_name
                '''
                read = await ChatConsumer.toreadReceiveBool(self)
                # print(read)
                msg = await ChatConsumer.newText(
                    read,
                    message,
                    style,
                    sender_pk,
                    receiver_pk,
                )

                await self.channel_layer.group_send(
                    self.room_group_name,
                    {
                        'type': 'chat_message',
                        'pk': msg.pk,
                        'message': message,
                        'style': style,
                        'sender': sender_pk,
                        'receiver': receiver_pk,
                        'read': read,
                    }
                )

    async def info_message(self, event):
        await self.send(text_data=json.dumps({
            'to': event['to'],

            'type': 'info',
            'e': event['e'],
        }))

    async def chat_message(self, event):
        # print(event)
        await self.send(text_data=json.dumps({
            'sender': event['sender'],
            'receiver': event['receiver'],

            'type': 'text',
            'pk': event['pk'],
            'message': event['message'],
            'style': event['style'],
            'read': event['read'],
        }))

    async def audio_message(self, event):
        # backend always send json
        # onmessage always receive json
        # frontend can send blob, self.scope point to user
        await self.send(
            text_data=json.dumps({
                'pk': event['pk'],
                'sender': event['sender'],
                'receiver': event['receiver'],

                'type': 'audio',
                'audio': base64.b64encode(event['audio']).decode('utf-8'),
                'read': event['read'],
            }),
            # bytes_data=event['audio']
        )
```

team consumer is half different half the same. The most complicated part of each consumer is the receive method that checks the conditionals.

Regard this post: Design/Architecture: web-socket one connection vs multiple connections

current server:

cpu: 4 cores

ram: 16GB

bandwidth: 14mbps

I am not sure if this the correct way of doing it, I read a lot of relevant post suggest using less connections, does it mean one socket for one user, or one socket throughout the entire application? I don’t know what is the suitable architecture for my application.

sorry, I am not intended to post the entire thing up to let you to solve it for me, I just need a direction, if you have been there please show me a way to go.

if I should put it all in one, wouldn’t that be difficult to combine three very different consumers together with clarity and elegancy? And wouldn’t that be insecure since anyone can connect to it, send via it and listen to it?

if my structure is fine, can I just add a user and team contact restriction then?

Body:
I am building the chat functionality on my app with django-channels and redis, and I am new to websocket.

after collecting enough infomation, here's my sketch of the application.

basically there are two types of chat:

team chat

user chat

they are all integrited into one chat friends view.

for team chat, such a team with pk=8, the user connects to

let route = `ws://${window.location.host}/ws/team/${team.pk}/`

to send and receive messages. and if the user is not in the team, the connection will be rejected.

this means if you joined to team8, team12, team13... you be connected to ws8, ws12, ws13...

for user app, establish ws connection between two user: for example, ws1 is used for user1 to receive message, which if user2 want to send message to user1, user2 must connect to the socket.

this means if you have n contacts, it will be n ws connections.

the chat consumer only applies in chat view, and I have a notification app uses ws and is implemented throughout the application. user1 connect to note1 to receive system infomation.

this means if n user is online, n note socket connections will be established.

soon I noticed the performance and number limit issue, which per browser only allow those for particular domain:

IE 6
chrome 256
firefox 200
safari(macos) 1273

and the larger the amount of connections, the more pressue there will be for server.

my app's target user works in office, therefore the messages are important and should be saved in the database.

class ChatDatabaseMixin:
    @staticmethod
    @database_sync_to_async
    def newText(read, text, style, sender_pk, receiver_pk):
        msg = Message(
            sender=User.objects.get(pk=sender_pk).chatProfile,
            receiver=User.objects.get(pk=receiver_pk).chatProfile,
            text=text,
            style=style,
            read=read,
        )
        msg.save()
        return msg

    @staticmethod
    @database_sync_to_async
    def newAudio(read, binary, sender_pk, receiver_pk):
        msg = Message(
            sender=User.objects.get(pk=sender_pk).chatProfile,
            receiver=User.objects.get(pk=receiver_pk).chatProfile,
            audio=binary,
            read=read,
        )
        msg.save()
        return msg

    @staticmethod
    @database_sync_to_async
    def talkAble(sender_pk: int, receiver_pk: int):
        return Relation.talkAble(sender_pk, receiver_pk)

it is complicated since user and team both support sending varies media:

class ChatConsumer(ChatDatabaseMixin, AsyncJsonWebsocketConsumer):
    @staticmethod
    def send_online(sender_pk, receiver_pk):
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            __class__.rn(receiver_pk),
            {
                'type': 'online_status',
                'message': 'online',
                'user': sender_pk,
            }
        )

    async def online_status(self, event):
        # print(f"{event['user']} online to {self.room_name}")
        await self.send(text_data=json.dumps({
            'type': 'online',
            'message': event['message'],
            'user': event['user'],
        }))

    async def receive(self, text_data=None, bytes_data=None):
        sender_pk = int(self.scope["user"].pk)
        receiver_pk = int(self.room_name)
        async def receive(self, text_data=None, bytes_data=None):
        sender_pk = int(self.scope["user"].pk)
        receiver_pk = int(self.room_name)
        talkable = await ChatConsumer.talkAble(sender_pk, receiver_pk)
        if not talkable['status']:
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'info_message',
                    'to': sender_pk,
                    'e': talkable['e'],
                }
            )
            return
        try:
            e = talkable['e']
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'info_message',
                    'to': sender_pk,
                    'e': e,
                }
            )
        except KeyError:
            pass
        if bytes_data:
            if len(bytes_data) > 1000000:
                await self.channel_layer.group_send(
                    self.room_group_name,
                    {
                        'type': 'info_message',
                        'to': sender_pk,
                        'e': 'sorry the audio is too long, please limit it by 30seconds',
                    }
                )
                return
            # audio
            read = await ChatConsumer.toreadReceiveBool(self)
            msg = await ChatConsumer.newAudio(
                read,
                bytes_data,
                sender_pk,
                receiver_pk,
            )

            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'audio_message',
                    'pk': msg.pk,
                    'audio': bytes_data,
                    'sender': sender_pk,
                    'receiver': receiver_pk,
                    'read': read,
                }
            )
        else:
            # text
            text_data_json = json.loads(text_data)
            if text_data_json['type'] == 'text':
                message = text_data_json['message']
                style = None
                try:
                    style = text_data_json['style']
                except KeyError:
                    pass
                '''
                sender: self.scope["user"].pk
                receiver: self.room_name
                '''
                read = await ChatConsumer.toreadReceiveBool(self)
                # print(read)
                msg = await ChatConsumer.newText(
                    read,
                    message,
                    style,
                    sender_pk,
                    receiver_pk,
                )

                await self.channel_layer.group_send(
                    self.room_group_name,
                    {
                        'type': 'chat_message',
                        'pk': msg.pk,
                        'message': message,
                        'style': style,
                        'sender': sender_pk,
                        'receiver': receiver_pk,
                        'read': read,
                    }
                )

    async def info_message(self, event):
        await self.send(text_data=json.dumps({
            'to': event['to'],

            'type': 'info',
            'e': event['e'],
        }))

    async def chat_message(self, event):
        # print(event)
        await self.send(text_data=json.dumps({
            'sender': event['sender'],
            'receiver': event['receiver'],

            'type': 'text',
            'pk': event['pk'],
            'message': event['message'],
            'style': event['style'],
            'read': event['read'],
        }))

    async def audio_message(self, event):
        # backend always send json
        # onmessage always receive json
        # frontend can send blob, self.scope point to user
        await self.send(
            text_data=json.dumps({
                'pk': event['pk'],
                'sender': event['sender'],
                'receiver': event['receiver'],

                'type': 'audio',
                'audio': base64.b64encode(event['audio']).decode('utf-8'),
                'read': event['read'],
            }),
            # bytes_data=event['audio']
        )

team consumer is half different half the same. The most complicated part of each consumer is the receive method that checks the conditionals.

Regard this post: Design/Architecture: web-socket one connection vs multiple connections

current server:

cpu: 4 cores

ram: 16GB

bandwidth: 14mbps

I am not sure if this the correct way of doing it, I read a lot of relevant post suggest using less connections, does it mean one socket for one user, or one socket throughout the entire application? I don’t know what is the suitable architecture for my application.

sorry, I am not intended to post the entire thing up to let you to solve it for me, I just need a direction, if you have been there please show me a way to go.

if I should put it all in one, wouldn’t that be difficult to combine three very different consumers together with clarity and elegancy? And wouldn’t that be insecure since anyone can connect to it, send via it and listen to it?

if my structure is fine, can I just add a user and team contact restriction then?


问:
An incompatible API is extended in typescript
Ask a question, the following code:

```<code>class VideoRecorder extends MediaRecorder {
// It works fine on safari 14+ and above, but if the version is less than 14, how to deal with it?
}
</code>```

The problem is: the MediaRecorder API cannot be used in the safari browser with a lower version, resulting in an error report and a white screen on the page. In a situation like this, can you still use extends? Is there any better way to do it?

```<code>// VideoRecorder.ts

if (MediaRecorder) {
class VideoRecorder extends MediaRecorder {}
} else {
// do something
}

export default VideoRecorder;
</code>```

Body:
Ask a question, the following code:

class VideoRecorder extends MediaRecorder {
// It works fine on safari 14+ and above, but if the version is less than 14, how to deal with it?
}

The problem is: the MediaRecorder API cannot be used in the safari browser with a lower version, resulting in an error report and a white screen on the page. In a situation like this, can you still use extends? Is there any better way to do it?

// VideoRecorder.ts

if (MediaRecorder) {
class VideoRecorder extends MediaRecorder {}
} else {
// do something
}

export default VideoRecorder;


问:
How do you have custom default settings for new users in kde5 before the first login?

I am a kde5 system administrator with many users and how do I make it so that when a new user is created, some settings are automatically applied to them before the first login. These settings should be applied if the user is created by the kde5 system settings or the useradd command.

I have tried to copy .kde user directory but could not find it, and I can't figure out how to configure the /etc/skel directory.

[Solved]
ChatGPT
To automatically apply settings to new users in KDE5, you need to create a skeleton directory that contains the necessary configuration files. Here are the steps to do that:

Create a directory named "skel" in the /etc directory:
bash
Copy code
sudo mkdir /etc/skel
Copy the configuration files that you want to apply to new users to the /etc/skel directory. For example, to set the background image for new users, copy the background image file to /etc/skel/Pictures directory:
bash
Copy code
sudo cp ~/Pictures/background.jpg /etc/skel/Pictures/
Set the correct permissions for the files in the skel directory:
bash
Copy code
sudo chown -R root:root /etc/skel
sudo chmod -R 755 /etc/skel
Next, all new users will inherit this directory and its contents. Any new user added will automatically copy the contents of the skel directory.
The next time a new user is created using "useradd" or KDE5 system settings, the files in the /etc/skel directory will be copied to the new user's home directory automatically, and they will have the desired configuration settings from the start.


问:
AdminLTE Template with full body background image
This is a question specifically for AdminLTE, which is built on top of Bootstrap. So all exiting free-form full page body background image questions don't apply, even this one -- Full body background with Twitter Bootstrap, because the full page body background image has to cooperate with AdminLTE in harmony. I hacked my own way, but everything is out of whack. Hence the question.

This is my standard way to use the AdminLTE Template:

...

```

All my pages are build with such structure.

Now one page I need to have a full page body background image, with the layout by above AdminLTE Template intact, all showing transparently on top of the background image.

A fully working example appreciated, not necessarily within my above pages structure, but most-recommended way is definitely welcome.

Body:
This is a question specifically for AdminLTE, which is built on top of Bootstrap. So all exiting free-form full page body background image questions don't apply, even this one -- Full body background with Twitter Bootstrap, because the full page body background image has to cooperate with AdminLTE in harmony. I hacked my own way, but everything is out of whack. Hence the question.

This is my standard way to use the AdminLTE Template:

...

All my pages are build with such structure.

Now one page I need to have a full page body background image, with the layout by above AdminLTE Template intact, all showing transparently on top of the background image.

A fully working example appreciated, not necessarily within my above pages structure, but most-recommended way is definitely welcome.


问:
AI Trading - Portfolio Weights: Weights impact the next day from the previous day
Trying to implement weights but got stuck. Need some help.

Implement calculate_dividend_weights to return the weights for each stock based on its total dividend yield over time. This is similar to generating the weight for the index, but it's using dividend data instead. For example, assume the following is dividends data:
expected output example

`def calculate_dividend_weights(dividends):
"""
Calculate dividend weights.

```<code>Parameters
----------
dividends : DataFrame
    Dividend for each stock and date

Returns
-------
dividend_weights : DataFrame
    Weights for each stock and date
"""
#TODO: Implement function

 # create a copy of the dividends dataframe to avoid modifying the original
dividends_copy = dividends.copy()
# only first row to Nan but leave the dividend values for other rows unchanged
dividends_copy.loc[dividends_copy.index[0], dividends_copy.iloc[0] == 0] = np.nan
# sum total dividends per date
dividends_sum = dividends_copy.sum(axis=1)
# divide each ticker's dividends by total dividends per date to get weights
dividend_weights = dividends.div(dividends_sum, axis=0)
return dividend_weights
</code>```

project_tests.test_calculate_dividend_weights(calculate_dividend_weights)`

results

Was expecting the weights from a previous day to impact the weights on the next day for the same ticker.

Body:
Trying to implement weights but got stuck. Need some help.

Implement calculate_dividend_weights to return the weights for each stock based on its total dividend yield over time. This is similar to generating the weight for the index, but it's using dividend data instead. For example, assume the following is dividends data:
expected output example

`def calculate_dividend_weights(dividends):
"""
Calculate dividend weights.

Parameters
----------
dividends : DataFrame
    Dividend for each stock and date

Returns
-------
dividend_weights : DataFrame
    Weights for each stock and date
"""
#TODO: Implement function

 # create a copy of the dividends dataframe to avoid modifying the original
dividends_copy = dividends.copy()
# only first row to Nan but leave the dividend values for other rows unchanged
dividends_copy.loc[dividends_copy.index[0], dividends_copy.iloc[0] == 0] = np.nan
# sum total dividends per date
dividends_sum = dividends_copy.sum(axis=1)
# divide each ticker's dividends by total dividends per date to get weights
dividend_weights = dividends.div(dividends_sum, axis=0)
return dividend_weights

project_tests.test_calculate_dividend_weights(calculate_dividend_weights)`

results

Was expecting the weights from a previous day to impact the weights on the next day for the same ticker.


问:
NuxtJs store with nuxt-property-decorator throw should be a method that returns an object in store/jobs.ts warning
I am doing a project with NuxtJs version 2.15.8, and using store folder with vuex-module-decorators to create Actions, Mutations. And, to inside my pages and components, I am using nuxt-property-decorator getModule to consume my Store.

I am getting an error as 'state' should be a method that returns an object in store/content.ts

my content.ts file is like:

```<code>@Module({ namespaced: true, name: 'contentModule' })
export default class ContentModule extends VuexModule {
   //@Actions, Mutations and Getters here
}
</code>```

and i add my store's file in a main.ts file, with all my stores  as:

```<code>import Vuex from 'vuex'
import CompanyModule from './company'

export const store =  new Vuex.Store({
   state: () => ({}),
   modules: {
    contentModule: CompanyModule ,
   },
})
</code>```

And i keep getting this error. I have seen this  stackoverflow but I was not able to solve this problem. Does anyone is facing the same warnings?

Thanks in advance!!

Body:
I am doing a project with NuxtJs version 2.15.8, and using store folder with vuex-module-decorators to create Actions, Mutations. And, to inside my pages and components, I am using nuxt-property-decorator getModule to consume my Store.

I am getting an error as 'state' should be a method that returns an object in store/content.ts

my content.ts file is like:

@Module({ namespaced: true, name: 'contentModule' })
export default class ContentModule extends VuexModule {
   //@Actions, Mutations and Getters here
}

and i add my store's file in a main.ts file, with all my stores  as:

import Vuex from 'vuex'
import CompanyModule from './company'

export const store =  new Vuex.Store({
   state: () => ({}),
   modules: {
    contentModule: CompanyModule ,
   },
})

And i keep getting this error. I have seen this  stackoverflow but I was not able to solve this problem. Does anyone is facing the same warnings?

Thanks in advance!!


问:
can't instantiate chaincode write in golang 1.19 on fabric hyperledger 1.4
I write a chaincode in golang 1.19 and want to run on a fabric network, but when instantiate it error:

```<code>Error: could not assemble transaction, err proposal response was not successful, error code 500, msg error starting container: error starting container: Failed to generate platform-specific docker build: Error returned from build: 1 "chaincode/input/src/github.com/chaincode/lattice/vendor/golang.org/x/net/http2/transport.go:19:2: cannot find package "io/fs" in any of:
        /chaincode/input/src/github.com/chaincode/lattice/vendor/io/fs (vendor tree)
        /opt/go/src/io/fs (from $GOROOT)
        /chaincode/input/src/io/fs (from $GOPATH)
        /opt/gopath/src/io/fs
"
</code>```

I try to mount folder of golang 1.19 to replace golang in cli container, but it error when byfn.sh up:

```<code>Error: error getting chaincode code mycc: error getting chaincode package bytes: Error obtaining imports: command <go list -f {{ join .Imports "\n"}} github.com/chaincode/chaincode_example02/go/>: failed with error: "exit status 1"
no required module provides package github.com/chaincode/chaincode_example02/go: go.mod file not found in current directory or any parent directory; see 'go help modules'

!!!!!!!!!!!!!!! Chaincode installation on peer0.org1 has failed !!!!!!!!!!!!!!!!
========= ERROR !!! FAILED to execute End-2-End Scenario ===========

ERROR !!!! Test failed
</code>```

I want to know how to solve this problem. Do I have to rewrite chaincode in the same golang version?

Body:
I write a chaincode in golang 1.19 and want to run on a fabric network, but when instantiate it error:

Error: could not assemble transaction, err proposal response was not successful, error code 500, msg error starting container: error starting container: Failed to generate platform-specific docker build: Error returned from build: 1 "chaincode/input/src/github.com/chaincode/lattice/vendor/golang.org/x/net/http2/transport.go:19:2: cannot find package "io/fs" in any of:
        /chaincode/input/src/github.com/chaincode/lattice/vendor/io/fs (vendor tree)
        /opt/go/src/io/fs (from $GOROOT)
        /chaincode/input/src/io/fs (from $GOPATH)
        /opt/gopath/src/io/fs
"

I try to mount folder of golang 1.19 to replace golang in cli container, but it error when byfn.sh up:

Error: error getting chaincode code mycc: error getting chaincode package bytes: Error obtaining imports: command <go list -f {{ join .Imports "\n"}} github.com/chaincode/chaincode_example02/go/>: failed with error: "exit status 1"
no required module provides package github.com/chaincode/chaincode_example02/go: go.mod file not found in current directory or any parent directory; see 'go help modules'

!!!!!!!!!!!!!!! Chaincode installation on peer0.org1 has failed !!!!!!!!!!!!!!!!
========= ERROR !!! FAILED to execute End-2-End Scenario ===========

ERROR !!!! Test failed

I want to know how to solve this problem. Do I have to rewrite chaincode in the same golang version?