问:
TypeError: foo.setModel is not a function (problem with postgres and sequelize)
I'm working on the post function of a Cart_Items model using Postgres with sequelize and I'm getting an error that I can't figure out. I guess it pertains to the relationship with other models, but I can't see where the error is.

The relation of models is:

```<code>Cart.hasMany(Cart_items)
Cart_items.belongsTo(Cart)

Cart_items.hasMany(Product)
Product.belongsToMany(Cart_items, { through: "Cart-items-Products", paranoid: true });
</code>```

And the post function that should post:

```<code>{ "quantity":2, "cartId":1, "productId":2 }
</code>```

Is this one:

```<code>const { Cart_items, Cart, Product } = require('../../db')
const postCartItems = async ({ quantity, cartId, productId }) => {
    try {
        if (!quantity || !cartId || !productId) throw (" you must fill all fields ");

        const foundProduct = await Product.findByPk(productId);
        const foundCart = await Cart.findByPk(cartId)
        const cart_items = await Cart_items.create({ quantity, });
        await cart_items.setProduct(foundProduct)
        await cart_items.setCart(foundCart)
        return cart_items
    } catch (error) {
        throw (error)
    }
}

module.exports = { postCartItems }
</code>```

This is giving me an error with the setProduct:

TypeError: cart_items.setProduct is not a function

As I said before, I think that the problem might be related with the intermediary table between products and cart_items, but I don't know how to handle it.

Body:
I'm working on the post function of a Cart_Items model using Postgres with sequelize and I'm getting an error that I can't figure out. I guess it pertains to the relationship with other models, but I can't see where the error is.

The relation of models is:

Cart.hasMany(Cart_items)
Cart_items.belongsTo(Cart)

Cart_items.hasMany(Product)
Product.belongsToMany(Cart_items, { through: "Cart-items-Products", paranoid: true });

And the post function that should post:

{ "quantity":2, "cartId":1, "productId":2 }

Is this one:

const { Cart_items, Cart, Product } = require('../../db')
const postCartItems = async ({ quantity, cartId, productId }) => {
    try {
        if (!quantity || !cartId || !productId) throw (" you must fill all fields ");

        const foundProduct = await Product.findByPk(productId);
        const foundCart = await Cart.findByPk(cartId)
        const cart_items = await Cart_items.create({ quantity, });
        await cart_items.setProduct(foundProduct)
        await cart_items.setCart(foundCart)
        return cart_items
    } catch (error) {
        throw (error)
    }
}

module.exports = { postCartItems }

This is giving me an error with the setProduct:

TypeError: cart_items.setProduct is not a function

As I said before, I think that the problem might be related with the intermediary table between products and cart_items, but I don't know how to handle it.


来源: stackexchange

问:
How to check if a specific Google account is connected
I apologize in advance for language errors, I use Google Translate.

I use this code to open a draft in Gmail for a user to send an email to a client, the email has to be sent from a specific address, so I put the sender's address inside the URL so that the draft is opened in the sender's account.

This is the code:

```<code>Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias _
  "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
  ByVal lpFile As String, ByVal lpParameters As String, _
  ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
</code>```
```<code>Public Sub SendEmailWithURL(SenderAddress As String, ClientAddress As String)

    URL = "https://mail.google.com/mail/u/" & SenderAddress & "/?extsrc=mailto&url=mailto%3A?bcc=" & ClientAddress
    ShellExecute(0&, "Open", URL, vbNullString, vbNullString, vbNormalFocus)

End Sub
</code>```

The code works fine, but there is one problem:

If the account from which the message should be sent is not previously connected on this computer, the draft automatically becomes a draft on the default account (the first account opened on the computer).

I would like to check if the account that needs to send the message is already connected on this computer, so that I can at least show a notification to the user to know that the message will not be sent from his account.

ContentLicense: CC BY-SA 4.0

Body:
I apologize in advance for language errors, I use Google Translate.

I use this code to open a draft in Gmail for a user to send an email to a client, the email has to be sent from a specific address, so I put the sender's address inside the URL so that the draft is opened in the sender's account.

This is the code:

Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias _
  "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
  ByVal lpFile As String, ByVal lpParameters As String, _
  ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Public Sub SendEmailWithURL(SenderAddress As String, ClientAddress As String)

    URL = "https://mail.google.com/mail/u/" & SenderAddress & "/?extsrc=mailto&url=mailto%3A?bcc=" & ClientAddress
    ShellExecute(0&, "Open", URL, vbNullString, vbNullString, vbNormalFocus)

End Sub

The code works fine, but there is one problem:

If the account from which the message should be sent is not previously connected on this computer, the draft automatically becomes a draft on the default account (the first account opened on the computer).

I would like to check if the account that needs to send the message is already connected on this computer, so that I can at least show a notification to the user to know that the message will not be sent from his account.


问:
Initializing state with localstorage Next.js
I have an application that has a cart in Next.js, the cart is a piece of state that is also is assigned to a useContext to make it accessible to all props. In Next, it lives in the "App" component. I initialize the state with an empty array for now.

```<code>_app.js:

const [cartItems, setCartItems] = useState([])
</code>```

The issue comes by implementing localStorage, which is client side so Next can't recognize it. Makes sense to me. The issue comes when I want to initialize state with the localStorage of cart. I have it all implemented properly to where the cart syncs with localStorage (using useEffect)

```<code>useEffect(()=>{
   localStorage.setItem('cart', JSON.stringify(cartItems))
},[cartItems])
</code>```

I then tried to use a useEffect hook to set the state to the localStorage object, but here is the issue.

localStorage "cart" key is set to the value of cart -> when I reload the page, it then sees the cart is empty (because the state is initialized before the useEffect is run) which then sets localStorage to be an empty cart, which then sets the state to an empty array

How can I initialize state with localStorage in Next? Can I put the cart state in another "component" that then gets client side rendered? Because it's used in a context I don't know if I can move it outside of the _app.js component? Thanks so much for the help!

I have tried setting state using a useEffect hook, setting state to the value of localStorage. In a sense, I expected it to work as expected, but by the time I was accessing localStorage this way it had already been wiped clean.

Body:
I have an application that has a cart in Next.js, the cart is a piece of state that is also is assigned to a useContext to make it accessible to all props. In Next, it lives in the "App" component. I initialize the state with an empty array for now.

_app.js:

const [cartItems, setCartItems] = useState([])

The issue comes by implementing localStorage, which is client side so Next can't recognize it. Makes sense to me. The issue comes when I want to initialize state with the localStorage of cart. I have it all implemented properly to where the cart syncs with localStorage (using useEffect)

useEffect(()=>{
   localStorage.setItem('cart', JSON.stringify(cartItems))
},[cartItems])

I then tried to use a useEffect hook to set the state to the localStorage object, but here is the issue.

localStorage "cart" key is set to the value of cart -> when I reload the page, it then sees the cart is empty (because the state is initialized before the useEffect is run) which then sets localStorage to be an empty cart, which then sets the state to an empty array

How can I initialize state with localStorage in Next? Can I put the cart state in another "component" that then gets client side rendered? Because it's used in a context I don't know if I can move it outside of the _app.js component? Thanks so much for the help!

I have tried setting state using a useEffect hook, setting state to the value of localStorage. In a sense, I expected it to work as expected, but by the time I was accessing localStorage this way it had already been wiped clean.


问:
What is ipykernel and why does JupyterNotebook need it?
I've been thinking of a kernel as sort of a virtual environment for my jupyter notebook, but what is it actually?</p>


问:
can you explain the error, 'Refused to execute script'? What about my workaround?
I have the following error when I go to the path localhost:3000/home/:

GET http://localhost:3000/home/main.js net::ERR_ABORTED 404 (Not Found)

Refused to execute script from 'http://localhost:3000/home/main.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

If I delete the trailing /, it will work and the app will load without errors—without the Home component, but the app will still work.

Here is my route in React:

```<code><Routes>
    <Route path="/home/:id" element={<Home />} />
</Routes>
</code>```

Part of my webpack config:

```<code>module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, 'src/index.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    assetModuleFilename: 'assets/[name][ext]',
  },
  devtool: 'source-map',
  devServer: {
    static: {
      directory: path.resolve(__dirname, 'dist'),
    },
    port: 3000,
    open: true,
    hot: true,
    compress: true,
    historyApiFallback: true,
  },
</code>```

I was able to fix the error by adding <base href="/" /> in head of the index.html file.

Can someone explain what that is, and whether it normal to fix the error like that?

Body:
I have the following error when I go to the path localhost:3000/home/:

GET http://localhost:3000/home/main.js net::ERR_ABORTED 404 (Not Found)

Refused to execute script from 'http://localhost:3000/home/main.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

If I delete the trailing /, it will work and the app will load without errors—without the Home component, but the app will still work.

Here is my route in React:

<Routes>
    <Route path="/home/:id" element={<Home />} />
</Routes>

Part of my webpack config:

module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, 'src/index.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    assetModuleFilename: 'assets/[name][ext]',
  },
  devtool: 'source-map',
  devServer: {
    static: {
      directory: path.resolve(__dirname, 'dist'),
    },
    port: 3000,
    open: true,
    hot: true,
    compress: true,
    historyApiFallback: true,
  },

I was able to fix the error by adding <base href="/" /> in head of the index.html file.

Can someone explain what that is, and whether it normal to fix the error like that?


问:
Creating dataset with labels using networkx and dgl
I’m quite new to dgl, therefore I have a question.

Imagine, having a graphs with weights implemented in networkx and also the corresponding labels for them (let’s say stored in a list).

```<code>import networkx as nx
import dgl
import torch

labels = [0,1]

G1=nx.Graph()
G1.add_edge(0,1,weight=0.1)
G1.add_edge(0,2,weight=0.2)
G1.add_edge(2,3,weight=0.3)

G2=nx.Graph()
G2.add_edge(0,2,weight=0.4)
G2.add_edge(0,1,weight=0.5)
G2.add_edge(0,3,weight=0.6)

dgl_G1 = dgl.DGLGraph()
dgl_G1.from_networkx(G1, edge_attrs=['weight'])

dgl_G2 = dgl.DGLGraph()
dgl_G2.from_networkx(G2, edge_attrs=['weight'])
</code>```

Is it somehow possible to assign labels to the dgl.DGLGraph() graph when it is already created (as in the example above)? Many thanks!

Body:
I’m quite new to dgl, therefore I have a question.

Imagine, having a graphs with weights implemented in networkx and also the corresponding labels for them (let’s say stored in a list).

import networkx as nx
import dgl
import torch

labels = [0,1]

G1=nx.Graph()
G1.add_edge(0,1,weight=0.1)
G1.add_edge(0,2,weight=0.2)
G1.add_edge(2,3,weight=0.3)

G2=nx.Graph()
G2.add_edge(0,2,weight=0.4)
G2.add_edge(0,1,weight=0.5)
G2.add_edge(0,3,weight=0.6)

dgl_G1 = dgl.DGLGraph()
dgl_G1.from_networkx(G1, edge_attrs=['weight'])

dgl_G2 = dgl.DGLGraph()
dgl_G2.from_networkx(G2, edge_attrs=['weight'])

Is it somehow possible to assign labels to the dgl.DGLGraph() graph when it is already created (as in the example above)? Many thanks!


问:
How to take max value of one column, after looking at distinct values in another column?
```<code>SELECT short_name, overall, club_name, nationality_name FROM FIFA.dbo.players_22

K. MbappÃ©  91  Paris Saint-Germain France
M. Neuer    90  FC Bayern MÃ¼nchen  Germany
M. ter Stegen   90  FC Barcelona    Germany
H. Kane 90  Tottenham Hotspur   England
N. KantÃ©   90  Chelsea France
K. Benzema  89  Real Madrid CF  France
</code>```

The goal is to only return the highest overall players from each country. So I need to make the nationality_name column distinct, then take the MAX(overall). The output should look like this.

```<code>K. MbappÃ©  91  Paris Saint-Germain France
M. Neuer    90  FC Bayern MÃ¼nchen  Germany
H. Kane     90  Tottenham Hotspur   England
</code>```

Also is there a way to easily change the foreign letters in the short_name column? It appears that my output is not recognizing accents on letters.

Body:
SELECT short_name, overall, club_name, nationality_name FROM FIFA.dbo.players_22

K. MbappÃ©  91  Paris Saint-Germain France
M. Neuer    90  FC Bayern MÃ¼nchen  Germany
M. ter Stegen   90  FC Barcelona    Germany
H. Kane 90  Tottenham Hotspur   England
N. KantÃ©   90  Chelsea France
K. Benzema  89  Real Madrid CF  France

The goal is to only return the highest overall players from each country. So I need to make the nationality_name column distinct, then take the MAX(overall). The output should look like this.

K. MbappÃ©  91  Paris Saint-Germain France
M. Neuer    90  FC Bayern MÃ¼nchen  Germany
H. Kane     90  Tottenham Hotspur   England

Also is there a way to easily change the foreign letters in the short_name column? It appears that my output is not recognizing accents on letters.


问:
Cannot assign roles to member even if all permissions are met
I'm trying to assign someone a role however it fails due to "Missing Access"

```<code>method: 'put',
path: '/guilds/GUILDIDHERE/members/MEMBERIDHERE/roles/ROLE IM TRYING TO ASSIGN',
code: 50001,
httpStatus: 403,
</code>```

This is the code I used

```<code>const role = await guild.roles.fetch("ROLEID HERE");

mention.roles.add(role);
</code>```

My bot has administrator permissions

My bots role is above the role I'm trying to assign

The member who I'm trying to assign the role to has no other roles!

Body:
I'm trying to assign someone a role however it fails due to "Missing Access"

method: 'put',
path: '/guilds/GUILDIDHERE/members/MEMBERIDHERE/roles/ROLE IM TRYING TO ASSIGN',
code: 50001,
httpStatus: 403,

This is the code I used

const role = await guild.roles.fetch("ROLEID HERE");

mention.roles.add(role);

My bot has administrator permissions

My bots role is above the role I'm trying to assign

The member who I'm trying to assign the role to has no other roles!


问:
Bootstrap collapsable table row with clickable link
I have a Bootstrap 5.2 table where when a row is clicked it will expand more information below the row. One of the columns of the row contains a link that should be clickable. Clicking anywhere else on the row should expand the detailed information. The link does not work. Clicking the link expands/collapses the detailed information.

```<code><table class="table">
    <thead class="table-light">
        <tr>
            <th scope="col">Order ID</th>
            <th scope="col">Status</th>
            <th scope="col">Address</th>
        </tr>
    </thead>
    <tbody>
        <tr data-bs-toggle="collapse" data-bs-target="#expanded-1">
            <td><a href="someurl" class="link-dark">some link</a></td>
            <td>status 1</td>
            <td>address 1</td>
        </tr>
        <tr class="collapse accordion-collapse" id="expanded-1">
            <td colspan="3">
                <table class="table">More detailed information</table>
            </td>
        </tr>
    </tbody>
</table>
</code>```

I have tried adding `onclick='event.stopPropagation();' to the link but that seemed to have no effect.

Body:
I have a Bootstrap 5.2 table where when a row is clicked it will expand more information below the row. One of the columns of the row contains a link that should be clickable. Clicking anywhere else on the row should expand the detailed information. The link does not work. Clicking the link expands/collapses the detailed information.

            Order ID
            Status
            Address

            some link
            status 1
            address 1

More detailed information

I have tried adding `onclick='event.stopPropagation();' to the link but that seemed to have no effect.


问:
How to update Django custom dashboard
I am building a custom dashboard that will only be accessible to the support team of a company. These support teams will receive complaints from a contact form but we want to be able to indicate each complaint that has been resolved from the dashboard as resolved after being attended to.

Therefore, I created a field of choices (pending and resolved) which I named status. This field is not exposed to the user in the contact form and on the backend, it's 'pending' by default.

See the contact model as shown below

```<code>class Contact(models.Model):
    STATUS_CHOICE = (
        ("1", "Pending"),
        ("2", "Resolved"),
    )
    name = models.CharField(max_length=100)
    phone = models.CharField(max_length=15)
    email = models.EmailField(max_length=254)
    subject = models.CharField(max_length=100)
    status = models.CharField(choices=STATUS_CHOICE, default="1", max_length=50, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    body = models.TextField()

    class Meta:
        ordering = ["-created"]
        verbose_name_plural = "Contacts"

    def __str__(self):
        return f"Message from: {self.name}"
</code>```

see my forms.py:

```<code>class ContactForm(forms.Form):
    name = forms.CharField(max_length=100, required=True)
    phone = forms.CharField(max_length=15, required=True)
    email = forms.EmailField(max_length=100, required=True)
    subject = forms.CharField(max_length=100, required=True)
    body = forms.CharField(required=True, label='Message', widget=forms.Textarea())

    class Meta:
        model = Contact
        fields = ['name', 'phone', 'email', 'subject', 'body']

    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)
</code>```

The intent of the view below is to ensure that all users that contact the company using the contact form receive an email and that the information is also saved in the database. This worked fine.

```<code>def contact(request):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            phone = form.cleaned_data['phone']
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            body = form.cleaned_data['body']

            contact = Contact.objects.create(
                name=name, phone=phone, email=email, subject=subject, body=body)

            html = render_to_string('pages/emails/contact_form_sub.html', {
                'name': name,
                'phone': phone,
                'email': email,
                'subject': subject,
                'body': body,
            })

            send_mail(subject='This message is from me', message='Hello world', from_email='codewithafripoint@gmail.com', recipient_list=[email], html_message=html)
            messages.success(request, 'Thank you for reaching out, we will get back to you.')
            form = ContactForm()
            context = {
                "form": form
            }
            return redirect('pages:contact')

        else:
            for key, error in list(form.errors.items()):
                if key == 'captcha' and error[0] == 'This field is required.':
                    messages.error(request, "You MUST pass the reCaptcha test!")
                    continue
                messages.error(request, error)

    context = {
        "form": form,
    }
    return render(request, 'pages/contact.html', context)

</code>```

The challenge I am having is how to ensure that after each complaint/contact/issue is resolved, the support team can update the status to Resolved as against the default Pending status.

I tried this but it seems to be giving me 'None' each time I update it:
Your assistance will be much appreciated.

```<code># Update status
def editStatus(request, pk):
    contact = get_object_or_404(Contact, pk=pk)
    # Define the edit post view function
    if request.method == 'POST':
        # Update the attributes of the post
        contact.status = request.POST.get('status')
        # Save the changes to the database
        contact.save()

        # Redirect to the post detail page
        return redirect('dashboard:contact_us_detail', pk=contact.pk)

    return render(request, 'dashboard/editstatus.html', {
        'contact': contact,
    })

</code>```

Title: How to update Django custom dashboard

Body:
I am building a custom dashboard that will only be accessible to the support team of a company. These support teams will receive complaints from a contact form but we want to be able to indicate each complaint that has been resolved from the dashboard as resolved after being attended to.

Therefore, I created a field of choices (pending and resolved) which I named status. This field is not exposed to the user in the contact form and on the backend, it's 'pending' by default.

See the contact model as shown below

class Contact(models.Model):
    STATUS_CHOICE = (
        ("1", "Pending"),
        ("2", "Resolved"),
    )
    name = models.CharField(max_length=100)
    phone = models.CharField(max_length=15)
    email = models.EmailField(max_length=254)
    subject = models.CharField(max_length=100)
    status = models.CharField(choices=STATUS_CHOICE, default="1", max_length=50, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    body = models.TextField()

    class Meta:
        ordering = ["-created"]
        verbose_name_plural = "Contacts"

    def __str__(self):
        return f"Message from: {self.name}"

see my forms.py:

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100, required=True)
    phone = forms.CharField(max_length=15, required=True)
    email = forms.EmailField(max_length=100, required=True)
    subject = forms.CharField(max_length=100, required=True)
    body = forms.CharField(required=True, label='Message', widget=forms.Textarea())

    class Meta:
        model = Contact
        fields = ['name', 'phone', 'email', 'subject', 'body']

    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)

The intent of the view below is to ensure that all users that contact the company using the contact form receive an email and that the information is also saved in the database. This worked fine.

def contact(request):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            phone = form.cleaned_data['phone']
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            body = form.cleaned_data['body']

            contact = Contact.objects.create(
                name=name, phone=phone, email=email, subject=subject, body=body)

            html = render_to_string('pages/emails/contact_form_sub.html', {
                'name': name,
                'phone': phone,
                'email': email,
                'subject': subject,
                'body': body,
            })

            send_mail(subject='This message is from me', message='Hello world', from_email='codewithafripoint@gmail.com', recipient_list=[email], html_message=html)
            messages.success(request, 'Thank you for reaching out, we will get back to you.')
            form = ContactForm()
            context = {
                "form": form
            }
            return redirect('pages:contact')

        else:
            for key, error in list(form.errors.items()):
                if key == 'captcha' and error[0] == 'This field is required.':
                    messages.error(request, "You MUST pass the reCaptcha test!")
                    continue
                messages.error(request, error)

    context = {
        "form": form,
    }
    return render(request, 'pages/contact.html', context)

The challenge I am having is how to ensure that after each complaint/contact/issue is resolved, the support team can update the status to Resolved as against the default Pending status.

I tried this but it seems to be giving me 'None' each time I update it:
Your assistance will be much appreciated.

# Update status
def editStatus(request, pk):
    contact = get_object_or_404(Contact, pk=pk)
    # Define the edit post view function
    if request.method == 'POST':
        # Update the attributes of the post
        contact.status = request.POST.get('status')
        # Save the changes to the database
        contact.save()

        # Redirect to the post detail page
        return redirect('dashboard:contact_us_detail', pk=contact.pk)

    return render(request, 'dashboard/editstatus.html', {
        'contact': contact,
    })


问:
CSV files and dicts
I have a code where children are supposed to get presents from Santa.
They all have their wishes (what they wanna get), but naughty children cannot receive any presents, only those who have been nice.
And so there are 3 files: nice.csv and naughty.csv, which contain children names and countries (countries don't matter) and wishlist.csv, which has names and their wishes, separated by coma.

This is my code:

```<code>class Child:
    """Child class."""

    def __init__(self, name, country):
        """Constructor."""
        self.name = name
        self.country = country

    def __repr__(self):
        """Representation."""
        return f"{self.name}"

class Gift:
    """Gift class."""

    def __init__(self, name):
        """Constructor."""
        self.name = name

    def __repr__(self):
        """Representation."""
        return f"{self.name}"

class World:
    """World class."""

    def __init__(self, nice_file, wishlist_file):
        """Constructor."""
        self.nice_file = nice_file
        self.wishlist_file = wishlist_file

    def read_file(self, filename):
        """Read file."""
        result = []
        with open(filename) as f:
            reader = csv.reader(f)
            for line in reader:
                result.append(line)
        return result

    def nice_list(self):
        """Nice children list."""
        nice = []
        for line in self.read_file(self.nice_file):
            name = Child(line[0], line[1])
            nice.append(name)
        return nice

    def wishlist(self):
        """Wishlist."""
        result = {}
        for line in self.read_file(self.wishlist_file):
            wishes = [Gift(x) for x in line[1:]]
            result[line[0]] = wishes
        return result
</code>```

The problem is that naughty kids also have their wishes in the wishlist. I want naughty kids to not be in my wishlist dictionary.

For example:

nice.csv: Molly,Germany

naughty.csv: Adam,USA

wishlist.csv: Molly,doll | Adam,robot

This is what I wanna get, and I don't know how to achieve this:

```<code>{'Molly': doll}
</code>```

This is what I get and is false:

```<code>{'Molly': doll, 'Adam': robot}
</code>```

Title: CSV files and dicts

Body:
I have a code where children are supposed to get presents from Santa.
They all have their wishes (what they wanna get), but naughty children cannot receive any presents, only those who have been nice.
And so there are 3 files: nice.csv and naughty.csv, which contain children names and countries (countries don't matter) and wishlist.csv, which has names and their wishes, separated by coma.

This is my code:

class Child:
    """Child class."""

    def __init__(self, name, country):
        """Constructor."""
        self.name = name
        self.country = country

    def __repr__(self):
        """Representation."""
        return f"{self.name}"

class Gift:
    """Gift class."""

    def __init__(self, name):
        """Constructor."""
        self.name = name

    def __repr__(self):
        """Representation."""
        return f"{self.name}"

class World:
    """World class."""

    def __init__(self, nice_file, wishlist_file):
        """Constructor."""
        self.nice_file = nice_file
        self.wishlist_file = wishlist_file

    def read_file(self, filename):
        """Read file."""
        result = []
        with open(filename) as f:
            reader = csv.reader(f)
            for line in reader:
                result.append(line)
        return result

    def nice_list(self):
        """Nice children list."""
        nice = []
        for line in self.read_file(self.nice_file):
            name = Child(line[0], line[1])
            nice.append(name)
        return nice

    def wishlist(self):
        """Wishlist."""
        result = {}
        for line in self.read_file(self.wishlist_file):
            wishes = [Gift(x) for x in line[1:]]
            result[line[0]] = wishes
        return result

The problem is that naughty kids also have their wishes in the wishlist. I want naughty kids to not be in my wishlist dictionary.

For example:

nice.csv: Molly,Germany

naughty.csv: Adam,USA

wishlist.csv: Molly,doll | Adam,robot

This is what I wanna get, and I don't know how to achieve this:

{'Molly': doll}

This is what I get and is false:

{'Molly': doll, 'Adam': robot}


问:
How to resolve multiple requests in a map using NodeJS?
I'm a bit confused on how to resolve my requests multiple times without affecting the performance of my code in nodejs (v16.13.0)

It turns out that I am doing a monthly report and in this I need different data to be able to generate it. What I do is obtain the monthly data from the beginning to the end of the month, in addition to other queries that I make to the database, which I have in supabase and that Postgree uses, to unify all my data.

I make use of promises, specifically Promise.all, since in this way I speed up the development of my asynchronous requests and once they have all finished resolving I use the data. This is the structure I currently use:

// Arrangements where I will store the response of the requests
let usersxData: UsersxModalityxRolexJob[] = [];
let data_monthly: HoursActivityWeeklySummary[] = [];
let attendance_schedule: AttendanceSchedule[] = [];
let time_off_request: TimeOffRequestRpc[] = [];
let configs: IndicatorConfigs[] = [];

// Class where I have the methods that make the requests to supabase
const supabaseService = new SupabaseService();

// The list of requests to resolve
const promises = [
  // Function that obtains a monthly summary in averages
  supabaseService.getSummaryWeekRpcWihoutFreelancers(req.query.start_date, req.query.end_date).then(dataFromDB => {
    data_monthly = dataFromDB as any;
  }),
  // User list
  supabaseService.getUsersEntity(res).then(dataFromDB => {
    usersxData = dataFromDB as any;
  }),
  // Schedule during the month
  supabaseService.getAttendaceScheduleRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    attendance_schedule = dataFromDB as any;
  }),
  supabaseService.getTimeOffRequestRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    time_off_request = dataFromDB as any;
  }),
  supabaseService.getConfigs(res).then(dataFromDB => {
    configs = dataFromDB;
  })
];

// resolve all requests
Promise.all(promises);

// get the schedule
res.json(attendance_schedule)```
</div>
</div>
</p>
<p>But I'm at a point where I need to make a multiple request. How is that? Once I get my schedule I want to iterate over that array that brings a date to consult my database and bring those days</p>
<p>It means that first I make my requests and with the response of this I want to make an iterable request again where I send to consult the DB on specific dates</p>
<p>To better illustrate myself, make the following code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//Arrays where the response of the requests
let userxData: UsersxModalityxRolexJob[] = [];
let data_monthly: HoursActivityWeeklySummary[] = [];
let time_attendance: TimeAttendance[] = [];
let time_off_request: TimeOffRequestRpc[] = [];
leave the configuration: FlagConfigs[] = [];

// Class where I have the methods that make the requests to supabase
const supabaseService = new SupabaseService();

// The list of requests to resolve
constant promises = [
  // Function that gets a monthly summary in averages
  supabaseService.getSummaryWeekRpcWihoutFreelancers(req.query.start_date, req.query.end_date).then(dataFromDB => {
    data_monthly = dataFromDB as any;
  }),
  // User list
  supabaseService.getUsersEntity(res).then(dataFromDB => {
    usersxData = dataFromDB like any;
  }),
  // Hours during the month
  supabaseService.getAttendaceScheduleRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    Assistance_schedule = dataFromDB like any;
  }),
  supabaseService.getTimeOffRequestRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    time_off_request = dataFromDB as any;
  }),
  supabaseService.getConfigs(res).then(dataFromDB => {
    settings = dataFromDB;
  })
];

// resolve all requests
Promise.all(promises);

schedule_attendance.map(async element => {

  let start_date = item.date_start.toString();
  let end_date = element.date_end.toString();
  let supabase = supabaseinstance();
  leave query = '';
  let {
    data,
    error
  } = wait supabase.rpc < HoursActivityWeeklySummary > ("weekly activity", {
      start_date,
      end_date
    })
    .select(query ? query : '*').in('title', ['DEV', 'SAC', 'DESIÑO']).in('modality', ['FULLTIME', 'PARTTIME']).order('username', {
      ascending: false
    });

  if (data) {
    return data
  } else {
    console.log(error)
  }

})</code>```

But I know and understand that the previous code from where you can see it is wrong, because the only thing that can cause it is that at some point in the request there is some kind of error. Also, I'm not respecting the structure of Promise.all as I need to declare promises in a higher scope where it can be used with it.

So how can I make multiple requests after I've made the main ones? What I'd like to see is an example of how this is done instead of getting the solution directly, which is why I'm not adding a demo of my current code.

UPDATE

    export const generateMonthlyReport = async(req: Request and any, res: Response, next: NextFunction) => {
      try {

        let usersxData: UsersxModalityxRolexJob[] = [];
        let data_monthly: HoursActivityWeeklySummary[] = [];
        let time_attendance: TimeAttendance[] = [];
        let time_off_request: TimeOffRequestRpc[] = [];
        let settings: FlagConfigs[] = [];
        let attendanceInMonthly: any[] = [];

        const supabaseService = new SupabaseService();

        const promises = [
          supabaseService.getSummaryWeekRpcWihoutFreelancers(req.query.start_date, req.query.end_date).then(dataFromDB => {
            data_monthly = dataFromDB as any;
          }),
          supabaseService.getUsersEntity(res).then(dataFromDB => {
            usersxData = dataFromDB like any;
          }),
          supabaseService.getAttendaceScheduleRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
            Assistance_schedule = dataFromDB like any;
          }),
          supabaseService.getTimeOffRequestRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
            time_off_request = dataFromDB as any;
          }),
          supabaseService.getConfigs(res).then(dataFromDB => {
            settings = dataFromDB;
          })
        ];

        await Promise.all(promises)

attendance_schedule.forEach(element => {
            let start_date = element.date_start.toString();
            let end_date = element.date_end.toString();

            supabaseService.getTrackedByDateAndIDArray(start_date, end_date).then(item => {
                console.log(item);
                attendanceInMonthly.push(item)
            })
        })

        res.json(assistanceInMonthly)

      } catch (error) {
        console.log(error);
        res.status(500).json({
          title: 'API-CIT Error',
          message: 'Internal Server Error'
        });
      }
    }```

Body:
I'm a bit confused on how to resolve my requests multiple times without affecting the performance of my code in nodejs (v16.13.0)

It turns out that I am doing a monthly report and in this I need different data to be able to generate it. What I do is obtain the monthly data from the beginning to the end of the month, in addition to other queries that I make to the database, which I have in supabase and that Postgree uses, to unify all my data.

I make use of promises, specifically Promise.all, since in this way I speed up the development of my asynchronous requests and once they have all finished resolving I use the data. This is the structure I currently use:

// Arrangements where I will store the response of the requests
let usersxData: UsersxModalityxRolexJob[] = [];
let data_monthly: HoursActivityWeeklySummary[] = [];
let attendance_schedule: AttendanceSchedule[] = [];
let time_off_request: TimeOffRequestRpc[] = [];
let configs: IndicatorConfigs[] = [];

// Class where I have the methods that make the requests to supabase
const supabaseService = new SupabaseService();

// The list of requests to resolve
const promises = [
  // Function that obtains a monthly summary in averages
  supabaseService.getSummaryWeekRpcWihoutFreelancers(req.query.start_date, req.query.end_date).then(dataFromDB => {
    data_monthly = dataFromDB as any;
  }),
  // User list
  supabaseService.getUsersEntity(res).then(dataFromDB => {
    usersxData = dataFromDB as any;
  }),
  // Schedule during the month
  supabaseService.getAttendaceScheduleRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    attendance_schedule = dataFromDB as any;
  }),
  supabaseService.getTimeOffRequestRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    time_off_request = dataFromDB as any;
  }),
  supabaseService.getConfigs(res).then(dataFromDB => {
    configs = dataFromDB;
  })
];

// resolve all requests
Promise.all(promises);

// get the schedule
res.json(attendance_schedule)

But I'm at a point where I need to make a multiple request. How is that? Once I get my schedule I want to iterate over that array that brings a date to consult my database and bring those days

It means that first I make my requests and with the response of this I want to make an iterable request again where I send to consult the DB on specific dates

To better illustrate myself, make the following code

//Arrays where the response of the requests
let userxData: UsersxModalityxRolexJob[] = [];
let data_monthly: HoursActivityWeeklySummary[] = [];
let time_attendance: TimeAttendance[] = [];
let time_off_request: TimeOffRequestRpc[] = [];
leave the configuration: FlagConfigs[] = [];

// Class where I have the methods that make the requests to supabase
const supabaseService = new SupabaseService();

// The list of requests to resolve
constant promises = [
  // Function that gets a monthly summary in averages
  supabaseService.getSummaryWeekRpcWihoutFreelancers(req.query.start_date, req.query.end_date).then(dataFromDB => {
    data_monthly = dataFromDB as any;
  }),
  // User list
  supabaseService.getUsersEntity(res).then(dataFromDB => {
    usersxData = dataFromDB like any;
  }),
  // Hours during the month
  supabaseService.getAttendaceScheduleRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    Assistance_schedule = dataFromDB like any;
  }),
  supabaseService.getTimeOffRequestRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
    time_off_request = dataFromDB as any;
  }),
  supabaseService.getConfigs(res).then(dataFromDB => {
    settings = dataFromDB;
  })
];

// resolve all requests
Promise.all(promises);

schedule_attendance.map(async element => {

  let start_date = item.date_start.toString();
  let end_date = element.date_end.toString();
  let supabase = supabaseinstance();
  leave query = '';
  let {
    data,
    error
  } = wait supabase.rpc < HoursActivityWeeklySummary > ("weekly activity", {
      start_date,
      end_date
    })
    .select(query ? query : '*').in('title', ['DEV', 'SAC', 'DESIÑO']).in('modality', ['FULLTIME', 'PARTTIME']).order('username', {
      ascending: false
    });

  if (data) {
    return data
  } else {
    console.log(error)
  }

})

But I know and understand that the previous code from where you can see it is wrong, because the only thing that can cause it is that at some point in the request there is some kind of error. Also, I'm not respecting the structure of Promise.all as I need to declare promises in a higher scope where it can be used with it.

So how can I make multiple requests after I've made the main ones? What I'd like to see is an example of how this is done instead of getting the solution directly, which is why I'm not adding a demo of my current code.

UPDATE

    export const generateMonthlyReport = async(req: Request and any, res: Response, next: NextFunction) => {
      try {

        let usersxData: UsersxModalityxRolexJob[] = [];
        let data_monthly: HoursActivityWeeklySummary[] = [];
        let time_attendance: TimeAttendance[] = [];
        let time_off_request: TimeOffRequestRpc[] = [];
        let settings: FlagConfigs[] = [];
        let attendanceInMonthly: any[] = [];

        const supabaseService = new SupabaseService();

        const promises = [
          supabaseService.getSummaryWeekRpcWihoutFreelancers(req.query.start_date, req.query.end_date).then(dataFromDB => {
            data_monthly = dataFromDB as any;
          }),
          supabaseService.getUsersEntity(res).then(dataFromDB => {
            usersxData = dataFromDB like any;
          }),
          supabaseService.getAttendaceScheduleRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
            Assistance_schedule = dataFromDB like any;
          }),
          supabaseService.getTimeOffRequestRpc(req.query.start_date, req.query.end_date).then(dataFromDB => {
            time_off_request = dataFromDB as any;
          }),
          supabaseService.getConfigs(res).then(dataFromDB => {
            settings = dataFromDB;
          })
        ];

        await Promise.all(promises)

attendance_schedule.forEach(element => {
            let start_date = element.date_start.toString();
            let end_date = element.date_end.toString();

            supabaseService.getTrackedByDateAndIDArray(start_date, end_date).then(item => {
                console.log(item);
                attendanceInMonthly.push(item)
            })
        })

        res.json(assistanceInMonthly)

      } catch (error) {
        console.log(error);
        res.status(500).json({
          title: 'API-CIT Error',
          message: 'Internal Server Error'
        });
      }
    }


问:
How to show the last and the highest stackLabel in highcharts, and export the tooltip?
As in the fiddle: fiddle

I just want to show the last stacklabel(39), and the highest(133), can I?

When exporting, I want to export the last tooltip as well, how？
Thanks.

```<code> yAxis: {
   stackLabels: {
     allowOverlap: true,
     enabled: true
   }
 },
</code>```

Body:
As in the fiddle: fiddle

I just want to show the last stacklabel(39), and the highest(133), can I?

When exporting, I want to export the last tooltip as well, how？
Thanks.

 yAxis: {
   stackLabels: {
     allowOverlap: true,
     enabled: true
   }
 },


问:
JS array of time slots based on opening hours
I am writing an order ahead application that allows the user to select a pick up time from a select box.

This pickup time must be in intervals of x number of minutes i.e. every 20 minutes.

It needs to take into account business opening hours i.e. 12:00 > 14:00 and 16:30 > 21:30 i.e. only generate time slots between these hours, lunchtime opening and evening opening.

I am using data-fns and have the basic functionality working i.e. start time and hardcoded end time, it generates an array of available time slots at the minute interval.

```<code>import { addMinutes, set } from "date-fns";

const generateAvailableTimeSlots = (slotSizeInMinutes: number) => {
  const now = new Date();
  let firstAvailableSlot = now;

  while (firstAvailableSlot <= now) {
    // Set the first available slot to now + slotSizeInMinutes e.g. now + 20 minutes
    firstAvailableSlot = addMinutes(now, slotSizeInMinutes);
  }

  // Currently hard coded end time i.e. end of business day
  const endTime = set(now, { hours: 23, minutes: 30 });

  let slot = firstAvailableSlot;
  let availableTimeSlots = [];
  while (slot < endTime) {
    availableTimeSlots.push(slot);
    slot = addMinutes(slot, slotSizeInMinutes);
  }

  return availableTimeSlots;
};

export default generateAvailableTimeSlots;
</code>```

What would be the best way to improve this and to take into account business opening hours? i.e. Sunday the business is not open in the morning, every other day it's open for 2 hours over lunch and then again in the evening.

I guess keeping it simple I could pass in a start time and an end time and call the function twice to generate two arrays of time slots (for lunchtimes and evenings) however it would be convenient only to call the function once and just not have the closed time slots selectable i.e. maybe return an array of objects for all available slots but mark some as not available

Body:
I am writing an order ahead application that allows the user to select a pick up time from a select box.

This pickup time must be in intervals of x number of minutes i.e. every 20 minutes.

It needs to take into account business opening hours i.e. 12:00 > 14:00 and 16:30 > 21:30 i.e. only generate time slots between these hours, lunchtime opening and evening opening.

I am using data-fns and have the basic functionality working i.e. start time and hardcoded end time, it generates an array of available time slots at the minute interval.

import { addMinutes, set } from "date-fns";

const generateAvailableTimeSlots = (slotSizeInMinutes: number) => {
  const now = new Date();
  let firstAvailableSlot = now;

  while (firstAvailableSlot <= now) {
    // Set the first available slot to now + slotSizeInMinutes e.g. now + 20 minutes
    firstAvailableSlot = addMinutes(now, slotSizeInMinutes);
  }

  // Currently hard coded end time i.e. end of business day
  const endTime = set(now, { hours: 23, minutes: 30 });

  let slot = firstAvailableSlot;
  let availableTimeSlots = [];
  while (slot < endTime) {
    availableTimeSlots.push(slot);
    slot = addMinutes(slot, slotSizeInMinutes);
  }

  return availableTimeSlots;
};

export default generateAvailableTimeSlots;

What would be the best way to improve this and to take into account business opening hours? i.e. Sunday the business is not open in the morning, every other day it's open for 2 hours over lunch and then again in the evening.

I guess keeping it simple I could pass in a start time and an end time and call the function twice to generate two arrays of time slots (for lunchtimes and evenings) however it would be convenient only to call the function once and just not have the closed time slots selectable i.e. maybe return an array of objects for all available slots but mark some as not available


问:
Build Issue After Upgradingt to Android Studio Dolphin | 2021.3.1 Patch 1 | Navigation Directions
I updated my IDE to Android Studio Dolphin | 2021.3.1 Patch 1 and I am getting build error. I don't now why. But they seems only related with navigation-directions from Navigation.

here is the screen shots

I couldn't find the solution for this on the internet so any help would be great, thanks.


问:
Error with axios receiving data from local server
This is my nodejs code that I am running trying to get data from und.com and then get the output to my react code. I am having an issue with axios trying to pull in the data.

```<code>const express = require("express");
const cheerio = require("cheerio");
const axios = require("axios");

const app = express();
app.post("/post", (req, res) => {
    console.log("Connected to react");
    res.redirect("/");
})
const PORT = process.env.PORT || 3002;

const website = "https://und.com";

let options = {
headers: {
    "user-agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
}
};

app.get("/", (req, res) => {
// Make the HTTP request using axios
axios(website, options)
.then(({data}) => {
    const $ = cheerio.load(data);
    const result = $(".post__meta h3 a:last-child")
    .map((_, e) => $(e).text().trim())
    .get();
    console.log(result);
    // Use cheerio to manipulate the HTML data

    // Set the content type of the response to "text/html"
    res.set("Content-Type", "text/html");

    // Send the HTML data as the response
    res.send(result);
    })
    .catch((error) => {
        // The HTTP request failed
        console.log("An error occurred:", error);

        // Set the status code of the response to indicate an error
        res.status(500);

        // Send an error message as the response
        res.send("An error occurred while making the HTTP request.");
    });
    })

app.listen(PORT, () => {
    console.log(`server is running on PORT: ${PORT} `);
})
</code>```

Below this is my react app trying to pull the data that is outputted in

```<code>import axios from "axios";

const url = "http://localhost:3002";

const Home = () => {
return axios({
    method: "post",
    url: `${url}`,

    headers: {
    "Content-Type": "application/json"
    },
    json: true
})
    .then((response) => {
    console.log("POST response: ", response);
    })
    .catch((err) => {
    console.log("POST error: ", err);
    });
};

export default Home;
</code>```

however I am getting an axios error trying to pull this data in. axios error ERR_NETWORK.

Body:
This is my nodejs code that I am running trying to get data from und.com and then get the output to my react code. I am having an issue with axios trying to pull in the data.

const express = require("express");
const cheerio = require("cheerio");
const axios = require("axios");

const app = express();
app.post("/post", (req, res) => {
    console.log("Connected to react");
    res.redirect("/");
})
const PORT = process.env.PORT || 3002;

const website = "https://und.com";

let options = {
headers: {
    "user-agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
}
};

app.get("/", (req, res) => {
// Make the HTTP request using axios
axios(website, options)
.then(({data}) => {
    const $ = cheerio.load(data);
    const result = $(".post__meta h3 a:last-child")
    .map((_, e) => $(e).text().trim())
    .get();
    console.log(result);
    // Use cheerio to manipulate the HTML data

    // Set the content type of the response to "text/html"
    res.set("Content-Type", "text/html");

    // Send the HTML data as the response
    res.send(result);
    })
    .catch((error) => {
        // The HTTP request failed
        console.log("An error occurred:", error);

        // Set the status code of the response to indicate an error
        res.status(500);

        // Send an error message as the response
        res.send("An error occurred while making the HTTP request.");
    });
    })

app.listen(PORT, () => {
    console.log(`server is running on PORT: ${PORT} `);
})

Below this is my react app trying to pull the data that is outputted in

import axios from "axios";

const url = "http://localhost:3002";

const Home = () => {
return axios({
    method: "post",
    url: `${url}`,

    headers: {
    "Content-Type": "application/json"
    },
    json: true
})
    .then((response) => {
    console.log("POST response: ", response);
    })
    .catch((err) => {
    console.log("POST error: ", err);
    });
};

export default Home;

however I am getting an axios error trying to pull this data in. axios error ERR_NETWORK.


问:
Send HTTP request containing index.html content to server from client
Right now in my code, the index.html file is read on the server and then sent from the server to the client connection. I need to make it so that I have a separate client application that formulates the HTTP request and sends it to the server to send HTTP response. Just not quite sure how to do that. I have an echo-client.py file but it doesn't work at the moment. The server application works and displays the index.html at localhost:14000 with the server.py code below:

server.py

```<code>"""
 Implements a simple HTTP/1.0 Server

"""
import socket
# Define socket host and port
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 14000

# Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
print('Listening on port %s ...' % SERVER_PORT)

while True:
   # Wait for client connections
    client_connection, client_address = server_socket.accept()

    # Get the content of index.html
    # HTTP Request
    fin = open('index.html')
    content = fin.read()
    fin.close()

    # Send HTTP response
    response = 'HTTP/1.0 200 OK\n\n' + content
    client_connection.sendall(response.encode())
    # client_connection.close()

# Close socket
server_socket.close()
</code>```

I've tried configuring the client.py application like this but it says:

```<code>  File "/Users/jamesmeegan/Desktop/COSC 350 Data Comm/Problem3_HW3/echo-client.py", line 33, in <module>
    s.sendall((content))
TypeError: a bytes-like object is required, not 'str'
</code>```

and I'm not sure how I would even receive it on the server end.

client.py

```<code># echo-client.py

import socket

HOST = "127.0.0.1"  # The server's hostname or IP address
PORT = 14000  # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))

    fin = open('index.html')
    content = fin.read()
    fin.close()

    s.sendall((content))
    data = s.recv(1024)

print(f"Received {data!r}")
</code>```

Body:
Right now in my code, the index.html file is read on the server and then sent from the server to the client connection. I need to make it so that I have a separate client application that formulates the HTTP request and sends it to the server to send HTTP response. Just not quite sure how to do that. I have an echo-client.py file but it doesn't work at the moment. The server application works and displays the index.html at localhost:14000 with the server.py code below:

server.py

"""
 Implements a simple HTTP/1.0 Server

"""
import socket
# Define socket host and port
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 14000

# Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
print('Listening on port %s ...' % SERVER_PORT)

while True:
   # Wait for client connections
    client_connection, client_address = server_socket.accept()

    # Get the content of index.html
    # HTTP Request
    fin = open('index.html')
    content = fin.read()
    fin.close()

    # Send HTTP response
    response = 'HTTP/1.0 200 OK\n\n' + content
    client_connection.sendall(response.encode())
    # client_connection.close()

# Close socket
server_socket.close()

I've tried configuring the client.py application like this but it says:

  File "/Users/jamesmeegan/Desktop/COSC 350 Data Comm/Problem3_HW3/echo-client.py", line 33, in <module>
    s.sendall((content))
TypeError: a bytes-like object is required, not 'str'

and I'm not sure how I would even receive it on the server end.

client.py

# echo-client.py

import socket

HOST = "127.0.0.1"  # The server's hostname or IP address
PORT = 14000  # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))

    fin = open('index.html')
    content = fin.read()
    fin.close()

    s.sendall((content))
    data = s.recv(1024)

print(f"Received {data!r}")


问:
setState triggers infinite loop
I am trying to rerender component after retrieving data from the backend on page load with axios as well as clicking the Enter course name button in the form. So far I am able to rerender after the page has loaded using setState for isLoading. However, when I try to rerender on button click for courseList by using setCourseList() in handleClick, it seems to trigger an infinite loop of re-rendering. I don't know what is causing the issue... Is it using setCourseList in an event handler? If so, how can I avoid infinite rerendering?

```<code>import React from 'react';
import '../App.css';
//import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import axios from 'axios';
import Cookies from 'universal-cookie';
import { Link } from "react-router-dom";

function Course() {
    //const navigate = useNavigate();s

    const cookies = new Cookies();
    const [showResults, setShowResults] = useState(true);
    const [isLoading, setLoading] = useState(true);

    const [data, setData] = useState({
        email: cookies.get('email'),
        addName: '',
      });

    const [courseList, setCourseList] = useState([]);
    axios
    .post('http://localhost:8000/api/course', data)
    .then((res) => {
        setLoading(false);
        setCourseList(res.data.course);
        console.log(res.data.course);
    })
    .catch(err => {
      console.error(err);
    });

    function handleInput(e) {
        const newData={...data};
        newData[e.target.id] = e.target.value;
        setData(newData);
    }

    function handleClick() {
        setShowResults(false);
        setLoading(true);
        console.log(data.addName);
        axios
        .post('http://localhost:8000/api/add-course', data)
        .then((res) => {
            setCourseList(res.data.course);
            console.log(res);
        })
        .catch(err => {
          console.error(err);
        });
    }
    if (isLoading) {
        return (<body>
            <div className="Loading">
            <h2>Loading...</h2>
            </div>
            </body>);
    }

    return (
        <div id="course_page" className="course_page">
         <body>
            <h2 id="title">Course</h2>
            <div className="form1" id="form1">
            { courseList ? <form>
                {courseList.map(course => (
                    <Link className="btn" to="/Start">
                    <input id={course.courseName} class={course.courseName} type="submit" value={course.courseName}/>
                    </Link>
            ))}
            </form> : null }
            { showResults ? <form onSubmit={(e) => handleClick(e)}>
                <input type="text" onChange={(e) => handleInput(e)} className="addName" name="addName" value={data.addName} id="addName" placeholder="Enter course name"/>
                <input id="addCourse" className="addCourse" type="submit" value="Add Course"/>
            </form> : null }

            </div>
            </body>
        </div>
      );
}

export default Course;
</code>```

Title: setState triggers infinite loop

Body:
I am trying to rerender component after retrieving data from the backend on page load with axios as well as clicking the Enter course name button in the form. So far I am able to rerender after the page has loaded using setState for isLoading. However, when I try to rerender on button click for courseList by using setCourseList() in handleClick, it seems to trigger an infinite loop of re-rendering. I don't know what is causing the issue... Is it using setCourseList in an event handler? If so, how can I avoid infinite rerendering?

import React from 'react';
import '../App.css';
//import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import axios from 'axios';
import Cookies from 'universal-cookie';
import { Link } from "react-router-dom";

function Course() {
    //const navigate = useNavigate();s

    const cookies = new Cookies();
    const [showResults, setShowResults] = useState(true);
    const [isLoading, setLoading] = useState(true);

    const [data, setData] = useState({
        email: cookies.get('email'),
        addName: '',
      });

    const [courseList, setCourseList] = useState([]);
    axios
    .post('http://localhost:8000/api/course', data)
    .then((res) => {
        setLoading(false);
        setCourseList(res.data.course);
        console.log(res.data.course);
    })
    .catch(err => {
      console.error(err);
    });

    function handleInput(e) {
        const newData={...data};
        newData[e.target.id] = e.target.value;
        setData(newData);
    }

    function handleClick() {
        setShowResults(false);
        setLoading(true);
        console.log(data.addName);
        axios
        .post('http://localhost:8000/api/add-course', data)
        .then((res) => {
            setCourseList(res.data.course);
            console.log(res);
        })
        .catch(err => {
          console.error(err);
        });
    }
    if (isLoading) {
        return (

Loading...

            );
    }

    return (

Course

            { courseList ? <form>
                {courseList.map(course => (
                    <Link className="btn" to="/Start">
                    <input id={course.courseName} class={course.courseName} type="submit" value={course.courseName}/>
                    </Link>
            ))}
            </form> : null }
            { showResults ? <form onSubmit={(e) => handleClick(e)}>
                <input type="text" onChange={(e) => handleInput(e)} className="addName" name="addName" value={data.addName} id="addName" placeholder="Enter course name"/>
                <input id="addCourse" className="addCourse" type="submit" value="Add Course"/>
            </form> : null }

      );
}

export default Course;


问:
Gradle How to add dependencies between subprojects in root project's build.gradle
I am working on a multi-module gradle java project where it has three project modules
1.webapp
2.common
3.data-client

I have four build.gradle files. Three inside these projects and one file in the root folder.

I am trying to add a dependency between webapp and common project inside the build.gradle of root project. Below is my build.gradle file but when I run gradle build. I am getting an error mentioned below. I know I can add the dependency directly in the sub-project but I want to know why this is not working. My gradle version is 7.6

```<code>org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'web-app-gradle-local'.
    at org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method implementation() for arguments [project ':common'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
    at org.gradle.internal.metaobject.AbstractDynamicObject$CustomMissingMethodExecutionFailed.<init>(AbstractDynamicObject.java:190)
    at org.gradle.internal.metaobject.AbstractDynamicObject.methodMissingException(AbstractDynamicObject.java:184)
    at org.gradle.internal.metaobject.ConfigureDelegate.invokeMethod(ConfigureDelegate.java:93)
</code>```

Build.gradle

```<code>plugins {
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'junit:junit:4.13.2'
    implementation 'org.springframework.boot:spring-boot-starter-security:3.0.0'
    implementation 'com.google.guava:guava:31.1-jre'
}

project(':web-app') {
    dependencies {
        implementation project (':common')
    }
}
</code>```

Body:
I am working on a multi-module gradle java project where it has three project modules
1.webapp
2.common
3.data-client

I have four build.gradle files. Three inside these projects and one file in the root folder.

I am trying to add a dependency between webapp and common project inside the build.gradle of root project. Below is my build.gradle file but when I run gradle build. I am getting an error mentioned below. I know I can add the dependency directly in the sub-project but I want to know why this is not working. My gradle version is 7.6

org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'web-app-gradle-local'.
    at org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method implementation() for arguments [project ':common'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
    at org.gradle.internal.metaobject.AbstractDynamicObject$CustomMissingMethodExecutionFailed.<init>(AbstractDynamicObject.java:190)
    at org.gradle.internal.metaobject.AbstractDynamicObject.methodMissingException(AbstractDynamicObject.java:184)
    at org.gradle.internal.metaobject.ConfigureDelegate.invokeMethod(ConfigureDelegate.java:93)

Build.gradle

plugins {
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'junit:junit:4.13.2'
    implementation 'org.springframework.boot:spring-boot-starter-security:3.0.0'
    implementation 'com.google.guava:guava:31.1-jre'
}

project(':web-app') {
    dependencies {
        implementation project (':common')
    }
}


问:
Why my data visualization model takes index values instead of "Year" column values
Im trying to do visualize my data. In my table ı have 3 column and ım trying to visualize them, but when ı write the "Year" column my model doesn't take Year column and it takes index values of year table's, so can you please help me ım new learner about data thing.

This is my table that ım working on it

This is the problem that ı mentioned


问:
How to write Unit test for DAL which call stored procedure and direct SQL commands
I am writing unit test cases for DAL methods (which are calling stored procedures and some direct SQL commands and not returning methods). How can I mock the results coming from db in unit tests?

Please let me know sample references or suggestions. Please find the below sample code

```<code>public class Notification : Base, INotificationBal
{
    public void InsertNotification(NotificationType notif)
    {
        using (var con = GetConnction())
        {
            using (var command = CreatSqlCommand(con, "sp_InsertNotifDetails"))
            {
                // notif.NotificationType=1, notif.NotificationName="Mobile"
                command.SetParamsValues(
                        ("@NotificationType", notif.NotificationType),
                        ("@NotificationName", notif.NotificationName)
                        ));
                command.ExecuteNonQuery());
            }
        }
    }
}
</code>```

Thanks,
Sam

I am not aware of this.

Body:
I am writing unit test cases for DAL methods (which are calling stored procedures and some direct SQL commands and not returning methods). How can I mock the results coming from db in unit tests?

Please let me know sample references or suggestions. Please find the below sample code

public class Notification : Base, INotificationBal
{
    public void InsertNotification(NotificationType notif)
    {
        using (var con = GetConnction())
        {
            using (var command = CreatSqlCommand(con, "sp_InsertNotifDetails"))
            {
                // notif.NotificationType=1, notif.NotificationName="Mobile"
                command.SetParamsValues(
                        ("@NotificationType", notif.NotificationType),
                        ("@NotificationName", notif.NotificationName)
                        ));
                command.ExecuteNonQuery());
            }
        }
    }
}

Thanks,
Sam

I am not aware of this.


问:
Getting original index values after performing statistical outlier in open3d
I have all my data stored in a geopandas geodataframe, let's call it df1.

I make a temporary copy df2

```<code>df2 = df1
</code>```

I initiate a PointCloud() object, add the pointcloud and colours in the usual way

```<code>pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(np.asarray(df2[['x', 'y', 'z']]))
pcd.colors = o3d.utility.Vector3dVector(np.asarray(df2[['red', 'green', 'blue']] / 65535))
</code>```

I run a statistical outlier

```<code>cl, ind = pcd.remove_statistical_outlier(nb_neighbors=nb, std_ratio=ratio)
</code>```

I now want to add a column to the original df marking those that have been filtered out by the statistical outlier algorithm as False and those remaining as True. So I use the ind which is just an index list of the kept points.

```<code>df1['stat_filtered'] = np.where(df1.index.isin(ind), True, False)
</code>```

To my mind this should add True or False to the df1['stat_filtered'] column relative to the index.

I can then repeat the process, this time filtering on the new column to selecting onlt those that are true.

```<code>df2 = df1.loc[(df1['stat_filtered'] == True)]
</code>```

However, open3d works in numpy arrays, so once I have converted the dataframe to a pcd I imagine the original index is lost?

I could do a spatial join to reassign the true values I suppose, but that sounds computationally intensive and with large pointclouds there may be identical points which will cause issues. Is there any way to retain the original index so I can just update the dataframe's column in the manner I outline above?

Body:
I have all my data stored in a geopandas geodataframe, let's call it df1.

I make a temporary copy df2

df2 = df1

I initiate a PointCloud() object, add the pointcloud and colours in the usual way

pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(np.asarray(df2[['x', 'y', 'z']]))
pcd.colors = o3d.utility.Vector3dVector(np.asarray(df2[['red', 'green', 'blue']] / 65535))

I run a statistical outlier

cl, ind = pcd.remove_statistical_outlier(nb_neighbors=nb, std_ratio=ratio)

I now want to add a column to the original df marking those that have been filtered out by the statistical outlier algorithm as False and those remaining as True. So I use the ind which is just an index list of the kept points.

df1['stat_filtered'] = np.where(df1.index.isin(ind), True, False)

To my mind this should add True or False to the df1['stat_filtered'] column relative to the index.

I can then repeat the process, this time filtering on the new column to selecting onlt those that are true.

df2 = df1.loc[(df1['stat_filtered'] == True)]

However, open3d works in numpy arrays, so once I have converted the dataframe to a pcd I imagine the original index is lost?

I could do a spatial join to reassign the true values I suppose, but that sounds computationally intensive and with large pointclouds there may be identical points which will cause issues. Is there any way to retain the original index so I can just update the dataframe's column in the manner I outline above?


问:
webpagetest private install, how to link the server with agent NOT using AWS

Unfortunately, although the webpagetest documentation for installation of private instances here https://docs.webpagetest.org/private-instances/ tells you how to install the server and the client, the information on how to link the two is missing, other than a dead link.

Does anyone know how to do it?

The server has a locations.ini file which looks like this:

```<code>[locations]
1=Test_loc
default=Test_loc

; These are the top-level locations that are listed in the location dropdown
; Each one points to one or more browser configurations

[Test_loc]
1=Test
label=Test Location

; Tese are the browser-specific configurations that match the configurations
; defined in the top-level locations.  Each one of these MUST match the location
; name configured on the test agent (urlblast.ini or wptdriver.ini)

[Test]
browser=Chrome,Firefox
label="Test Location"
</code>```

There is nowhere to add the IP of the agent, or any kind of authentication.

When you install the agent using the auto install script, you supply some basic info like this:

```<code>WPT_SERVER="something.yourdomain.net" WPT_LOCATION="Azure Europe North"  WPT_KEY="somekey" DISABLE_IPV6=y  bash <(curl -s https://raw.githubusercontent.com/WPO-Foundation/wptagent-install/master/debian.sh
</code>```

The params are not undocumented anywhere obvious, but we can assume that:

WPT_Server is the URL of your server instance (which is also localhost in my case as the agent is on the same server as the master)

PTP_LOCATION this is just a text string you make up?  It has no obvious use.

WPT_KEY, this is a big mystery, as nothing seems to use this.

Does anyone have any idea how to configure the master to know about the slave (This doesnt seem to be in locations.ini as nothing in this file relates to the agent, it's just labels), and how to configure the agent to "see" the master?

I took a wild guess at the locations.ini file for my agent of this:

```<code>[locations]
1=Azure Europe North_loc
default=Azure Europe North_loc

; These are the top-level locations that are listed in the location dropdown
; Each one points to one or more browser configurations

[Azure Europe North_loc]
1=Azure Europe North
label=Test Location

; Tese are the browser-specific configurations that match the configurations
; defined in the top-level locations.  Each one of these MUST match the location
; name configured on the test agent (urlblast.ini or wptdriver.ini)

[Azure Europe North]
browser=Chrome,Firefox
label="Azure Europe North"
key=somekey
</code>```

This didnt work unfortunately (no agents listed on the server)

Also, it is undocumented which ports you need to open between agent and server.  Anyone know?

There seems to be no way to tell the agent where the server is, or what ports its on, and no way to tell the server what the IP or dns name is of the agent.

Body:
Unfortunately, although the webpagetest documentation for installation of private instances here https://docs.webpagetest.org/private-instances/ tells you how to install the server and the client, the information on how to link the two is missing, other than a dead link.

Does anyone know how to do it?

The server has a locations.ini file which looks like this:

[locations]
1=Test_loc
default=Test_loc

; These are the top-level locations that are listed in the location dropdown
; Each one points to one or more browser configurations

[Test_loc]
1=Test
label=Test Location

; Tese are the browser-specific configurations that match the configurations
; defined in the top-level locations.  Each one of these MUST match the location
; name configured on the test agent (urlblast.ini or wptdriver.ini)

[Test]
browser=Chrome,Firefox
label="Test Location"

There is nowhere to add the IP of the agent, or any kind of authentication.

When you install the agent using the auto install script, you supply some basic info like this:

WPT_SERVER="something.yourdomain.net" WPT_LOCATION="Azure Europe North"  WPT_KEY="somekey" DISABLE_IPV6=y  bash <(curl -s https://raw.githubusercontent.com/WPO-Foundation/wptagent-install/master/debian.sh

The params are not undocumented anywhere obvious, but we can assume that:

WPT_Server is the URL of your server instance (which is also localhost in my case as the agent is on the same server as the master)

PTP_LOCATION this is just a text string you make up?  It has no obvious use.

WPT_KEY, this is a big mystery, as nothing seems to use this.

Does anyone have any idea how to configure the master to know about the slave (This doesnt seem to be in locations.ini as nothing in this file relates to the agent, it's just labels), and how to configure the agent to "see" the master?

I took a wild guess at the locations.ini file for my agent of this:

[locations]
1=Azure Europe North_loc
default=Azure Europe North_loc

; These are the top-level locations that are listed in the location dropdown
; Each one points to one or more browser configurations

[Azure Europe North_loc]
1=Azure Europe North
label=Test Location

; Tese are the browser-specific configurations that match the configurations
; defined in the top-level locations.  Each one of these MUST match the location
; name configured on the test agent (urlblast.ini or wptdriver.ini)

[Azure Europe North]
browser=Chrome,Firefox
label="Azure Europe North"
key=somekey

This didnt work unfortunately (no agents listed on the server)

Also, it is undocumented which ports you need to open between agent and server.  Anyone know?

There seems to be no way to tell the agent where the server is, or what ports its on, and no way to tell the server what the IP or dns name is of the agent.


问:
How can i use sqlalchemy stream with postgres if it is crashes with NoActiveSQLTransactionError?
```<code>from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine

    async with create_async_engine(my_db_url, isolation_level="AUTOCOMMIT").connect() as conn:
        await conn.begin()
        assert conn.in_transaction() is True
        result = await conn.stream(text(f"select * from existent_table"))
        async for row in result:
            print(f"{row}")
</code>```

This is a literally example from the manual https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#sqlalchemy.ext.asyncio.AsyncConnection.stream

But i am getting this error:

```<code>self = <AdaptedConnection <asyncpg.connection.Connection object at 0x7fa0c86c6260>>
error = NoActiveSQLTransactionError('cursor cannot be created outside of a transaction')

    def _handle_exception(self, error):
        if self._connection.is_closed():
            self._transaction = None
            self._started = False

        if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error):
            exception_mapping = self.dbapi._asyncpg_error_translate

            for super_ in type(error).__mro__:
                if super_ in exception_mapping:
                    translated_error = exception_mapping[super_](
                        "%s: %s" % (type(error), error)
                    )
                    translated_error.pgcode = (
                        translated_error.sqlstate
                    ) = getattr(error, "sqlstate", None)
>                   raise translated_error from error
E                   sqlalchemy.exc.DBAPIError: (sqlalchemy.dialects.postgresql.asyncpg.Error) <class 'asyncpg.exceptions.NoActiveSQLTransactionError'>: cursor cannot be created outside of a transaction
E                   [SQL: select * from table_fca3cc5354ab445cb11cafd79791a9c5]
E                   (Background on this error at: https://sqlalche.me/e/14/dbapi)
</code>```

How is it possible if i already asserded transaction exists? And how to get it work?

If i remove isolation level - error disappears, but stream results is empty. Not sure i should really comment off isolation level.

Body:
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine

    async with create_async_engine(my_db_url, isolation_level="AUTOCOMMIT").connect() as conn:
        await conn.begin()
        assert conn.in_transaction() is True
        result = await conn.stream(text(f"select * from existent_table"))
        async for row in result:
            print(f"{row}")

This is a literally example from the manual https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#sqlalchemy.ext.asyncio.AsyncConnection.stream

But i am getting this error:

self = <AdaptedConnection <asyncpg.connection.Connection object at 0x7fa0c86c6260>>
error = NoActiveSQLTransactionError('cursor cannot be created outside of a transaction')

    def _handle_exception(self, error):
        if self._connection.is_closed():
            self._transaction = None
            self._started = False

        if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error):
            exception_mapping = self.dbapi._asyncpg_error_translate

            for super_ in type(error).__mro__:
                if super_ in exception_mapping:
                    translated_error = exception_mapping[super_](
                        "%s: %s" % (type(error), error)
                    )
                    translated_error.pgcode = (
                        translated_error.sqlstate
                    ) = getattr(error, "sqlstate", None)
>                   raise translated_error from error
E                   sqlalchemy.exc.DBAPIError: (sqlalchemy.dialects.postgresql.asyncpg.Error) <class 'asyncpg.exceptions.NoActiveSQLTransactionError'>: cursor cannot be created outside of a transaction
E                   [SQL: select * from table_fca3cc5354ab445cb11cafd79791a9c5]
E                   (Background on this error at: https://sqlalche.me/e/14/dbapi)

How is it possible if i already asserded transaction exists? And how to get it work?

If i remove isolation level - error disappears, but stream results is empty. Not sure i should really comment off isolation level.


问:
Active Storage loading forever with ImageMagick
I have been trying to add image uploading and displaying feature to my web app, and decided to use Active Storage following this documentation: https://edgeguides.rubyonrails.org/active_storage_overview.html. I know libvips would be faster, but I decided to use ImageMagick because it is widely used. However, after following all the steps, when I visit some pages that display image, I am stuck and the page is loading forever. Terminal displays following message:

```<code>17:44:28 web.1  |   ↳ app/models/product.rb:65:in `block in images_as_thumbnail'
17:44:28 web.1  |   Disk Storage (12.4ms) Downloaded file from key: 53x4a0bwrpa7si019zkg7vqp303j
</code>```

For images_as_thumbnail, the definition is:

```<code>def images_as_thumbnail
    images.map do |image|
        image.variant(resize_to_limit: [150, 150]).processed
    end
end
</code>```

It sometimes work, but it gets stuck pretty often. Does anyone know what might be causing problem here?

Body:
I have been trying to add image uploading and displaying feature to my web app, and decided to use Active Storage following this documentation: https://edgeguides.rubyonrails.org/active_storage_overview.html. I know libvips would be faster, but I decided to use ImageMagick because it is widely used. However, after following all the steps, when I visit some pages that display image, I am stuck and the page is loading forever. Terminal displays following message:

17:44:28 web.1  |   ↳ app/models/product.rb:65:in `block in images_as_thumbnail'
17:44:28 web.1  |   Disk Storage (12.4ms) Downloaded file from key: 53x4a0bwrpa7si019zkg7vqp303j

For images_as_thumbnail, the definition is:

def images_as_thumbnail
    images.map do |image|
        image.variant(resize_to_limit: [150, 150]).processed
    end
end

It sometimes work, but it gets stuck pretty often. Does anyone know what might be causing problem here?


问:
http set-cookie doesn't work cross-origin
I am trying to set a signed cookie on an HTTPS request to a backend server that is on a different domain than the frontend receiving the response. However, after including every 'required' condition for this to work, the cookie still doesn't set.
The attached email is the request.


问:
Docker container can't find an installed node dependency
When I start up my docker container it can't find one of my installed dependencies. I've tried removing my build + node_modules folder, going into my docker container terminal and running yarn list and searching for the dependency there (it is). I've also tried running yarn add <dependency and it says it works, but still throws the error error TS2307: Cannot find module '<dependency>' or its corresponding type declarations.

It works fine locally, just not on docker.

Here is my Dockerfile

```<code>FROM node:16-alpine AS dev

WORKDIR /app
COPY yarn.lock ./
COPY package.json ./
COPY . .
WORKDIR /app/api
RUN yarn install
RUN yarn build

EXPOSE 8000

CMD ["yarn", "dev"]
</code>```

And my docker compose:

```<code>services:
  api:
    profiles: ['api', 'web']
    container_name: slots-api
    stdin_open: true
    build:
      context: ./
      dockerfile: api/Dockerfile
      target: dev
    environment:
      NODE_ENV: development
    ports:
      - 8000:8000
      - 9229:9229 # for debugging
    volumes:
      - ./api:/app/api
      - /app/node_modules/ # do not mount node_modules
      - /app/api/node_modules/ # do not mount node_modules
    depends_on:
      - database
    command: yarn dev
</code>```

Body:
When I start up my docker container it can't find one of my installed dependencies. I've tried removing my build + node_modules folder, going into my docker container terminal and running yarn list and searching for the dependency there (it is). I've also tried running yarn add <dependency and it says it works, but still throws the error error TS2307: Cannot find module '<dependency>' or its corresponding type declarations.

It works fine locally, just not on docker.

Here is my Dockerfile

FROM node:16-alpine AS dev

WORKDIR /app
COPY yarn.lock ./
COPY package.json ./
COPY . .
WORKDIR /app/api
RUN yarn install
RUN yarn build

EXPOSE 8000

CMD ["yarn", "dev"]

And my docker compose:

services:
  api:
    profiles: ['api', 'web']
    container_name: slots-api
    stdin_open: true
    build:
      context: ./
      dockerfile: api/Dockerfile
      target: dev
    environment:
      NODE_ENV: development
    ports:
      - 8000:8000
      - 9229:9229 # for debugging
    volumes:
      - ./api:/app/api
      - /app/node_modules/ # do not mount node_modules
      - /app/api/node_modules/ # do not mount node_modules
    depends_on:
      - database
    command: yarn dev