问:
Modal isn't showing properly
I am trying to get my modal to pop open correctly. I'm using reactstrap. Currently when hitting the button to get it to display it shows up on the bottom:

Also the close modal button is somehow on the bottom of the modal header. I wanted the modal to open up on the middle of the page and dim the background. This same thing is happening on another modal which also renders on this page (Once someone hits add plant, it has an option to view or delete and delete is a modal as well). The delete modal is doing the same thing:

I don't think this has anything to do with it, but the add new plant is on its own component and is tied to the parent app component. The delete is on the same component. The form that pops up is on a component that I named plantform, here is some code from that:

const PlantForm = props => {
    const [plant, setPlant] = useState({
        id: props.number,
        nickname:"",
        species: "",
        h2oFrequency: ""
    })

    const changeHandler = (event) => {
        setPlant({
            ...plant,
            [event.target.name] : event.target.value
        })
    }

    return(
        <Modal isOpen={props.modalProp} toggle={props.modalToggle} style={{width: "40%", marginLeft:"34%"}}>
            <ModalHeader toggle={props.modalToggle} style={{background: "linear-gradient(to right, #81814D, #687158)", textAlign:"center"}}>Add Plant</ModalHeader>
            <ModalBody style={{padding: "15px", border:"1px solid #C7BEAE", background: "linear-gradient(to right, #81814D, #687158)"}}>
                <Form onSubmit={event =>{
                    event.preventDefault()
                    props.addPlant(plant)

                    setPlant({id: "", nickname:"", species: "", h2oFrequency: ""})
                    props.setNumber(props.number+1)
                    props.modalToggle()
                }} >

                        <Title>Add a New Plant</Title>

                    Nickname your Plant:
                    <Input
                        id="nickname"
                        type="text"
                        name="nickname"
                        placeholder="Enter your plant's nickname"
                        value={plant.nickname}
                        onChange={changeHandler}
                        />
                    Enter your Plant's Species:
                    <Input
                        id="species"
                        type="text"
                        name="species"
                        placeholder="Enter your plant's nickname"
                        value={plant.species}
                        onChange={changeHandler}
                        />
                    Select your Water Schedule:
                    <Select
                        id="h2o"
                        name="h2oFrequency"
                        value={plant.h2oFrequency}
                        onChange={changeHandler}
                        >
                        <option value="" disabled={true}>Select Your Water Schedule</option>
                        <option value="Daily">Daily</option>
                        <option value="Weekly">Weekly</option>
                        <option value="Bi-Weekly">Bi-Weekly</option>
                        <option value="Monthly">Monthly</option>
                    </Select>
                    <Button type="submit">Add Plant</Button>
                </Form>
            </ModalBody>
          </Modal>
    )
}

export default PlantForm;```
</div>
</div>
</p>

<p>Here is the code for the delete modal that's on the same component:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const PlantList = props => {

    const [modal, setModal]= useState(false);
    const toggle = () => setModal(!modal);

    const [plants] = useState([])

    const [plantId, setPlantId] = useState("");
    const openDeleteModal = (id)=> {
        setPlantId(id)
        toggle()
    }
    const deletePlant=() => {
        props.setPlants(props.plants.filter(plant=> plant.id!==plantId))
        setPlantId("")
        toggle()
    }
   console.log(plants)
    return(
        <div>
            <div>
                <Title>List of Plants</Title>
            </div>
            <PlantDiv>
                <Modal isOpen={modal} toggle={toggle} style={{width: "20%", marginLeft:"40%"}}>
                        <ModalBody style={{padding: "15px", border:"1px solid #C7BEAE", background: "linear-gradient(to right, #81814D, #687158)"}}>
                            <ModalPara>Would you like to delete? </ModalPara>
                        </ModalBody>
                        <ModalFooter style={{padding: "15px", border:"1px solid #C7BEAE", background: "linear-gradient(to right, #81814D, #687158)"}}>
                            <Button onClick={deletePlant}>Yes</Button>
                            <Button onClick={toggle}>No</Button>
                        </ModalFooter>
                    </Modal>
            {props.plants.map(plant =>
                <Card key={plant.id}>
                    <Para>Plant Nickname: {plant.nickname}</Para>
                    <Para>Plant Species: {plant.species}</Para>
                    <Para>Water Frequency: {plant.h2oFrequency}</Para>
                    <Link to={`/editplant/${plant.id}`}>
                    <Button>View</Button>
                    </Link>
                    <Button onClick={()=>openDeleteModal(plant.id)}>Delete</Button>

                </Card>
                )}
                </PlantDiv>
                <Button onClick={props.plantToggle}>Add Plant</Button>

        </div>
    )
}

export default PlantList;</code>```

As a side note, I am using styled-components to style some things on the page which is why some of the tags look odd.

答:
This is a very normal thing to want! Here's the recipe that everyone follows:

You'll need a background div as a parent of the modal itself that takes the whole height and width of a page. Make it black with some opacity so it has that 'dimming' effect. (Note that you'll probably want to do something like background-color: rgba(0, 0, 0, 0.7) rather than giving an opacity to the background itself so the modal isn't transparent.)

To center the modal, follow this classic advice:
https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

To get the close button to position properly in your header, try making the header position:relative (so that you can position its children absolutely relative to it) and the close button position: absolute, probably right: 0; top: 0 or as desired.

Title: Modal isn't showing properly

Body:
I am trying to get my modal to pop open correctly. I'm using reactstrap. Currently when hitting the button to get it to display it shows up on the bottom:

Also the close modal button is somehow on the bottom of the modal header. I wanted the modal to open up on the middle of the page and dim the background. This same thing is happening on another modal which also renders on this page (Once someone hits add plant, it has an option to view or delete and delete is a modal as well). The delete modal is doing the same thing:

I don't think this has anything to do with it, but the add new plant is on its own component and is tied to the parent app component. The delete is on the same component. The form that pops up is on a component that I named plantform, here is some code from that:

const PlantForm = props => {
    const [plant, setPlant] = useState({
        id: props.number,
        nickname:"",
        species: "",
        h2oFrequency: ""
    })

    const changeHandler = (event) => {
        setPlant({
            ...plant,
            [event.target.name] : event.target.value
        })
    }

    return(
        <Modal isOpen={props.modalProp} toggle={props.modalToggle} style={{width: "40%", marginLeft:"34%"}}>
            <ModalHeader toggle={props.modalToggle} style={{background: "linear-gradient(to right, #81814D, #687158)", textAlign:"center"}}>Add Plant</ModalHeader>
            <ModalBody style={{padding: "15px", border:"1px solid #C7BEAE", background: "linear-gradient(to right, #81814D, #687158)"}}>
                <Form onSubmit={event =>{
                    event.preventDefault()
                    props.addPlant(plant)

                    setPlant({id: "", nickname:"", species: "", h2oFrequency: ""})
                    props.setNumber(props.number+1)
                    props.modalToggle()
                }} >

                        <Title>Add a New Plant</Title>

                    Nickname your Plant:
                    <Input
                        id="nickname"
                        type="text"
                        name="nickname"
                        placeholder="Enter your plant's nickname"
                        value={plant.nickname}
                        onChange={changeHandler}
                        />
                    Enter your Plant's Species:
                    <Input
                        id="species"
                        type="text"
                        name="species"
                        placeholder="Enter your plant's nickname"
                        value={plant.species}
                        onChange={changeHandler}
                        />
                    Select your Water Schedule:
                    <Select
                        id="h2o"
                        name="h2oFrequency"
                        value={plant.h2oFrequency}
                        onChange={changeHandler}
                        >
                        <option value="" disabled={true}>Select Your Water Schedule</option>
                        <option value="Daily">Daily</option>
                        <option value="Weekly">Weekly</option>
                        <option value="Bi-Weekly">Bi-Weekly</option>
                        <option value="Monthly">Monthly</option>
                    </Select>
                    <Button type="submit">Add Plant</Button>
                </Form>
            </ModalBody>
          </Modal>
    )
}

export default PlantForm;

Here is the code for the delete modal that's on the same component:

const PlantList = props => {

    const [modal, setModal]= useState(false);
    const toggle = () => setModal(!modal);

    const [plants] = useState([])

    const [plantId, setPlantId] = useState("");
    const openDeleteModal = (id)=> {
        setPlantId(id)
        toggle()
    }
    const deletePlant=() => {
        props.setPlants(props.plants.filter(plant=> plant.id!==plantId))
        setPlantId("")
        toggle()
    }
   console.log(plants)
    return(

                <Title>List of Plants</Title>

            <PlantDiv>
                <Modal isOpen={modal} toggle={toggle} style={{width: "20%", marginLeft:"40%"}}>
                        <ModalBody style={{padding: "15px", border:"1px solid #C7BEAE", background: "linear-gradient(to right, #81814D, #687158)"}}>
                            <ModalPara>Would you like to delete? </ModalPara>
                        </ModalBody>
                        <ModalFooter style={{padding: "15px", border:"1px solid #C7BEAE", background: "linear-gradient(to right, #81814D, #687158)"}}>
                            <Button onClick={deletePlant}>Yes</Button>
                            <Button onClick={toggle}>No</Button>
                        </ModalFooter>
                    </Modal>
            {props.plants.map(plant =>
                <Card key={plant.id}>
                    <Para>Plant Nickname: {plant.nickname}</Para>
                    <Para>Plant Species: {plant.species}</Para>
                    <Para>Water Frequency: {plant.h2oFrequency}</Para>
                    <Link to={`/editplant/${plant.id}`}>
                    <Button>View</Button>
                    </Link>
                    <Button onClick={()=>openDeleteModal(plant.id)}>Delete</Button>

                </Card>
                )}
                </PlantDiv>
                <Button onClick={props.plantToggle}>Add Plant</Button>

    )
}

export default PlantList;

As a side note, I am using styled-components to style some things on the page which is why some of the tags look odd.


来源: stackexchange

问:
When a property value is changed in a class via @Published, some of the observedObjects wont get updated?
These are all the codes.

the SurveyQuestion class

```<code>class SurveyQuestion: ObservableObject {
    @Published var text: String

    init() {
        print("Initialising now ...")
        self.text = "HELLO"
        changeText()
    }

    func changeText() {
        print("Changing Text Now from \(text).. ")

        if self.text == "HELLO"{
            self.text = "BYE"
        }
        else{
            self.text = "HELLO"
        }

        print("to \(self.text) \n")

    }
}
</code>```

SubView.swift

```<code>struct SubView: View {

    @ObservedObject var someOtherClass = SurveyQuestion()

    var body: some View {
        Text("Text now is \(someOtherClass.text)")

    }
}
</code>```

ContentView.swift

```<code>struct ContentView: View {

    @ObservedObject var someClass = SurveyQuestion()

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.someClass.changeText()
            }) {
                Text("Change Text ")
            }

            Text("Text now is \(someClass.text)")

            SubView()

        }
    }
}
</code>```

Whenever I click 'changeText' button, it changes the text in  Text("Text now is (someClass.text)") but not Subview(). They should all be updated with the same text change.
Any idea what went wrong here?

答: Your someClass and someOtherClass are two completely different objects. Changing one has no effect on the other. If this was supposed to be a singleton observable that could affect different views simultaneously, you wanted an environment object.

ContentLicense: CC BY-SA 4.0

Body:
These are all the codes.

the SurveyQuestion class

class SurveyQuestion: ObservableObject {
    @Published var text: String

    init() {
        print("Initialising now ...")
        self.text = "HELLO"
        changeText()
    }

    func changeText() {
        print("Changing Text Now from \(text).. ")

        if self.text == "HELLO"{
            self.text = "BYE"
        }
        else{
            self.text = "HELLO"
        }

        print("to \(self.text) \n")

    }
}

SubView.swift

struct SubView: View {

    @ObservedObject var someOtherClass = SurveyQuestion()

    var body: some View {
        Text("Text now is \(someOtherClass.text)")

    }
}

ContentView.swift

struct ContentView: View {

    @ObservedObject var someClass = SurveyQuestion()

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.someClass.changeText()
            }) {
                Text("Change Text ")
            }

            Text("Text now is \(someClass.text)")

            SubView()

        }
    }
}

Whenever I click 'changeText' button, it changes the text in  Text("Text now is (someClass.text)") but not Subview(). They should all be updated with the same text change.
Any idea what went wrong here?


问:
From picture in cell to footer
Given a workbook like this one:

I need to add the logo from cell A2 - worksheet A, in the footer of worksheets B,C.

Here's the code I've found and modified a little bit but it is not working.

```<code>Sub Logo()

Dim printWorksheet As Worksheet
Dim logoShape As Shape
Dim tempImageFile As String

Set printWorksheet = ThisWorkbook.ActiveSheet
Set logoShape = ThisWorkbook.Sheets("A").Shapes("myLogo")

tempImageFile = Environ("temp") & Application.PathSeparator & "image.jpg"
Save_Object_As_Picture logoShape, tempImageFile

With printWorksheet.PageSetup
.RightHeaderPicture.FileName = tempImageFile
.RightHeader = "&G"
End With
</code>```

答:
I have found a solutions (http://www.vbforums.com/showthread.php?538529-Export-an-Image-from-Excel-Sheet-to-Hard-Drive), that I have adopted to this task.
The key is, that a chart object can be exported as a picture, so the original shape is copied into a chart.
The chart is created, used, and deleted.
The ShapeExportAsPicture has two arguments: the shape, that is to be exported as picture and the full path where to store it.</p>

```<code>Sub Logo()
    Dim printWorksheet As Worksheet
    Dim logoShape As Shape
    Dim tempImageFile As String

    Set printWorksheet = ThisWorkbook.ActiveSheet
    Set logoShape = ThisWorkbook.Sheets("A").Shapes("myLogo")
    logoShape.Visible = True
    tempImageFile = Environ("temp") & Application.PathSeparator & "image.jpg"
    Call ShapeExportAsPicture(logoShape, tempImageFile)

    With printWorksheet.PageSetup
        .RightFooterPicture.Filename = tempImageFile
        .RightFooter = "&G"
    End With
    logoShape.Visible = False
End Sub

Private Sub ShapeExportAsPicture(pShape As Shape, sPathImageLocation As String)
    Dim sTempChart As String
    Dim shTempSheet As Worksheet
    Set shTempSheet = pShape.Parent
    Charts.Add 'Add a temporary chart
    ActiveChart.Location Where:=xlLocationAsObject, Name:=shTempSheet.Name
    Selection.Border.LineStyle = 0
    sTempChart = Selection.Name & " " & Split(ActiveChart.Name, " ")(2)
    With shTempSheet
        'Change the dimensions of the chart to the size of the original shape
        With .Shapes(sTempChart)
            .Width = pShape.Width
            .Height = pShape.Height
        End With
        pShape.Copy  'Copy the shape
        With ActiveChart 'Paste the shape into the chart
            .ChartArea.Select
            .Paste
        End With
        'export the chart
        .ChartObjects(1).Chart.Export Filename:=sPathImageLocation, FilterName:="jpg"
        .Shapes(sTempChart).Delete 'Delete the chart.
      End With
End Sub
</code>```

Title: From picture in cell to footer

Body:
Given a workbook like this one:

I need to add the logo from cell A2 - worksheet A, in the footer of worksheets B,C.

Here's the code I've found and modified a little bit but it is not working.

Sub Logo()

Dim printWorksheet As Worksheet
Dim logoShape As Shape
Dim tempImageFile As String

Set printWorksheet = ThisWorkbook.ActiveSheet
Set logoShape = ThisWorkbook.Sheets("A").Shapes("myLogo")

tempImageFile = Environ("temp") & Application.PathSeparator & "image.jpg"
Save_Object_As_Picture logoShape, tempImageFile

With printWorksheet.PageSetup
.RightHeaderPicture.FileName = tempImageFile
.RightHeader = "&G"
End With

Body:
I have found a solutions (http://www.vbforums.com/showthread.php?538529-Export-an-Image-from-Excel-Sheet-to-Hard-Drive), that I have adopted to this task.
The key is, that a chart object can be exported as a picture, so the original shape is copied into a chart.
The chart is created, used, and deleted.
The ShapeExportAsPicture has two arguments: the shape, that is to be exported as picture and the full path where to store it.

Sub Logo()
    Dim printWorksheet As Worksheet
    Dim logoShape As Shape
    Dim tempImageFile As String

    Set printWorksheet = ThisWorkbook.ActiveSheet
    Set logoShape = ThisWorkbook.Sheets("A").Shapes("myLogo")
    logoShape.Visible = True
    tempImageFile = Environ("temp") & Application.PathSeparator & "image.jpg"
    Call ShapeExportAsPicture(logoShape, tempImageFile)

    With printWorksheet.PageSetup
        .RightFooterPicture.Filename = tempImageFile
        .RightFooter = "&G"
    End With
    logoShape.Visible = False
End Sub

Private Sub ShapeExportAsPicture(pShape As Shape, sPathImageLocation As String)
    Dim sTempChart As String
    Dim shTempSheet As Worksheet
    Set shTempSheet = pShape.Parent
    Charts.Add 'Add a temporary chart
    ActiveChart.Location Where:=xlLocationAsObject, Name:=shTempSheet.Name
    Selection.Border.LineStyle = 0
    sTempChart = Selection.Name & " " & Split(ActiveChart.Name, " ")(2)
    With shTempSheet
        'Change the dimensions of the chart to the size of the original shape
        With .Shapes(sTempChart)
            .Width = pShape.Width
            .Height = pShape.Height
        End With
        pShape.Copy  'Copy the shape
        With ActiveChart 'Paste the shape into the chart
            .ChartArea.Select
            .Paste
        End With
        'export the chart
        .ChartObjects(1).Chart.Export Filename:=sPathImageLocation, FilterName:="jpg"
        .Shapes(sTempChart).Delete 'Delete the chart.
      End With
End Sub


问:
Django - retrieve url from HttpResponse object?
In Django test cases, how do you get the url from a HttpResponse object?

If I have the following Django app:

urls.py

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('httpresponse/', views.http_response, name='http_response'),
]
</code>```

views.py

```<code>from django.shortcuts import render

def http_response(request):
    return render(request, template_name='home.html')
</code>```

tests.py

```<code>from django.test import TestCase
from django.urls import reverse

http_response = reverse('http_response')

class TestTemplateResponse(TestCase):
    def test_http_response(self):
        response = self.client.get(http_response)
        self.assertEqual(response.url, http_response)
</code>```

The unit test fails with the following message:

AttributeError: 'HttpResponse' object has no attribute 'url'.

Is there any way to get the client to return a Response object, instead of HttpResponse?

答:
From the code given above and your comment suggesting that you are trying to redirect user to home page if they are authenticated doesn't match up. In the code above if someone is visiting the /httpresponse then you are just rendering a template(which returns HttpResponse).

HttpResponse object doesn't have the url property. Now, if you were to use login_required decorator with the view you've written, it would redirect unauthenticated users to login page. In this case(redirect), an HttpResponseRedirect instance is returned which indeed has the url property.

Django source code: https://github.com/django/django/blob/d6aff369ad33457ae2355b5b210faf1c4890ff35/django/http/response.py#L465

So, to test if authenticated users are getting redirected to home page view when visiting singup you should first setup the redirect for authenticated users. And then you should be able to access the url property of the response.

Body:
In Django test cases, how do you get the url from a HttpResponse object?

If I have the following Django app:

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('httpresponse/', views.http_response, name='http_response'),
]

views.py

from django.shortcuts import render

def http_response(request):
    return render(request, template_name='home.html')

tests.py

from django.test import TestCase
from django.urls import reverse

http_response = reverse('http_response')

class TestTemplateResponse(TestCase):
    def test_http_response(self):
        response = self.client.get(http_response)
        self.assertEqual(response.url, http_response)

The unit test fails with the following message:

AttributeError: 'HttpResponse' object has no attribute 'url'.

Is there any way to get the client to return a Response object, instead of HttpResponse?


问:
Azure Storage Explorer: How to query Table Storage Rowkey with "Contains"?
We are sending our logs to Azure Table Storage. I am trying to query those logs but finding it hard to do via Azure Storage Explorer.  I can't imagine why there is not a "contains" option to filter the RowKey column (where our actual log data is contained.)

Am I missing something obvious? Or is there a better tool for this job?

答:
Contains unfortunately is not a supported query operator in Azure Table Storage.

For a list of supported/unsupported query operators, please see this link: https://learn.microsoft.com/en-us/rest/api/storageservices/query-operators-supported-for-the-table-service.


问:
REACT: Can´t pass parameter to a lifting up event handler
I can´t pass the parameters from a child component to a parent component using the same event handler.

My components' tree follows this structure:

ProductList

ProductsGrid

PaginationBar

In the ProducList component I have this event handler

```<code>handlePagination = (index) => { bla bla bla }

<PaginationBar
  OnPagination={(index) => this.handlePagination(index)}
  pages={this.state.pages}
/>
</code>```

In the Pagination Bar when I render the page.

```<code>  render() {
    return (
      <nav aria-label="Catalog page navigation">
        <ul className="pagination">
          <li className={this.navButtonEnabled(0)} key="page-item-0">
            <a
              className="page-link"
              onClick={this.props.OnPagination(0)}
              href="#"
              aria-label="Previous"
            >
              <span aria-hidden="true">Previous 3</span>
            </a>
          </li>
          <li className={this.navButtonEnabled(1)} key="page-item-1">
            <a
              className="page-link"
              onClick={this.props.OnPagination(1)}
              href="#"
            >
              <span aria-hidden="true">
                {this.navButtonDisplay(this.props.pages.navigation[1])}
              </span>
            </a>
          </li>
          <li className={this.navButtonEnabled(2)} key="page-item-2">
            <a
              className="page-link"
              onClick={this.props.OnPagination(2)}
              href="#"
            >
              <span aria-hidden="true">
                {this.navButtonDisplay(this.props.pages.navigation[2])}
              </span>
            </a>
          </li>
          <li className={this.navButtonEnabled(3)} key="page-item-3">
            <a
              className="page-link"
              onClick={this.props.OnPagination(3)}
              href="#"
            >
              <span aria-hidden="true">
                {this.navButtonDisplay(this.props.pages.navigation[3])}
              </span>
            </a>
          </li>
          <li className={this.navButtonEnabled(4)} key="page-item-4">
            <a
              className="page-link"
              onClick={this.props.OnPagination(4)}
              href="#"
              aria-label="Next"
            >
              <span aria-hidden="true">Next 3</span>
            </a>
          </li>
        </ul>
      </nav>
    );
  }
}
</code>```

In the onClick event, I call the event handler with the index number (this is the parameter I want to pass), according the button clicked I render correctly the ProductsGrid. But it doesn't work at all, I tried several approaches, I just want to pass a number via a parameter for a lifting up event handler. What am I doing wrong?

This is the error presented in the console.

react_devtools_backend.js:6 Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
    in Pagination (created by Catalog)
    in Catalog (created by App)
    in main (created by App)
    in App

I am not changing any state during the render process, the event handler changes the status, when the button is clicked. This is not a render process.

答:
Please replace

```<code>onClick={this.props.OnPagination(0)}
</code>```

With

```<code>onClick={() => {this.props.OnPagination(0)}}
</code>```

Here is complete code (I have commented some code so that I can run this easily to my end):

```<code>import React from "react";

export default class ProductList extends React.Component {
    handlePagination = (index) => {
        console.log(index, 'index');
    };

    render() {
        return (
            <PaginationBar OnPagination={(index) => this.handlePagination(index)}
                // pages={this.state.pages}
            />
        );
    }
}

class PaginationBar extends React.Component {
    render() {
        return (
            <nav aria-label="Catalog page navigation">
                <ul className="pagination">
                    <li key="page-item-0">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(0)}}
                            href="#"
                            aria-label="Previous"
                        >
                            <span aria-hidden="true">Previous 3</span>
                        </a>
                    </li>
                    <li key="page-item-1">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(1)}}
                            href="#"
                        >
              <span aria-hidden="true">
                {/*{this.navButtonDisplay(this.props.pages.navigation[1])}*/}
                Previous 2
              </span>
                        </a>
                    </li>
                    <li key="page-item-2">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(2)}}
                            href="#"
                        >
              <span aria-hidden="true">
                {/*{this.navButtonDisplay(this.props.pages.navigation[2])}*/}
                Previous 1
              </span>
                        </a>
                    </li>
                    <li key="page-item-3">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(3)}}
                            href="#"
                        >
              <span aria-hidden="true">
                {/*{this.navButtonDisplay(this.props.pages.navigation[3])}*/}
                Next 2
              </span>
                        </a>
                    </li>
                    <li key="page-item-4">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(4)}}
                            href="#"
                            aria-label="Next"
                        >
                            <span aria-hidden="true">Next 3</span>
                        </a>
                    </li>
                </ul>
            </nav>
        );
    }
}
</code>```

Body:
I can´t pass the parameters from a child component to a parent component using the same event handler.

My components' tree follows this structure:

ProductList

ProductsGrid

PaginationBar

In the ProducList component I have this event handler

handlePagination = (index) => { bla bla bla }

<PaginationBar
  OnPagination={(index) => this.handlePagination(index)}
  pages={this.state.pages}
/>

In the Pagination Bar when I render the page.

  render() {
    return (

              Previous 3

                {this.navButtonDisplay(this.props.pages.navigation[1])}

                {this.navButtonDisplay(this.props.pages.navigation[2])}

                {this.navButtonDisplay(this.props.pages.navigation[3])}

              Next 3

    );
  }
}

In the onClick event, I call the event handler with the index number (this is the parameter I want to pass), according the button clicked I render correctly the ProductsGrid. But it doesn't work at all, I tried several approaches, I just want to pass a number via a parameter for a lifting up event handler. What am I doing wrong?

This is the error presented in the console.

react_devtools_backend.js:6 Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
    in Pagination (created by Catalog)
    in Catalog (created by App)
    in main (created by App)
    in App

I am not changing any state during the render process, the event handler changes the status, when the button is clicked. This is not a render process.

Body:
Please replace

onClick={this.props.OnPagination(0)}

With

onClick={() => {this.props.OnPagination(0)}}

Here is complete code (I have commented some code so that I can run this easily to my end):

import React from "react";

export default class ProductList extends React.Component {
    handlePagination = (index) => {
        console.log(index, 'index');
    };

    render() {
        return (
            <PaginationBar OnPagination={(index) => this.handlePagination(index)}
                // pages={this.state.pages}
            />
        );
    }
}

class PaginationBar extends React.Component {
    render() {
        return (
            <nav aria-label="Catalog page navigation">
                <ul className="pagination">
                    <li key="page-item-0">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(0)}}
                            href="#"
                            aria-label="Previous"
                        >
                            <span aria-hidden="true">Previous 3</span>
                        </a>
                    </li>
                    <li key="page-item-1">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(1)}}
                            href="#"
                        >
              <span aria-hidden="true">
                {/*{this.navButtonDisplay(this.props.pages.navigation[1])}*/}
                Previous 2
              </span>
                        </a>
                    </li>
                    <li key="page-item-2">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(2)}}
                            href="#"
                        >
              <span aria-hidden="true">
                {/*{this.navButtonDisplay(this.props.pages.navigation[2])}*/}
                Previous 1
              </span>
                        </a>
                    </li>
                    <li key="page-item-3">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(3)}}
                            href="#"
                        >
              <span aria-hidden="true">
                {/*{this.navButtonDisplay(this.props.pages.navigation[3])}*/}
                Next 2
              </span>
                        </a>
                    </li>
                    <li key="page-item-4">
                        <a
                            className="page-link"
                            onClick={() => {this.props.OnPagination(4)}}
                            href="#"
                            aria-label="Next"
                        >
                            <span aria-hidden="true">Next 3</span>
                        </a>
                    </li>
                </ul>
            </nav>
        );
    }
}


问:
Rails 3.1: Views not rendering in namespace layout
In routes.rb:

```<code>namespace :admin do
    root :controller => "base", :action => "index"
    resources :products
end
</code>```

The products controller inherits from the base controller:

```<code>class Admin::BaseController < ApplicationController
   #layout 'admin'
   def index
   end
end

class Admin::ProductsController < Admin::BaseController
   def index
   end
end
</code>```

Without "layout 'admin'", both index views render normally.

With "layout 'admin'", the admin layout is rendered, but the views are not rendered, despite WEBricks message:

```<code>Rendered admin/products/index.html.erb within layouts/admin
</code>```

答: <%= yield %> might help there, mate

ContentLicense: CC BY-SA 3.0

Body:
In routes.rb:

namespace :admin do
    root :controller => "base", :action => "index"
    resources :products
end

The products controller inherits from the base controller:

class Admin::BaseController < ApplicationController
   #layout 'admin'
   def index
   end
end

class Admin::ProductsController < Admin::BaseController
   def index
   end
end

Without "layout 'admin'", both index views render normally.

With "layout 'admin'", the admin layout is rendered, but the views are not rendered, despite WEBricks message:

Rendered admin/products/index.html.erb within layouts/admin

Body: <%= yield %> might help there, mate


问:
Not able to fetch website data using Importxml in Google Sheets
I am trying to fetch this website (https://www.covidhotspots.in/?city=Mumbai&source=share) data using Importxml in Google Sheets but it gives me no data.

I am trying to apply below formula but it is giving me #NA

```<code>=IMPORTXML("https://www.covidhotspots.in/?city=Mumbai&source=share","//li/text()")
</code>```

I want to fetch geocodes as mentioned in the below images

答:
Issue

IMPORTXML can only read the HTML source of a website. Therefore, those elements and components of a website added dynamically will not be able to be retrieved by the IMPORTXML.

If in your browser you take a look and view the source of the website, specifically focusing on the parent ul element that contains the li that you want to retrieve, you will find that the ul element is empty. This is because the children are inserted dynamically throughout a Javascript script (and that is why when you call this IMPORTXML accordinly to that ul nothing is returned, because it is empty in the source HTML).

Possible workaround

Sometimes, in the Javascript files of the website, you can find out the URL of the source of data being inserted dynamically but that is a tedious task to achieve.

I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

Body:
I am trying to fetch this website (https://www.covidhotspots.in/?city=Mumbai&source=share) data using Importxml in Google Sheets but it gives me no data.

I am trying to apply below formula but it is giving me #NA

=IMPORTXML("https://www.covidhotspots.in/?city=Mumbai&source=share","//li/text()")

I want to fetch geocodes as mentioned in the below images


问:
How do I access a prefab and all of its instantiated clones in c# and unity?
I need a little help again please. I'm currently working on powerups and it's setup so that the powerup affectsthe prefab thats put into its prefab slot, so this is means it is currently only affecting one object (in my case, enemy). When the game starts I spawn about 20 enemies and if i pickup the powerup I want it to affect all those spawned enemies and not only the one that is dragged onto the script, does anyone have a solution or alternate method to do this please?</p>

答:
To get all game objects to an array you can use the Tag.

Just add an 'Enemy' tag to the prefab and use the code below:

```<code>public GameObject[] enemys;

void Start()
    {
        respawns = GameObject.FindGameObjectsWithTag("Enemy");
    }
</code>```

Full Unity documentation HERE

Body:
To get all game objects to an array you can use the Tag.

Just add an 'Enemy' tag to the prefab and use the code below:

public GameObject[] enemys;

void Start()
    {
        respawns = GameObject.FindGameObjectsWithTag("Enemy");
    }

Full Unity documentation HERE


问:
OroPlatform without any entity alias
My OroPlatform-based system has no registered alias.

When I enter the command php bin/console oro:entity-alias:debug in the terminal, it returns only the result below:

```<code>Class Alias Plural Alias
</code>```

Does anyone have any idea what may have made all entity alias disappear?

答:
Thankyou for your help.

Yeah, I figured that would be it. I've done this before, but to no avail. I'm going back to the commits.

But I still have no idea what is going on. I will check for any inconsistencies in the DB.

Title: OroPlatform without any entity alias

Body:
My OroPlatform-based system has no registered alias.

When I enter the command php bin/console oro:entity-alias:debug in the terminal, it returns only the result below:

Class Alias Plural Alias

Does anyone have any idea what may have made all entity alias disappear?


问:
How to use the like function to delete the table record?
I have a problem to use the like % function to delete the table record, it cannot follow the 299-1_B to delete the row in the table.

I am used below the sample code to delete:

DELETE FROM filing_code_management WHERE folder_location LIKE '299-1_B%'
```

<p><code>table structure</code></p>

<pre class="lang-html prettyprint-override"><code>no|folder_location
-- ------------------------------------
1   299_A/299-1_B/299-1-1_C/299-1-1-1_D
2   299_A/299-1_B
3   300_B/300-1_C
3   299_A/299-1_B/299-1-1_C/299-1-1-2_F
4   299_A/299-1_B/299-1-2_P/299-1-2-1_Q
</code>```

If success to show the result, the result just show 300_B/300-1_C record. Hope someone can guide me which part I am getting wrong.

答:
I think you want to find the pattern anywhere in the string:

```<code>folder_location LIKE '%299-1_B%'
</code>```

Or perhaps:

```<code>folder_location LIKE '299-1_B%' OR folder_location LIKE '%/299-1_B%'
</code>```

That said, you appear to be storing multiple values in a string.  That is bad, bad, bad.  You should have a separate table with one row per folder location, rather than forcing all of them into a single string.

Body:
I have a problem to use the like % function to delete the table record, it cannot follow the 299-1_B to delete the row in the table.

I am used below the sample code to delete:

DELETE FROM filing_code_management WHERE folder_location LIKE '299-1_B%'

table structure

no|folder_location
-- ------------------------------------
1   299_A/299-1_B/299-1-1_C/299-1-1-1_D
2   299_A/299-1_B
3   300_B/300-1_C
3   299_A/299-1_B/299-1-1_C/299-1-1-2_F
4   299_A/299-1_B/299-1-2_P/299-1-2-1_Q

If success to show the result, the result just show 300_B/300-1_C record. Hope someone can guide me which part I am getting wrong.

Body:
I think you want to find the pattern anywhere in the string:

folder_location LIKE '%299-1_B%'

Or perhaps:

folder_location LIKE '299-1_B%' OR folder_location LIKE '%/299-1_B%'

That said, you appear to be storing multiple values in a string.  That is bad, bad, bad.  You should have a separate table with one row per folder location, rather than forcing all of them into a single string.


问:
Running Oracle SQL scripts with Ansible playbook
A look at the core database modules in Ansible documentation shows no signs of a module for Oracle. What is the best way to handle SQL/PLSQL deployments via Ansible for Oracle databases?

Are we expected to use roles from Ansible Galaxy to handle this? Very few people seem to have downloaded roles listed on Galaxy for Oracle.

答:
I'm not sure if this is related to your question, but I originally was looking for Ansible modules to Start/Stop and get the Status of an Oracle database. I couldn't find anything suitable so I wrote my own ansible modules. Modules give you the power to define a standard interface, with OK/Failed/Changed responses to tasks, while performing as much low-level activity/commands as you need (in this way they are much more flexible than the simple shell/command modules). I wrote the modules to be idempotent -- they won't attempt to start databases that are already started, and won't attempt to stop databases that are already stopped. And if a stop/stop function isn't successful, it returns Failed with stdout/stderr.

Along with Oracle databases, I've also written modules to provide interfaces for Business Objects and Weblogic services. The modules are significant up-front work, but once they are stable they can be used in a wide range of playbooks.

I haven't looked at Galaxy to see if there is anything else like this, and unfortunately due to the nature of my client/contract I'm not sure that I can share the modules that we have developed. I just thought I'd offer this as a possible avenue for you to explore.


问:
number of paths in graph
how could the number of paths in a directed  graph calculated? Are there any algorithms for this purpose?

Best wishes

EDIT: The graph is not a tree.

答:
Let A be the adjacency matrix of a graph G. Then A^n (i.e. A multiplied n times with itself) has the following interesting property:

The entry at position (i,j) of A^n equals the number of different paths of length n from vertex i to vertex j.

Hence:

represent the graph as an adjacency matrix A

multiply A it with itself repeatedly until you get bored

in each step: compute the sum of all matrix elements and add it to the result, starting at 0

It might be wise to first check whether G contains a cycle, because in this case it contains infinitely many paths. In order to detect cycles, set all edge weights to -1 and use Bellman-Ford.

ContentLicense: CC BY-SA 2.5

Title: number of paths in graph


问:
Trying to display image in guillotine.js with dynamic width & height. Working fine with fixed width & height
Trying to display image in guillotine.js with dynamic width & height. Working fine with fixed width & height.

```<code>jQuery(function() {

      var picture = $('#sample_picture');

      // Make sure the image is completely loaded before calling the plugin
      picture.one('load', function(){
        // Initialize plugin (with custom event)
        picture.guillotine({

         var mysize = '<?php echo $size1 ; ?>';
         switch(mysize) {

         case '9x11':
          width: 268,
          height: 375,
          break;
          }
          eventOnChange: 'guillotinechange'});
</code>```

Its working fine with fixed width & height

```<code>picture.guillotine({

          width: 314,
          height: 224,
          }
          eventOnChange: 'guillotinechange'});
</code>```

Note : Variable $size1 from php assigned to mysize correctly.

Help me sort out this issue. Thanks

答:
the main

Your method to work not is so good, you could know about of identation and later is understand how work the programing lenguage. Later that saw your develop problem i try to solve your code issue and i could solved it seeing you fixed example(has errors) and i did it. i hope help you

```<code>jQuery(function() {
let picture = $('#sample_picture');

// Make sure the image is completely loaded before calling the plugin
picture.one('load', ()=>{
    // Initialize plugin (with custom event)

    let mysize = '<?php echo $size1 ; ?>',
        sizes={}
    switch(mysize) {

        case '9x11':
            sizes={
                width: 268,
                height: 375,
            }
        break;
    }
    picture.guillotine(sizes
    eventOnChange: 'guillotinechange'});
</code>```

Body:
Trying to display image in guillotine.js with dynamic width & height. Working fine with fixed width & height.

jQuery(function() {

      var picture = $('#sample_picture');

      // Make sure the image is completely loaded before calling the plugin
      picture.one('load', function(){
        // Initialize plugin (with custom event)
        picture.guillotine({

         var mysize = '<?php echo $size1 ; ?>';
         switch(mysize) {

         case '9x11':
          width: 268,
          height: 375,
          break;
          }
          eventOnChange: 'guillotinechange'});

Its working fine with fixed width & height

picture.guillotine({

          width: 314,
          height: 224,
          }
          eventOnChange: 'guillotinechange'});

Note : Variable $size1 from php assigned to mysize correctly.

Help me sort out this issue. Thanks

Body:
the main

Your method to work not is so good, you could know about of identation and later is understand how work the programing lenguage. Later that saw your develop problem i try to solve your code issue and i could solved it seeing you fixed example(has errors) and i did it. i hope help you

jQuery(function() {
let picture = $('#sample_picture');

// Make sure the image is completely loaded before calling the plugin
picture.one('load', ()=>{
    // Initialize plugin (with custom event)

    let mysize = '<?php echo $size1 ; ?>',
        sizes={}
    switch(mysize) {

        case '9x11':
            sizes={
                width: 268,
                height: 375,
            }
        break;
    }
    picture.guillotine(sizes
    eventOnChange: 'guillotinechange'});


问:
how to know what ReceiveBufferSize to set?
I've figured out that default ReceiveBufferSize (8192) doesn't work for me - I lose packet
Sockets: sometimes (rarely) packets are lost during receiving

However msdn has warning about increasing BufferSize:

http://msdn.microsoft.com/ru-ru/library/system.net.sockets.socket.receivebuffersize.aspx
A larger buffer size potentially reduces the number of empty acknowledgements (TCP packets with no data portion), but might also delay the recognition of connection difficulties. Consider increasing the buffer size if you are transferring large files, or you are using a high bandwidth, high latency connection (such as a satellite broadband provider.)

I know that I need to receive ~2000 packets per second and each datagram contains about 50-100 bytes of data. I'm using low-latency connection (everything in lan). I'm receiving stock exchange data from udp multicast so sometimes traffic my significantly jump (lehman brothers bankruptcy etc.) but let's assume that I will not receive more than 20 000 packets per second.

How to calculate ReceiveBufferSize that will fit my needs?

I absolutely not agree to lose packets, but I do not lose perfomance or reliability or anything else as well.

答:
As you're using UDP, increasing the receive buffer size does not adversely affect detection of connection issues.

Size the buffer according to how long you need to be able to buffer incoming data without your software reading them from the socket - and according to how much memory is available.

You can't control the rate at which data arrives. Also, among others, the Garbage Collector might interrupt your processing. So you're unable to control processing rate reliably, too.
Thus you will have to make tests and/or assumptions and adapt when necessary. If memory is readily available you can choose to have more of a safety buffer by increasing the receive buffer size.


问:
Regex: Invalid group specifier name - react native
My regex works in browser but shows an error in react-native expo app (android) development

Regex:

```<code>/^(?=.{0,20}$)(?![_.0-9])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/
</code>```

error:

```<code>Invalid regular expression: invalid group specifier name
no stack
</code>```

How to fix this error, thanks

答:
I suggest converting the (?<![_.]) lookbehind into a (?!.*[_.]$) lookahead and tighten it a bit (since the length can be checked with the consuming pattern part):

```<code>/^(?!.*[_.]$)(?![_.0-9])(?!.*[_.]{2})[a-zA-Z0-9._]{0,20}$/
</code>```

Details

^ - start of string

(?!.*[_.]$) - no . or _ allowed at the end

(?![_.0-9]) - no _, . and digit allowed at the start

(?!.*[_.]{2}) - no consecutive . or _ allowed anywhere

[a-zA-Z0-9._]{0,20} - 0 to 20 letters, digits, . or _

$ - end of string.

Body:
My regex works in browser but shows an error in react-native expo app (android) development

Regex:

/^(?=.{0,20}$)(?![_.0-9])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/

error:

Invalid regular expression: invalid group specifier name
no stack

How to fix this error, thanks

Body:
I suggest converting the (?<![_.]) lookbehind into a (?!.*[_.]$) lookahead and tighten it a bit (since the length can be checked with the consuming pattern part):

/^(?!.*[_.]$)(?![_.0-9])(?!.*[_.]{2})[a-zA-Z0-9._]{0,20}$/

Details

^ - start of string

(?!.*[_.]$) - no . or _ allowed at the end

(?![_.0-9]) - no _, . and digit allowed at the start

(?!.*[_.]{2}) - no consecutive . or _ allowed anywhere

[a-zA-Z0-9._]{0,20} - 0 to 20 letters, digits, . or _

$ - end of string.


问:
How can I check if an array contains a value of another array?
I would like to check to see if an array contains a value from another array. For example, I would like to check if the array A contains a value from an array B.

I'm looking for any value not one specific value.

答:
Example:

```<code>val a = arrayOf(1, 2, 5, 7, 9, 15)
val b = arrayOf(15, 3, 5, 8)
val c = a intersect b.toList()
if (!c.isEmpty()) {
    println("Arrays have common elements ${c}")
} else {
    println("Arrays do not have common elements")
}
</code>```

Result:

```<code>Arrays have common elements [5, 15]
</code>```

Implementation intersect in Kotlin use Set:

```<code>val set = this.toMutableSet()
set.retainAll(other)
return set
</code>```

and should be enough for most typical casses, for example if both array have 10 000 000 elements, this take about 8 s.

In case when arrays are very large (e.q. when set of such large number of element doesn't fit in memory), possible solution is do sort arrays, and do something like merge of sorted arrays:

```<code>fun hasIntersection(a: IntArray, b: IntArray): Boolean {
    a.sort()
    b.sort()
    var i = 0
    var j = 0
    while (i < a.size && j < b.size) {
        if (a[i] < b[j]) {
            i++
        } else if (a[i] > b[j]) {
            j++
        } else {
            return true
        }
    }
    return false
}
</code>```

Body:
Example:

val a = arrayOf(1, 2, 5, 7, 9, 15)
val b = arrayOf(15, 3, 5, 8)
val c = a intersect b.toList()
if (!c.isEmpty()) {
    println("Arrays have common elements ${c}")
} else {
    println("Arrays do not have common elements")
}

Result:

Arrays have common elements [5, 15]

Implementation intersect in Kotlin use Set:

val set = this.toMutableSet()
set.retainAll(other)
return set

and should be enough for most typical casses, for example if both array have 10 000 000 elements, this take about 8 s.

In case when arrays are very large (e.q. when set of such large number of element doesn't fit in memory), possible solution is do sort arrays, and do something like merge of sorted arrays:

fun hasIntersection(a: IntArray, b: IntArray): Boolean {
    a.sort()
    b.sort()
    var i = 0
    var j = 0
    while (i < a.size && j < b.size) {
        if (a[i] < b[j]) {
            i++
        } else if (a[i] > b[j]) {
            j++
        } else {
            return true
        }
    }
    return false
}


问:
MVC3 + EF4.1 Code First but using .NET Memebership - eh?
I'm currently learning MVC3, EF4.1 and really like the Code First approach.

However, I want to use the built-in .NET Memembership Provider and DB that is generated.

What I can't work out, is how I code up my Domain to link into the Membership DB and also how to get the DB to generate via EF.  I can run the appropriate scripts to generate the DB but then this doesn't work and really doesn't feel right anyhow.

I don't expect full on answers, I just really need pointing in the direction of a tutorial that explains how this could be accomplished.

If the only answer is to implement my own Membership Provider then ok, but again - it feels like a lot of unnecessary work considering that MVC ships with an implementation all ready out of the box?

Regards,

Wayne

答:
if your membership tables are in a different database than your domain tables then you can not use a single DbContext in EF. What you can do in here is that you can create two contexts say SecurityContext and DomainContext for each of those databases. But you will not be able to query by joining entities that reside on each of this contexts and both contexts will not use the same transaction when updating database(ie not a single unit of work).

I would suggest you create those membership tables in your database instead of two databases. Then you can use a single DbContext here(or event 2 if they are completely independent). Here if you modeled all tables, column and relationships correctly you can generate the full database using EF. But if I remember correctly SqlMembershipProvider use stored procedures. If so you will have bit trouble creating the entire database.

If you can provide more info it is easier to give a more specific solution.


问:
Python: Add or remove timezone hours from a timestamp and get actual time
In Python, I need to get the actual time of a given string timestamp converted to a different timezone without timezone information. I am using pytz to do this. But all I get is the given DateTime with the timezone information appended to it.

Base datetime : 2020-05-29 19:00:00 (A string datetime without timezone info)

Requirement: When this time is converted to (US Zipcode 90071) -0700 timezone,
it should return "2020-05-29 12:00:00", not "2020-05-29 19:00:00-0700"

Code:

```<code>import pytz
from datetime import datetime
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder

date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zip = "90071"

search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zip)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])
tz = pytz.timezone(timezone)
new_timestamp = tz.localize(date_time_obj)

new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')
</code>```

But this returns 2020-05-29 19:00:00.000000-0700. I need to retrieve a DateTime object/string with the actual time shown in that timezone without a timezone chunk attached to the end of the DateTime.

答:
It appears that your original date and time are in UTC.  So for localize to work properly, you have to start with the proper timezone attached.

```<code>date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc)
</code>```

Then you can remove it again after the conversion:

```<code>return date_time_obj.astimezone(tz).replace(tzinfo=None)
</code>```

Body:
In Python, I need to get the actual time of a given string timestamp converted to a different timezone without timezone information. I am using pytz to do this. But all I get is the given DateTime with the timezone information appended to it.

Base datetime : 2020-05-29 19:00:00 (A string datetime without timezone info)

Requirement: When this time is converted to (US Zipcode 90071) -0700 timezone,
it should return "2020-05-29 12:00:00", not "2020-05-29 19:00:00-0700"

Code:

import pytz
from datetime import datetime
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder

date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zip = "90071"

search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zip)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])
tz = pytz.timezone(timezone)
new_timestamp = tz.localize(date_time_obj)

new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')

But this returns 2020-05-29 19:00:00.000000-0700. I need to retrieve a DateTime object/string with the actual time shown in that timezone without a timezone chunk attached to the end of the DateTime.

Body:
It appears that your original date and time are in UTC.  So for localize to work properly, you have to start with the proper timezone attached.

date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc)

Then you can remove it again after the conversion:

return date_time_obj.astimezone(tz).replace(tzinfo=None)


问:
NormalizedUserName VS Username in DotNet Core
I'm trying to create a custom implementation of IUserLoginStore for MongoDB and I noticed when using

```<code>UserManager<ApplicationUser>
</code>```

with the method

```<code> var userResult = await _userManager.CreateAsync(user);
</code>```

it goes through the implementation of

```<code>GetUserNameAsync
FindByNameAsync
SetNormalizedUserNameAsync
GetUserIdAsync
</code>```

I would like to clarify two questions:

what's the purpose of having a NormalizedUsername and a UserName?
the only difference that I could notice id that the normalizedUserName is in uppercase.

I'm using my Implementation only to store users from an external login(Google plus), is there a way that I can omit username and NormilizedUserName since basically, I'm using the email in these three fields, I'm feeling that  I'm duplicating data and it doesn't make any sense to me.

any recommendations?

答:
The Normalized Name ensures that symbols used by URL Encoding such as &, ? and Quotes aren't included so that it can be used as a QueryString() or in a URL, and it will survive Encoding unscathed.

Emails don't include those characters which are probably being checked/disallowed by Validation so in this particular case there is not difference between Name and Normalized name.

Body:
I'm trying to create a custom implementation of IUserLoginStore for MongoDB and I noticed when using

UserManager<ApplicationUser>

with the method

 var userResult = await _userManager.CreateAsync(user);

it goes through the implementation of

GetUserNameAsync
FindByNameAsync
SetNormalizedUserNameAsync
GetUserIdAsync

I would like to clarify two questions:

what's the purpose of having a NormalizedUsername and a UserName?
the only difference that I could notice id that the normalizedUserName is in uppercase.

I'm using my Implementation only to store users from an external login(Google plus), is there a way that I can omit username and NormilizedUserName since basically, I'm using the email in these three fields, I'm feeling that  I'm duplicating data and it doesn't make any sense to me.

any recommendations?


问:
How do you test code that is not a model or controller
I have a class defined in a file my Rails project's lib dir that will implement a bunch of utility functions as class methods. I'd like to write tests against those methods using Test::Unit and have them run as part of the project's regular testing routine.

I tried sticking a file at the top level of the test dir...

```<code>require 'test_helper'

class UtilsTest < ActiveSupport::TestCase
  should 'be true' do
    assert false
  end
end
</code>```

...but that didn't work. The test didn't run.

What is the normal way to test code that is not one of the regular parts of Rails?

答:
You can put them in your units directory without any complications.

My Library:

```<code>[ cpm juno ~/apps/feedback ] cat lib/my_library.rb
class MyLib
  def look_at_me
    puts "I DO WEIRD STUFF"
  end
end
</code>```

My Test:

```<code>[ cpm juno ~/apps/feedback ] cat test/unit/fake_test.rb
require 'test_helper'

class FakeTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  def test_truth
    require 'my_library'

    puts "RUNNING THIS NOW"
    MyLib.new.look_at_me
    assert true
  end
end
</code>```

And running it:

```<code>[ cpm juno ~/apps/feedback ] rake test:units
(in /home/cpm/apps/feedback)
/usr/bin/ruby1.8 -Ilib:test "/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/unit/fake_test.rb"
Loaded suite /usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
RUNNING THIS NOW
I DO WEIRD STUFF
.
Finished in 0.254404 seconds.

1 tests, 1 assertions, 0 failures, 0 errors
Loaded suite /var/lib/gems/1.8/bin/rake
Started

Finished in 0.00094 seconds.

0 tests, 0 assertions, 0 failures, 0 errors
</code>```

As long as it ends in _test.rb it should pick it up.

OwnerDisplayName: Ethan

Body:
I have a class defined in a file my Rails project's lib dir that will implement a bunch of utility functions as class methods. I'd like to write tests against those methods using Test::Unit and have them run as part of the project's regular testing routine.

I tried sticking a file at the top level of the test dir...

require 'test_helper'

class UtilsTest < ActiveSupport::TestCase
  should 'be true' do
    assert false
  end
end

...but that didn't work. The test didn't run.

What is the normal way to test code that is not one of the regular parts of Rails?

Body:
You can put them in your units directory without any complications.

My Library:

[ cpm juno ~/apps/feedback ] cat lib/my_library.rb
class MyLib
  def look_at_me
    puts "I DO WEIRD STUFF"
  end
end

My Test:

[ cpm juno ~/apps/feedback ] cat test/unit/fake_test.rb
require 'test_helper'

class FakeTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  def test_truth
    require 'my_library'

    puts "RUNNING THIS NOW"
    MyLib.new.look_at_me
    assert true
  end
end

And running it:

[ cpm juno ~/apps/feedback ] rake test:units
(in /home/cpm/apps/feedback)
/usr/bin/ruby1.8 -Ilib:test "/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/unit/fake_test.rb"
Loaded suite /usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
RUNNING THIS NOW
I DO WEIRD STUFF
.
Finished in 0.254404 seconds.

1 tests, 1 assertions, 0 failures, 0 errors
Loaded suite /var/lib/gems/1.8/bin/rake
Started

Finished in 0.00094 seconds.

0 tests, 0 assertions, 0 failures, 0 errors

As long as it ends in _test.rb it should pick it up.

OwnerDisplayName: cpm


问:
Django ForeignKey on a View
i'm building a django app from an existing database. for better or worse, i have a couple of views that i would like to base my models off. they look something like this:

```<code>class Device(Model):
  id = models.IntegerField( primary_key=True, db_column='node_id' )
  name = models.CharField(max_length=127, db_column='node' )
  class Meta:
    db_table = 'node' # db view
    managed = False

class Entity(Model):
  id = models.IntegerField( primary_key=True, db_column='_id' )
  device = models.ForeignKey(Device, db_column='node_id' )
  class Meta:
    db_table = 'entity' # db view
    managed = Fase
</code>```

so things work okay. however, when i try to use a template that utilises the ForeignKey it is very slow:

```<code>{% for e in entities %}
  {{ e.device.name }}
{% endfor %}
</code>```

looking at the logs, it appears to be repeating queries for each 'node_id', and ultimately timeout out.

(of course, if i do not include e.device.name is all quick)

is there a way i can optimise this?

to be fair, the 'entity' view already has the name of the device as another field (node), so i could use this instead but i would like the relation to exist.

答:
have you try .select_related() in your view?

```<code>entities = Entity.objects.select_related('device').filter(...)
</code>```

in the other hand, if it is and old database, and no autogenerated by django, probably node_id may not be an index in the database, this will slow down a lot any JOIN.

Title: Django ForeignKey on a View

Body:
i'm building a django app from an existing database. for better or worse, i have a couple of views that i would like to base my models off. they look something like this:

class Device(Model):
  id = models.IntegerField( primary_key=True, db_column='node_id' )
  name = models.CharField(max_length=127, db_column='node' )
  class Meta:
    db_table = 'node' # db view
    managed = False

class Entity(Model):
  id = models.IntegerField( primary_key=True, db_column='_id' )
  device = models.ForeignKey(Device, db_column='node_id' )
  class Meta:
    db_table = 'entity' # db view
    managed = Fase

so things work okay. however, when i try to use a template that utilises the ForeignKey it is very slow:

{% for e in entities %}
  {{ e.device.name }}
{% endfor %}

looking at the logs, it appears to be repeating queries for each 'node_id', and ultimately timeout out.

(of course, if i do not include e.device.name is all quick)

is there a way i can optimise this?

to be fair, the 'entity' view already has the name of the device as another field (node), so i could use this instead but i would like the relation to exist.

Body:
have you try .select_related() in your view?

entities = Entity.objects.select_related('device').filter(...)

in the other hand, if it is and old database, and no autogenerated by django, probably node_id may not be an index in the database, this will slow down a lot any JOIN.


问:
Inquiring pod and service subnets from inside Kubernetes cluster
How can one inquire the Kubernetes pod and service subnets in use (e.g. 10.244.0.0/16 and 10.96.0.0/12 respectively) from inside a Kubernetes cluster in a portable and simple way?

For instance, kubectl get cm -n kube-system kubeadm-config -o yaml reports podSubnet and serviceSubnet. But this is not fully portable because a cluster may have been set up by another means than kubeadm.

kubectl get cm -n kube-system kube-proxy -o yaml reports clusterCIDR (i.e. pod subnet) and kubectl get pod -n kube-system kube-apiserver-master1 -o yaml reports the value
passed as command-line option --service-cluster-ip-range to kube-apiserver (i.e. service subnet). master1 stands for the name of any control plane node. But this seems a bit complex.

Is there a better way available e.g. with the Kubernetes 1.17 API?

答:
I don't think it would be possible to obtain what you want in a portable and simple way.
If you don't specify Cidr's parameters it will assign default one.

As you have many ways to run kubernetes as unmanaged clusters like kubeadm, minikbue, k3s, micork8s or managed like Cloud providers (GKE, Azure, AWS) it's hard to find one way to list all cidrs in all environments. Another obstacle can be versions of Kubernetes or CNI.

In Kubernetes 1.17 Release notes you can find information that

Deprecate the default service IP CIDR. The previous default was 10.0.0.0/24 which will be removed in 6 months/2 releases. Cluster admins must specify their own desired value, by using --service-cluster-ip-range on kube-apiserver.

As example of Kubeadm: $ kubeadm init --pod-network-cidr 10.100.0.0/12 --service-cidr 10.99.0.0/12

There are a few ways to get this pod and service-cidr:

```<code>$ kubectl cluster-info dump | grep -E '(service-cluster-ip-range|cluster-cidr)'
                            "--service-cluster-ip-range=10.99.0.0/12",
                            "--cluster-cidr=10.100.0.0/12",

$ kubeadm config view | grep Subnet
  podSubnet: 10.100.0.0/12
  serviceSubnet: 10.99.0.0/12
</code>```

But if you will check all pods in this cluster, some pods are starting with 192.168.190.X or 192.168.137.X

```<code>$ kubectl get pods -A -owide
NAMESPACE     NAME                                       READY   STATUS    RESTARTS   AGE    IP                NODE             NOMINATED NODE   READINESS GATES
default       nginx                                      1/1     Running   0          62m    192.168.190.129   kubeadm-worker   <none>           <none>
kube-system   calico-kube-controllers-77c5fc8d7f-9n6m5   1/1     Running   0          118m   192.168.137.66    kubeadm-master   <none>           <none>
kube-system   calico-node-2kx2v                          1/1     Running   0          117m   10.128.0.4        kubeadm-worker   <none>           <none>
kube-system   calico-node-8xqd9                          1/1     Running   0          118m   10.128.0.3        kubeadm-master   <none>           <none>
kube-system   coredns-66bff467f8-sgmkw                   1/1     Running   0          120m   192.168.137.65    kubeadm-master   <none>           <none>
kube-system   coredns-66bff467f8-t84ht                   1/1     Running   0          120m   192.168.137.67    kubeadm-master   <none>           <none>
</code>```

If you will describe any CNI pods you can find another CIDRs:

```<code>CALICO_IPV4POOL_CIDR:               192.168.0.0/16
</code>```

For GKE example you will have:
node CIDRs

```<code>$ kubectl describe node | grep CIDRs
PodCIDRs:                     10.52.1.0/24
PodCIDRs:                     10.52.0.0/24
PodCIDRs:                     10.52.2.0/24

$ gcloud container clusters describe cluster-2 --zone=europe-west2-b | grep Cidr
clusterIpv4Cidr: 10.52.0.0/14
  clusterIpv4Cidr: 10.52.0.0/14
  clusterIpv4CidrBlock: 10.52.0.0/14
  servicesIpv4Cidr: 10.116.0.0/20
  servicesIpv4CidrBlock: 10.116.0.0/20
  podIpv4CidrSize: 24
servicesIpv4Cidr: 10.116.0.0/20
</code>```

Honestly I don't think there is an easy and portable way to list all podCidrs and serviceCidrs in one simple command.

Body:
I don't think it would be possible to obtain what you want in a portable and simple way.
If you don't specify Cidr's parameters it will assign default one.

As you have many ways to run kubernetes as unmanaged clusters like kubeadm, minikbue, k3s, micork8s or managed like Cloud providers (GKE, Azure, AWS) it's hard to find one way to list all cidrs in all environments. Another obstacle can be versions of Kubernetes or CNI.

In Kubernetes 1.17 Release notes you can find information that

Deprecate the default service IP CIDR. The previous default was 10.0.0.0/24 which will be removed in 6 months/2 releases. Cluster admins must specify their own desired value, by using --service-cluster-ip-range on kube-apiserver.

As example of Kubeadm: $ kubeadm init --pod-network-cidr 10.100.0.0/12 --service-cidr 10.99.0.0/12

There are a few ways to get this pod and service-cidr:

$ kubectl cluster-info dump | grep -E '(service-cluster-ip-range|cluster-cidr)'
                            "--service-cluster-ip-range=10.99.0.0/12",
                            "--cluster-cidr=10.100.0.0/12",

$ kubeadm config view | grep Subnet
  podSubnet: 10.100.0.0/12
  serviceSubnet: 10.99.0.0/12

But if you will check all pods in this cluster, some pods are starting with 192.168.190.X or 192.168.137.X

$ kubectl get pods -A -owide
NAMESPACE     NAME                                       READY   STATUS    RESTARTS   AGE    IP                NODE             NOMINATED NODE   READINESS GATES
default       nginx                                      1/1     Running   0          62m    192.168.190.129   kubeadm-worker   <none>           <none>
kube-system   calico-kube-controllers-77c5fc8d7f-9n6m5   1/1     Running   0          118m   192.168.137.66    kubeadm-master   <none>           <none>
kube-system   calico-node-2kx2v                          1/1     Running   0          117m   10.128.0.4        kubeadm-worker   <none>           <none>
kube-system   calico-node-8xqd9                          1/1     Running   0          118m   10.128.0.3        kubeadm-master   <none>           <none>
kube-system   coredns-66bff467f8-sgmkw                   1/1     Running   0          120m   192.168.137.65    kubeadm-master   <none>           <none>
kube-system   coredns-66bff467f8-t84ht                   1/1     Running   0          120m   192.168.137.67    kubeadm-master   <none>           <none>

If you will describe any CNI pods you can find another CIDRs:

CALICO_IPV4POOL_CIDR:               192.168.0.0/16

For GKE example you will have:
node CIDRs

$ kubectl describe node | grep CIDRs
PodCIDRs:                     10.52.1.0/24
PodCIDRs:                     10.52.0.0/24
PodCIDRs:                     10.52.2.0/24

$ gcloud container clusters describe cluster-2 --zone=europe-west2-b | grep Cidr
clusterIpv4Cidr: 10.52.0.0/14
  clusterIpv4Cidr: 10.52.0.0/14
  clusterIpv4CidrBlock: 10.52.0.0/14
  servicesIpv4Cidr: 10.116.0.0/20
  servicesIpv4CidrBlock: 10.116.0.0/20
  podIpv4CidrSize: 24
servicesIpv4Cidr: 10.116.0.0/20

Honestly I don't think there is an easy and portable way to list all podCidrs and serviceCidrs in one simple command.


问:
PHP dynamic calander
Im trying to make a calander in php (for school). it has to be made 100% generated values. I can do that but I cant figure out how to make it start on monday. It has to be made with only php and html,so no js css or sql is allowed to make it easier.  I'm probaly doing everything wrong here but if anyone knows how I can make a calander, all help is welcome.  (: </p>

```<code><?php
$D1 = date("l-j-m");
$D2 = date("l-j-m", strtotime("+ 1 days"));
$D3 = date("l-j-m", strtotime("+ 2 days"));
$D4 = date("l-j-m", strtotime("+ 3 days"));
$D5 = date("l-j-m", strtotime("+ 4 days"));
$D6 = date("l-j-m", strtotime("+ 5 days"));
$D7 = date("l-j-m", strtotime("+ 6 days"));

$U1 = date("g-a");
$U2 = date("g-a", strtotime("+ 1 hours"));
$U3 = date("g-a", strtotime("+ 2 hours"));
$U4 = date("g-a", strtotime("+ 3 hours"));
$U5 = date("g-a", strtotime("+ 4 hours"));
$U6 = date("g-a", strtotime("+ 5 hours"));
$U7 = date("g-a", strtotime("+ 6 hours"));
$U8 = date("g-a", strtotime("+ 1 hours"));
$U9 = date("g-a", strtotime("+ 2 hours"));
$U10 = date("g-a", strtotime("+ 3 hours"));
$U11 = date("g-a", strtotime("+ 4 hours"));
$U12= date("g-a", strtotime("+ 5 hours"));
$U13 = date("g-a", strtotime("+ 6 hours"));

?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Recept 2</title>
  </head>
  <body>
    <table border="solid">
    <thead>
      <tr>
        <th></th>
        <th><?php echo($D1); ?></th>
        <th><?php echo($D2); ?></th>
        <th><?php echo($D3); ?></th>
        <th><?php echo($D4); ?></th>
        <th><?php echo($D5); ?></th>
        <th><?php echo($D6); ?></th>
        <th><?php echo($D7); ?></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><?php echo($U1); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U2); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U3); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U4); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U5); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U6) ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U7); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U8); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td>1<?php echo($U9); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U10); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U11); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><?php echo($U12); ?></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
    </table>
  </body>
</html>
</code>```

答:
You can use the following HTML template along with the PHP code below - not the most elegant solution but should be simple enough for understanding by a newbie:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-type" content="text/html;charset=utf-8">

         JANUARY
         FEBRUARY
         MARCH
         APRIL

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

{SECTION_1}

         MAY
         JUNE
         JULY
         AUGUST

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

{SECTION_2}

         SEPTEMBER
         OCTOBER
         NOVEMBER
         DECEMBER

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

        M
        T
        W
        T
        F
        S
        S

{SECTION_3}

```

<pre class="lang-php prettyprint-override"><code><?php

// returns HTML for the given month
function month_calendar($year,$month)
{
    $my_time = mktime(0,0,0,$month,1,$year); // Unix timestamp for the beginning of the month
    $start_day = date('N', $my_time);
    $start_week = (int)date('W',$my_time); // because date returns zero-padded value
    $daysInMonth = date('t',$my_time); // how many days in the given month
    $dayNumber = date('z',$my_time) + 1; // day of the year for the 1st date of the month (0 - 365)

    $output = Array();
    // show first week
    $current_week = '<td align="center" class="week_num">'.($start_week++).'</td>';
    if($start_week > 52) $start_week = 1;

    $dayOfWeek = 1;
    while($dayOfWeek < $start_day)
    {
      // show empty cells until we reach the start of the month
        $current_week .= '<td class="day"> </td>';
        $dayOfWeek++;
    }
    $dayOfMonth = 1;
    while($dayOfWeek <= 7)
    {
        $current_week .= '<td class="day"><span class="week_'.($dayOfWeek > 5 ? 'end' : 'day').'" style="padding:2px">'.($dayOfMonth++).'</span></td>';
        $dayOfWeek++;
        $dayNumber++;
    }
    $output[] = $current_week;

    while($dayOfMonth <= $daysInMonth)
    {
      $current_week = '<td align="center" class="week_num">'.($start_week++).'</td>';
        if($start_week > 52) $start_week = 1;
        $dayOfWeek = 1;
        while($dayOfWeek <= 7)
        {
            if($dayOfMonth <= $daysInMonth) $current_week .= '<td class="day"><span class="week_'.($dayOfWeek > 5 ? 'end' : 'day').'" style="padding:2px">'.($dayOfMonth++).'</span></td>';
                else $current_week .= '<td class="day"> </td>'; // show empty cells after the end of the month
            $dayOfWeek++;
            $dayNumber++;
        }
        $output[] = $current_week;
    }
    return $output;
}

// returns HTML for 4 months - starting at the given month/year
function section($year,$month)
{
    $month_1 = month_calendar($year, $month);
    $month_2 = month_calendar($year, $month + 1);
    $month_3 = month_calendar($year, $month + 2);
    $month_4 = month_calendar($year, $month + 3);
    $max_weeks = max(
      count($month_1),
      count($month_2),
      count($month_3),
      count($month_4)
    );
    $empty_week = '';
    for($i = 1; $i <= 8; $i++) // 7 days + a cell for the week number
        $empty_week .= '<td class="day"> </td>';
    $output = '';
    for($i = 0; $i < $max_weeks; $i++)
    {
        $output .= '<tr>';
        $output .= $month_1[$i] != '' ? $month_1[$i] : $empty_week;
        $output .= $month_2[$i] != '' ? $month_2[$i] : $empty_week;
        $output .= $month_3[$i] != '' ? $month_3[$i] : $empty_week;
        $output .= $month_4[$i] != '' ? $month_4[$i] : $empty_week;
        $output .= '</tr>';
    }
    return $output;
}

    if($template = @file_get_contents('/tempates/calendar.html'))
    {
        // show calendar
        $cal_year = 2020;
        $template = str_replace('<tr><td>{SECTION_1}</td></tr>',section($cal_year,1),$template);
        $template = str_replace('<tr><td>{SECTION_2}</td></tr>',section($cal_year,5),$template);
        $template = str_replace('<tr><td>{SECTION_3}</td></tr>',section($cal_year,9),$template);
        echo $template;
    }
    else die('Could not find template - calendar.html');
?>
</code>```

Title: PHP dynamic calander

Body:
Im trying to make a calander in php (for school). it has to be made 100% generated values. I can do that but I cant figure out how to make it start on monday. It has to be made with only php and html,so no js css or sql is allowed to make it easier.  I'm probaly doing everything wrong here but if anyone knows how I can make a calander, all help is welcome.  (:

<?php
$D1 = date("l-j-m");
$D2 = date("l-j-m", strtotime("+ 1 days"));
$D3 = date("l-j-m", strtotime("+ 2 days"));
$D4 = date("l-j-m", strtotime("+ 3 days"));
$D5 = date("l-j-m", strtotime("+ 4 days"));
$D6 = date("l-j-m", strtotime("+ 5 days"));
$D7 = date("l-j-m", strtotime("+ 6 days"));

$U1 = date("g-a");
$U2 = date("g-a", strtotime("+ 1 hours"));
$U3 = date("g-a", strtotime("+ 2 hours"));
$U4 = date("g-a", strtotime("+ 3 hours"));
$U5 = date("g-a", strtotime("+ 4 hours"));
$U6 = date("g-a", strtotime("+ 5 hours"));
$U7 = date("g-a", strtotime("+ 6 hours"));
$U8 = date("g-a", strtotime("+ 1 hours"));
$U9 = date("g-a", strtotime("+ 2 hours"));
$U10 = date("g-a", strtotime("+ 3 hours"));
$U11 = date("g-a", strtotime("+ 4 hours"));
$U12= date("g-a", strtotime("+ 5 hours"));
$U13 = date("g-a", strtotime("+ 6 hours"));

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Recept 2</title>

        <?php echo($D1); ?>
        <?php echo($D2); ?>
        <?php echo($D3); ?>
        <?php echo($D4); ?>
        <?php echo($D5); ?>
        <?php echo($D6); ?>
        <?php echo($D7); ?>

        <?php echo($U1); ?>

        <?php echo($U2); ?>

        <?php echo($U3); ?>

        <?php echo($U4); ?>

        <?php echo($U5); ?>

        <?php echo($U6) ?>

        <?php echo($U7); ?>

        <?php echo($U8); ?>

        1<?php echo($U9); ?>

        <?php echo($U10); ?>

        <?php echo($U11); ?>

        <?php echo($U12); ?>

Body:
You can use the following HTML template along with the PHP code below - not the most elegant solution but should be simple enough for understanding by a newbie:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<style type="text/css">
th.br_bot
{
    border-bottom: 1px solid black;
    padding: 2px;
}

th.br_btr
{
    border-bottom: 1px solid black;
    border-right: 1px solid black;
    padding: 2px;
}

td.week_num
{
    font-size: 9pt;
    border-bottom: 1px solid black;
    border-right: 1px solid black;
    background-color: #D0D0D0;
    padding: 2px;
}

td.day
{
    font-size: 9pt;
    border-bottom: 1px solid black;
    border-right: 1px solid black;
}

td.day_red
{
    font-size: 9pt;
    border-bottom: 1px solid black;
    border-right: 1px solid black;
    background-color: #EFC2C3;
}

td.day_blue
{
    font-size: 9pt;
    border-bottom: 1px solid black;
    border-right: 1px solid black;
    background-color: #B6CBEF;
}

span.week_day
{
    color: black;
}

span.week_end
{
    color: red;
}

</style>
</head>
<body>
<table id="cal" cellspacing="0" cellpadding="0" style="border-left:1px solid black; border-top:1px solid black;font-weight:bold;">
    <tr style="font-size:9pt;" bgcolor="#D6B695">
        <th colspan="8" class="br_btr">&nbsp;JANUARY&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;FEBRUARY&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;MARCH&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;APRIL&nbsp;</th>
    </tr>
    <tr>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
    </tr>
    <tr><td>{SECTION_1}</td></tr>

    <tr style="font-size:9pt;" bgcolor="#D6B695">
        <th colspan="8" class="br_btr">&nbsp;MAY&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;JUNE&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;JULY&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;AUGUST&nbsp;</th>
    </tr>
    <tr>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
    </tr>
    <tr><td>{SECTION_2}</td></tr>

    <tr style="font-size:9pt;" bgcolor="#D6B695">
        <th colspan="8" class="br_btr">&nbsp;SEPTEMBER&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;OCTOBER&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;NOVEMBER&nbsp;</th>
        <th colspan="8" class="br_btr">&nbsp;DECEMBER&nbsp;</th>
    </tr>
    <tr>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
        <th class="br_bot">&nbsp;</th>
        <th class="br_bot">M</th>
        <th class="br_bot">T</th>
        <th class="br_bot">W</th>
        <th class="br_bot">T</th>
        <th class="br_bot">F</th>
        <th class="br_bot">S</th>
        <th class="br_btr">S</th>
    </tr>
    <tr><td>{SECTION_3}</td></tr>
</table>
</body>
</html>

<?php

// returns HTML for the given month
function month_calendar($year,$month)
{
    $my_time = mktime(0,0,0,$month,1,$year); // Unix timestamp for the beginning of the month
    $start_day = date('N', $my_time);
    $start_week = (int)date('W',$my_time); // because date returns zero-padded value
    $daysInMonth = date('t',$my_time); // how many days in the given month
    $dayNumber = date('z',$my_time) + 1; // day of the year for the 1st date of the month (0 - 365)

    $output = Array();
    // show first week
    $current_week = '<td align="center" class="week_num">'.($start_week++).'</td>';
    if($start_week > 52) $start_week = 1;

    $dayOfWeek = 1;
    while($dayOfWeek < $start_day)
    {
      // show empty cells until we reach the start of the month
        $current_week .= '<td class="day">&nbsp;</td>';
        $dayOfWeek++;
    }
    $dayOfMonth = 1;
    while($dayOfWeek <= 7)
    {
        $current_week .= '<td class="day"><span class="week_'.($dayOfWeek > 5 ? 'end' : 'day').'" style="padding:2px">'.($dayOfMonth++).'</span></td>';
        $dayOfWeek++;
        $dayNumber++;
    }
    $output[] = $current_week;

    while($dayOfMonth <= $daysInMonth)
    {
      $current_week = '<td align="center" class="week_num">'.($start_week++).'</td>';
        if($start_week > 52) $start_week = 1;
        $dayOfWeek = 1;
        while($dayOfWeek <= 7)
        {
            if($dayOfMonth <= $daysInMonth) $current_week .= '<td class="day"><span class="week_'.($dayOfWeek > 5 ? 'end' : 'day').'" style="padding:2px">'.($dayOfMonth++).'</span></td>';
                else $current_week .= '<td class="day">&nbsp;</td>'; // show empty cells after the end of the month
            $dayOfWeek++;
            $dayNumber++;
        }
        $output[] = $current_week;
    }
    return $output;
}

// returns HTML for 4 months - starting at the given month/year
function section($year,$month)
{
    $month_1 = month_calendar($year, $month);
    $month_2 = month_calendar($year, $month + 1);
    $month_3 = month_calendar($year, $month + 2);
    $month_4 = month_calendar($year, $month + 3);
    $max_weeks = max(
      count($month_1),
      count($month_2),
      count($month_3),
      count($month_4)
    );
    $empty_week = '';
    for($i = 1; $i <= 8; $i++) // 7 days + a cell for the week number
        $empty_week .= '<td class="day">&nbsp;</td>';
    $output = '';
    for($i = 0; $i < $max_weeks; $i++)
    {
        $output .= '<tr>';
        $output .= $month_1[$i] != '' ? $month_1[$i] : $empty_week;
        $output .= $month_2[$i] != '' ? $month_2[$i] : $empty_week;
        $output .= $month_3[$i] != '' ? $month_3[$i] : $empty_week;
        $output .= $month_4[$i] != '' ? $month_4[$i] : $empty_week;
        $output .= '</tr>';
    }
    return $output;
}

    if($template = @file_get_contents('/tempates/calendar.html'))
    {
        // show calendar
        $cal_year = 2020;
        $template = str_replace('<tr><td>{SECTION_1}</td></tr>',section($cal_year,1),$template);
        $template = str_replace('<tr><td>{SECTION_2}</td></tr>',section($cal_year,5),$template);
        $template = str_replace('<tr><td>{SECTION_3}</td></tr>',section($cal_year,9),$template);
        echo $template;
    }
    else die('Could not find template - calendar.html');
?>


答:
Please use below query,</p>

```<code>DELETE FROM filing_code_management WHERE folder_location LIKE '%299-1_B%'
</code>```

Title: How to use the like function to delete the table record?

Body:
I have a problem to use the like % function to delete the table record, it cannot follow the 299-1_B to delete the row in the table.

I am used below the sample code to delete:

DELETE FROM filing_code_management WHERE folder_location LIKE '299-1_B%'

table structure

no|folder_location
-- ------------------------------------
1   299_A/299-1_B/299-1-1_C/299-1-1-1_D
2   299_A/299-1_B
3   300_B/300-1_C
3   299_A/299-1_B/299-1-1_C/299-1-1-2_F
4   299_A/299-1_B/299-1-2_P/299-1-2-1_Q

If success to show the result, the result just show 300_B/300-1_C record. Hope someone can guide me which part I am getting wrong.

Body:
Please use below query,

DELETE FROM filing_code_management WHERE folder_location LIKE '%299-1_B%'