问:
Making Adapter class work with different items Kotlin
How can i make "ExampleAdapter" a generic class in order to make it work with multiple different items with just passing a specific itemBinding in it's parameters.
Here's a code example:

```<code>class ExampleAdapter (var exampleList: MutableList<Example>): RecyclerView.Adapter<ExampleAdapter.ViewHolder>() {

class ViewHolder(var binding: ExampleItemBinding) : RecyclerView.ViewHolder(binding.root)

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val binding = ExampleItemBinding.inflate(inflater)
    return ViewHolder(binding)
}

@SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {

}

override fun getItemCount(): Int = exampleList.size
</code>```

}

答:
Sealed classes are a good tool to use here.

Create a hierarchy for the data types that you want to include:

```<code>sealed interface AdapterItem
class Foo : AdapterItem
class Bar : AdapterItem
</code>```

Then create matching hierarchy of ViewHolder types:

```<code>sealed class AdapterItemViewHolder(view: View) : RecyclerView.ViewHolder(view)

class FooViewHolder(view: View): AdapterItemViewHolder(view) {
  fun bind(foo: Foo) { TODO() }
}

class BarViewHolder(view: View): AdapterItemViewHolder(view) {
  fun bind(bar: Bar) { TODO() }
}
</code>```

Then your adapter can take in AdapterItem (any type) and you can do exhaustive when expressions to ensure all the types are covered.

```<code>class FooBarAdapter(
  private val data: List<AdapterItem>
) : RecyclerView.Adapter<AdapterItemViewHolder>() {
  override fun getItemCount() = data.size

  override fun getItemViewType(position: Int) = when (data[position]) {
    is Foo -> FOO_ITEM
    is Bar -> BAR_ITEM
  }

  override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
  ): AdapterItemViewHolder {
    return when (viewType) {
      FOO_ITEM -> FooViewHolder(createFooView())
      BAR_ITEM -> BarViewHolder(createBarView())
      else -> throw IllegalStateException("Invalid view type $viewType")
    }
  }

  override fun onBindViewHolder(holder: AdapterItemViewHolder, position: Int) {
    when (val item = data[position]) {
      is Foo -> (holder as FooViewHolder).bind(item)
      is Bar -> (holder as BarViewHolder).bind(item)
    }
  }

  companion object {
    private const val FOO_ITEM = 1
    private const val BAR_ITEM = 2
  }
}
</code>```

Body:
How can i make "ExampleAdapter" a generic class in order to make it work with multiple different items with just passing a specific itemBinding in it's parameters.
Here's a code example:

class ExampleAdapter (var exampleList: MutableList<Example>): RecyclerView.Adapter<ExampleAdapter.ViewHolder>() {

class ViewHolder(var binding: ExampleItemBinding) : RecyclerView.ViewHolder(binding.root)

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val binding = ExampleItemBinding.inflate(inflater)
    return ViewHolder(binding)
}

@SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {

}

override fun getItemCount(): Int = exampleList.size

}

Body:
Sealed classes are a good tool to use here.

Create a hierarchy for the data types that you want to include:

sealed interface AdapterItem
class Foo : AdapterItem
class Bar : AdapterItem

Then create matching hierarchy of ViewHolder types:

sealed class AdapterItemViewHolder(view: View) : RecyclerView.ViewHolder(view)

class FooViewHolder(view: View): AdapterItemViewHolder(view) {
  fun bind(foo: Foo) { TODO() }
}

class BarViewHolder(view: View): AdapterItemViewHolder(view) {
  fun bind(bar: Bar) { TODO() }
}

Then your adapter can take in AdapterItem (any type) and you can do exhaustive when expressions to ensure all the types are covered.

class FooBarAdapter(
  private val data: List<AdapterItem>
) : RecyclerView.Adapter<AdapterItemViewHolder>() {
  override fun getItemCount() = data.size

  override fun getItemViewType(position: Int) = when (data[position]) {
    is Foo -> FOO_ITEM
    is Bar -> BAR_ITEM
  }

  override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
  ): AdapterItemViewHolder {
    return when (viewType) {
      FOO_ITEM -> FooViewHolder(createFooView())
      BAR_ITEM -> BarViewHolder(createBarView())
      else -> throw IllegalStateException("Invalid view type $viewType")
    }
  }

  override fun onBindViewHolder(holder: AdapterItemViewHolder, position: Int) {
    when (val item = data[position]) {
      is Foo -> (holder as FooViewHolder).bind(item)
      is Bar -> (holder as BarViewHolder).bind(item)
    }
  }

  companion object {
    private const val FOO_ITEM = 1
    private const val BAR_ITEM = 2
  }
}


来源: stackexchange

问:
How to capture subdomain in nginx ingress
I want to capture subdomain and rewrite URL with /subdomain, For example bhautik.bhau.tk rewrite to bhau.tk/bhautik.

I also https://github.com/google/re2/wiki/Syntax tried group syntax

Here is my nginx ingress config:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: subdomain
  namespace: subdomain
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    # nginx.ingress.kubernetes.io/rewrite-target: /$sub
    nginx.ingress.kubernetes.io/server-snippet: |
      set $prefix abcd;
      if ($host ~ ^(\w+).bhau\.tk$) {
        // TODO?
      }
    nginx.ingress.kubernetes.io/rewrite-target: /$prefix/$uri
spec:
  rules:
  - host: "*.bhau.tk"
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: subdomain
            port:
              number: 80
```

How do I capture subdomain from $host?

答:
You can try out the</p>
```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/server-snippet: |
        if ($host ~ "bhautik.bhau.tk")
        {
            rewrite ^ https://bhau.tk$host permanent;
        }
  name: test-ingress
spec:
  rules:
  - host: bhau.tk
    http:
      paths:
      - backend:
          serviceName: app-service
          servicePort: 3000
        path: (/|$)(.*)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to capture subdomain and rewrite URL with /subdomain, For example bhautik.bhau.tk rewrite to bhau.tk/bhautik.

I also https://github.com/google/re2/wiki/Syntax tried group syntax

Here is my nginx ingress config:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: subdomain
  namespace: subdomain
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    # nginx.ingress.kubernetes.io/rewrite-target: /$sub
    nginx.ingress.kubernetes.io/server-snippet: |
      set $prefix abcd;
      if ($host ~ ^(\w+).bhau\.tk$) {
        // TODO?
      }
    nginx.ingress.kubernetes.io/rewrite-target: /$prefix/$uri
spec:
  rules:
  - host: "*.bhau.tk"
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: subdomain
            port:
              number: 80

How do I capture subdomain from $host?

Body:
You can try out the

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/server-snippet: |
        if ($host ~ "bhautik.bhau.tk")
        {
            rewrite ^ https://bhau.tk$host permanent;
        }
  name: test-ingress
spec:
  rules:
  - host: bhau.tk
    http:
      paths:
      - backend:
          serviceName: app-service
          servicePort: 3000
        path: (/|$)(.*)


问:
Trying to understand Unreal Engine 4 replication
I'm trying to understand how to call events between client and server. My goal for now is simple. I want to create anything that is interactable for 2 players.

Easiest thing I could think of was cube that is switching color when clicked. So I did create actor based blueprint, checked "Replicates" and AlwaysRelevant to be sure. PlayerController is also replicated and there is no pawn needed.

Color change blueprint:

SM is just static mesh if that is important. As far as I know client have no authority to call multicast events so I wanted to push it through server but it stops there. Called from server works as expected and color itself IS replicated to client, however client cannot change color himself.

What am I missing in this concept? I've watched like 5 videos about replication and I started to think there is something missing which is either obvious for everyone but me or their examples do not need things I do here.

答: You can't have it in PlayerController, it's got to be in a Pawn, or if not, in PlayerState, or it won't get shared to other clients.</p>


问:
Web Development :: VSCode, Live Server Plugin, Firefox -- Browser Always Caching, Not Refreshing
I'm using VSCode, Live Server plugin for HTML5 web development.  When i make a change to my web page then save Live Server should refresh what i see within Firefox.  It does refresh but it is always to the oldest cache of the web page when live server first started up.  I must always tap CTRL-F5 to force a web page refresh within firefox.  The moment i save again within VSCode, the browser display reverts right back to the oldest, first copy.

I've already tried enabling "Disable Cache" within the FF Dev Tools > Networking area.  Didnt help.  I've tried about.config | browser.cache.disk.enable set to false.  Didnt help.

Just wondering if this is normal behavior or if the Live Server plugin (Ritwick Dey) for VSCode is broken.

At the present time

答: Ok it seemsthe problem was i was using a service worker (sw.js).  The browser saw the file, autoloaded it and apparently took full control over caching in the browser -- basically, no matter what i did caching and refreshing was meaningless.  I really need to understand this sw.js thing.</p>


问:
Using a CancelToken with an axios instance
I've read several similar questions, but I'm still struggling to be able to cancel my requests given my code structure.

On clicking one of the following elements I'd like to be able to cancel all other requests except the new one, however it seems to cancel all requests, and then prevents axios making any new ones. I'm new to cancelling tokens, so don't really know what I'm doing wrong here:

```<code>import {cancelTokenSource} from 'API';

let isActiveRequest;

document.body.addEventListener('click', async(e) => {
    const userElement = e.target.closest('.user-element');
    const appElement = e.target.closest('.app-element');

    if(isActiveRequest) {
        cancelTokenSource.cancel();
        isActiveRequest = false;
    }

    if(userElement) {
        isActiveRequest = true;
        try{
            const users = await Admin.getUsers();
            isActiveRequest = false;
            // display users
        } catch(err) { isActiveRequest = false; }
    }
    if(appElement) {
        isActiveRequest = true;
        try{
            const applications = await Admin.getApplications();
            isActiveRequest = false;
            // display applications
        } catch(err) { isActiveRequest = false; }
    }
});
</code>```

API.js

```<code>export const cancelTokenSource = axios.CancelToken.source();

export default axios.create({
    baseURL: 'http://localhost:8080',
    cancelToken: cancelTokenSource.token
});
</code>```

Admin.js

```<code>export default class Admin {

    getUsers({index, limit, orderField, orderDirection}) {
        return API.get('/admin/applicants', { params: { index, limit, orderField, orderDirection } });
    }
    getApplications({index, limit, orderField, orderDirection}) {
        return JRS.get('/admin/applications', { params: { index, limit, orderField, orderDirection} });

    ...
}
</code>```

Thanks

***Update

Thought maybe I need a new cancel token per request (as maybe it's the old token blocking any new requests), so tried this:

API.js

```<code>export let cancelTokenSource;

export default axios.create({
    baseURL: 'http://localhost:8080',
    cancelToken: new axios.CancelToken(c => cancelTokenSource = c),
});
</code>```

main.js

```<code>if(isActiveRequest) {
    cancelTokenSource();
    isActiveRequest = false;
}
</code>```

But no luck. I guess maybe because the instance of axios is the same for each request?

I'm going to try adding the cancel token to the Admin.js functions next

答:
Yup, adding the cancel token to the individual requests, rather than the axios instance worked:

```<code>import {cancelTokenSource} from 'Admin';  // Different

let isActiveRequest;

document.body.addEventListener('click', async(e) => {
    const userElement = e.target.closest('.user-element');
    const appElement = e.target.closest('.app-element');

    if(isActiveRequest) {
        cancelTokenSource();  // Different
        isActiveRequest = false;
    }

    if(userElement) {
        isActiveRequest = true;
        try{
            const users = await Admin.getUsers();
            isActiveRequest = false;
            // display users
        } catch(err) { isActiveRequest = false; }
    }
    if(appElement) {
        isActiveRequest = true;
        try{
            const applications = await Admin.getApplications();
            isActiveRequest = false;
            // display applications
        } catch(err) { isActiveRequest = false; }
    }
});
</code>```

API.js

```<code>// Cancel token removed
export default axios.create({
    baseURL: 'http://localhost:8080',
});
</code>```

Admin.js

```<code>export let cancelTokenSource; // Added from API.js

export default class Admin {

    getUsers({index, limit, orderField, orderDirection}) {
        return API.get('/admin/applicants', {
            params: { index, limit, orderField, orderDirection },
            cancelToken: new axios.CancelToken(c => cancelTokenSource = c)  // Added

        });
    }
    getApplications({index, limit, orderField, orderDirection}) {
        return JRS.get('/admin/applications', {
            params: { index, limit, orderField, orderDirection}
            cancelToken: new axios.CancelToken(c => cancelTokenSource = c)  // Added
        });

    ...
}
</code>```

Body:
I've read several similar questions, but I'm still struggling to be able to cancel my requests given my code structure.

On clicking one of the following elements I'd like to be able to cancel all other requests except the new one, however it seems to cancel all requests, and then prevents axios making any new ones. I'm new to cancelling tokens, so don't really know what I'm doing wrong here:

import {cancelTokenSource} from 'API';

let isActiveRequest;

document.body.addEventListener('click', async(e) => {
    const userElement = e.target.closest('.user-element');
    const appElement = e.target.closest('.app-element');

    if(isActiveRequest) {
        cancelTokenSource.cancel();
        isActiveRequest = false;
    }

    if(userElement) {
        isActiveRequest = true;
        try{
            const users = await Admin.getUsers();
            isActiveRequest = false;
            // display users
        } catch(err) { isActiveRequest = false; }
    }
    if(appElement) {
        isActiveRequest = true;
        try{
            const applications = await Admin.getApplications();
            isActiveRequest = false;
            // display applications
        } catch(err) { isActiveRequest = false; }
    }
});

API.js

export const cancelTokenSource = axios.CancelToken.source();

export default axios.create({
    baseURL: 'http://localhost:8080',
    cancelToken: cancelTokenSource.token
});

Admin.js

export default class Admin {

    getUsers({index, limit, orderField, orderDirection}) {
        return API.get('/admin/applicants', { params: { index, limit, orderField, orderDirection } });
    }
    getApplications({index, limit, orderField, orderDirection}) {
        return JRS.get('/admin/applications', { params: { index, limit, orderField, orderDirection} });

    ...
}

Thanks

***Update

Thought maybe I need a new cancel token per request (as maybe it's the old token blocking any new requests), so tried this:

API.js

export let cancelTokenSource;

export default axios.create({
    baseURL: 'http://localhost:8080',
    cancelToken: new axios.CancelToken(c => cancelTokenSource = c),
});

main.js

if(isActiveRequest) {
    cancelTokenSource();
    isActiveRequest = false;
}

But no luck. I guess maybe because the instance of axios is the same for each request?

I'm going to try adding the cancel token to the Admin.js functions next

Body:
Yup, adding the cancel token to the individual requests, rather than the axios instance worked:

import {cancelTokenSource} from 'Admin';  // Different

let isActiveRequest;

document.body.addEventListener('click', async(e) => {
    const userElement = e.target.closest('.user-element');
    const appElement = e.target.closest('.app-element');

    if(isActiveRequest) {
        cancelTokenSource();  // Different
        isActiveRequest = false;
    }

    if(userElement) {
        isActiveRequest = true;
        try{
            const users = await Admin.getUsers();
            isActiveRequest = false;
            // display users
        } catch(err) { isActiveRequest = false; }
    }
    if(appElement) {
        isActiveRequest = true;
        try{
            const applications = await Admin.getApplications();
            isActiveRequest = false;
            // display applications
        } catch(err) { isActiveRequest = false; }
    }
});

API.js

// Cancel token removed
export default axios.create({
    baseURL: 'http://localhost:8080',
});

Admin.js

export let cancelTokenSource; // Added from API.js

export default class Admin {

    getUsers({index, limit, orderField, orderDirection}) {
        return API.get('/admin/applicants', {
            params: { index, limit, orderField, orderDirection },
            cancelToken: new axios.CancelToken(c => cancelTokenSource = c)  // Added

        });
    }
    getApplications({index, limit, orderField, orderDirection}) {
        return JRS.get('/admin/applications', {
            params: { index, limit, orderField, orderDirection}
            cancelToken: new axios.CancelToken(c => cancelTokenSource = c)  // Added
        });

    ...
}


问:
VBA code to copy and paste rows three times from one worksheet to another
My idea is to get the data that I have on "A4" ("Data" worksheet) and paste it 4 times on "B4" ("Forecast" worksheet). After that, take the data from "A5" and do the same (starting from the first blank cell) until there is no more data on the "A" column. After there is no more data, the process should stop.

How do I tell excel to paste the value in the first blank cell in column B ("Forecast" worksheet)?

```<code>Sub Test()

    Dim wsSource As Worksheet, wsTarget As Worksheet
    Dim i As Integer, k As Integer

    Set wsSource = ThisWorkbook.Worksheets("Data")
    Set wsTarget = ThisWorkbook.Worksheets("Forecast")

    k = wsSource.Range("A4", wsSource.Range("A4").End(xlDown)).Rows.Count

    For i = 1 To k

        wsTarget.Range("B4", "B7").Value = wsSource.Range("A" & 3 + i).Value

    Next

End Sub
</code>```

答:
Copy Repetitions

A Quick Fix

Sub Test()

    Dim wsSource As Worksheet, wsTarget As Worksheet
    Dim sCell As Range, tCell As Range
    Dim i As Long, j As Long, k As Long

    Set wsSource = ThisWorkbook.Worksheets("Data")
    Set wsTarget = ThisWorkbook.Worksheets("Forecast")

    k = wsSource.Range("A4", wsSource.Range("A4").End(xlDown)).Rows.Count

    Set sCell = wsSource.Range("A4")
    Set tCell = wsTarget.Range("B4")

    For i = 1 To k
        For j = 1 To 4
            tCell.Value = sCell.Value
            Set tCell = tCell.Offset(1)
        Next j
        Set sCell = sCell.Offset(1)
    Next i

End Sub
```
<p><strong>My Choice</strong></p>
<pre class="lang-vb prettyprint-override"><code>Sub CopyRepetitions()

    ' Source
    Const sName As String = "Data"
    Const sfCellAddress As String = "A4"
    ' Destination
    Const dName As String = "Forecast"
    Const dfCellAddress As String = "B4"
    Const Repetitions As Long = 4
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Reference the source (one-column) range ('srg').

    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)

    Dim srg As Range
    Dim srCount As Long

    With sws.Range(sfCellAddress)
        Dim lCell As Range: Set lCell = .Resize(sws.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If lCell Is Nothing Then Exit Sub ' no data
        srCount = lCell.Row - .Row + 1
        Set srg = .Resize(srCount)
    End With

    ' Write values from the source range the source array ('sData')

    Dim sData As Variant

    If srCount = 1 Then
        ReDim sData(1 To 1, 1 To 1): sData(1, 1) = srg.Value
    Else
        sData = srg.Value
    End If

    ' Define the destination array ('dData').

    Dim drCount As Long: drCount = srCount * Repetitions
    Dim dData As Variant: ReDim dData(1 To drCount, 1 To 1)

    ' Write the repeating values from the source- to the destination array.

    Dim sr As Long
    Dim rep As Long
    Dim dr As Long

    For sr = 1 To srCount
        For rep = 1 To Repetitions
            dr = dr + 1
            dData(dr, 1) = sData(sr, 1)
        Next rep
    Next sr

    ' Write the values from the destination array to the destination
    ' one-column range and clear the data below.

    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    With dws.Range(dfCellAddress)
        .Resize(drCount).Value = dData
        .Resize(dws.Rows.Count - .Row - drCount + 1).Offset(drCount).Clear
    End With

    ' Inform.
    MsgBox "Repetitions copied.", vbInformation

End Sub
</code>```

Body:
My idea is to get the data that I have on "A4" ("Data" worksheet) and paste it 4 times on "B4" ("Forecast" worksheet). After that, take the data from "A5" and do the same (starting from the first blank cell) until there is no more data on the "A" column. After there is no more data, the process should stop.

How do I tell excel to paste the value in the first blank cell in column B ("Forecast" worksheet)?

Sub Test()

    Dim wsSource As Worksheet, wsTarget As Worksheet
    Dim i As Integer, k As Integer

    Set wsSource = ThisWorkbook.Worksheets("Data")
    Set wsTarget = ThisWorkbook.Worksheets("Forecast")

    k = wsSource.Range("A4", wsSource.Range("A4").End(xlDown)).Rows.Count

    For i = 1 To k

        wsTarget.Range("B4", "B7").Value = wsSource.Range("A" & 3 + i).Value

    Next

End Sub

Body:
Copy Repetitions

A Quick Fix

Sub Test()

    Dim wsSource As Worksheet, wsTarget As Worksheet
    Dim sCell As Range, tCell As Range
    Dim i As Long, j As Long, k As Long

    Set wsSource = ThisWorkbook.Worksheets("Data")
    Set wsTarget = ThisWorkbook.Worksheets("Forecast")

    k = wsSource.Range("A4", wsSource.Range("A4").End(xlDown)).Rows.Count

    Set sCell = wsSource.Range("A4")
    Set tCell = wsTarget.Range("B4")

    For i = 1 To k
        For j = 1 To 4
            tCell.Value = sCell.Value
            Set tCell = tCell.Offset(1)
        Next j
        Set sCell = sCell.Offset(1)
    Next i

End Sub

My Choice

Sub CopyRepetitions()

    ' Source
    Const sName As String = "Data"
    Const sfCellAddress As String = "A4"
    ' Destination
    Const dName As String = "Forecast"
    Const dfCellAddress As String = "B4"
    Const Repetitions As Long = 4
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Reference the source (one-column) range ('srg').

    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)

    Dim srg As Range
    Dim srCount As Long

    With sws.Range(sfCellAddress)
        Dim lCell As Range: Set lCell = .Resize(sws.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If lCell Is Nothing Then Exit Sub ' no data
        srCount = lCell.Row - .Row + 1
        Set srg = .Resize(srCount)
    End With

    ' Write values from the source range the source array ('sData')

    Dim sData As Variant

    If srCount = 1 Then
        ReDim sData(1 To 1, 1 To 1): sData(1, 1) = srg.Value
    Else
        sData = srg.Value
    End If

    ' Define the destination array ('dData').

    Dim drCount As Long: drCount = srCount * Repetitions
    Dim dData As Variant: ReDim dData(1 To drCount, 1 To 1)

    ' Write the repeating values from the source- to the destination array.

    Dim sr As Long
    Dim rep As Long
    Dim dr As Long

    For sr = 1 To srCount
        For rep = 1 To Repetitions
            dr = dr + 1
            dData(dr, 1) = sData(sr, 1)
        Next rep
    Next sr

    ' Write the values from the destination array to the destination
    ' one-column range and clear the data below.

    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    With dws.Range(dfCellAddress)
        .Resize(drCount).Value = dData
        .Resize(dws.Rows.Count - .Row - drCount + 1).Offset(drCount).Clear
    End With

    ' Inform.
    MsgBox "Repetitions copied.", vbInformation

End Sub


问:
3D Object Faces Disappearing in p5.js
I am trying to make a 3D box with a pattern on each side using the following code but when viewed from certain angles, the back faces disappear when looking through the transparent parts of the forward faces.  I was also wondering if it is possible to have a different pattern on each face?  Many thanks in advance!

let r = 10
let a = 0
let c = 20
let angle = 0
let art

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  art = createGraphics(800, 800)

}

function draw() {
  background(0);

  let x = r + c * cos(a)
  let y = r + c * sin(a)

  art.fill(r, a, c)
  art.ellipse(x + 400, y + 400, 10, 10)

  c += 0.2
  a += 1.8

  push()
  texture(art)
  rotateX(angle)
  rotateY(angle)
  rotateZ(angle)
  box(400)

  angle += 0.0003
  pop()

  orbitControl();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { margin: 0; overflow: hidden; }</code>```

```

答:
This happens because in in WebGL, once a pixels is drawn, regardless of the level of level of transparency of that pixel, if another triangle would draw to that same pixel, but at a further depth, it is discarded (I think the alpha information from the original pixel(s) may no longer be available). In order for transparency to work properly in WebGL it is necessary to draw all triangles in depth order (furthest from the camera first). And even then if two triangles intersect there will still be problems.

In your case because you have many pixels that are completely transparent and others that are completely opaque there is another solution: a custom fragment shader that discards pixels if the texture alpha is below some threshold.

const vert = `
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;

attribute vec3 aPosition;
attribute vec2 aTexCoord;

varying vec2 vTexCoord;

void main() {
  vTexCoord = aTexCoord;

  vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);
  gl_Position = uProjectionMatrix * viewModelPosition;
}`;

const frag = `
precision mediump float;

// ranges from 0..1
varying vec2 vTexCoord;

uniform sampler2D uSampler;

void main() {
  vec4 tex = texture2D(uSampler, vTexCoord);
  if (tex.a < 0.05) {
    discard;
  }

  gl_FragColor = tex;
}`;

let r = 10
let a = 0
let c = 20
let angle = 0
let art
let discardShader;

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  art = createGraphics(800, 800)
  discardShader = createShader(vert, frag)
  textureMode(NORMAL)
}

function draw() {
  background(0);

  let x = r + c * cos(a)
  let y = r + c * sin(a)

  art.fill(r, a, c)
  art.ellipse(x + 400, y + 400, 10, 10)

  c += 0.2
  a += 1.8

  push()
  noStroke()
  texture(art)
  shader(discardShader)
  rotateX(angle)
  rotateY(angle)
  rotateZ(angle)
  box(400)

  angle += 0.0003
  pop()

  orbitControl();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
  overflow: hidden;
}</code>```

```

Note #1: It is important that you use p5.js v1.4.1 for this to work because prior to that there was a bug that prevented user shaders from working with textures.

Note #2: If your texture had partial opacity then this would not work and instead you would want to render each plane of the box separately and in the correct order (farthest from the camera first).

Title: 3D Object Faces Disappearing in p5.js

Body:
I am trying to make a 3D box with a pattern on each side using the following code but when viewed from certain angles, the back faces disappear when looking through the transparent parts of the forward faces.  I was also wondering if it is possible to have a different pattern on each face?  Many thanks in advance!

let r = 10
let a = 0
let c = 20
let angle = 0
let art

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  art = createGraphics(800, 800)

}

function draw() {
  background(0);

  let x = r + c * cos(a)
  let y = r + c * sin(a)

  art.fill(r, a, c)
  art.ellipse(x + 400, y + 400, 10, 10)

  c += 0.2
  a += 1.8

  push()
  texture(art)
  rotateX(angle)
  rotateY(angle)
  rotateZ(angle)
  box(400)

  angle += 0.0003
  pop()

  orbitControl();
}

html, body { margin: 0; overflow: hidden; }

Body:
This happens because in in WebGL, once a pixels is drawn, regardless of the level of level of transparency of that pixel, if another triangle would draw to that same pixel, but at a further depth, it is discarded (I think the alpha information from the original pixel(s) may no longer be available). In order for transparency to work properly in WebGL it is necessary to draw all triangles in depth order (furthest from the camera first). And even then if two triangles intersect there will still be problems.

In your case because you have many pixels that are completely transparent and others that are completely opaque there is another solution: a custom fragment shader that discards pixels if the texture alpha is below some threshold.

const vert = `
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;

attribute vec3 aPosition;
attribute vec2 aTexCoord;

varying vec2 vTexCoord;

void main() {
  vTexCoord = aTexCoord;

  vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);
  gl_Position = uProjectionMatrix * viewModelPosition;
}`;

const frag = `
precision mediump float;

// ranges from 0..1
varying vec2 vTexCoord;

uniform sampler2D uSampler;

void main() {
  vec4 tex = texture2D(uSampler, vTexCoord);
  if (tex.a < 0.05) {
    discard;
  }

  gl_FragColor = tex;
}`;

let r = 10
let a = 0
let c = 20
let angle = 0
let art
let discardShader;

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  art = createGraphics(800, 800)
  discardShader = createShader(vert, frag)
  textureMode(NORMAL)
}

function draw() {
  background(0);

  let x = r + c * cos(a)
  let y = r + c * sin(a)

  art.fill(r, a, c)
  art.ellipse(x + 400, y + 400, 10, 10)

  c += 0.2
  a += 1.8

  push()
  noStroke()
  texture(art)
  shader(discardShader)
  rotateX(angle)
  rotateY(angle)
  rotateZ(angle)
  box(400)

  angle += 0.0003
  pop()

  orbitControl();
}

html,
body {
  margin: 0;
  overflow: hidden;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>

Note #1: It is important that you use p5.js v1.4.1 for this to work because prior to that there was a bug that prevented user shaders from working with textures.

Note #2: If your texture had partial opacity then this would not work and instead you would want to render each plane of the box separately and in the correct order (farthest from the camera first).


问:
I cannot find the error TypeError: Cannot read properties of undefined (reading 'name')
I'm new to react and I need some help when I´m trying to bring some "products" from an array of objects that I have in one file of my react app called "products.js".

The thing is that I am able to draw the products within the array in the Home Screen. However when I try to draw those products on my details products page (this one is a page where I can see an individual product details) "ProductDetails.js" I'm getting the error (regardless if I try to bring product.name or product.price or whatever):

TypeError: Cannot read properties of undefined (reading 'name')

In order for you to have an idea about what I'm talking about I will share to you some snippets from my code to put you in context. I will Start with the exact error message and I will finish with a Glance of My Project Dependencies.

Error Message

```<code>TypeError: Cannot read properties of undefined (reading 'name')
ProductDetails
C:/Users/jjimennz/OneDrive/Desktop/eCommerce MERN Stack/Sprint1/frontend/src/views/ProductDetails.js:19

 16 | const ProductDetails = ({ match }) => {
  17 |   const product = products.find((p) => p._id === match.params.id);
  18 |
> 19 |   return <div>{product.name}</div>;
  20 | };
  21 |
  22 | export default ProductDetails;
</code>```

this is the View I'm having TROUBLE with and is not only with the "product.name" I happens with anything "product.price" "product.image"...  this is the details product screen, the view that is supposed to show me each individual product with its details on its own page, which I called  "ProductDetails.js"

```<code>import React from "react";
import products from "../products";

const ProductDetails = ({ match }) => {
  const product = products.find((p) => p._id === match.params.id);

  return <div>{product.name}</div>;
};

export default ProductDetails;
</code>```

This is the File  with the array containing the products I want to draw on the above product details screen. this file is the one called  "products.js":

```<code>const products = [
  {
    _id: 1,
    name: "Nemeziz 19.4",
    image:
      "https://assets.adidas.com/images/w_600,f_auto,q_auto/75987ad2e31644d59d24ab3000fce766_9366/Botines_Nemeziz_19.4_Pasto_Sintetico_Verde_FV3317_41_detail.jpg",
    description: "Breve descripcion de los zapatos",
    brand: "Adidas",
    category: "Zapatos",
    price: 89.99,
    countInStock: 20,
    rating: 4.5,
    numReviews: 14,
  },
  {
    _id: 2,
    name: "Adidas Ace",
    image: "https://www.sports-ws.com/img/item/F163AD0/F163AD0654.jpg",
    description: "Breve descripcion de los zapatos",
    brand: "Adidas",
    category: "Zapatos",
    price: 149.99,
    countInStock: 8,
    rating: 4.5,
    numReviews: 15,
  },
];

export default products
</code>```

This is the view for the Home Screen, where I show all of the products within the above array, this one works just fine and draws every product within the array on the screen. this one is called "HomeScreen.js"

```<code>import React from "react";
import { Row, Col } from "react-bootstrap";
import Product from "../components/Product";
import products from "../products";

const HomeScreen = () => {
  return (
    <>
      <h1>Latest Products</h1>
      <Row>
        {products.map((product) => (
          <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
            <Product product={product} />
          </Col>
        ))}
      </Row>
    </>
  );
};

export default HomeScreen;
</code>```

This is the Product component, this one basically draws each individual product within the array on the above Home Screen view. This one as the above Home Screen also works just fine, it brings me the product with its name, its price and image. I did call this component "Product.js"*

```<code>import React from "react";
import { Link } from "react-router-dom";
import { Card } from "react-bootstrap";
import Rating from "./Rating";

const Product = ({ product }) => {
  return (
    <Card className="my-3 p-3 rounded">
      <Link to={`/product/${product._id}`}>
        <Card.Img src={product.image} variant="top" />
      </Link>
      <Card.Body>
        <Link to={`/product/${product._id}`}>
          <Card.Title as="div">
            <strong>{product.name}</strong>
          </Card.Title>
        </Link>

        <Card.Text as="div">
          <Rating
            value={product.rating}
            text={`${product.numReviews} reviews`}
          />
        </Card.Text>
        <Card.Text as="h3">${product.price}</Card.Text>
      </Card.Body>
    </Card>
  );
};

export default Product;
</code>```

"App.js" file, so you have a better understanding about what is going on on my project

```<code>import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./views/HomeScreen";
import ProductDetails from "./views/ProductDetails";

function App() {
  return (
    <Router>
      <Header />
      <main className="py-3">
        <Container>
          <Route path="/" component={HomeScreen} exact />
          <Route path="/product/:id" component={ProductDetails} />
        </Container>
      </main>
      <Footer />
    </Router>
  );
}

export default App;
</code>```

This is My "package.json" file with dependencies in my project, just in case It helps to help me with this

```<code>{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0",
    "react-dom": "^17.0.2",
    "react-router-bootstrap": "^0.25.0",
    "react-router-dom": "^5.3.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

Here you have an Screenshot of the error message on the products details view

Here you have an Screenshot of the page that works the Home Screen

答:
```<code>Try this: Make changes in below two files only.

For ProductDetails.js

import React from "react";
import products from "../products";
import { useParams } from 'react-router-dom'

const ProductDetails = () => {
    const {id} = useParams()
    const product = products.find(p=>p._id === id)
    return <div>{product.name}</div>;

}

export default ProductDetails;
</code>```

for App.js

```<code>import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./views/HomeScreen";
import ProductDetails from "./views/ProductDetails";
function App() {
      return (
        <Router>
          <Header/>
          <main className='py-3'>
            <Container>
              <Routes>
                <Route path ='/' element={<HomeScreen/>} exact />
                <Route path ='/product/:id' element={<ProductDetails/>}/>
              </Routes>
            </Container>
          </main>
          <Footer/>
        </Router>
      );
    }

    export default App;
</code>```

Body:
I'm new to react and I need some help when I´m trying to bring some "products" from an array of objects that I have in one file of my react app called "products.js".

The thing is that I am able to draw the products within the array in the Home Screen. However when I try to draw those products on my details products page (this one is a page where I can see an individual product details) "ProductDetails.js" I'm getting the error (regardless if I try to bring product.name or product.price or whatever):

TypeError: Cannot read properties of undefined (reading 'name')

In order for you to have an idea about what I'm talking about I will share to you some snippets from my code to put you in context. I will Start with the exact error message and I will finish with a Glance of My Project Dependencies.

Error Message

TypeError: Cannot read properties of undefined (reading 'name')
ProductDetails
C:/Users/jjimennz/OneDrive/Desktop/eCommerce MERN Stack/Sprint1/frontend/src/views/ProductDetails.js:19

 16 | const ProductDetails = ({ match }) => {
  17 |   const product = products.find((p) => p._id === match.params.id);
  18 |
> 19 |   return
{product.name}
;
  20 | };
  21 |
  22 | export default ProductDetails;

this is the View I'm having TROUBLE with and is not only with the "product.name" I happens with anything "product.price" "product.image"...  this is the details product screen, the view that is supposed to show me each individual product with its details on its own page, which I called  "ProductDetails.js"

import React from "react";
import products from "../products";

const ProductDetails = ({ match }) => {
  const product = products.find((p) => p._id === match.params.id);

  return
{product.name}
;
};

export default ProductDetails;

This is the File  with the array containing the products I want to draw on the above product details screen. this file is the one called  "products.js":

const products = [
  {
    _id: 1,
    name: "Nemeziz 19.4",
    image:
      "https://assets.adidas.com/images/w_600,f_auto,q_auto/75987ad2e31644d59d24ab3000fce766_9366/Botines_Nemeziz_19.4_Pasto_Sintetico_Verde_FV3317_41_detail.jpg",
    description: "Breve descripcion de los zapatos",
    brand: "Adidas",
    category: "Zapatos",
    price: 89.99,
    countInStock: 20,
    rating: 4.5,
    numReviews: 14,
  },
  {
    _id: 2,
    name: "Adidas Ace",
    image: "https://www.sports-ws.com/img/item/F163AD0/F163AD0654.jpg",
    description: "Breve descripcion de los zapatos",
    brand: "Adidas",
    category: "Zapatos",
    price: 149.99,
    countInStock: 8,
    rating: 4.5,
    numReviews: 15,
  },
];

export default products

This is the view for the Home Screen, where I show all of the products within the above array, this one works just fine and draws every product within the array on the screen. this one is called "HomeScreen.js"

import React from "react";
import { Row, Col } from "react-bootstrap";
import Product from "../components/Product";
import products from "../products";

const HomeScreen = () => {
  return (
    <>

Latest Products

      <Row>
        {products.map((product) => (
          <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
            <Product product={product} />
          </Col>
        ))}
      </Row>
    </>
  );
};

export default HomeScreen;

This is the Product component, this one basically draws each individual product within the array on the above Home Screen view. This one as the above Home Screen also works just fine, it brings me the product with its name, its price and image. I did call this component "Product.js"*

import React from "react";
import { Link } from "react-router-dom";
import { Card } from "react-bootstrap";
import Rating from "./Rating";

const Product = ({ product }) => {
  return (
    <Card className="my-3 p-3 rounded">
      <Link to={`/product/${product._id}`}>
        <Card.Img src={product.image} variant="top" />
      </Link>
      <Card.Body>
        <Link to={`/product/${product._id}`}>
          <Card.Title as="div">
            {product.name}
          </Card.Title>
        </Link>

        <Card.Text as="div">
          <Rating
            value={product.rating}
            text={`${product.numReviews} reviews`}
          />
        </Card.Text>
        <Card.Text as="h3">${product.price}</Card.Text>
      </Card.Body>
    </Card>
  );
};

export default Product;

"App.js" file, so you have a better understanding about what is going on on my project

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./views/HomeScreen";
import ProductDetails from "./views/ProductDetails";

function App() {
  return (
    <Router>

        <Container>
          <Route path="/" component={HomeScreen} exact />
          <Route path="/product/:id" component={ProductDetails} />
        </Container>

    </Router>
  );
}

export default App;

This is My "package.json" file with dependencies in my project, just in case It helps to help me with this

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0",
    "react-dom": "^17.0.2",
    "react-router-bootstrap": "^0.25.0",
    "react-router-dom": "^5.3.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Here you have an Screenshot of the error message on the products details view

Here you have an Screenshot of the page that works the Home Screen

Body:
Try this: Make changes in below two files only.

For ProductDetails.js

import React from "react";
import products from "../products";
import { useParams } from 'react-router-dom'

const ProductDetails = () => {
    const {id} = useParams()
    const product = products.find(p=>p._id === id)
    return <div>{product.name}</div>;

}

export default ProductDetails;

for App.js

import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./views/HomeScreen";
import ProductDetails from "./views/ProductDetails";
function App() {
      return (
        <Router>
          <Header/>
          <main className='py-3'>
            <Container>
              <Routes>
                <Route path ='/' element={<HomeScreen/>} exact />
                <Route path ='/product/:id' element={<ProductDetails/>}/>
              </Routes>
            </Container>
          </main>
          <Footer/>
        </Router>
      );
    }

    export default App;


问:
Data truncation: Data too long for column 'column_name' at row 1
Spring-JPA wont save my entity because of this error:

```<code>Caused by: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'cryptocoin' at row 1
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:104)
</code>```

But my MySQL column has more than enough VARCHAR LENGTH to actually handle the input.
For example the input was "CRYPTO ENTRY" and the LENGTH was

```<code> `cryptocoin`  varchar(25) DEFAULT NULL,
</code>```

So you cant tell me it's "too long".
Im using MySQL Workbench 8.0.16.

However when I remove the space between and insert it like this "CRYPTOENTRY" , Spring-JPA saves it.

Summary:

"CRYPTO ENTRY" (white space between) wont save.
"CRYPTOENTRY" (no white space between) will save.

Anyone have a fix for this bug?

答:
Error message clearly states that there is problem with column column_name and not cryptocoin

```<code>Data too long for column 'column_name' at row 1
</code>```

Please check the length of column_name column and also validate the input for this column.

Body:
Spring-JPA wont save my entity because of this error:

Caused by: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'cryptocoin' at row 1
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:104)

But my MySQL column has more than enough VARCHAR LENGTH to actually handle the input.
For example the input was "CRYPTO ENTRY" and the LENGTH was

 `cryptocoin`  varchar(25) DEFAULT NULL,

So you cant tell me it's "too long".
Im using MySQL Workbench 8.0.16.

However when I remove the space between and insert it like this "CRYPTOENTRY" , Spring-JPA saves it.

Summary:

"CRYPTO ENTRY" (white space between) wont save.
"CRYPTOENTRY" (no white space between) will save.

Anyone have a fix for this bug?

Body:
Error message clearly states that there is problem with column column_name and not cryptocoin

Data too long for column 'column_name' at row 1

Please check the length of column_name column and also validate the input for this column.


问:
How can I pass a function to the child component?
I have this component with a modal for confirmation when deleting an item. How can I pass the function to the child component so that once I click the button Agree, it will trigger this function for delete.

The function to delete an item:

```<code> const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id);
    await deleteDoc(productDoc);
  };
</code>```

The Dialog:

```<code> <Modal
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        handleClose={handleClose}
      />
</code>```

The Reusable component:

```<code>import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;
</code>```

答:
Update the reusable component to accept an onConfirm prop and pass deleteProduct in as that argument. I've changed handleClose to onClose here for consistency.</p>
```<code><Modal
    title="Confirmation"
    subtitle={sample}
    isOpen={isOpen}
    onClose={handleClose}
    onConfirm={() => deleteProduct(id)}
/>
</code>```
```<code>// ...
const Modal = ({ title, subtitle, children, isOpen, onClose, onConfirm }) => {
    const handleConfirm = () => {
        alert("You Agreed!");
        onConfirm();
        onClose();
    };
// ...
</code>```

Body:
I have this component with a modal for confirmation when deleting an item. How can I pass the function to the child component so that once I click the button Agree, it will trigger this function for delete.

The function to delete an item:

 const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id);
    await deleteDoc(productDoc);
  };

The Dialog:

 <Modal
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        handleClose={handleClose}
      />

The Reusable component:

import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;

Body:
Update the reusable component to accept an onConfirm prop and pass deleteProduct in as that argument. I've changed handleClose to onClose here for consistency.

<Modal
    title="Confirmation"
    subtitle={sample}
    isOpen={isOpen}
    onClose={handleClose}
    onConfirm={() => deleteProduct(id)}
/>

// ...
const Modal = ({ title, subtitle, children, isOpen, onClose, onConfirm }) => {
    const handleConfirm = () => {
        alert("You Agreed!");
        onConfirm();
        onClose();
    };
// ...


问:
Keep rotation metadata with sharp node.js
I am working on an app that uses sharp for processing photos.
Currently, when we resize and then write to buffer an image with sharp resize and toBuffer, by default the two of them wipe the EXIF data. We want to remove all metadata except for orientation (if it exists).

I've read sharp's documentation and withMetadata seems to be the candidate to achieve what I want, the problem is that withMetadata preserves all metadata and I just want the orientation of the original image.

The original line of code is

await this.sharpInstance.resize(maxDimension, maxDimension).max().toBuffer()

I think that what I want is something like

await this.sharpInstance.withMetadata().resize(maxDimension, maxDimension).max().withMetadata().toBuffer()

but only for orientation metadata.

I would really appreciated some help to solve this. Thanks very much!

答:
A workaround for those not specifically interested in keeping the file's original rotation plus rotation metadata: Rotate the image so that the file has no metadata, but the rotation is correct.

To do this, it is not necessary to read the metadata, if you call the rotate() method without parameters, it will look up the information in the metadata and perform the appropriate rotation.


问:
Get value from ArrayList object in Java?
I know this is a quite basic question, but after reading some SO posts and google I couldn't understand the issue well, so.

I have a map object data, a System.out.println(data) shows me something like the following on the console:

```<code>{data=[{engine=engine1, keyword=keyword1, url=url1}, {engine=engine2, keyword=keyword2, url=url2}]}
</code>```

Also, a data shows me LinkedHashMap@11 size=1 on the console.

Now I wanted to have the first "engine" key value of the first array of "data", aka engine1.

Before that I tried to obtain the first of the array, so I tried the following, but I get errors.

```<code>data.get("data")[1]
Cannot evaluate because of compilation error(s): The type of the expression must be an array type but it resolved to Object.

data.get("data").get(1)
Cannot evaluate because of compilation error(s): The method get(int) is undefined for the type Object.
</code>```

How can I obtain the "engine1" value from "data"? Thanks for your help.

edit:

The code around it is as shown below.
data is declared by Map<String, Object> data.

```<code>import org.yaml.snakeyaml.Yaml;

~~

InputStream inputStream = new FileInputStream(new File("student.yml"));

Yaml yaml = new Yaml();
Map<String, Object> data = yaml.load(inputStream);
System.out.println(data);
</code>```

(not sure you need this info but just in case, "student.yml" file is as shown below)

data:
  - engine: engine1
    keyword: keyword1
    url: url1
  - engine: engine2
    keyword: keyword2
    url: url2
```

答:
Updating answer post question edit;
Please find below, the solution you want;</p>
```<code>import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class YamlParser {

    public static void main(String[] args) throws FileNotFoundException {

        InputStream inputStream = new FileInputStream(new File("src/main/resources/student.yml"));

        Yaml yaml = new Yaml();
        Map<String, Object> data = yaml.load(inputStream);
        System.out.println(data); // Prints full map
        List<Map<String,String>> eng = (List<Map<String,String>>) data.get("data"); //Casting object to List
        System.out.println(eng.get(0).get("engine")); // Prints the value : engine1
    }
}
</code>```

Body:
I know this is a quite basic question, but after reading some SO posts and google I couldn't understand the issue well, so.

I have a map object data, a System.out.println(data) shows me something like the following on the console:

{data=[{engine=engine1, keyword=keyword1, url=url1}, {engine=engine2, keyword=keyword2, url=url2}]}

Also, a data shows me LinkedHashMap@11 size=1 on the console.

Now I wanted to have the first "engine" key value of the first array of "data", aka engine1.

Before that I tried to obtain the first of the array, so I tried the following, but I get errors.

data.get("data")[1]
Cannot evaluate because of compilation error(s): The type of the expression must be an array type but it resolved to Object.

data.get("data").get(1)
Cannot evaluate because of compilation error(s): The method get(int) is undefined for the type Object.

How can I obtain the "engine1" value from "data"? Thanks for your help.

edit:

The code around it is as shown below.
data is declared by Map<String, Object> data.

import org.yaml.snakeyaml.Yaml;

~~

InputStream inputStream = new FileInputStream(new File("student.yml"));

Yaml yaml = new Yaml();
Map<String, Object> data = yaml.load(inputStream);
System.out.println(data);

(not sure you need this info but just in case, "student.yml" file is as shown below)

data:
  - engine: engine1
    keyword: keyword1
    url: url1
  - engine: engine2
    keyword: keyword2
    url: url2

Body:
Updating answer post question edit;
Please find below, the solution you want;

import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class YamlParser {

    public static void main(String[] args) throws FileNotFoundException {

        InputStream inputStream = new FileInputStream(new File("src/main/resources/student.yml"));

        Yaml yaml = new Yaml();
        Map<String, Object> data = yaml.load(inputStream);
        System.out.println(data); // Prints full map
        List<Map<String,String>> eng = (List<Map<String,String>>) data.get("data"); //Casting object to List
        System.out.println(eng.get(0).get("engine")); // Prints the value : engine1
    }
}


问:
C# - Use of unassigned local variable that has already been defined
I have declared the boolean variable "activated" outside of my for loop, I am changing its value inside the for loop, and when I am trying to use it outside of my loop next to the return statement, it says that it is unassigned. Any ideas?

```<code>private bool validityCheck()
    {
        char[] invalidCharacters = { '*', '\'', '.', ';', ':', ',' };

        bool activated;

        for (int i = 0; i < invalidCharacters.Length; i++)
        {
            activated = false;
            if (textBox1.Text.Contains(invalidCharacters[i]))
            {
                ErrorHandling(45, "Fields contain invalid characters", false);
                textBox1.BackColor = Color.Red;
                activated = true;
            }

            if (textBox2.Text.Contains(invalidCharacters[i]))
            {
                if (activated)
                    ErrorHandling(45, "Fields contain invalid characters", false);
                textBox2.BackColor = Color.Red;
            }
        }

        return activated;
    }
</code>```

I definitely expect that to happen if I simply remove for:

```<code>private bool validityCheck()
{
    bool activated;
    return activated;
}

</code>```

But since the loop will always have at least one iteration I expect compiler to be smart enough to figure that out and understand that actived is assigned before code leaves the loop. (I've heard of term "definite assignment" possibly related to this, but C# spec is too hard for me to parse yet)

答:
The Microsoft documentation for error CS0165 Use of unassigned local variable 'activated' states

This error is generated when the compiler encounters a construct that
might result in the use of an unassigned variable, even if your
particular code does not. This avoids the necessity of overly complex
rules for definite assignment.

The error exists to relieve the compiler of the task of determining that a value has been assigned when it is in a loop (something happens when it is inside the body of an if statement.)

The easiest way of avoiding the error is to assign a value to the variable before the loop.

Body:
I have declared the boolean variable "activated" outside of my for loop, I am changing its value inside the for loop, and when I am trying to use it outside of my loop next to the return statement, it says that it is unassigned. Any ideas?

private bool validityCheck()
    {
        char[] invalidCharacters = { '*', '\'', '.', ';', ':', ',' };

        bool activated;

        for (int i = 0; i < invalidCharacters.Length; i++)
        {
            activated = false;
            if (textBox1.Text.Contains(invalidCharacters[i]))
            {
                ErrorHandling(45, "Fields contain invalid characters", false);
                textBox1.BackColor = Color.Red;
                activated = true;
            }

            if (textBox2.Text.Contains(invalidCharacters[i]))
            {
                if (activated)
                    ErrorHandling(45, "Fields contain invalid characters", false);
                textBox2.BackColor = Color.Red;
            }
        }

        return activated;
    }

I definitely expect that to happen if I simply remove for:

private bool validityCheck()
{
    bool activated;
    return activated;
}

But since the loop will always have at least one iteration I expect compiler to be smart enough to figure that out and understand that actived is assigned before code leaves the loop. (I've heard of term "definite assignment" possibly related to this, but C# spec is too hard for me to parse yet)


问:
Why I get error when try build image in docker?
I want to make an image in docker. My app run in nodejs and use Mysql. When I build, it's error like this

```<code>todo-skyshi@1.0.0 start /todo-skyshi
#11 1.831 > node server.js
#11 1.831
#11 2.247 /todo-skyshi/config/database/dbConn.js:4
#11 2.247 const db = new Sequelize(DB_NAME, DB_USERNAME,DB_PASSWORD, {
#11 2.247                          ^
#11 2.247
#11 2.247 ReferenceError: DB_NAME is not defined
#11 2.247     at Object.<anonymous> (/todo-skyshi/config/database/dbConn.js:4:26)
#11 2.247     at Module._compile (internal/modules/cjs/loader.js:999:30)
#11 2.247     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
#11 2.247     at Module.load (internal/modules/cjs/loader.js:863:32)
#11 2.247     at Function.Module._load (internal/modules/cjs/loader.js:708:14)
#11 2.247     at Module.require (internal/modules/cjs/loader.js:887:19)
#11 2.247     at require (internal/modules/cjs/helpers.js:74:18)
#11 2.247     at Object.<anonymous> (/todo-skyshi/config/model/activity.js:2:12)
#11 2.247     at Module._compile (internal/modules/cjs/loader.js:999:30)
#11 2.247     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
#11 2.261 npm ERR! code ELIFECYCLE
#11 2.264 npm ERR! errno 1
#11 2.271 npm ERR! todo-skyshi@1.0.0 start: `node server.js`
#11 2.271 npm ERR! Exit status 1
#11 2.271 npm ERR!
#11 2.271 npm ERR! Failed at the todo-skyshi@1.0.0 start script.
#11 2.272 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
#11 2.336
#11 2.337 npm ERR! A complete log of this run can be found in:
#11 2.337 npm ERR!     /root/.npm/_logs/2022-02-13T02_20_56_653Z-debug.log
------
executor failed running [npm start]: exit code: 1
</code>```

It's like the env on my DB params, how to build image in docker that can read env when I want to run with this command ?

```<code>docker run -e MYSQL_HOST=172.17.0.1 -e MYSQL_USER=xxxx -e MYSQL_PASWORD=xxxx -e MYSQL_DBNAME=todo -p 8090:3030 agamtheos/todo-skyshi
</code>```

this is my Dockerfile :

```<code>FROM node:12-alpine

RUN apk update

RUN mkdir /todo-skyshi
ADD . /todo-skyshi
WORKDIR /todo-skyshi

RUN npm update
RUN ["npm", "start"]
</code>```

Appreciate for any answer

答:
ReferenceError: DB_NAME is not defined
#11 2.247     at Object. (/todo-skyshi/config/database/dbConn.js:4:26).

Abobe error clearly says that variables you are trying to access are not defined.

Env variables name passed in docker run command are different than used in code.
DB_NAME, DB_USERNAME,DB_PASSWORD.
For example

DB_NAME  can be accessed as  process.env.MYSQL_DBNAME and so other env variables.

Body:
I want to make an image in docker. My app run in nodejs and use Mysql. When I build, it's error like this

todo-skyshi@1.0.0 start /todo-skyshi
#11 1.831 > node server.js
#11 1.831
#11 2.247 /todo-skyshi/config/database/dbConn.js:4
#11 2.247 const db = new Sequelize(DB_NAME, DB_USERNAME,DB_PASSWORD, {
#11 2.247                          ^
#11 2.247
#11 2.247 ReferenceError: DB_NAME is not defined
#11 2.247     at Object.<anonymous> (/todo-skyshi/config/database/dbConn.js:4:26)
#11 2.247     at Module._compile (internal/modules/cjs/loader.js:999:30)
#11 2.247     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
#11 2.247     at Module.load (internal/modules/cjs/loader.js:863:32)
#11 2.247     at Function.Module._load (internal/modules/cjs/loader.js:708:14)
#11 2.247     at Module.require (internal/modules/cjs/loader.js:887:19)
#11 2.247     at require (internal/modules/cjs/helpers.js:74:18)
#11 2.247     at Object.<anonymous> (/todo-skyshi/config/model/activity.js:2:12)
#11 2.247     at Module._compile (internal/modules/cjs/loader.js:999:30)
#11 2.247     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
#11 2.261 npm ERR! code ELIFECYCLE
#11 2.264 npm ERR! errno 1
#11 2.271 npm ERR! todo-skyshi@1.0.0 start: `node server.js`
#11 2.271 npm ERR! Exit status 1
#11 2.271 npm ERR!
#11 2.271 npm ERR! Failed at the todo-skyshi@1.0.0 start script.
#11 2.272 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
#11 2.336
#11 2.337 npm ERR! A complete log of this run can be found in:
#11 2.337 npm ERR!     /root/.npm/_logs/2022-02-13T02_20_56_653Z-debug.log
------
executor failed running [npm start]: exit code: 1

It's like the env on my DB params, how to build image in docker that can read env when I want to run with this command ?

docker run -e MYSQL_HOST=172.17.0.1 -e MYSQL_USER=xxxx -e MYSQL_PASWORD=xxxx -e MYSQL_DBNAME=todo -p 8090:3030 agamtheos/todo-skyshi

this is my Dockerfile :

FROM node:12-alpine

RUN apk update

RUN mkdir /todo-skyshi
ADD . /todo-skyshi
WORKDIR /todo-skyshi

RUN npm update
RUN ["npm", "start"]

Appreciate for any answer


答:
It would be preferable for you to provide a bit more information about the desired output, but it looks like you want a percent change between the end of months for consecutive years.

You can sort the EOM column if it isn't already sorted, then perform a groupby on the month and calculate the percent change. Thanks to @mozway for suggesting the use of a join so that the groupby only needs to be performed once

For example:

```<code>df = pd.DataFrame({'EOM':['1/31/2021','1/31/2022','1/31/2023','2/28/2021','2/28/2022','2/28/2023'],'Nike':[100,110,132,100,120,144],'Adidas':[80,80,88,90,90,99]})
df.sort_values(by='EOM', inplace=True)
df['EOM'] = pd.to_datetime(df['EOM'])
df['month'] = df['EOM'].dt.month

df = df.join(df.groupby("month")[['Nike','Adidas']].transform('pct_change')*100, rsuffix="_pct_change")
</code>```

Result:

```<code>>>> df
         EOM  Nike  Adidas  month  Nike_pct_change  Adidas_pct_change
0 2021-01-31   100      80      1              NaN                NaN
1 2022-01-31   110      80      1             10.0                0.0
2 2023-01-31   132      88      1             20.0               10.0
3 2021-02-28   100      90      2              NaN                NaN
4 2022-02-28   120      90      2             20.0                0.0
5 2023-02-28   144      99      2             20.0               10.0
</code>```

Title: Pandas Monthly YoY?

Body:
Suppose I have a DF below:

EOM
Nike
Adidas

1/31/2021
100
80

1/31/2022
110
80

1/31/2023
132
88

...
...
...

How do I get:

EOM
Nike
Adidas

1/31/2021
null
null

1/31/2022
10%
0

1/31/2023
20%
10%

...
...
...

Body:
It would be preferable for you to provide a bit more information about the desired output, but it looks like you want a percent change between the end of months for consecutive years.

You can sort the EOM column if it isn't already sorted, then perform a groupby on the month and calculate the percent change. Thanks to @mozway for suggesting the use of a join so that the groupby only needs to be performed once

For example:

df = pd.DataFrame({'EOM':['1/31/2021','1/31/2022','1/31/2023','2/28/2021','2/28/2022','2/28/2023'],'Nike':[100,110,132,100,120,144],'Adidas':[80,80,88,90,90,99]})
df.sort_values(by='EOM', inplace=True)
df['EOM'] = pd.to_datetime(df['EOM'])
df['month'] = df['EOM'].dt.month

df = df.join(df.groupby("month")[['Nike','Adidas']].transform('pct_change')*100, rsuffix="_pct_change")

Result:

>>> df
         EOM  Nike  Adidas  month  Nike_pct_change  Adidas_pct_change
0 2021-01-31   100      80      1              NaN                NaN
1 2022-01-31   110      80      1             10.0                0.0
2 2023-01-31   132      88      1             20.0               10.0
3 2021-02-28   100      90      2              NaN                NaN
4 2022-02-28   120      90      2             20.0                0.0
5 2023-02-28   144      99      2             20.0               10.0


问:
Restart animation in CSS3: any better way than removing the element?
I have a CSS3 animation that needs to be restarted on a click. It's a bar showing how much time is left. I'm using the scaleY(0) transform to create the effect.

Now I need to restart the animation by restoring the bar to scaleY(1) and let it go to scaleY(0) again.
My first attempt to set scaleY(1) failed because it takes the same 15 seconds to bring it back to full length. Even if I change the duration to 0.1 second, I would need to delay or chain the assignment of scaleY(0) to let the bar replenishment complete.
It feels too complicated for such a simple task.

I also found an interesting tip to restart the animation by removing the element from the document, and then re-inserting a clone of it:
http://css-tricks.com/restart-css-animation/

It works, but is there a better way to restart a CSS animation?
I'm using Prototype and Move.js, but I'm not restricted to them.

答:
Note that with React, clearing the animation like this, a codesandbox I found helps.

Example I used in my code:

function MyComponent() {
  const [shouldTransition, setShouldTransition] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      // in my code, I change a background image here, and call this hook restart then animation,
      // which first clears the animationName
      setShouldTransition(false);
    }, timeout * 1000);
  }, [curr]);

  useEffect(() => {
    // then restore the animation name after it was cleared
    if (shouldTransition === false) {
      setShouldTransition(true);
    }
  }, [shouldTransition]);
  return (

  );
}
```

ContentLicense: CC BY-SA 3.0

Body:
Note that with React, clearing the animation like this, a codesandbox I found helps.

Example I used in my code:

function MyComponent() {
  const [shouldTransition, setShouldTransition] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      // in my code, I change a background image here, and call this hook restart then animation,
      // which first clears the animationName
      setShouldTransition(false);
    }, timeout * 1000);
  }, [curr]);

  useEffect(() => {
    // then restore the animation name after it was cleared
    if (shouldTransition === false) {
      setShouldTransition(true);
    }
  }, [shouldTransition]);
  return (
    <div
      ref={ref2}
      style={{
        animationName: shouldTransition ? "zoomin" : "",
      }}
    />
  );
}


答:
Use a shift method to calculate the YoY values.

Code:

import io
import pandas as pd

# Create sample data
s = '''EOM,Nike,Adidas
1/31/2021,100,80
1/31/2022,110,80
1/31/2023,132,88'''
df = pd.read_csv(io.StringIO(s))

# Convert EOM to datetime type
df['EOM'] = pd.to_datetime(df['EOM'])

# Add temporary columns for calculation
df['month'] = df['EOM'].dt.month
df['day'] = df['EOM'].dt.day

# Ensure df is sorted
df = df.sort_values(['day', 'month', 'EOM'])

# Set all the date-related columns as index
df = df.set_index(['EOM', 'month', 'day'])

# Shift a row forward by group
df_shift = df.groupby(['month', 'day']).shift()

# Calculate YoY
df = (df - df_shift).div(df_shift) * 100

# Drop the temporary columns
df = df.reset_index().drop(['month', 'day'], axis=1)
```

Output:

EOM
Nike
Adidas

2021-01-31
nan
nan

2022-01-31
10
0

2023-01-31
20
10

Title: Pandas Monthly YoY?

Body:
Use a shift method to calculate the YoY values.

Code:

import io
import pandas as pd

# Create sample data
s = '''EOM,Nike,Adidas
1/31/2021,100,80
1/31/2022,110,80
1/31/2023,132,88'''
df = pd.read_csv(io.StringIO(s))

# Convert EOM to datetime type
df['EOM'] = pd.to_datetime(df['EOM'])

# Add temporary columns for calculation
df['month'] = df['EOM'].dt.month
df['day'] = df['EOM'].dt.day

# Ensure df is sorted
df = df.sort_values(['day', 'month', 'EOM'])

# Set all the date-related columns as index
df = df.set_index(['EOM', 'month', 'day'])

# Shift a row forward by group
df_shift = df.groupby(['month', 'day']).shift()

# Calculate YoY
df = (df - df_shift).div(df_shift) * 100

# Drop the temporary columns
df = df.reset_index().drop(['month', 'day'], axis=1)

Output:

EOM
Nike
Adidas

2021-01-31
nan
nan

2022-01-31
10
0

2023-01-31
20
10


问:
How can I download multiple parts of a file in parallel with PHP's curl library?
I decided to start a project about download acceleration with curl in PHP, using curl_multi functions.

Here is my code:

```<code>set_time_limit(0);
error_reporting(E_ALL);
$fileurl = "http://hq-scenes.com/tv.exe";
$filename = basename($fileurl);
$size = getFileSize($fileurl);
$splits = range(0, $size, round($size/5));
$megaconnect = curl_multi_init();
$partnames = array();
for ($i = 0; $i < sizeof($splits); $i++) {
    $ch[$i] = curl_init();
    curl_setopt($ch[$i], CURLOPT_URL, $fileurl);
    curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch[$i], CURLOPT_VERBOSE, 1);
    curl_setopt($ch[$i], CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch[$i], CURLOPT_FRESH_CONNECT, 0);
    curl_setopt($ch[$i], CURLOPT_CONNECTTIMEOUT, 10);
    $partnames[$i] = $filename . $i;
    $bh[$i] = fopen(getcwd(). '/' . $partnames[$i], 'w+');
    curl_setopt($ch[$i], CURLOPT_FILE, $bh[$i]);
        $x = ($i == 0 ? 0 : $splits[$i]+1);
        $y = ($i == sizeof($splits)-1 ? $size : $splits[$i+1]);
        $range = $x.'-'.$y;
    curl_setopt($ch[$i], CURLOPT_RANGE, $range);
    curl_setopt($ch[$i], CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.29 Safari/535.1");
    curl_multi_add_handle($megaconnect, $ch[$i]);
}

$active = null;

do {
    $mrc = curl_multi_exec($megaconnect, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($megaconnect) != -1) {
        do {
            $mrc = curl_multi_exec($megaconnect, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}
$final = fopen($filename, "w+");
for ($i = 0; $i < sizeof($splits); $i++) {
    $contents = fread($bh[$i], filesize($partnames[$i]));
    fclose($bh[$i]);
    fwrite($final, $contents);
}
fclose($final);

function getFileSize($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $h = fopen('header', "w+");
    curl_setopt($ch, CURLOPT_WRITEHEADER, $h);

    $data = curl_exec($ch);
    curl_close($ch);

    if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
        return $contentLength = (int)$matches[1];
    }
    else return false;
}
</code>```

Everything goes OK, except one thing:

The last part file doesn't reach the end of the file.
the actual file size is : 3279848 bytes

ranges are:

```<code>0-655970
655971-1311940
1311941-1967910
1967911-2623880
2623881-3279848
</code>```

part files with size

```<code>tv.exe0 655360
tv.exe1 655360
tv.exe2 655360
tv.exe3 655360
tv.exe4 655360
</code>```

That makes the final file 3276800 bytes length, but it must be 3279848 bytes.
And of course the executable didn't work :(

Notice that the part files have the same size. Even the last one, which should have some more bytes. So the problem is in the download range or something, not in the merge process.

What did I do wrong?

答:
you must set your filepointers to 0 before fread. reading xy bytes from end is 0 bytes ;) </p>

```<code>$final = fopen($filename, "w+");
for ($i = 0; $i < sizeof($splits); $i++) {
  fseek($bh[$i], 0, SEEK_SET);
  $contents = fread($bh[$i], filesize($partnames[$i]));
  fclose($bh[$i]);
  fwrite($final, $contents);
}
</code>```

Body:
I decided to start a project about download acceleration with curl in PHP, using curl_multi functions.

Here is my code:

set_time_limit(0);
error_reporting(E_ALL);
$fileurl = "http://hq-scenes.com/tv.exe";
$filename = basename($fileurl);
$size = getFileSize($fileurl);
$splits = range(0, $size, round($size/5));
$megaconnect = curl_multi_init();
$partnames = array();
for ($i = 0; $i < sizeof($splits); $i++) {
    $ch[$i] = curl_init();
    curl_setopt($ch[$i], CURLOPT_URL, $fileurl);
    curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch[$i], CURLOPT_VERBOSE, 1);
    curl_setopt($ch[$i], CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch[$i], CURLOPT_FRESH_CONNECT, 0);
    curl_setopt($ch[$i], CURLOPT_CONNECTTIMEOUT, 10);
    $partnames[$i] = $filename . $i;
    $bh[$i] = fopen(getcwd(). '/' . $partnames[$i], 'w+');
    curl_setopt($ch[$i], CURLOPT_FILE, $bh[$i]);
        $x = ($i == 0 ? 0 : $splits[$i]+1);
        $y = ($i == sizeof($splits)-1 ? $size : $splits[$i+1]);
        $range = $x.'-'.$y;
    curl_setopt($ch[$i], CURLOPT_RANGE, $range);
    curl_setopt($ch[$i], CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.29 Safari/535.1");
    curl_multi_add_handle($megaconnect, $ch[$i]);
}

$active = null;

do {
    $mrc = curl_multi_exec($megaconnect, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($megaconnect) != -1) {
        do {
            $mrc = curl_multi_exec($megaconnect, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}
$final = fopen($filename, "w+");
for ($i = 0; $i < sizeof($splits); $i++) {
    $contents = fread($bh[$i], filesize($partnames[$i]));
    fclose($bh[$i]);
    fwrite($final, $contents);
}
fclose($final);

function getFileSize($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $h = fopen('header', "w+");
    curl_setopt($ch, CURLOPT_WRITEHEADER, $h);

    $data = curl_exec($ch);
    curl_close($ch);

    if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
        return $contentLength = (int)$matches[1];
    }
    else return false;
}

Everything goes OK, except one thing:

The last part file doesn't reach the end of the file.
the actual file size is : 3279848 bytes

ranges are:

0-655970
655971-1311940
1311941-1967910
1967911-2623880
2623881-3279848

part files with size

tv.exe0 655360
tv.exe1 655360
tv.exe2 655360
tv.exe3 655360
tv.exe4 655360

That makes the final file 3276800 bytes length, but it must be 3279848 bytes.
And of course the executable didn't work :(

Notice that the part files have the same size. Even the last one, which should have some more bytes. So the problem is in the download range or something, not in the merge process.

What did I do wrong?

Body:
you must set your filepointers to 0 before fread. reading xy bytes from end is 0 bytes ;)

$final = fopen($filename, "w+");
for ($i = 0; $i < sizeof($splits); $i++) {
  fseek($bh[$i], 0, SEEK_SET);
  $contents = fread($bh[$i], filesize($partnames[$i]));
  fclose($bh[$i]);
  fwrite($final, $contents);
}


问:
How to return a numpy array of the indices of the first element in each row of a numpy array with a given value?
Given a numpy array of shape (2, 4):

```<code>input = np.array([[False, True, False, True], [False, False, True, True]])
</code>```

I want to return an array of shape (N,) where each element of the array is the index of the first True value:

```<code>expected = np.array([1, 2])
</code>```

Is there an easy way to do this using numpy functions and without resorting to standard loops?

答:
np.max with axis finds the max along the dimension; argmax finds the first max index:

```<code>In [42]: arr = np.array([[False, True, False, True], [False, False, True, True]])
In [43]: np.argmax(arr, axis=1)
Out[43]: array([1, 2])
</code>```

Body:
Given a numpy array of shape (2, 4):

input = np.array([[False, True, False, True], [False, False, True, True]])

I want to return an array of shape (N,) where each element of the array is the index of the first True value:

expected = np.array([1, 2])

Is there an easy way to do this using numpy functions and without resorting to standard loops?

Body:
np.max with axis finds the max along the dimension; argmax finds the first max index:

In [42]: arr = np.array([[False, True, False, True], [False, False, True, True]])
In [43]: np.argmax(arr, axis=1)
Out[43]: array([1, 2])


问:
facing issue in cython on raspberrypi
I am trying to install the tensorflow dependencies .One of the codes is:

```<code>$ sudo apt-get install liblapack-dev cython
</code>```

and i got an error:

```<code>E: Package 'cython' has no installation candidate
</code>```

答: the cython package has been updated to cython3. And i was able to install it successfully.

Title: facing issue in cython on raspberrypi

Body:
I am trying to install the tensorflow dependencies .One of the codes is:

$ sudo apt-get install liblapack-dev cython

and i got an error:

E: Package 'cython' has no installation candidate


问:
Prevent GCP billing access to editor
I am using the default "Editor" role  for a GCP account. I would like to disable the ability for the Editor Role from having access to the all Billing information. I there a way to do this easily?  I have read through the IAM documentation but it is very confusing.</p>

答:
The role Editor is a member of the Basic roles. You cannot modify Basic roles as they are managed by Google.

Select one or more Predefined Roles and assign that to IAM members.

Another option is to create a Custom role with the permissions you require and assign that to IAM members.

Google Cloud IAM Basic roles

Google Cloud IAM Predefined roles

Google Cloud IAM Custom roles

Title: Prevent GCP billing access to editor


问:
Java inner class and static nested class
What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?</p>

答: Static nested classes access PRIVATE class-level static variables of the class they are defined in. That can be huge from an architectural standpoint (i.e. Service Locator pattern employing nested static helper classes in Services), and may help OP see why they exist along with inner classes.</p>

OwnerDisplayName: Omnipotent

LastEditorDisplayName: skiphoppy


问:
How to properly use regex to search from a command's output in Bash?
I have a command lando info which has a fairly large multi-line output:

```<code>[ { service: 'appserver',
    urls:
     [ 'https://localhost:52836',
       'http://localhost:52837',
       'http://if-build-d9.lndo.site/',
       'https://if-build-d9.lndo.site/' ],
    type: 'php',
    healthy: true,
    via: 'apache',
    webroot: './web',
    config: { php: '/Users/runo/.lando/config/drupal9/php.ini' },
    version: '7.3',
    meUser: 'www-data',
    hasCerts: true,
    hostnames: [ 'appserver.ifbuildd9.internal' ] },
  { service: 'database',
    urls: [],
    type: 'mysql',
    healthy: true,
    internal_connection: { host: 'database', port: '3306' },
    external_connection: { host: '127.0.0.1', port: '52835' },
    healthcheck: 'bash -c "[ -f /bitnami/mysql/.mysql_initialized ]"',
    creds: { database: 'drupal9', password: 'drupal9', user: 'drupal9' },
    config: { database: '/Users/runo/.lando/config/drupal9/mysql.cnf' },
    version: '5.7',
    meUser: 'www-data',
    hasCerts: false,
    hostnames: [ 'database.ifbuildd9.internal' ] },
  { service: 'redis_primary',
    urls: [ 'http://if-build-d9-redis-primary.lndo.site/' ],
    type: 'redis',
    healthy: true,
    internal_connection: { host: 'redis_primary', port: '6379' },
    external_connection: { host: '127.0.0.1', port: '52838' },
    config: {},
    version: '6',
    meUser: 'www-data',
    hasCerts: false,
    hostnames: [ 'redis_primary.ifbuildd9.internal' ] },
  { service: 'mailhog',
    urls: [ 'http://localhost:52840', 'http://if-build-d9-mail.lndo.site/' ],
    type: 'mailhog',
    healthy: true,
    hogfrom: [ 'appserver' ],
    internal_connection: { host: 'mailhog', port: '1025' },
    external_connection: { host: '127.0.0.1', port: '52839' },
    config: {},
    version: 'v1.0.0',
    meUser: 'mailhog',
    hasCerts: false,
    hostnames: [ 'mailhog.ifbuildd9.internal' ] } ]
</code>```

I want to capture the value http://if-build-d9.lndo.site in a bash variable.

What I have is this shell script, but it returns empty values:

```<code> lando_info=$(lando info);
 regex_pattern='/http:\/\/[\w\S]*.lndo.site/g';
 [[ "$lando_info" =~ $regex_pattern ]];
 echo "${BASH_REMATCH[0]}"
 echo "${BASH_REMATCH[1]}"
 echo "${BASH_REMATCH[2]}"
</code>```

This outputs empty strings.

I know the regex itself should be valid as I tested it on https://www.regexpal.com/ with that command output and pattern.

It matches on

http://if-build-d9.lndo.site (this is the only match I care about)

http://if-build-d9-redis-primary.lndo.site

http://if-build-d9-mail.lndo.site

So it appears that my use of regex in Bash is not correct.

答: I ended up using jq with better results.</p>

Body:
I have a command lando info which has a fairly large multi-line output:

[ { service: 'appserver',
    urls:
     [ 'https://localhost:52836',
       'http://localhost:52837',
       'http://if-build-d9.lndo.site/',
       'https://if-build-d9.lndo.site/' ],
    type: 'php',
    healthy: true,
    via: 'apache',
    webroot: './web',
    config: { php: '/Users/runo/.lando/config/drupal9/php.ini' },
    version: '7.3',
    meUser: 'www-data',
    hasCerts: true,
    hostnames: [ 'appserver.ifbuildd9.internal' ] },
  { service: 'database',
    urls: [],
    type: 'mysql',
    healthy: true,
    internal_connection: { host: 'database', port: '3306' },
    external_connection: { host: '127.0.0.1', port: '52835' },
    healthcheck: 'bash -c "[ -f /bitnami/mysql/.mysql_initialized ]"',
    creds: { database: 'drupal9', password: 'drupal9', user: 'drupal9' },
    config: { database: '/Users/runo/.lando/config/drupal9/mysql.cnf' },
    version: '5.7',
    meUser: 'www-data',
    hasCerts: false,
    hostnames: [ 'database.ifbuildd9.internal' ] },
  { service: 'redis_primary',
    urls: [ 'http://if-build-d9-redis-primary.lndo.site/' ],
    type: 'redis',
    healthy: true,
    internal_connection: { host: 'redis_primary', port: '6379' },
    external_connection: { host: '127.0.0.1', port: '52838' },
    config: {},
    version: '6',
    meUser: 'www-data',
    hasCerts: false,
    hostnames: [ 'redis_primary.ifbuildd9.internal' ] },
  { service: 'mailhog',
    urls: [ 'http://localhost:52840', 'http://if-build-d9-mail.lndo.site/' ],
    type: 'mailhog',
    healthy: true,
    hogfrom: [ 'appserver' ],
    internal_connection: { host: 'mailhog', port: '1025' },
    external_connection: { host: '127.0.0.1', port: '52839' },
    config: {},
    version: 'v1.0.0',
    meUser: 'mailhog',
    hasCerts: false,
    hostnames: [ 'mailhog.ifbuildd9.internal' ] } ]

I want to capture the value http://if-build-d9.lndo.site in a bash variable.

What I have is this shell script, but it returns empty values:

 lando_info=$(lando info);
 regex_pattern='/http:\/\/[\w\S]*.lndo.site/g';
 [[ "$lando_info" =~ $regex_pattern ]];
 echo "${BASH_REMATCH[0]}"
 echo "${BASH_REMATCH[1]}"
 echo "${BASH_REMATCH[2]}"

This outputs empty strings.

I know the regex itself should be valid as I tested it on https://www.regexpal.com/ with that command output and pattern.

It matches on

http://if-build-d9.lndo.site (this is the only match I care about)

http://if-build-d9-redis-primary.lndo.site

http://if-build-d9-mail.lndo.site

So it appears that my use of regex in Bash is not correct.


问:
I cant make my bot go online and it shows TypeError [CLIENT_MISSING_INTENTS] (vscode)

const Discord = require("discord.js");
const Bot = new Discord.Client({Intents:[Discord.Intents.FLAGS.GUILD_MEMBERS, Discord.Intents.FLAGS.GUILDS]})

Bot.on('ready', () => {
    console.log("The bot is online")

    let commands = Bot.application.commands;

    commands.create({
        name: "hello" ,
        description: "reply hello to the user",
        options: [
            {
                name: "person",
                description: "The user you want to say hello to",
                require: true,
                type: Discord.Constants.ApplicationCommandOptionTypes.USER

            }
        ]
    })
 })

    Bot.on('interactionCreate', interaction => {
     if(!interaction.isCommand()) return;
     let name  = interaction.commandName
     let options = interaction.options;

     if(name == "hello") {
        interaction.reply({
            content: "Hello",
            ephemeral: false
        })
    }
    if(name == "sayhello"){
        let user = options.getUser('person');

        interaction.reply({
            content: 'Hello ${user.username}
        })
    }
})

bot.login("token")
```

答:
Since discord.js v13, you need to provide Intents when declaring the client. They were introduced by Discord so that developers can choose what type of data the bot will need to receive. All you have to do is add intents when declaring the client. The code might look something like this:

const { Client } = require('discord.js')
const client = new Client({
    intents: [
        Discord.Intents.FLAGS.GUILDS,
        Discord.Intents.FLAGS.GUILD_MESSAGES
    ]
})
```

And also, as pointed by @Richie Bendall, you have capitalised the I when declaring the intents. You can learn more about intents in here => Gateway Intents | Discord.js

Body:
Since discord.js v13, you need to provide Intents when declaring the client. They were introduced by Discord so that developers can choose what type of data the bot will need to receive. All you have to do is add intents when declaring the client. The code might look something like this:

const { Client } = require('discord.js')
const client = new Client({
    intents: [
        Discord.Intents.FLAGS.GUILDS,
        Discord.Intents.FLAGS.GUILD_MESSAGES
    ]
})

And also, as pointed by @Richie Bendall, you have capitalised the I when declaring the intents. You can learn more about intents in here => Gateway Intents | Discord.js


答: The intents is option is lowercase, not capitalised. See ClientOptions.

Title: I cant make my bot go online and it shows TypeError [CLIENT_MISSING_INTENTS] (vscode)

Body:
const Discord = require("discord.js");
const Bot = new Discord.Client({Intents:[Discord.Intents.FLAGS.GUILD_MEMBERS, Discord.Intents.FLAGS.GUILDS]})

Bot.on('ready', () => {
    console.log("The bot is online")

    let commands = Bot.application.commands;

    commands.create({
        name: "hello" ,
        description: "reply hello to the user",
        options: [
            {
                name: "person",
                description: "The user you want to say hello to",
                require: true,
                type: Discord.Constants.ApplicationCommandOptionTypes.USER

            }
        ]
    })
 })

    Bot.on('interactionCreate', interaction => {
     if(!interaction.isCommand()) return;
     let name  = interaction.commandName
     let options = interaction.options;

     if(name == "hello") {
        interaction.reply({
            content: "Hello",
            ephemeral: false
        })
    }
    if(name == "sayhello"){
        let user = options.getUser('person');

        interaction.reply({
            content: 'Hello ${user.username}
        })
    }
})

bot.login("token")


问:
What's the meaning of Python error message `KeyError: 'The grouper name created_at is not found'`?
I'm trying to take a series of tweets and group them into 1 hour intervals based on when the tweets were created, and sum the likes the tweets got for each 1 hour interval.

The tweets have been converted to a pandas dataframe, eg:

```<code>df.head(1)
    author_id   username    author_followers    author_tweets   author_description  author_location text    created_at  lang    tweet_id    retweets    replies likes   quotes
0   2395138046  WorldCoinIndex  12832   46121   Cryptocurrency index | prices | 24hr volume | ...   None    Cryptocurrencies $ETH $LTC $DASH $XMR $ZCASH h...   2022-02-11 23:59:38+00:00   en  1492287240990507009 0   1   0   0
</code>```

EXPECTATION

The code i'm applying to the above dataframe:

```<code>df.likes.resample('H', on='created_at').sum()
</code>```

My understanding is likes specifies the column to be summed, 'H' specifies the 1 hour time intervals, and the on parameter defines the time series key created_at. based on the time series key parameter created_at.

RESULTING ERROR MESSAGE

KeyError: 'The grouper name created_at is not found'

ASSESSMENT

When I search that error message, I see mostly references for the groupby method, which I considered, but figured Time Series would be simpler.

Shouldn't it return an index error if it's the 'created_at' parameter that's problematic?

答:
Based on documentation:

on str, optional For a DataFrame, column to use instead of index for
resampling. Column must be datetime-like.

When you use the .likes actually there is no column with the specified name on the column you try to sample over.
Example:

```<code>index = pd.date_range('1/1/2000', periods=9, freq='T')
df = pd.DataFrame({'likes': range(9), 'user':['ali' for i in range(9)]}, index=index)
df['create on'] = df.index
</code>```

This produce the error:

```<code>df.likes.resample('3T', on = 'create on').sum()
</code>```

And the right way:

```<code>df.resample('3T', on = 'create on').sum()
</code>```

the output:

Body:
I'm trying to take a series of tweets and group them into 1 hour intervals based on when the tweets were created, and sum the likes the tweets got for each 1 hour interval.

The tweets have been converted to a pandas dataframe, eg:

df.head(1)
    author_id   username    author_followers    author_tweets   author_description  author_location text    created_at  lang    tweet_id    retweets    replies likes   quotes
0   2395138046  WorldCoinIndex  12832   46121   Cryptocurrency index | prices | 24hr volume | ...   None    Cryptocurrencies $ETH $LTC $DASH $XMR $ZCASH h...   2022-02-11 23:59:38+00:00   en  1492287240990507009 0   1   0   0

EXPECTATION

The code i'm applying to the above dataframe:

df.likes.resample('H', on='created_at').sum()

My understanding is likes specifies the column to be summed, 'H' specifies the 1 hour time intervals, and the on parameter defines the time series key created_at. based on the time series key parameter created_at.

RESULTING ERROR MESSAGE

KeyError: 'The grouper name created_at is not found'

ASSESSMENT

When I search that error message, I see mostly references for the groupby method, which I considered, but figured Time Series would be simpler.

Shouldn't it return an index error if it's the 'created_at' parameter that's problematic?

Body:
Based on documentation:

on str, optional For a DataFrame, column to use instead of index for
resampling. Column must be datetime-like.

When you use the .likes actually there is no column with the specified name on the column you try to sample over.
Example:

index = pd.date_range('1/1/2000', periods=9, freq='T')
df = pd.DataFrame({'likes': range(9), 'user':['ali' for i in range(9)]}, index=index)
df['create on'] = df.index

This produce the error:

df.likes.resample('3T', on = 'create on').sum()

And the right way:

df.resample('3T', on = 'create on').sum()

the output: