问:
Python prompt opens whenever I try to open anaconda
I've deleted and installed anaconda several times. It runs a few times at first, but then it opens python prompt instead. How do I fix this?

I've reinstalled it with add to path so it opens with the prompt but that didn't work. This is what I get in python:
Python 3.9.13 (main, Aug 25 2022, 23:51:50) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32

Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated.  Libraries may fail to load.  To activate this environment
please see https://conda.io/activation


来源: stackexchange

问:
Not able to paste images onto another using Python?
I got a bunch of images to which i wanted to randomly place another set of images.I used the below code

```<code>import glob
import random
from PIL import Image

images=glob.glob('E:\\IMGONIMG\\BG/*.png')
image=glob.glob('E:\\IMGONIMG\\IMGS/*.png')
print(images)
print(image)
i=0
for img in images:
    img_bg = Image.open(img)
    width, height = img_bg.size
    i=i+1
    #images = glob.glob('*.png')
    for im in image:
        imgg = Image.open(im)
        x = random.randint(40, width-40)
        y = random.randint(40, height-40)
        img_bg.paste(imgg, (x, y, x+10, y+10))
    img_bg.save('E:/IMGONIMG/result{i}.png', 'PNG')
</code>```

But somehow it doesnt run and shows the error

ValueError                                Traceback (most recent call
last) Cell In[8], line 19
17     x = random.randint(40, width-40)
18     y = random.randint(40, height-40)
---> 19     img_bg.paste(imgg, (x, y, x+10, y+10))
20 img_bg.save('E:/IMGONIMG/result{i}.png', 'PNG')

File
~\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\Image.py:1666,
in Image.paste(self, im, box, mask)    1664     self.im.paste(im, box,
mask.im)    1665 else:
-> 1666     self.im.paste(im, box)

ValueError: images do not match

Help me please

ContentLicense: CC BY-SA 4.0

Body:
I got a bunch of images to which i wanted to randomly place another set of images.I used the below code

import glob
import random
from PIL import Image

images=glob.glob('E:\\IMGONIMG\\BG/*.png')
image=glob.glob('E:\\IMGONIMG\\IMGS/*.png')
print(images)
print(image)
i=0
for img in images:
    img_bg = Image.open(img)
    width, height = img_bg.size
    i=i+1
    #images = glob.glob('*.png')
    for im in image:
        imgg = Image.open(im)
        x = random.randint(40, width-40)
        y = random.randint(40, height-40)
        img_bg.paste(imgg, (x, y, x+10, y+10))
    img_bg.save('E:/IMGONIMG/result{i}.png', 'PNG')

But somehow it doesnt run and shows the error

ValueError                                Traceback (most recent call
last) Cell In[8], line 19
17     x = random.randint(40, width-40)
18     y = random.randint(40, height-40)
---> 19     img_bg.paste(imgg, (x, y, x+10, y+10))
20 img_bg.save('E:/IMGONIMG/result{i}.png', 'PNG')

File
~\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\Image.py:1666,
in Image.paste(self, im, box, mask)    1664     self.im.paste(im, box,
mask.im)    1665 else:
-> 1666     self.im.paste(im, box)

ValueError: images do not match

Help me please


问:
How to make API request from Google authentication in ASP.NET?
I do not understand how I can get the authorization code/access token to make a request.

This is my .AddGoogle():

```<code>builder.Services.AddAuthentication(o =>
{
    o.DefaultChallengeScheme = "Google";
    o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie().AddGoogle("Google",options =>
{
    IConfigurationSection auth = builder.Configuration.GetSection("Authentication:Google");
    options.ClientId = auth["ClientId"];
    options.ClientSecret = auth["ClientSecret"];
    options.CallbackPath = "/Home";
    options.AuthorizationEndpoint += "?prompt=consent";
    options.SaveTokens = true;
    options.Scope.Add(FitnessService.Scope.FitnessActivityRead);
});
</code>```

So I log in / register, and then what?

I've tried this method

```<code>UserCredential credential;

var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
               {
                   ClientSecrets = new ClientSecrets()
                                       {
                                           ClientId = configuration.GetSection("Authentication:Google")["ClientId"],
                                           ClientSecret = configuration.GetSection("Authentication:Google")["ClientSecret"]
                                       },
                   Scopes = new[] {
                                      FitnessService.Scope.FitnessActivityRead,
                                      FitnessService.Scope.FitnessActivityWrite,
                                      FitnessService.Scope.FitnessSleepRead,
                                      FitnessService.Scope.FitnessSleepWrite
                                  },
            });

            var token = new TokenResponse
                            {
                                AccessToken = "",
                                RefreshToken = ""
                            };

            credential = new UserCredential(flow, "user", token);

            FitnessService fitnessService = new FitnessService(new BaseClientService.Initializer()
            {
                ApplicationName = "Exrecise App",
                HttpClientInitializer = credential
            });

            var resp = await fitnessService.Users.Sessions.List("me").ExecuteAsync();
</code>```

But how do I get the tokens to begin with?

I even tried HttpClient (by pasting the token from OAuthplayground)

```<code>HttpClient http = new HttpClient();

var resp = await http.SendAsync(new HttpRequestMessage()
            {
                RequestUri = new UriBuilder("https://www.googleapis.com/fitness/v1/users/me/sessions").Uri,
                Headers =
                {
                    { "Authorization","Bearer " }
                },
                Method = HttpMethod.Get
            });

return Ok(await resp.Content.ReadAsStringAsync());
</code>```

Same problem, how do I get the access token from the currently signed in user?

I looked everywhere, but every solution is either outdated or is unclear or just doesn't work for some reason.

Body:
I do not understand how I can get the authorization code/access token to make a request.

This is my .AddGoogle():

builder.Services.AddAuthentication(o =>
{
    o.DefaultChallengeScheme = "Google";
    o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie().AddGoogle("Google",options =>
{
    IConfigurationSection auth = builder.Configuration.GetSection("Authentication:Google");
    options.ClientId = auth["ClientId"];
    options.ClientSecret = auth["ClientSecret"];
    options.CallbackPath = "/Home";
    options.AuthorizationEndpoint += "?prompt=consent";
    options.SaveTokens = true;
    options.Scope.Add(FitnessService.Scope.FitnessActivityRead);
});

So I log in / register, and then what?

I've tried this method

UserCredential credential;

var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
               {
                   ClientSecrets = new ClientSecrets()
                                       {
                                           ClientId = configuration.GetSection("Authentication:Google")["ClientId"],
                                           ClientSecret = configuration.GetSection("Authentication:Google")["ClientSecret"]
                                       },
                   Scopes = new[] {
                                      FitnessService.Scope.FitnessActivityRead,
                                      FitnessService.Scope.FitnessActivityWrite,
                                      FitnessService.Scope.FitnessSleepRead,
                                      FitnessService.Scope.FitnessSleepWrite
                                  },
            });

            var token = new TokenResponse
                            {
                                AccessToken = "",
                                RefreshToken = ""
                            };

            credential = new UserCredential(flow, "user", token);

            FitnessService fitnessService = new FitnessService(new BaseClientService.Initializer()
            {
                ApplicationName = "Exrecise App",
                HttpClientInitializer = credential
            });

            var resp = await fitnessService.Users.Sessions.List("me").ExecuteAsync();

But how do I get the tokens to begin with?

I even tried HttpClient (by pasting the token from OAuthplayground)

HttpClient http = new HttpClient();

var resp = await http.SendAsync(new HttpRequestMessage()
            {
                RequestUri = new UriBuilder("https://www.googleapis.com/fitness/v1/users/me/sessions").Uri,
                Headers =
                {
                    { "Authorization","Bearer " }
                },
                Method = HttpMethod.Get
            });

return Ok(await resp.Content.ReadAsStringAsync());

Same problem, how do I get the access token from the currently signed in user?

I looked everywhere, but every solution is either outdated or is unclear or just doesn't work for some reason.


问:
Tumblr different pages need different layouts html/css - columns page vs single post/container page
This is my first ever question on stackoverflow so I apologize if I'm not following standard etiquette.

I'm working on a blog final project for a class that requires a custom theme and I'm using tumblr to host it for reasons independent of coding. This is the first time I've used css for more than extremely basic styling purposes, and I'm relatively new to html/css-related work in general.

For my main page, I have a sticky sidebar on the left 1/4 of the page, and then 3 columns for posts in a tiled gallery sort of like (similar to masonry but I used css grid because masonry confused me). Overall, I'm pretty satisfied with how this is turning out. Due to my inexperience, it's not where I would ideally have it designed, but my goal is to be able to work on it as I learn more html/css/js after this class is over.
main page layout
about page currently

However, I'm having trouble with fixing an individual post page and my about page: when you click on an individual post, it's also being shown as a 3 column post, which is not my intention at all. Same with the about page. I think this is due to my usage of css-grid on the main page, but I'm confused as to how I can fix this on individual posts.

a note on my html/css - my friend let me borrow most of the sidebar-specific code which is why it's much nicer than some of the stuff I've written and she's helped me a lot during this process but the page issue isn't something she's ever really encountered because she doesn't use css-grid or columned design often.

I've tried simply writing a completely new html for the about page, but my sidebar uses meta/variables (that I think are) built into the tumblr theme editing interface, so my sidebar wouldn't show up correctly when I tried to do that. And I haven't tried anything for the posts because I didn't even realize they had an issue until earlier today.

I can provide other code snippets if this would help, but I'm not sure what to include other than these:

#sidebar {
       top: 35%;
       position: -webkit-sticky;
       position: sticky;
       background: #ffffff;
       height: 40vh;
       width: 20%;
       text-align: center;
       padding: 25px 10px 10px 10px;
       border: 2px solid;
       border-radius: 70% 30% / 20% 40%;
       margin: 2% 2%;
       }
```
<pre class="lang-css prettyprint-override"><code>#container {
        column-count: 3;
        display:inline-block;
        grid-template-columns: auto auto auto;
        grid-area: container;
        width: 100%;
        column-gap: 20px;
        }

#house {
        display: flex;
        flex-direction: row;
        justify-content: right;
        }

.content{
        width: 90%;
        background-color: #ffffff;
        padding: 20px;
        margin: auto;
        margin-bottom: 10px;
        float: left;
        }
</code>```

{Title}

                {Description}

{text:link 1}

{text:link 2}

{text:link 3}

{text:link 4}

            {block:Posts}

                [I've omitted the post types and their meta info for clarity]

            {/block:Posts}

```

Any help at all would be greatly appreciated! If this has already been answered please direct me there as well, I'm not too well-versed in navigating stackoverflow yet.

Body:
This is my first ever question on stackoverflow so I apologize if I'm not following standard etiquette.

I'm working on a blog final project for a class that requires a custom theme and I'm using tumblr to host it for reasons independent of coding. This is the first time I've used css for more than extremely basic styling purposes, and I'm relatively new to html/css-related work in general.

For my main page, I have a sticky sidebar on the left 1/4 of the page, and then 3 columns for posts in a tiled gallery sort of like (similar to masonry but I used css grid because masonry confused me). Overall, I'm pretty satisfied with how this is turning out. Due to my inexperience, it's not where I would ideally have it designed, but my goal is to be able to work on it as I learn more html/css/js after this class is over.
main page layout
about page currently

However, I'm having trouble with fixing an individual post page and my about page: when you click on an individual post, it's also being shown as a 3 column post, which is not my intention at all. Same with the about page. I think this is due to my usage of css-grid on the main page, but I'm confused as to how I can fix this on individual posts.

a note on my html/css - my friend let me borrow most of the sidebar-specific code which is why it's much nicer than some of the stuff I've written and she's helped me a lot during this process but the page issue isn't something she's ever really encountered because she doesn't use css-grid or columned design often.

I've tried simply writing a completely new html for the about page, but my sidebar uses meta/variables (that I think are) built into the tumblr theme editing interface, so my sidebar wouldn't show up correctly when I tried to do that. And I haven't tried anything for the posts because I didn't even realize they had an issue until earlier today.

I can provide other code snippets if this would help, but I'm not sure what to include other than these:

#sidebar {
       top: 35%;
       position: -webkit-sticky;
       position: sticky;
       background: #ffffff;
       height: 40vh;
       width: 20%;
       text-align: center;
       padding: 25px 10px 10px 10px;
       border: 2px solid;
       border-radius: 70% 30% / 20% 40%;
       margin: 2% 2%;
       }

#container {
        column-count: 3;
        display:inline-block;
        grid-template-columns: auto auto auto;
        grid-area: container;
        width: 100%;
        column-gap: 20px;
        }

#house {
        display: flex;
        flex-direction: row;
        justify-content: right;
        }

.content{
        width: 90%;
        background-color: #ffffff;
        padding: 20px;
        margin: auto;
        margin-bottom: 10px;
        float: left;
        }

{Title}

                {Description}

{text:link 1}

{text:link 2}

{text:link 3}

{text:link 4}

            {block:Posts}

                [I've omitted the post types and their meta info for clarity]

            {/block:Posts}

Any help at all would be greatly appreciated! If this has already been answered please direct me there as well, I'm not too well-versed in navigating stackoverflow yet.


问:
I want the enter key press to work as submit button and run the js function
I want if user enter the value and press enter key instead of submit button. The function calvol() should run and give the result.

HTML

```<code>    <body>
        <div class="container-fluid">
        <div class="row inpdip">
          <div class="col diptext">
            <label for="dip">Dip</label>
          </div>
          <div class="col">
            <input type="number" class="inpbox" id="dip">
          </div>
        </div>
        <div class="row">
            <div class="col">
            </div>
            <div class="col">
                <button class="btn btn-dark" id="myBtn" type="submit" onclick="calvol()">Submit</button>
            </div>
        </div>
        <div class="row outputvol">
          <div class="col diptext ">
            Volume :
          </div>
          <div class="col">
            <span class="" id="result"></span>
          </div>
        </div>
    </body>
</code>```

JavaScript

```<code>function calvol() {
var R = 10.5;
var L = 62.5;
var inputh = document.getElementById('dip').value;

if (inputh>210){
    document.getElementById('result').innerHTML = "Dip is over the tank limit." ;
} else if (inputh<= 0) {
    document.getElementById('result').innerHTML = "Enter a higher number" ;
} else {
var h = inputh/10;
let TankVolume = L * (R * R * Math.acos((R - h)/ R) - (R - h) * Math.sqrt(2 * R * h - h * h));
let volume = Math.round(TankVolume);
console.log(volume)
document.getElementById('result').innerHTML = volume +"  Liter" ;
}
}

var input = document.getElementById("dip");
input.onkeyup = function(e){
  if(e.keyCode == 13){
     calvol();
  }
}
</code>```

I want if user enter the value and press enter key instead of submit button. The function calvol() should run and give the result.

Body:
I want if user enter the value and press enter key instead of submit button. The function calvol() should run and give the result.

HTML

            Dip

            <input type="number" class="inpbox" id="dip">

                <button class="btn btn-dark" id="myBtn" type="submit" onclick="calvol()">Submit</button>

            Volume :

JavaScript

function calvol() {
var R = 10.5;
var L = 62.5;
var inputh = document.getElementById('dip').value;

if (inputh>210){
    document.getElementById('result').innerHTML = "Dip is over the tank limit." ;
} else if (inputh<= 0) {
    document.getElementById('result').innerHTML = "Enter a higher number" ;
} else {
var h = inputh/10;
let TankVolume = L * (R * R * Math.acos((R - h)/ R) - (R - h) * Math.sqrt(2 * R * h - h * h));
let volume = Math.round(TankVolume);
console.log(volume)
document.getElementById('result').innerHTML = volume +"  Liter" ;
}
}

var input = document.getElementById("dip");
input.onkeyup = function(e){
  if(e.keyCode == 13){
     calvol();
  }
}

I want if user enter the value and press enter key instead of submit button. The function calvol() should run and give the result.


问:
Open all links in a new tab using xpath and run a command Selenium - Python
New to selenium. I am trying to have Selenium open a new tab for each/every link provided in a dynamic table. I would like to run the same command on each tab (input information). Below is my current code. The code allows me to search and access the data table using its xpath. In the xpath I put a * in the "tr[ ]" which allows me to select all the needed links in the table cells. However, the code only takes me to the first link in the data table and runs the command.

```<code>driver.get('https://www.#.com')
driver.maximize_window()
time.sleep(2)

link = driver.find_element('link text', 'Search')
link.click()
time.sleep(4)

table = driver.find_element('xpath', '//*[@id="TableBody"]/tr[*]/td[1]/div[2]/a')
table.click()
time.sleep(4)

#Enter text in the links page
high_field = driver.find_element('id', 'formBid')
high_field.send_keys('#')
low_field = driver.find_element('id', 'formBidMin')
low_field.send_keys('#')
low_field.send_keys(Keys.RETURN)
print('Text entered!')

time.sleep(10)
</code>```

How can I solve the following:

Have each link open in a new tab

Run a command in each tab (same command)

Body:
New to selenium. I am trying to have Selenium open a new tab for each/every link provided in a dynamic table. I would like to run the same command on each tab (input information). Below is my current code. The code allows me to search and access the data table using its xpath. In the xpath I put a * in the "tr[ ]" which allows me to select all the needed links in the table cells. However, the code only takes me to the first link in the data table and runs the command.

driver.get('https://www.#.com')
driver.maximize_window()
time.sleep(2)

link = driver.find_element('link text', 'Search')
link.click()
time.sleep(4)

table = driver.find_element('xpath', '//*[@id="TableBody"]/tr[*]/td[1]/div[2]/a')
table.click()
time.sleep(4)

#Enter text in the links page
high_field = driver.find_element('id', 'formBid')
high_field.send_keys('#')
low_field = driver.find_element('id', 'formBidMin')
low_field.send_keys('#')
low_field.send_keys(Keys.RETURN)
print('Text entered!')

time.sleep(10)

How can I solve the following:

Have each link open in a new tab

Run a command in each tab (same command)


问:
API pull request from Rapid API
Still a bit new to swift but I am trying to pull information from MS Financial using Rapid API. However, nothing is coming through and I believe its because my DataModel is wrong I am a little confused how I would set it up. Since the first key is dyanmic. I do know what it will be everytime but I don't know how to implement that. This is what I have:

```<code>import Foundation

struct RealTimeData : Codable{
    let performanceID : Groups
}

struct Groups : Codable{
    let tradingStatus : Names
}

struct Names : Codable {
    let value : String
}
</code>```

And this is what the JSON return looks like:

```<code>{
  "0P0000OQN8": {
    "netChange": {
      "value": -47.04,
      "filtered": false
    },
    "previousClosePrice": {
      "value": 923.39,
      "filtered": false
    },
    "adjustedClosePrice": {
      "value": 923.39,
      "filtered": false
    },
    "name": {
      "value": "Tesla",
      "filtered": false
    },
    "percentNetChange": {
      "value": -5.0943,
      "filtered": false
    },
    "tradingStatus": {
      "value": "Closed",
      "filtered": false
    },
    "lastPrice": {
      "value": 876.35,
      "filtered": false,
      "date": {
        "value": "2022-02-17T16:15:00-05:00",
        "filtered": false
      }
    }
  }
</code>```

All I want to grab is the lastPrice value. But the whole JSON starts with the performanceID in it. So I am a little confused.

This is the link to rapid api to see how the request is made:

https://rapidapi.com/apidojo/api/ms-finance/

and its the get-realtime-data one.

Thank you,

Title: API pull request from Rapid API

Body:
Still a bit new to swift but I am trying to pull information from MS Financial using Rapid API. However, nothing is coming through and I believe its because my DataModel is wrong I am a little confused how I would set it up. Since the first key is dyanmic. I do know what it will be everytime but I don't know how to implement that. This is what I have:

import Foundation

struct RealTimeData : Codable{
    let performanceID : Groups
}

struct Groups : Codable{
    let tradingStatus : Names
}

struct Names : Codable {
    let value : String
}

And this is what the JSON return looks like:

{
  "0P0000OQN8": {
    "netChange": {
      "value": -47.04,
      "filtered": false
    },
    "previousClosePrice": {
      "value": 923.39,
      "filtered": false
    },
    "adjustedClosePrice": {
      "value": 923.39,
      "filtered": false
    },
    "name": {
      "value": "Tesla",
      "filtered": false
    },
    "percentNetChange": {
      "value": -5.0943,
      "filtered": false
    },
    "tradingStatus": {
      "value": "Closed",
      "filtered": false
    },
    "lastPrice": {
      "value": 876.35,
      "filtered": false,
      "date": {
        "value": "2022-02-17T16:15:00-05:00",
        "filtered": false
      }
    }
  }

All I want to grab is the lastPrice value. But the whole JSON starts with the performanceID in it. So I am a little confused.

This is the link to rapid api to see how the request is made:

https://rapidapi.com/apidojo/api/ms-finance/

and its the get-realtime-data one.

Thank you,


问:
Insert statement without N' prefix of value
I have a question around SQL Server. How to take data backup without prefix N' in each value before.

Database ... > Tasks ... > Generate Scripts ... > Next ... >
select specific database objects...>choose table..>next..> open new querywindow..>
advanced ..>type of datatoscript..>schema only...next

The insert script I get looks like this:

```<code>INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (1, N'abc', 10.0000, N'unknowN')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (2, N'unknown', 20.0000, N'che')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (3, N'nkiln', 89.0000, N'nl')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (4, N'ravin', 0.0000, N'nrN')
GO
</code>```

I want an insert script without the prefix N' like this:

```<code>INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (1, 'abc', 10.0000, 'unknowN')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (2, 'unknown', 20.0000, 'che')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (3, 'nkiln', 89.0000, 'nl')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (4, N'ravin', 0.0000, N'nrN')
GO
</code>```

Please tell me any setting need and  how to take insert scripts backup without prefix N' .

Body:
I have a question around SQL Server. How to take data backup without prefix N' in each value before.

Database ... > Tasks ... > Generate Scripts ... > Next ... >
select specific database objects...>choose table..>next..> open new querywindow..>
advanced ..>type of datatoscript..>schema only...next

The insert script I get looks like this:

INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (1, N'abc', 10.0000, N'unknowN')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (2, N'unknown', 20.0000, N'che')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (3, N'nkiln', 89.0000, N'nl')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (4, N'ravin', 0.0000, N'nrN')
GO

I want an insert script without the prefix N' like this:

INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (1, 'abc', 10.0000, 'unknowN')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (2, 'unknown', 20.0000, 'che')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (3, 'nkiln', 89.0000, 'nl')
GO
INSERT [dbo].[emp] ([id], [name], [sal], [loc]) VALUES (4, N'ravin', 0.0000, N'nrN')
GO

Please tell me any setting need and  how to take insert scripts backup without prefix N' .


问:
Why ab+ mode not supporting read() in python (rb,rb+ works)?
```<code>import pickle
myfile=open(r'student_data.txt','ab+') #rb or rb+ works

data={}
try:
    while True:
        data=pickle.load(myfile)
        print(data)
except EOFError:
    myfile.close()
</code>```

I thought ab+ should retain data at the same time allow read but it doesn't seem to work, can somebody point out the error in my code...

Body:
import pickle
myfile=open(r'student_data.txt','ab+') #rb or rb+ works

data={}
try:
    while True:
        data=pickle.load(myfile)
        print(data)
except EOFError:
    myfile.close()

I thought ab+ should retain data at the same time allow read but it doesn't seem to work, can somebody point out the error in my code...


问:
Nginx Too Many Redirect - Wordpress Container Reverse Proxy
I am trying to reverse proxy a wordpress containerized app. I've turned off the proxy of cloudflare and make them act as DNS only. here is my nginx conf file:

```<code>server {
    root /var/www/html;
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name [redacted].us www.[redacted].us;
    location / {
        proxy_pass         http://127.0.0.1:81/;
        proxy_redirect     off;
        #proxy_set_header   Host localhost:81;
        proxy_set_header   Host $http_host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

    ssl_certificate /etc/letsencrypt/live/[redacted].us/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/[redacted].us/privkey.pem;
 # managed by Certbot

}

server {
    if ($host = www.[redacted].us) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = [redacted].us) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    #listen [::]:80;
    server_name [redacted].us www.[redacted].us;
    return 404; # managed by Certbot
}
</code>```

If proxy set header is change to the one that is commented the infinite redirect is resolve but every link inside is broken. I use certbot to auto renew the ssl certificate and I believe i leaving the default configuration file as default. Any work around because I can't even open the Admin panel yet to see how wordpress handle the request

Body:
I am trying to reverse proxy a wordpress containerized app. I've turned off the proxy of cloudflare and make them act as DNS only. here is my nginx conf file:

server {
    root /var/www/html;
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name [redacted].us www.[redacted].us;
    location / {
        proxy_pass         http://127.0.0.1:81/;
        proxy_redirect     off;
        #proxy_set_header   Host localhost:81;
        proxy_set_header   Host $http_host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

    ssl_certificate /etc/letsencrypt/live/[redacted].us/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/[redacted].us/privkey.pem;
 # managed by Certbot

}

server {
    if ($host = www.[redacted].us) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = [redacted].us) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    #listen [::]:80;
    server_name [redacted].us www.[redacted].us;
    return 404; # managed by Certbot
}

If proxy set header is change to the one that is commented the infinite redirect is resolve but every link inside is broken. I use certbot to auto renew the ssl certificate and I believe i leaving the default configuration file as default. Any work around because I can't even open the Admin panel yet to see how wordpress handle the request


问:
How does Spring Config Server Fetch Values from Git using Queues
I am doing a course from Udemy, and implemented Spring Cloud Config Server, with Git as Backend. Every thing seems to be working fine.

I have following Spring Cloud Config Server: ConfigServer-RI

In ConfigServer-RI I have following entry in application.properties file, for configuring rabbit mq.

```<code>spring.cloud.config.server.git.uri=https://github.com/Naresh-Chaurasia/ConfigServer-RI
spring.cloud.config.server.git.default-label=main
spring.cloud.config.server.git.clone-on-start=true
management.endpoints.web.exposure.include=bus-refresh

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
</code>```

I also have User Microservice: User-RI

In User-RI, I have following entry in application.properties

```<code>spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
</code>```

Now if i make change in applicaiton.properties in Git file, https://github.com/Naresh-Chaurasia/ConfigServer-RI, and then call, the Spring Config Server, with following  URL http://localhost:8012/actuator/bus-refresh, the changes that are done in the Git properties file are reflected in User-RI Microservice i.e. the changes from Git repository properties file are accessible to User-RI Microservice without restarting it.

Question: I am not able to understand, how the data is flowing from Git Repository to Microservices, when I configure the queue details in application.properties file.

Thanks.

Body:
I am doing a course from Udemy, and implemented Spring Cloud Config Server, with Git as Backend. Every thing seems to be working fine.

I have following Spring Cloud Config Server: ConfigServer-RI

In ConfigServer-RI I have following entry in application.properties file, for configuring rabbit mq.

spring.cloud.config.server.git.uri=https://github.com/Naresh-Chaurasia/ConfigServer-RI
spring.cloud.config.server.git.default-label=main
spring.cloud.config.server.git.clone-on-start=true
management.endpoints.web.exposure.include=bus-refresh

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

I also have User Microservice: User-RI

In User-RI, I have following entry in application.properties

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

Now if i make change in applicaiton.properties in Git file, https://github.com/Naresh-Chaurasia/ConfigServer-RI, and then call, the Spring Config Server, with following  URL http://localhost:8012/actuator/bus-refresh, the changes that are done in the Git properties file are reflected in User-RI Microservice i.e. the changes from Git repository properties file are accessible to User-RI Microservice without restarting it.

Question: I am not able to understand, how the data is flowing from Git Repository to Microservices, when I configure the queue details in application.properties file.

Thanks.


问:
Three js overlapping HTML Content
I'm running a live model in a website using three js and a GTFLoader, but I want to add a form using html, but the model hides it at the back. When I first open the page, it displays half of a test, but when I click on model, it disappears the form and a text.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Turbo Shaft</title>

    <script src="https://cdn.jsdelivr.net/npm/three@0.122.0/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.122.0/examples/js/controls/OrbitControls.min.js"></script>
    <script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script>
    <style>
        body {
            overflow: hidden;
            margin: 0px;

            /* background: linear-gradient(#e4e0ba, #f7d9aa);
            margin: 0px;
            overflow: hidden; */
            z-index: 1;

        }
        #c {

            z-index: 2;

        }

    </style>

</head>

<body id="c">
    <div id="canvas">
        sadasdasdasdasdasdasdasdadas
      </div>
     <form  class="form" id='formId' action=''>
         Speed FrontFan:
        <input type='text'
               id='nm'
               name='nm'>
        </input>
    </form>

gdfgdfsgdfsgsfd

    <script src="js/script.js"></script>
</body>
</html>

</code>```
```<code>const scene = new THREE.Scene()
scene.add(new THREE.AxesHelper(5))

const light = new THREE.SpotLight()
light.position.set(10, 10, 10)
scene.add(light)

var mesh01;

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)

camera.position.z = 2

const renderer = new THREE.WebGLRenderer({ alpha: true })

renderer.setSize(window.innerWidth, window.innerHeight)
document.getElementById('canvas').appendChild(renderer.domElement)

const controls = new THREE.OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

var turboshaftModel;

const loader = new THREE.GLTFLoader()
    loader.load (
        'models/b.glb',
        function (gltf) {
            turboshaftModel  = gltf.scene;
            console.log(turboshaftModel);
            scene.add(gltf.scene)

            function spindle() {
                requestAnimationFrame( spindle );

                turboshaftModel.getObjectByName("FRONTFAN").rotation.z = (Date.now() * 0.0003) * Math.PI * 0.3;
                turboshaftModel.getObjectByName("LOWPRCOMPRESSOR").rotation.z = -1 * (Date.now() * 0.0003) * Math.PI * 0.3;
                turboshaftModel.getObjectByName("HIGHPRESSURECOMPRESSOR").rotation.z = (Date.now() * 0.0003) * Math.PI * 0.3;
                turboshaftModel.getObjectByName("TURBINE").rotation.z = (Date.now() * 0.0003) * Math.PI * 0.3;

                renderer.render( scene, camera );
            };
            spindle();

        },
        (xhr) => {
            console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
        },
        (error) => {
            console.log(error);
        }

    )

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

function animate() {
    requestAnimationFrame(animate)

    controls.update()

    render()

}

function render() {
    renderer.render(scene, camera)
}

animate()
</code>```

Another HTML element is hidden by the model.

Title: Three js overlapping HTML Content

Body:
I'm running a live model in a website using three js and a GTFLoader, but I want to add a form using html, but the model hides it at the back. When I first open the page, it displays half of a test, but when I click on model, it disappears the form and a text.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Turbo Shaft</title>

        sadasdasdasdasdasdasdasdadas

     <form  class="form" id='formId' action=''>
         Speed FrontFan:
        <input type='text'
               id='nm'
               name='nm'>
        </input>
    </form>

gdfgdfsgdfsgsfd

const scene = new THREE.Scene()
scene.add(new THREE.AxesHelper(5))

const light = new THREE.SpotLight()
light.position.set(10, 10, 10)
scene.add(light)

var mesh01;

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)

camera.position.z = 2

const renderer = new THREE.WebGLRenderer({ alpha: true })

renderer.setSize(window.innerWidth, window.innerHeight)
document.getElementById('canvas').appendChild(renderer.domElement)

const controls = new THREE.OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

var turboshaftModel;

const loader = new THREE.GLTFLoader()
    loader.load (
        'models/b.glb',
        function (gltf) {
            turboshaftModel  = gltf.scene;
            console.log(turboshaftModel);
            scene.add(gltf.scene)

            function spindle() {
                requestAnimationFrame( spindle );

                turboshaftModel.getObjectByName("FRONTFAN").rotation.z = (Date.now() * 0.0003) * Math.PI * 0.3;
                turboshaftModel.getObjectByName("LOWPRCOMPRESSOR").rotation.z = -1 * (Date.now() * 0.0003) * Math.PI * 0.3;
                turboshaftModel.getObjectByName("HIGHPRESSURECOMPRESSOR").rotation.z = (Date.now() * 0.0003) * Math.PI * 0.3;
                turboshaftModel.getObjectByName("TURBINE").rotation.z = (Date.now() * 0.0003) * Math.PI * 0.3;

                renderer.render( scene, camera );
            };
            spindle();

        },
        (xhr) => {
            console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
        },
        (error) => {
            console.log(error);
        }

    )

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

function animate() {
    requestAnimationFrame(animate)

    controls.update()

    render()

}

function render() {
    renderer.render(scene, camera)
}

animate()

Another HTML element is hidden by the model.


问:
Requested data didn't came to database and nodejs post text is not showing afterwards submitting
I requested data, but it's neither shows error nor data was added to database.

```<code>
const express = require("express");
const { hostname } = require("os");
const path = require("path")
const bodyparser = require("body-parser")
const mongoose = require('mongoose');
main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://localhost/contactdance');
}
const app = express()
const port = 80;
//Defining mongoose scheme

const contactSchema = new mongoose.Schema({
    name: String,
    phone: String,
    email: String,
    address: String,
    desc: String
  });
const Contact = mongoose.model('Contact', contactSchema);

// EXPRESS SPECIFIC STUFF

app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded())

// PUG SPECIFIC STUFF
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', path.join(__dirname, 'view')) // Set the views directory

//end point
app.get('/', (req, res)=>{
    const params ={ }
    res.status(200).render('home.pug', params);
})

app.get('/contact', (req, res)=>{
  const params ={ }
  res.status(200).render('contact.pug', params);
})

app.post('/contact', (req, res)=>{
  var myData = new Contact(req.body);
  myData.save().then(()=>{
  res.send("This item has been saved to the database")
  }).catch(()=>{
  res.status(400).send("item was not saved to the databse")
})
})

app.listen(port, ()=>{
    console.log(`The application started successfully on port ${port}`);
});
</code>```

i expected to see text whether it succeeded or not but it didnt happen neither data was added.It didnt showed me error and i am like WTF.when i sew collections database contact was added but not data inside of it.

Body:
I requested data, but it's neither shows error nor data was added to database.

const express = require("express");
const { hostname } = require("os");
const path = require("path")
const bodyparser = require("body-parser")
const mongoose = require('mongoose');
main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://localhost/contactdance');
}
const app = express()
const port = 80;
//Defining mongoose scheme

const contactSchema = new mongoose.Schema({
    name: String,
    phone: String,
    email: String,
    address: String,
    desc: String
  });
const Contact = mongoose.model('Contact', contactSchema);

// EXPRESS SPECIFIC STUFF

app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded())

// PUG SPECIFIC STUFF
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', path.join(__dirname, 'view')) // Set the views directory

//end point
app.get('/', (req, res)=>{
    const params ={ }
    res.status(200).render('home.pug', params);
})

app.get('/contact', (req, res)=>{
  const params ={ }
  res.status(200).render('contact.pug', params);
})

app.post('/contact', (req, res)=>{
  var myData = new Contact(req.body);
  myData.save().then(()=>{
  res.send("This item has been saved to the database")
  }).catch(()=>{
  res.status(400).send("item was not saved to the databse")
})
})

app.listen(port, ()=>{
    console.log(`The application started successfully on port ${port}`);
});

i expected to see text whether it succeeded or not but it didnt happen neither data was added.It didnt showed me error and i am like WTF.when i sew collections database contact was added but not data inside of it.


问:
Extending image tag over an existing tag by overlapping
I am trying to extend the image to the top, passed the previous HTML tag. This is what I have so far:

```<code> .toggle-modal {
  display: block;
  cursor: pointer;
  padding: 8px 30px;
  position: relative;
  margin: 0 auto;
  top: 10px;
  left: 80px;
}
#image {
  width: 200px;
  height: 180px;
}
<div className='card'>
  <FaRegStar size={20} className='toggle-modal' onClick={openModal}/>
  <Modal toggle={modalState} action={openModal} />
  <div onClick={refreshOverview}>
    {product.image ? (<img src={product.image[0].url} alt={product.name} id='image'/>) :
    'image not available'
    }
  </div>
</div>
</code>```

rendered top image card

Body:
I am trying to extend the image to the top, passed the previous HTML tag. This is what I have so far:

 .toggle-modal {
  display: block;
  cursor: pointer;
  padding: 8px 30px;
  position: relative;
  margin: 0 auto;
  top: 10px;
  left: 80px;
}
#image {
  width: 200px;
  height: 180px;
}

  <FaRegStar size={20} className='toggle-modal' onClick={openModal}/>
  <Modal toggle={modalState} action={openModal} />

    {product.image ? () :
    'image not available'
    }

rendered top image card


问:
How to show price by calculating distance using graph with PHP and mysql?
I am working on a project called the courier management system where I need to show the price of courier product price by calculating the receiver place to destination place by using a graph(the shortest path algorithm can be the Dijkstra algorithm for example).

Can anyone please help me with this?

I have no idea how to implement this, I am  a very beginner in this field


问:
jQuery animating absolute position of div not working in IE 7
The following code is invoked by 3  tags at the top of the page. The page is a series of thumbnails that are filtered by clicking the  tags (http://parlaycreative.com/work). This functionality works fine in SF and FF on Win and OSX but not in IE. In IE the first time a  is clicked the code works correctly, however the second time when s are already faded out  the code does not function. Does IE have a problem selecting elements with display:none?

```<code>jQuery(document).ready(function() {
//Align objects in grid
    moveProjects('', 0);

// filter project previews on click
jQuery('.category-filter').mouseup(function() {
    var filter_string = '';

    // toggle .active state of fitler links
    if ( jQuery(this).is('.active')) {
        jQuery(this).removeClass('active');
    }
    else {
        jQuery(this).addClass('active');
    }

    jQuery('.category-filter').each(function(index) {
        if(jQuery(this).is('.active')) {
            filter_string += '.' + jQuery(this).text().toLowerCase() + ',';
        }
    });

    // Remove trailing comma
    filter_string = filter_string.substring(0, filter_string.length-1);

    // Fade .project-preview-wrapper if inactive types
    jQuery('.project-preview-wrapper').not(filter_string).fadeOut('fast');

    setTimeout(moveProjects, 250, filter_string, 500);
});

// Set aboslute position of .project-preview-wrapper in grid
function moveProjects (filter_string, time) {
    var cur_item = 0;
    var num_cols = 4;
    var num_rows = 0;
    var preview_width = 150;
    var preview_height = 150;
    var margin = 9;

    jQuery('.project-preview-wrapper').each(function (index) {
        var left_val = margin * (cur_item % num_cols) + preview_width * (cur_item % num_cols);
        var top_val = num_rows * (preview_height + margin);
        if (jQuery(this).css('display') != 'none') {
            jQuery(this).animate({'left':left_val,'top':top_val}, time);
            if (cur_item % num_cols == 3) {
                num_rows ++;
            }
            cur_item++;
        }
        else if (jQuery(this).is(filter_string) || filter_string == '') {
            jQuery(this).animate({'left':left_val,'top':top_val}, 0).delay(time).fadeIn('fast');
            if (cur_item % num_cols == 3) {
                num_rows ++;
            }
            cur_item++;
        }
     });
    num_rows = Math.ceil(cur_item / num_cols);
    jQuery('.view-id-work').animate({'height':(num_rows) * (preview_height + margin)},time);
};
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The following code is invoked by 3  tags at the top of the page. The page is a series of thumbnails that are filtered by clicking the  tags (http://parlaycreative.com/work). This functionality works fine in SF and FF on Win and OSX but not in IE. In IE the first time a  is clicked the code works correctly, however the second time when s are already faded out  the code does not function. Does IE have a problem selecting elements with display:none?

jQuery(document).ready(function() {
//Align objects in grid
    moveProjects('', 0);

// filter project previews on click
jQuery('.category-filter').mouseup(function() {
    var filter_string = '';

    // toggle .active state of fitler links
    if ( jQuery(this).is('.active')) {
        jQuery(this).removeClass('active');
    }
    else {
        jQuery(this).addClass('active');
    }

    jQuery('.category-filter').each(function(index) {
        if(jQuery(this).is('.active')) {
            filter_string += '.' + jQuery(this).text().toLowerCase() + ',';
        }
    });

    // Remove trailing comma
    filter_string = filter_string.substring(0, filter_string.length-1);

    // Fade .project-preview-wrapper if inactive types
    jQuery('.project-preview-wrapper').not(filter_string).fadeOut('fast');

    setTimeout(moveProjects, 250, filter_string, 500);
});

// Set aboslute position of .project-preview-wrapper in grid
function moveProjects (filter_string, time) {
    var cur_item = 0;
    var num_cols = 4;
    var num_rows = 0;
    var preview_width = 150;
    var preview_height = 150;
    var margin = 9;

    jQuery('.project-preview-wrapper').each(function (index) {
        var left_val = margin * (cur_item % num_cols) + preview_width * (cur_item % num_cols);
        var top_val = num_rows * (preview_height + margin);
        if (jQuery(this).css('display') != 'none') {
            jQuery(this).animate({'left':left_val,'top':top_val}, time);
            if (cur_item % num_cols == 3) {
                num_rows ++;
            }
            cur_item++;
        }
        else if (jQuery(this).is(filter_string) || filter_string == '') {
            jQuery(this).animate({'left':left_val,'top':top_val}, 0).delay(time).fadeIn('fast');
            if (cur_item % num_cols == 3) {
                num_rows ++;
            }
            cur_item++;
        }
     });
    num_rows = Math.ceil(cur_item / num_cols);
    jQuery('.view-id-work').animate({'height':(num_rows) * (preview_height + margin)},time);
};
});


问:
getting 500 error nginx over https | Docker
Trying to learn and understand the docker and how it works. I am trying to deploy and run an application on the docker container. Everything seems to be working as expected.

Nginx server is up and running.

Redis server is also up and running.

DB service seems to be working as expected.

However I am trying to enable the HTTPS on the application and as per the instructions, I am suppose to provide few details on the server environment for SSL setup which includes

```<code>environment:
  - VIRTUAL_HOST=mydomain.com
  - LETSENCRYPT_HOST=mydomain.com
  - LETSENCRYPT_EMAIL=xxx
</code>```

When I am accessing the application dummy page (an HTML) it seems to be working as expected and I am able to open the page, however when trying to access the same page over https, I am getting 500 error. I tried to see the log file under /var folder but don't see any error in the file.

tailing the container for the logs showing me only this line:

```<code>nginx.1    | test.xxx.com xxx.x.xxx.xxx - - [10/Dec/2022:06:05:20 +0000] "GET /favicon.ico HTTP/2.0" 500 177 "https://test.xxx.com/dummy-html.html" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0"
</code>```

I don't see any other details. Here is my docker-compose.yaml file

```<code>version: '2'

x-logging:
  &default-logging
  logging:
    driver: json-file
    options:
      max-size: 100m

services:
  nginx:
    image: jdj/latest
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ./srv/nginx/vhost.d:/etc/nginx/vhost.d
      - ./srv/nginx/html:/usr/share/nginx/html
      - ./srv/ssl_certs:/etc/nginx/certs:ro
    ports:
      - "80:80"
      - "443:443"
    <<: *default-logging
    restart: always

  letsencrypt:
    image: jdj/jrcs-letsencrypt-nginx-proxy-companion:2.0
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./srv/ssl_certs:/etc/nginx/certs:rw
    volumes_from:
      - nginx
    <<: *default-logging
    restart: always

  server:
    image: jdj/jdj:1.13.0
    environment:
      - VIRTUAL_HOST=mydomain.com
      - LETSENCRYPT_HOST=mydomain.com
      - LETSENCRYPT_EMAIL=xxx
    volumes:
      - ./jdj.conf:/jdj.conf:ro
    privileged: true
    <<: *default-logging
    restart: always

  workers:
    image: jdj/jdj:1.13.0
    command: ["./scripts/workers"]
    volumes:
      - ./jdj.conf:/jdj.conf:ro
    privileged: true
    <<: *default-logging
    restart: always

    db:
    image: postgres:13.0
    env_file: jdj.conf
    volumes:
      - postgres-data:/var/lib/postgresql/data/
    <<: *default-logging
    restart: always

  redis:
    image: redis:6.0
    command: [
      "bash", "-c",
      'docker-entrypoint.sh --appendonly yes --requirepass "$$REDIS_PASSWORD"'
    ]
    env_file: jdj.conf
    volumes:
      - redis-data:/data
    <<: *default-logging
    restart: always

volumes:
  postgres-data:
  redis-data:
</code>```

I am not sure what is the issue or is there a way I can see the details on error?

Body:
Trying to learn and understand the docker and how it works. I am trying to deploy and run an application on the docker container. Everything seems to be working as expected.

Nginx server is up and running.

Redis server is also up and running.

DB service seems to be working as expected.

However I am trying to enable the HTTPS on the application and as per the instructions, I am suppose to provide few details on the server environment for SSL setup which includes

environment:
  - VIRTUAL_HOST=mydomain.com
  - LETSENCRYPT_HOST=mydomain.com
  - LETSENCRYPT_EMAIL=xxx

When I am accessing the application dummy page (an HTML) it seems to be working as expected and I am able to open the page, however when trying to access the same page over https, I am getting 500 error. I tried to see the log file under /var folder but don't see any error in the file.

tailing the container for the logs showing me only this line:

nginx.1    | test.xxx.com xxx.x.xxx.xxx - - [10/Dec/2022:06:05:20 +0000] "GET /favicon.ico HTTP/2.0" 500 177 "https://test.xxx.com/dummy-html.html" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0"

I don't see any other details. Here is my docker-compose.yaml file

version: '2'

x-logging:
  &default-logging
  logging:
    driver: json-file
    options:
      max-size: 100m

services:
  nginx:
    image: jdj/latest
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ./srv/nginx/vhost.d:/etc/nginx/vhost.d
      - ./srv/nginx/html:/usr/share/nginx/html
      - ./srv/ssl_certs:/etc/nginx/certs:ro
    ports:
      - "80:80"
      - "443:443"
    <<: *default-logging
    restart: always

  letsencrypt:
    image: jdj/jrcs-letsencrypt-nginx-proxy-companion:2.0
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./srv/ssl_certs:/etc/nginx/certs:rw
    volumes_from:
      - nginx
    <<: *default-logging
    restart: always

  server:
    image: jdj/jdj:1.13.0
    environment:
      - VIRTUAL_HOST=mydomain.com
      - LETSENCRYPT_HOST=mydomain.com
      - LETSENCRYPT_EMAIL=xxx
    volumes:
      - ./jdj.conf:/jdj.conf:ro
    privileged: true
    <<: *default-logging
    restart: always

  workers:
    image: jdj/jdj:1.13.0
    command: ["./scripts/workers"]
    volumes:
      - ./jdj.conf:/jdj.conf:ro
    privileged: true
    <<: *default-logging
    restart: always

    db:
    image: postgres:13.0
    env_file: jdj.conf
    volumes:
      - postgres-data:/var/lib/postgresql/data/
    <<: *default-logging
    restart: always

  redis:
    image: redis:6.0
    command: [
      "bash", "-c",
      'docker-entrypoint.sh --appendonly yes --requirepass "$$REDIS_PASSWORD"'
    ]
    env_file: jdj.conf
    volumes:
      - redis-data:/data
    <<: *default-logging
    restart: always

volumes:
  postgres-data:
  redis-data:

I am not sure what is the issue or is there a way I can see the details on error?


问:
Rename key of array of nested object which is state in react
I have following array of nested object coming from react state:

```<code>const categories = useSelector((state) => state.category.nestedCategory);
</code>```

Categories have following data:

```<code>[
    {
        "_id": "63887a03ca16e96af0512f99",
        "name": "all products",
        "slug": "all_products",
        "children": [
            {
                "_id": "63887a53ca16e96af0512f9b",
                "name": "Electronics",
                "slug": "electornics",
                "children": [
                    {
                        "_id": "63887b5b3a8d48488d1474e1",
                        "name": "Cell Phone",
                        "slug": "cell_phone",
                        "children": [
                            {
                                "_id": "63887b9c3a8d48488d1474e3",
                                "name": "Android",
                                "slug": "android",
                                "children": []
                            },
                            {
                                "_id": "63887bbb3a8d48488d1474e5",
                                "name": "IOS",
                                "slug": "ios",
                                "children": []
                            }
                        ]
                    }
                ]
            },
            {
                "_id": "63887bed3a8d48488d1474e7",
                "name": "Clothing",
                "slug": "clothing",
                "children": [
                    {
                        "_id": "6391bef981673ebab711ae95",
                        "name": "Mens",
                        "slug": "mens",
                        "children": []
                    },
                    {
                        "_id": "6391bf3781673ebab711ae97",
                        "name": "Womens",
                        "slug": "womens",
                        "children": []
                    }
                ]
            }
        ]
    }
]
</code>```

Here I have function to rename the key "name" to "label" and "_id" to "value".

```<code>const newKeys = {
    displayName: "label",
    displayId: "value",
  };

  const renameKeys = (obj, newKeys) => {
    const keyValues = Object.keys(obj).map((key) => {
      let newKey = null;

      if (key === "children") {
        obj[key] = obj[key].map((obj) => renameKeys(obj, newKeys));
      }
      if (key === "name") {
        newKey = newKeys.displayName;
      }
      if (key === "_id") {
        newKey = newKeys.displayId;
      } else {
        newKey = key;
      }

      return {
        [newKey]: obj[key],
      };
    });
    return Object.assign({}, ...keyValues);
  };
</code>```

I have iterate through array to rename key with the map function inside useEffect hooks:

```<code>useEffect(() => {
    getCategoryList(dispatch);
    console.log(categories.map((o) => renameKeys(o, newKeys)));
  }, [dispatch]);
</code>```

But, it is throwing following errors, is there any other way to assign the children object key with new name:

```<code>Uncaught TypeError: Cannot assign to read only property 'children' of object
</code>```

Body:
I have following array of nested object coming from react state:

const categories = useSelector((state) => state.category.nestedCategory);

Categories have following data:

[
    {
        "_id": "63887a03ca16e96af0512f99",
        "name": "all products",
        "slug": "all_products",
        "children": [
            {
                "_id": "63887a53ca16e96af0512f9b",
                "name": "Electronics",
                "slug": "electornics",
                "children": [
                    {
                        "_id": "63887b5b3a8d48488d1474e1",
                        "name": "Cell Phone",
                        "slug": "cell_phone",
                        "children": [
                            {
                                "_id": "63887b9c3a8d48488d1474e3",
                                "name": "Android",
                                "slug": "android",
                                "children": []
                            },
                            {
                                "_id": "63887bbb3a8d48488d1474e5",
                                "name": "IOS",
                                "slug": "ios",
                                "children": []
                            }
                        ]
                    }
                ]
            },
            {
                "_id": "63887bed3a8d48488d1474e7",
                "name": "Clothing",
                "slug": "clothing",
                "children": [
                    {
                        "_id": "6391bef981673ebab711ae95",
                        "name": "Mens",
                        "slug": "mens",
                        "children": []
                    },
                    {
                        "_id": "6391bf3781673ebab711ae97",
                        "name": "Womens",
                        "slug": "womens",
                        "children": []
                    }
                ]
            }
        ]
    }
]

Here I have function to rename the key "name" to "label" and "_id" to "value".

const newKeys = {
    displayName: "label",
    displayId: "value",
  };

  const renameKeys = (obj, newKeys) => {
    const keyValues = Object.keys(obj).map((key) => {
      let newKey = null;

      if (key === "children") {
        obj[key] = obj[key].map((obj) => renameKeys(obj, newKeys));
      }
      if (key === "name") {
        newKey = newKeys.displayName;
      }
      if (key === "_id") {
        newKey = newKeys.displayId;
      } else {
        newKey = key;
      }

      return {
        [newKey]: obj[key],
      };
    });
    return Object.assign({}, ...keyValues);
  };

I have iterate through array to rename key with the map function inside useEffect hooks:

useEffect(() => {
    getCategoryList(dispatch);
    console.log(categories.map((o) => renameKeys(o, newKeys)));
  }, [dispatch]);

But, it is throwing following errors, is there any other way to assign the children object key with new name:

Uncaught TypeError: Cannot assign to read only property 'children' of object


问:
How to get selenium to work on WSL2 for windows?
Im trying to get selenium to work on WSL2 with Ubuntu but it doesnot seem to work. Whats a bigger issue however is that I cannot pinpoint the exact cause of this because my google searches turn up nothing on the matter. The error I seem to be getting is:

Code:

```<code>from selenium import webdriver

driver = webdriver.Chrome()

driver.get("http://selenium.dev")

driver.quit()
</code>```

Error:

```<code>SessionNotCreatedException: Message: session not created exception: Missing or invalid capabilities
  (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Linux 5.10.102.1-microsoft-standard-WSL2 x86_64)
</code>```

So from my understanding - its detecting the driver but then not running it? Is there a way to fix this ?

Body:
Im trying to get selenium to work on WSL2 with Ubuntu but it doesnot seem to work. Whats a bigger issue however is that I cannot pinpoint the exact cause of this because my google searches turn up nothing on the matter. The error I seem to be getting is:

Code:

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("http://selenium.dev")

driver.quit()

Error:

SessionNotCreatedException: Message: session not created exception: Missing or invalid capabilities
  (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Linux 5.10.102.1-microsoft-standard-WSL2 x86_64)

So from my understanding - its detecting the driver but then not running it? Is there a way to fix this ?


问:
If I put the name of a K8s svc in the spec.host of Istio's DestinationRule, will all traffic going to that service go through the DestinationRule?
Istio has a custom resource called DestinationRule, and this resource has an argument called spec.host as shown below.

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: my-destination-rule
spec:
  host: my-svc
```

I want to make all traffic through this service go through DestinationRule.
If I enter the name of the service in the host, will all traffic go through the DestinationRule, not just the case of calling with the name of the service using Service Discovery? For example, does the DestinationRule apply even when prodding through external DNS?

Body:
Istio has a custom resource called DestinationRule, and this resource has an argument called spec.host as shown below.

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: my-destination-rule
spec:
  host: my-svc

I want to make all traffic through this service go through DestinationRule.
If I enter the name of the service in the host, will all traffic go through the DestinationRule, not just the case of calling with the name of the service using Service Discovery? For example, does the DestinationRule apply even when prodding through external DNS?


问:
Is there a general formula for max_file_size given inode attributes?
Examaple problem:
Given:
2KB block size
Inode consists of:
5 direct pointers
3 indirect pointers
2 doubly indirect pointers
1 triply indirect pointer
Assume a pointer is 8B.

What is the maximum size of a file that an inode can point to in this system? How many distinct blocks must be read to read the entirety of a 128MB file?

I've been seeing inconsistent answers online and am not sure who to trust on this.


问:
duplicate value should not repeat in lookupedit of gridcontrol
I have a lookup city column in grid control, if I select a particular city in 1st column then press enter key and select same city which I select in 1st row, but if select the that same city it have to shown "the city name is duplicate"

I need to known the code by using the CELLVALUECHANGED key


问:
Angular doing random redirects in production
So, when i enter my website: https://new.chatenium.hu , it redirect me to the login page no matter what i do

My friend told that the website is working just fine on his pc.

Is it working on your pc?

If yes, then why its not working on mine?

If no, then why is it working on my friends's pc?

Heres to routing file:

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AnswerComponent } from './chat/call/answer/answer.component';
import { CallComponent } from './chat/call/call.component';
import { ChatComponent } from './chat/chat.component';
import { AddComponent } from './chat/friends/add/add.component';
import { FriendsComponent } from './chat/friends/friends.component';
import { MyfriendsComponent } from './chat/friends/myfriends/myfriends.component';
import { RequestComponent } from './chat/friends/request/request.component';
import { DmComponent } from './chat/message/dm/dm.component';
import { MessageComponent } from './chat/message/message.component';
import { LoginComponent } from './login/login.component';
import { MainpageComponent } from './mainpage/mainpage.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { RegisterComponent } from './register/register.component';

const routes: Routes = [
  { path: 'register', pathMatch: 'full', component: RegisterComponent },
  { path: 'login', pathMatch: 'full', component: LoginComponent },
  {
    path: 'chat',
    component: ChatComponent,
    children: [
      {
        path: 'friends',
        component: FriendsComponent,
        children: [
          { path: '', component: MyfriendsComponent },
          { path: 'add', component: AddComponent },
          { path: 'request', component: RequestComponent },
        ],
      },
      { path: 'message', component: MessageComponent },
      { path: 'message/dm/:otherUid', component: MessageComponent },
    ],
  },
  { path: '', component: MainpageComponent },
  { path: 'chat/call/:callid/:frid', component: CallComponent },
  { path: 'chat/call/answer/:callid/:author', component: AnswerComponent },
  { path: '**', component: NotfoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

</code>```

Can you help me?

Thanks!

Body:
So, when i enter my website: https://new.chatenium.hu , it redirect me to the login page no matter what i do

My friend told that the website is working just fine on his pc.

Is it working on your pc?

If yes, then why its not working on mine?

If no, then why is it working on my friends's pc?

Heres to routing file:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AnswerComponent } from './chat/call/answer/answer.component';
import { CallComponent } from './chat/call/call.component';
import { ChatComponent } from './chat/chat.component';
import { AddComponent } from './chat/friends/add/add.component';
import { FriendsComponent } from './chat/friends/friends.component';
import { MyfriendsComponent } from './chat/friends/myfriends/myfriends.component';
import { RequestComponent } from './chat/friends/request/request.component';
import { DmComponent } from './chat/message/dm/dm.component';
import { MessageComponent } from './chat/message/message.component';
import { LoginComponent } from './login/login.component';
import { MainpageComponent } from './mainpage/mainpage.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { RegisterComponent } from './register/register.component';

const routes: Routes = [
  { path: 'register', pathMatch: 'full', component: RegisterComponent },
  { path: 'login', pathMatch: 'full', component: LoginComponent },
  {
    path: 'chat',
    component: ChatComponent,
    children: [
      {
        path: 'friends',
        component: FriendsComponent,
        children: [
          { path: '', component: MyfriendsComponent },
          { path: 'add', component: AddComponent },
          { path: 'request', component: RequestComponent },
        ],
      },
      { path: 'message', component: MessageComponent },
      { path: 'message/dm/:otherUid', component: MessageComponent },
    ],
  },
  { path: '', component: MainpageComponent },
  { path: 'chat/call/:callid/:frid', component: CallComponent },
  { path: 'chat/call/answer/:callid/:author', component: AnswerComponent },
  { path: '**', component: NotfoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Can you help me?

Thanks!


问:
xQueueReceive does not receive messages after receiving the first message (ESP8266-FreeRTOS-SDK)
In the code, the function led_send_message is being called by a different c file after the initializations have been completed. The first message is received by the xQueueReceive function but any further messages show no response.

```<code>    BaseType_t led_send_message(led_messages_e led_msgID)
    {

            led_queue_message_t led_msg;
            led_msg.led_message = led_msgID;

            return xQueueSend(led_queue_handle, &led_msg, portMAX_DELAY);

    }

void led_task(void){

    led_queue_message_t msg;
    uint32_t blink_duration = 1000;

    while(1){

        if (xQueueReceive(led_queue_handle, &msg, portMAX_DELAY))
            {
                switch(msg.led_message)
                {
                case LED_BLINK_SLOW_START:

                    ESP_LOGI(TAG, "LED_BLINK_SLOW_START");
                    led_blink_function(1000);
                    xQueueReset(led_queue_handle);
                    break;

                case LED_BLINK_SLOW_STOP:
                    ESP_LOGI(TAG, "LED_BLINK_SLOW_STOP");
                    suspend_led_task();

                    break;

                case LED_BLINK_FAST_START:

                    ESP_LOGI(TAG, "LED_BLINK_FAST_START");
                    led_blink_function(1000);

                    break;

                case LED_BLINK_FAST_STOP:
                    ESP_LOGI(TAG, "LED_BLINK_FAST_STOP");
                    led_blink_function(2000);
                    suspend_led_task();

                    break;

                case LED_BLINK_STOP:
                    ESP_LOGI(TAG, "LED_BLINK_STOP");
                    suspend_led_task();

                    break;

                default:
                    break;
                }
            }
    }
}
</code>```

Initialization done in the main set up here :

```<code>led_queue_handle = xQueueCreate(5,sizeof(led_queue_message_t));

xTaskCreate(&led_task, "led_task", 4096, NULL, 5, &led_task_handle);
</code>```

When I use the led_send_message in another file wifi_app.c, it receives the first message I send but the second message I send does not show up, even though the second xQueueSend returns pdTRUE.

```<code>static void wifi_app_event_handler(void* event_handler_arg, esp_event_base_t event_base,
        int32_t event_id, void* event_data)
{
    if(event_base == WIFI_EVENT)
    {
        switch(event_id)
        {
        case WIFI_EVENT_STA_START:
            ESP_LOGI(TAG, "59 WIFI_EVENT_STA_START");
            BaseType_t message_sent = led_send_message(LED_BLINK_FAST_START);
            if (message_sent == pdTRUE){
                printf("MESSAGE SENT SUCCESSFULLY");
            }

        case WIFI_EVENT_STA_CONNECTED:
            ESP_LOGI(TAG, "WIFI_EVENT_STA_CONNECTED");

            break;

        case WIFI_EVENT_STA_DISCONNECTED:
            ESP_LOGI(TAG, "WIFI_EVENT_STA_DISCONNECTED");
            BaseType_t message_sent2 = led_send_message(LED_BLINK_FAST_START);
            if (message_sent2 == pdTRUE){
                printf("MESSAGE SENT SUCCESSFULLY");
            }
            break;

        case WIFI_EVENT_STA_STOP:
            ESP_LOGI(TAG, "WIFI_EVENT_STA_STOP");
            break;

        default:
            break;
        }
    }
    else if(event_base == IP_EVENT)
    {
        switch(event_id)
        {

        case IP_EVENT_STA_GOT_IP:
            ESP_LOGI(TAG, "IP_EVENT_STA_GOT_IP");
            wifi_app_send_message(IP_APP_STA_GOT_IP);
            break;
        }
    }
}
</code>```

Body:
In the code, the function led_send_message is being called by a different c file after the initializations have been completed. The first message is received by the xQueueReceive function but any further messages show no response.

    BaseType_t led_send_message(led_messages_e led_msgID)
    {

            led_queue_message_t led_msg;
            led_msg.led_message = led_msgID;

            return xQueueSend(led_queue_handle, &led_msg, portMAX_DELAY);

    }

void led_task(void){

    led_queue_message_t msg;
    uint32_t blink_duration = 1000;

    while(1){

        if (xQueueReceive(led_queue_handle, &msg, portMAX_DELAY))
            {
                switch(msg.led_message)
                {
                case LED_BLINK_SLOW_START:

                    ESP_LOGI(TAG, "LED_BLINK_SLOW_START");
                    led_blink_function(1000);
                    xQueueReset(led_queue_handle);
                    break;

                case LED_BLINK_SLOW_STOP:
                    ESP_LOGI(TAG, "LED_BLINK_SLOW_STOP");
                    suspend_led_task();

                    break;

                case LED_BLINK_FAST_START:

                    ESP_LOGI(TAG, "LED_BLINK_FAST_START");
                    led_blink_function(1000);

                    break;

                case LED_BLINK_FAST_STOP:
                    ESP_LOGI(TAG, "LED_BLINK_FAST_STOP");
                    led_blink_function(2000);
                    suspend_led_task();

                    break;

                case LED_BLINK_STOP:
                    ESP_LOGI(TAG, "LED_BLINK_STOP");
                    suspend_led_task();

                    break;

                default:
                    break;
                }
            }
    }
}

Initialization done in the main set up here :

led_queue_handle = xQueueCreate(5,sizeof(led_queue_message_t));

xTaskCreate(&led_task, "led_task", 4096, NULL, 5, &led_task_handle);

When I use the led_send_message in another file wifi_app.c, it receives the first message I send but the second message I send does not show up, even though the second xQueueSend returns pdTRUE.

static void wifi_app_event_handler(void* event_handler_arg, esp_event_base_t event_base,
        int32_t event_id, void* event_data)
{
    if(event_base == WIFI_EVENT)
    {
        switch(event_id)
        {
        case WIFI_EVENT_STA_START:
            ESP_LOGI(TAG, "59 WIFI_EVENT_STA_START");
            BaseType_t message_sent = led_send_message(LED_BLINK_FAST_START);
            if (message_sent == pdTRUE){
                printf("MESSAGE SENT SUCCESSFULLY");
            }

        case WIFI_EVENT_STA_CONNECTED:
            ESP_LOGI(TAG, "WIFI_EVENT_STA_CONNECTED");

            break;

        case WIFI_EVENT_STA_DISCONNECTED:
            ESP_LOGI(TAG, "WIFI_EVENT_STA_DISCONNECTED");
            BaseType_t message_sent2 = led_send_message(LED_BLINK_FAST_START);
            if (message_sent2 == pdTRUE){
                printf("MESSAGE SENT SUCCESSFULLY");
            }
            break;

        case WIFI_EVENT_STA_STOP:
            ESP_LOGI(TAG, "WIFI_EVENT_STA_STOP");
            break;

        default:
            break;
        }
    }
    else if(event_base == IP_EVENT)
    {
        switch(event_id)
        {

        case IP_EVENT_STA_GOT_IP:
            ESP_LOGI(TAG, "IP_EVENT_STA_GOT_IP");
            wifi_app_send_message(IP_APP_STA_GOT_IP);
            break;
        }
    }
}


问:
No module named discord.ui
Im running a script for a bot with the website Replit and when I see people add select or buttons to their script it works. For some reason mine doesnt work, when I run it gives me the error ModuleNotFoundError: No module named 'discord.ui'. I dont know if its because of my version or maybe the website. This is the code:

```<code>import discord, os, requests, json, random, time
from discord.ext import commands
from replit import db
import urllib
from discord.ui import Select
</code>```

When I see youtube tutorials on this it works perfectly and when I read the comments there was no trouble, so I dont know why mine doesnt work. Please help.

Title: No module named discord.ui

Body:
Im running a script for a bot with the website Replit and when I see people add select or buttons to their script it works. For some reason mine doesnt work, when I run it gives me the error ModuleNotFoundError: No module named 'discord.ui'. I dont know if its because of my version or maybe the website. This is the code:

import discord, os, requests, json, random, time
from discord.ext import commands
from replit import db
import urllib
from discord.ui import Select

When I see youtube tutorials on this it works perfectly and when I read the comments there was no trouble, so I dont know why mine doesnt work. Please help.


问:
import scala.util.Success (or Failure) lead to an "error: value util is not a member of String"
my environment shows that I'm using 2.12.10 Scala and 3.1.1 Spark versions:

```<code>scala: String = 2.12.10
spark: String = 3.1.1
</code>```

However, my following code refuse to import scala.util.Failure and import scala.util.Success

while both exists for a long time: I can see them mentioned, here: https://www.scala-lang.org/api/2.12.2/scala/util/Success.html

import java.util.Map;
import fr.ecoemploi.application.etude.swagger.invoker._
import fr.ecoemploi.application.etude.swagger.model.Commune;
import fr.ecoemploi.application.etude.swagger.api.CogControllerApi;
import fr.ecoemploi.application.etude.swagger.invoker.CollectionFormats._
import fr.ecoemploi.application.etude.swagger.invoker.ApiKeyLocations._

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer

implicit val system = ActorSystem("system")
implicit val executionContext = system.dispatcher
implicit val materializer: ActorMaterializer = ActorMaterializer()

import scala.util.Failure
import scala.util.Success

//import scala.concurrent.ExecutionContext.Implicits.global
//import scala.concurrent.Future

val apiInvoker = ApiInvoker()
val cogService = CogControllerApi("http://localhost:9090")
val request = cogService.obtenirCommunes(2022);

val response = apiInvoker.execute(request)

response.onComplete {
    case Success(ApiResponse(code, content, headers)) =>
        System.out.println(s"Status code: $code}")
        System.out.println(s"Response headers: ${headers.mkString(", ")}")
        System.out.println(s"Response body: $content")

    case Failure(error @ ApiError(code, message, responseContent, cause, headers)) =>
        System.err.println("Exception when calling CogControllerApi#obtenirCommunes")
        System.err.println(s"Status code: $code}")
        System.err.println(s"Reason: $responseContent")
        //System.err.println(s"Response headers: ${headers.mkString(", ")}")
        error.printStackTrace();

    case Failure(exception) =>
        System.err.println("Exception when calling CogControllerApi#obtenirCommunes")
        exception.printStackTrace();
}
```
```<console>:40: error: value util is not a member of String
       import scala.util.Failure
                    ^
<console>:41: error: value util is not a member of String
       import scala.util.Success
                    ^
<console>:55: error: not found: value Success
           case Success(ApiResponse(code, content, headers)) =>
                ^
<console>:60: error: not found: value Failure
           case Failure(error @ ApiError(code, message, responseContent, cause, headers)) =>
                ^
<console>:67: error: not found: value Failure
           case Failure(exception) =>
```

Body:
my environment shows that I'm using 2.12.10 Scala and 3.1.1 Spark versions:

scala: String = 2.12.10
spark: String = 3.1.1

However, my following code refuse to import scala.util.Failure and import scala.util.Success

while both exists for a long time: I can see them mentioned, here: https://www.scala-lang.org/api/2.12.2/scala/util/Success.html

import java.util.Map;
import fr.ecoemploi.application.etude.swagger.invoker._
import fr.ecoemploi.application.etude.swagger.model.Commune;
import fr.ecoemploi.application.etude.swagger.api.CogControllerApi;
import fr.ecoemploi.application.etude.swagger.invoker.CollectionFormats._
import fr.ecoemploi.application.etude.swagger.invoker.ApiKeyLocations._

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer

implicit val system = ActorSystem("system")
implicit val executionContext = system.dispatcher
implicit val materializer: ActorMaterializer = ActorMaterializer()

import scala.util.Failure
import scala.util.Success

//import scala.concurrent.ExecutionContext.Implicits.global
//import scala.concurrent.Future

val apiInvoker = ApiInvoker()
val cogService = CogControllerApi("http://localhost:9090")
val request = cogService.obtenirCommunes(2022);

val response = apiInvoker.execute(request)

response.onComplete {
    case Success(ApiResponse(code, content, headers)) =>
        System.out.println(s"Status code: $code}")
        System.out.println(s"Response headers: ${headers.mkString(", ")}")
        System.out.println(s"Response body: $content")

    case Failure(error @ ApiError(code, message, responseContent, cause, headers)) =>
        System.err.println("Exception when calling CogControllerApi#obtenirCommunes")
        System.err.println(s"Status code: $code}")
        System.err.println(s"Reason: $responseContent")
        //System.err.println(s"Response headers: ${headers.mkString(", ")}")
        error.printStackTrace();

    case Failure(exception) =>
        System.err.println("Exception when calling CogControllerApi#obtenirCommunes")
        exception.printStackTrace();
}

<console>:40: error: value util is not a member of String
       import scala.util.Failure
                    ^
<console>:41: error: value util is not a member of String
       import scala.util.Success
                    ^
<console>:55: error: not found: value Success
           case Success(ApiResponse(code, content, headers)) =>
                ^
<console>:60: error: not found: value Failure
           case Failure(error @ ApiError(code, message, responseContent, cause, headers)) =>
                ^
<console>:67: error: not found: value Failure
           case Failure(exception) =>


问:
Populate google bar chart on a blade view dynamically using laravel controller
I'm following a Laravel with Shopify REST API tutorial.

There I'm trying to add a simple google bar chart to indicate dates of the month V number of sales

So my

X axis -> Dates of the month

Y axis -> Number of sales of the day

E.g.:

```<code>2022-12-01 -> 3
2022-12-02 -> 7
2022-12-03 -> 1
.....
2022-12-31 -> 9
</code>```

From my controller, I get the dates of the month as follows,

```<code>$list=array();
$month = 12;
$year = 2022;

for($d=1; $d<=31; $d++)
{
    $time=mktime(12, 0, 0, $month, $d, $year);
    if (date('m', $time)==$month)
        $list[]=date('Y-m-d', $time);
}

$new_list = implode(",",$list);
</code>```

and I get the sales using Shopify REST.

```<code>$tot_o = $result_1['count'];
</code>```

Then I passed them to my blade view.

And in my blade, I tried inserting the Google chart as follows,

```<code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load("current", {packages:['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ["Date", "Sales", { role: "style" } ],
            [{{ $dates }}, {{ $sales }}, "#b87333"]
        ]);

        var view = new google.visualization.DataView(data);
        view.setColumns([
            0,
            1,
            {calc: "stringify", sourceColumn: 1, type: "string", role: "annotation"},
            2
        ]);

        var options = {
            title: "Density of Precious Metals, in g/cm^3",
            width: 600,
            height: 200,
            bar: {groupWidth: "95%"},
            legend: { position: "none" },
        };
        var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
        chart.draw(view, options);
    }
</script>
</code>```

But this outputs me an empty chart...

Now my question is,

How can I pass those controller values to the chart on my blade and populate the chart correctly?

Body:
I'm following a Laravel with Shopify REST API tutorial.

There I'm trying to add a simple google bar chart to indicate dates of the month V number of sales

So my

X axis -> Dates of the month

Y axis -> Number of sales of the day

E.g.:

2022-12-01 -> 3
2022-12-02 -> 7
2022-12-03 -> 1
.....
2022-12-31 -> 9

From my controller, I get the dates of the month as follows,

$list=array();
$month = 12;
$year = 2022;

for($d=1; $d<=31; $d++)
{
    $time=mktime(12, 0, 0, $month, $d, $year);
    if (date('m', $time)==$month)
        $list[]=date('Y-m-d', $time);
}

$new_list = implode(",",$list);

and I get the sales using Shopify REST.

$tot_o = $result_1['count'];

Then I passed them to my blade view.

And in my blade, I tried inserting the Google chart as follows,

But this outputs me an empty chart...

Now my question is,

How can I pass those controller values to the chart on my blade and populate the chart correctly?