问:
PowerShell to Get SharePoint Calendar items
I am looking for an option to get SharePoint Calendar items using PowerShell. Could you please answer if you have better way to achieve?

I wants to download all calendar items as csv format from windows 10 machines.

Thank you in advance.

答:
you can do this with pnp powershell module:
https://learn.microsoft.com/en-us/powershell/sharepoint/sharepoint-pnp/sharepoint-pnp-cmdlets?view=sharepoint-ps

first connect to site:

Connect-PnPOnline -Url "{siteurl}"
```

<h3>list items</h3>

<p>recurring events are stored in one listitem. the recurrence pattern is stored in the field "RecurrenceData". so, if you just wanna get the items as they are stored, you can do that with following command:</p>

<pre class="lang-bsh prettyprint-override"><code>$listItems = Get-PnPListItem -List "{listtitle}"
$items = @()
foreach ($item in $listItems) {
    $items += [PSCustomObject]@{
        Title          = $item["Title"]
        Location       = $item["Location"]
        Category       = $item["Category"]
        EventDate      = $item["EventDate"]
        EndDate        = $item["EndDate"]
        fAllDayEvent   = $item["fAllDayEvent"]
        fRecurrence    = $item["fRecurrence"]
        RecurrenceID   = $item["RecurrenceID"]
        RecurrenceData = $item["RecurrenceData"]
    }
}
$items | Export-Csv -Path "items.csv" -Encoding UTF8 -Delimiter ";" -NoTypeInformation
</code>```

items.csv:

```<code>"Title";"Location";"Category";"EventDate";"EndDate";"fAllDayEvent";"fRecurrence";"RecurrenceID";"RecurrenceData"
"test";"asdf";"Treffen";"6/12/2020 9:00:00 AM";"6/12/2020 10:00:00 AM";"False";"False";;
"recurring";;;"6/15/2020 9:00:00 AM";"6/24/2020 10:00:00 AM";"False";"True";;"<recurrence><rule><firstDayOfWeek>mo</firstDayOfWeek><repeat><daily dayFrequency=""1"" /></repeat><repeatInstances>10</repeatInstances></rule></recurrence>"
"allday event";;;"6/26/2020 12:00:00 AM";"6/26/2020 11:59:00 PM";"True";"False";;
</code>```

split recurring events

if you wanna get the recurring events split up, it gets complicated. i tried that with the sprestmethod "/_api/web/lists/GetByTitle('{listtitle}')/RenderListDataAsStream". in the viewxml you can define the daterange for week, month, or year:

$view = [System.IO.File]::ReadAllText("$PSScriptRoot\view.year.xml")
$p = @{
  parameters = @{
    ViewXml = $view
  }
}
$result = Invoke-PnPSPRestMethod -Url "/_api/web/lists/GetByTitle('{listtitle}')/RenderListDataAsStream" -Method Post -Content $p
$items = $result.Row
$items | Export-Csv -Path "items-year.csv"
```

<pre class="lang-xml prettyprint-override"><code><View Type="CALENDAR" TabularView="FALSE" RecurrenceRowset="TRUE" Level="1" BaseViewID="2" ContentTypeID="0x">
  <Query>
    <Where>
      <DateRangesOverlap>
        <FieldRef Name="EventDate" />
        <FieldRef Name="EndDate" />
        <FieldRef Name="RecurrenceID" />
        <Value Type="DateTime">
          <Year />
        </Value>
      </DateRangesOverlap>
    </Where>
  </Query>
  <QueryOptions>
    <RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>
    <ExpandRecurrence>TRUE</ExpandRecurrence>
    <CalendarDate>2020-01-01T12:00:00Z</CalendarDate>
  </QueryOptions>
  <ViewFields>
    <FieldRef Name="EventDate" />
    <FieldRef Name="EndDate" />
    <FieldRef Name="fRecurrence" />
    <FieldRef Name="EventType" />
    <FieldRef Name="WorkspaceLink" />
    <FieldRef Name="Title" />
    <FieldRef Name="Location" />
    <FieldRef Name="Description" />
    <FieldRef Name="Workspace" />
    <FieldRef Name="MasterSeriesItemID" />
    <FieldRef Name="fAllDayEvent" />
  </ViewFields>
  <ViewData>
    <FieldRef Name="Title" Type="CalendarMonthTitle" />
    <FieldRef Name="Title" Type="CalendarWeekTitle" />
    <FieldRef Name="Location" Type="CalendarWeekLocation" />
    <FieldRef Name="Title" Type="CalendarDayTitle" />
    <FieldRef Name="Location" Type="CalendarDayLocation" />
  </ViewData>
  <Toolbar Type="Standard" />
</View>
</code>```

in <CalendarDate>2020-01-01T12:00:00Z</CalendarDate> you can define the date of the view

Body:
you can do this with pnp powershell module:
https://learn.microsoft.com/en-us/powershell/sharepoint/sharepoint-pnp/sharepoint-pnp-cmdlets?view=sharepoint-ps

first connect to site:

Connect-PnPOnline -Url "{siteurl}"

list items

recurring events are stored in one listitem. the recurrence pattern is stored in the field "RecurrenceData". so, if you just wanna get the items as they are stored, you can do that with following command:

$listItems = Get-PnPListItem -List "{listtitle}"
$items = @()
foreach ($item in $listItems) {
    $items += [PSCustomObject]@{
        Title          = $item["Title"]
        Location       = $item["Location"]
        Category       = $item["Category"]
        EventDate      = $item["EventDate"]
        EndDate        = $item["EndDate"]
        fAllDayEvent   = $item["fAllDayEvent"]
        fRecurrence    = $item["fRecurrence"]
        RecurrenceID   = $item["RecurrenceID"]
        RecurrenceData = $item["RecurrenceData"]
    }
}
$items | Export-Csv -Path "items.csv" -Encoding UTF8 -Delimiter ";" -NoTypeInformation

items.csv:

"Title";"Location";"Category";"EventDate";"EndDate";"fAllDayEvent";"fRecurrence";"RecurrenceID";"RecurrenceData"
"test";"asdf";"Treffen";"6/12/2020 9:00:00 AM";"6/12/2020 10:00:00 AM";"False";"False";;
"recurring";;;"6/15/2020 9:00:00 AM";"6/24/2020 10:00:00 AM";"False";"True";;"<recurrence><rule><firstDayOfWeek>mo</firstDayOfWeek><repeat><daily dayFrequency=""1"" /></repeat><repeatInstances>10</repeatInstances></rule></recurrence>"
"allday event";;;"6/26/2020 12:00:00 AM";"6/26/2020 11:59:00 PM";"True";"False";;

split recurring events

if you wanna get the recurring events split up, it gets complicated. i tried that with the sprestmethod "/_api/web/lists/GetByTitle('{listtitle}')/RenderListDataAsStream". in the viewxml you can define the daterange for week, month, or year:

$view = [System.IO.File]::ReadAllText("$PSScriptRoot\view.year.xml")
$p = @{
  parameters = @{
    ViewXml = $view
  }
}
$result = Invoke-PnPSPRestMethod -Url "/_api/web/lists/GetByTitle('{listtitle}')/RenderListDataAsStream" -Method Post -Content $p
$items = $result.Row
$items | Export-Csv -Path "items-year.csv"

<View Type="CALENDAR" TabularView="FALSE" RecurrenceRowset="TRUE" Level="1" BaseViewID="2" ContentTypeID="0x">
  <Query>
    <Where>
      <DateRangesOverlap>
        <FieldRef Name="EventDate" />
        <FieldRef Name="EndDate" />
        <FieldRef Name="RecurrenceID" />
        <Value Type="DateTime">
          <Year />
        </Value>
      </DateRangesOverlap>
    </Where>
  </Query>
  <QueryOptions>
    <RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>
    <ExpandRecurrence>TRUE</ExpandRecurrence>
    <CalendarDate>2020-01-01T12:00:00Z</CalendarDate>
  </QueryOptions>
  <ViewFields>
    <FieldRef Name="EventDate" />
    <FieldRef Name="EndDate" />
    <FieldRef Name="fRecurrence" />
    <FieldRef Name="EventType" />
    <FieldRef Name="WorkspaceLink" />
    <FieldRef Name="Title" />
    <FieldRef Name="Location" />
    <FieldRef Name="Description" />
    <FieldRef Name="Workspace" />
    <FieldRef Name="MasterSeriesItemID" />
    <FieldRef Name="fAllDayEvent" />
  </ViewFields>
  <ViewData>
    <FieldRef Name="Title" Type="CalendarMonthTitle" />
    <FieldRef Name="Title" Type="CalendarWeekTitle" />
    <FieldRef Name="Location" Type="CalendarWeekLocation" />
    <FieldRef Name="Title" Type="CalendarDayTitle" />
    <FieldRef Name="Location" Type="CalendarDayLocation" />
  </ViewData>
  <Toolbar Type="Standard" />
</View>

in <CalendarDate>2020-01-01T12:00:00Z</CalendarDate> you can define the date of the view


来源: stackexchange

问:
How can I fix useState not updating?
, I got the problem with useState on my ImageSlider. It doesn't update and I have no idea how to fix it. I tried everything and cleaned out the code. My friend also checked my code and nothing. I consoled it and it show just sticking to second image. I am learning so please excuse me if my mistake is very basic.

import React, {
  useState,
  useEffect
} from 'react';
import text from './ImageSliderText'

function ImageSlider() {

  const [choosen, setChoosen] = useState('')

  const changeHandler = () => {
    console.log(choosen)
    if (text.ImageSliderText[0].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[1].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[1].header;
      setChoosen(text.ImageSliderText[1].logo);
    } else if (text.ImageSliderText[1].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[2].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[2].header;
      setChoosen(text.ImageSliderText[2].logo);
      console.log('after', choosen)
    } else if (text.ImageSliderText[2].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[3].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[3].header;
      setChoosen(text.ImageSliderText[3].logo);
    } else if (text.ImageSliderText[3].logo === choosen) {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[4].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[4].header;
      setChoosen(text.ImageSliderText[4].logo);
    } else {
      document.getElementById('imageSParagraph').innerHTML = text.ImageSliderText[0].paragraph;
      document.getElementById('imageSHeader').innerHTML = text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    }
    setTimeout(() => changeHandler(), 4000)
  }
  useEffect(() => {
    setChoosen('tak')
    setTimeout(() => console.log('hehe', choosen), 4000)
    // changeHandler()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (

 {
      text.ImageSliderText[0].paragraph
    }

 {
      text.ImageSliderText[0].header
    }
 <
    /div> <
    /div>
 {
      text.ImageSliderText.map((element, index) => {
        return ( <
          div className = 'imageSlider__imagebox'
          key = {
            index
          } >
          <
          img style = {
            {
              opacity: choosen === element.logo ? '1' : '0.3'
            }
          }
          src = {
            element.logo
          }
          alt = 'logo'
          className = 'imageSlider__imagebox--image' / >
          <
          /div>
        )
      })
    } <
    /div>               <
    /div>
  )
}

export default ImageSlider

Here is other file with text.

import logo1 from '../../Images/dun.png'
import logo2 from '../../Images/frog.png'
import logo3 from '../../Images/green.png'
import logo4 from '../../Images/story.png'

export default {
  ImageSliderText: [{
      logo: logo1,
      paragraph: '"Uneasy barton seeing remark happen his has. Am possible offering at contempt mr distance stronger an. Attachment excellence announcing or reasonable am on if indulgence. Exeter talked in agreed spirit no he unable do.  "',
      header: 'Olivia Malerse, Dun Dunder'
    },
    {
      logo: logo2,
      paragraph: '"Greatest properly off ham exercise all. Unsatiable invitation its possession nor off. All difficulty estimating unreserved increasing the solicitude."',
      header: 'Joseph Redmaye'
    },
    {
      logo: logo3,
      paragraph: '"Among ready to which up. Attacks smiling and may out assured moments man nothing outward. Thrown any behind afford either the set depend one temper."',
      header: 'Meda Watson'
    },
    {
      logo: logo4,
      paragraph: '"And can event rapid any shall woman green. Hope they dear who its bred. Sm iling nothing affixed he carried it clothes calling he no."',
      header: 'Daniel Quentin'
    }
  ]
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
So we have a little bit of work to do on this. First I will give you the fixed code and then lets talk about what you can do better.

```<code>function ImageSlider() {
  const [choosen, setChoosen] = useState("");

  const changeHandler = () => {
    if (text.ImageSliderText[0].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[1].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[1].header;
      setChoosen(text.ImageSliderText[1].logo);
    } else if (text.ImageSliderText[1].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[2].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[2].header;
      setChoosen(text.ImageSliderText[2].logo);
    } else if (text.ImageSliderText[2].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[3].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[3].header;
      setChoosen(text.ImageSliderText[3].logo);
    } else if (text.ImageSliderText[3].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[0].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    } else {
      console.log("in here");
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[0].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    }
  };
  useEffect(() => {
    setTimeout(() => changeHandler(), 4000);
    console.log("hehe", choosen);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [choosen]);
</code>```

Issues:

1.) Your useEffect is only running once. That is what the [] means. The square brackets is where you put variables in that you want to monitor, then when they change, rerun this effect. So in the updated code, I have put choosen(should be spelt chosen, but call it anything you like) in there as that is what we are updating. This way, it will rerun the code everytime you setChoosen. So we are going to take the setChoosen out of your useEffect as you are setting it somewhere else.

2.) You only have 4 items in your array. Trying to access [4] is going to access the 5th element in your away which will blow up...You should be using index's based on the current length of your data.

3.) You aren't thinking in react. React is all about building reusable components. Here is an example of how I would rebuild your slider.

Recommendations:

Read Think in react: https://reactjs.org/docs/thinking-in-react.html

Get an account on https://codesandbox.io/ or other playground where
you can type code and send it to people to ask for help.

Keep Practicing

Here is an example for you I put together showing you once you take the time to build out components, how you can easily reuse them to create/modify the rotator you are building:
https://codesandbox.io/s/eloquent-pike-xklcj?file=/src/App.js

ContentLicense: CC BY-SA 4.0

Title: How can I fix useState not updating?

Body:
So we have a little bit of work to do on this. First I will give you the fixed code and then lets talk about what you can do better.

function ImageSlider() {
  const [choosen, setChoosen] = useState("");

  const changeHandler = () => {
    if (text.ImageSliderText[0].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[1].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[1].header;
      setChoosen(text.ImageSliderText[1].logo);
    } else if (text.ImageSliderText[1].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[2].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[2].header;
      setChoosen(text.ImageSliderText[2].logo);
    } else if (text.ImageSliderText[2].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[3].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[3].header;
      setChoosen(text.ImageSliderText[3].logo);
    } else if (text.ImageSliderText[3].logo === choosen) {
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[0].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    } else {
      console.log("in here");
      document.getElementById("imageSParagraph").innerHTML =
        text.ImageSliderText[0].paragraph;
      document.getElementById("imageSHeader").innerHTML =
        text.ImageSliderText[0].header;
      setChoosen(text.ImageSliderText[0].logo);
    }
  };
  useEffect(() => {
    setTimeout(() => changeHandler(), 4000);
    console.log("hehe", choosen);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [choosen]);

Issues:

1.) Your useEffect is only running once. That is what the [] means. The square brackets is where you put variables in that you want to monitor, then when they change, rerun this effect. So in the updated code, I have put choosen(should be spelt chosen, but call it anything you like) in there as that is what we are updating. This way, it will rerun the code everytime you setChoosen. So we are going to take the setChoosen out of your useEffect as you are setting it somewhere else.

2.) You only have 4 items in your array. Trying to access [4] is going to access the 5th element in your away which will blow up...You should be using index's based on the current length of your data.

3.) You aren't thinking in react. React is all about building reusable components. Here is an example of how I would rebuild your slider.

Recommendations:

Read Think in react: https://reactjs.org/docs/thinking-in-react.html

Get an account on https://codesandbox.io/ or other playground where
you can type code and send it to people to ask for help.

Keep Practicing

Here is an example for you I put together showing you once you take the time to build out components, how you can easily reuse them to create/modify the rotator you are building:
https://codesandbox.io/s/eloquent-pike-xklcj?file=/src/App.js


问:
Convert date string (from gmail) to timestamp | Python
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

```<code>from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)
</code>```

But got this error:

```<code>Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'
</code>```

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

答:
Close, you forgot to put the bracket around the last entry. </p>

```<code>date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
</code>```

Body:
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)

But got this error:

Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

Body:
Close, you forgot to put the bracket around the last entry.

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')


问:
Unable to see remote feed on local screen for web Application
I'm following agora.io sample for web app. And I got stuck in this case:

User A connecting by video call. but when connect client unable to see client screen in user A.

The video call is still continue but it's one side call.

How can I detect user B? i am open both screen in same browser with http://localhost:6143/

If i am worong then how i view both remote and local screen?

答:
In order to detect user streams within the channel you need to make sure to set onFirstRemoteVideoFrame within your Agora Engine Event Handler. The Event handler must also be created prior to joining the channel to function properly.

I'm not sure which SDK you are using since Agora doesn't offer a pure C# SDK. So I assume you are using either

the native C++ SDK : https://docs.agora.io/en/Video/API%20Reference/cpp/classagora_1_1rtc_1_1_i_rtc_engine_event_handler.html#a1caf7870fa39a8b938d8d485c3ee7dce

the Unity SDK : https://docs.agora.io/en/Video/API%20Reference/unity/namespaceagora__gaming__rtc.html#a956f307b5ff49f90348b41cf1f367ee3


问:
Angular2 RC5 how to properly configure test module
I'm updating my unit tests for Angular2 RC5. The changelog notes the following breaking change:

addProviders [is deprecated], use TestBed.configureTestingModule instead

But this seems to take error only when attempting to include a service in a test. Where my unit test used to do the following:

```<code>beforeEach(() => addProviders([
    MyService,
    MockBackend,
    ...
]));
</code>```

it should now configure the test module:

```<code>TestBed.configureTestingModule({
    providers: [
        StoryService,
        MockBackend,
        ...
    ]
});
</code>```

But that now throws an error

Service: MyService encountered a declaration exception FAILED

Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before TestBed.configureTestingModule.

I have checked that inject isn't been called before the configureTestingModule. This doesn't affect any other component/directive tests, they seem to pass just fine. How can I resolve this error for unit testing a service with RC5? I realize that I may have to wait until the the testing documentation are updated for RC5 but any insight into possible solutions would be much appreciated.

答:
The problem arise when the TestBed is initialized outside a before each when having two spec files or more.

For example:

```<code>  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });
</code>```

will instanciate a TestBed beforeEach tests, not only the spec file. Hence, if you have another .spec with a TestBed and a beforeEach it will be interpreted as 2 TestBed instanciated like this:

```<code>  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });
</code>```

The error

Failed: Cannot configure the test module when the test module has
  already been instantiated.

will be right, since you instanciate two TestBed (but in two spec files).

To solve this problem, you must always put the TestBed definition (so the beforeEach) in a describe like this:

```<code>describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm updating my unit tests for Angular2 RC5. The changelog notes the following breaking change:

addProviders [is deprecated], use TestBed.configureTestingModule instead

But this seems to take error only when attempting to include a service in a test. Where my unit test used to do the following:

beforeEach(() => addProviders([
    MyService,
    MockBackend,
    ...
]));

it should now configure the test module:

TestBed.configureTestingModule({
    providers: [
        StoryService,
        MockBackend,
        ...
    ]
});

But that now throws an error

Service: MyService encountered a declaration exception FAILED

Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before TestBed.configureTestingModule.

I have checked that inject isn't been called before the configureTestingModule. This doesn't affect any other component/directive tests, they seem to pass just fine. How can I resolve this error for unit testing a service with RC5? I realize that I may have to wait until the the testing documentation are updated for RC5 but any insight into possible solutions would be much appreciated.

Body:
The problem arise when the TestBed is initialized outside a before each when having two spec files or more.

For example:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });

will instanciate a TestBed beforeEach tests, not only the spec file. Hence, if you have another .spec with a TestBed and a beforeEach it will be interpreted as 2 TestBed instanciated like this:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });

The error

Failed: Cannot configure the test module when the test module has
  already been instantiated.

will be right, since you instanciate two TestBed (but in two spec files).

To solve this problem, you must always put the TestBed definition (so the beforeEach) in a describe like this:

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
});


问:
Typescript: define a class type from the return of a function (and use it as a type)
Is there a way to define a class from the return of a function, and then use that as a property type in an interface?

class Foo {};
function makeFoo<T extends Foo>(classType: T): T {
  return classType;
}
const Foo2 = makeFoo(Foo);
new Foo(); // OK
new Foo2(); // OK
interface IFoo {
  foo1: Foo; // OK
  foo2: Foo2; // 'Foo2' refers to a value, but is being used as a type here.
}
```

<p>The real world use case is I have a function that adds some static methods to classes using the class's generic types. So,</p>

<pre class="lang-js prettyprint-override"><code>class DataModel {}
class Foo<T extends DataModel> {}
class Bar extends Foo<DataModel> {
  getInstance() {
    return 'I am an instance';
  }
}

function addStatics<T extends DataModel, TF extends Foo<T>>(
  classType: TF,
): TF & { getStatic: () => T } {
  return Object.defineProperty(classType, 'getStatic', {
    value: () => {},
  });
}

// This is: typeof Bar & { getStatic: () => typeof DataModel; }
const BarWithStatics = addStatics(Bar);
console.log(BarWithStatics.getStatic(), new BarWithStatics().getInstance());
</code>```

In reality it's doing some things with a singleton instance, but yeah, this is the gist of it. I was hoping there was some way to do class BarWithStatics = addStatics(Bar) but no such luck.

答:
Of course as soon as I ask this I figure out the solution. You can extend the return of a function:

class BarWithStatics extends addStatics(Bar) {}
interface IFoo {
  bar: BarWithStatics;
}
```

Body:
Is there a way to define a class from the return of a function, and then use that as a property type in an interface?

class Foo {};
function makeFoo<T extends Foo>(classType: T): T {
  return classType;
}
const Foo2 = makeFoo(Foo);
new Foo(); // OK
new Foo2(); // OK
interface IFoo {
  foo1: Foo; // OK
  foo2: Foo2; // 'Foo2' refers to a value, but is being used as a type here.
}

The real world use case is I have a function that adds some static methods to classes using the class's generic types. So,

class DataModel {}
class Foo<T extends DataModel> {}
class Bar extends Foo<DataModel> {
  getInstance() {
    return 'I am an instance';
  }
}

function addStatics<T extends DataModel, TF extends Foo<T>>(
  classType: TF,
): TF & { getStatic: () => T } {
  return Object.defineProperty(classType, 'getStatic', {
    value: () => {},
  });
}

// This is: typeof Bar & { getStatic: () => typeof DataModel; }
const BarWithStatics = addStatics(Bar);
console.log(BarWithStatics.getStatic(), new BarWithStatics().getInstance());

In reality it's doing some things with a singleton instance, but yeah, this is the gist of it. I was hoping there was some way to do class BarWithStatics = addStatics(Bar) but no such luck.


问:
For a function comma(s), with s being a string containing lowercase letters and numbers, how can I add a comma after each number in Python?
The function can be comma(s), where s is a string argument containing lowercase letters and numbers, and it must return a string with a comma after each number but not if the number is the last character. E.g comma("sr43rt4d4") must return sr43,rt4,d4
In Python </p>

答:
You can use regex that getting all digit followed by lower case character then replace each value returned from the regex with the same value with , in between the result.

```<code>import re

s = "sr43rt4d4"
for i in re.findall(r"\d[a-z]", s):
    s = s.replace(i, "{},{}".format(*i))
print(s)
</code>```

Output

```<code>'sr43,rt4,d4'
</code>```

Body:
You can use regex that getting all digit followed by lower case character then replace each value returned from the regex with the same value with , in between the result.

import re

s = "sr43rt4d4"
for i in re.findall(r"\d[a-z]", s):
    s = s.replace(i, "{},{}".format(*i))
print(s)

Output

'sr43,rt4,d4'


问:
Cronjob Javascript, how to fire job limited times? ( set counter and max limit )
I'm new to Cronjob and looking for a way to fire it with interval but only 5 times.
Im firing an API call with cron and do not want to loop it.
Is it possible to set a counter and max limit of how many times cron has been executed?
or is there another better way of making delayed API calls with nodejs 5 times during 5 min ?</p>

答: Eventually, we end up dropping cron at all. Turns out cron is more time-oriented rather than count, but best workaround was storing counter outside of cron and checking count as the first thing in cron.</p>


问:
FileSystemWatcher stops catching events
I am writing a c# program to let me know when a file has been added or deleted.  I run it on my Windows 7 machine and watch an FTP server on our network.

It works fine but will suddenly stop catching any events.  I'm guessing that it might be losing connection to the server or there is a glitch in the network.

How can I handle this situation in the code.  Is there some exception I can watch for and try to restart the FileSystemWatcher object.

Any suggestions and code samples would be appreciated.

答:
I needed to add an error handler for the FileSystemWatcher

```<code>fileSystemWatcher.Error += new ErrorEventHandler(OnError);
</code>```

And then add this code:

```<code>private void OnError(object source, ErrorEventArgs e)
{
    if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
    {
        txtResults.Text += "Error: File System Watcher internal buffer overflow at " + DateTime.Now + "\r\n";
    }
    else
    {
        txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "\r\n";
    }
    NotAccessibleError(fileSystemWatcher ,e);
}
</code>```

Here is how I reset the SystemFileWatcher object:

```<code>   static void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
    {
        source.EnableRaisingEvents = false;
        int iMaxAttempts = 120;
        int iTimeOut = 30000;
        int i = 0;
        while (source.EnableRaisingEvents == false && i < iMaxAttempts)
        {
            i += 1;
            try
            {
                source.EnableRaisingEvents = true;
            }
            catch
            {
                source.EnableRaisingEvents = false;
                System.Threading.Thread.Sleep(iTimeOut);
            }
        }

    }
</code>```

I think this code should do what I want it to do.

Title: FileSystemWatcher stops catching events

Body:
I needed to add an error handler for the FileSystemWatcher

fileSystemWatcher.Error += new ErrorEventHandler(OnError);

And then add this code:

private void OnError(object source, ErrorEventArgs e)
{
    if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
    {
        txtResults.Text += "Error: File System Watcher internal buffer overflow at " + DateTime.Now + "\r\n";
    }
    else
    {
        txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "\r\n";
    }
    NotAccessibleError(fileSystemWatcher ,e);
}

Here is how I reset the SystemFileWatcher object:

   static void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
    {
        source.EnableRaisingEvents = false;
        int iMaxAttempts = 120;
        int iTimeOut = 30000;
        int i = 0;
        while (source.EnableRaisingEvents == false && i < iMaxAttempts)
        {
            i += 1;
            try
            {
                source.EnableRaisingEvents = true;
            }
            catch
            {
                source.EnableRaisingEvents = false;
                System.Threading.Thread.Sleep(iTimeOut);
            }
        }

    }

I think this code should do what I want it to do.


问:
cannot find module faker after npm install --save-dev
I want to install all my modules locally so I am installing everything with the "--save-dev" switch which updates the package.json.

I am trying to include this module so I installed using this command:

```<code>npm install Faker --save-dev
</code>```

My app structure is like this:

app
  controllers
  models
node_modules
  Faker
server.js

So Faker is in the right place but when I add this code in my server.js file:

```<code>var faker = require('./Faker');
</code>```

I get the following error message:

```<code>Error: Cannot find module './Faker'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/paulcowan/projects/async-talk/server.js:23:13)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
</code>```

But this works:

```<code>var Faker = require('./node_modules/Faker');
</code>```

I did not think that I would have to include the node_modules part.

答: Typescript users coming by, remember to install @types/faker. Then, import faker from 'faker'; works without errors.

Body:
I want to install all my modules locally so I am installing everything with the "--save-dev" switch which updates the package.json.

I am trying to include this module so I installed using this command:

npm install Faker --save-dev

My app structure is like this:

app
  controllers
  models
node_modules
  Faker
server.js

So Faker is in the right place but when I add this code in my server.js file:

var faker = require('./Faker');

I get the following error message:

Error: Cannot find module './Faker'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/paulcowan/projects/async-talk/server.js:23:13)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

But this works:

var Faker = require('./node_modules/Faker');

I did not think that I would have to include the node_modules part.


问:
Parsing comma separated list from HTML response in Go
I am receiving an HTML response in format

[["var1", "var2", "var3"], ["foo", "doo", "goo"], ["moo", "loo", "roo"]]

Is the only way to parse this by using regex on brackets and then looping and slicing each slice again by comma or is there some more efficient way to get the lists into slices? There are tens of thousands of "rows" so performance could be of some significance.

Thanks a lot for your help!

答:
The simple solution is using encoding/json as @icza suggested

```<code>v := `[["var1", "var2", "var3"], ["foo", "doo", "goo"], ["moo", "loo", "roo"]]`
var s [][]string
json.Unmarshal([]byte(v), &s)
fmt.Print(s)
</code>```

Body:
The simple solution is using encoding/json as @icza suggested

v := `[["var1", "var2", "var3"], ["foo", "doo", "goo"], ["moo", "loo", "roo"]]`
var s [][]string
json.Unmarshal([]byte(v), &s)
fmt.Print(s)


问:
Convert table into XML
I have table as below

```<code>Project  Folder   Type     Type_Name    Name          Value
Project1  ABC    Workflow   wf_name   Batch_Table   Table_Name
Project1  ABC    Workflow   wf_name   Batch_Conn    JDBC
Project1  ABC    Mapping    mapp_name BALANCE_Table Bal_Table_Name
Project1  ABC    Mapping    mapp_name Schema        Schema_Name
</code>```

And I need to convert that into the below XML. Is there any way we can achieve this in SQL Server?

I have attached the desired output.

https://i.stack.imgur.com/Yydr4.png

答: You can add FOR XML PATH to your query.

Title: Convert table into XML

Body:
I have table as below

Project  Folder   Type     Type_Name    Name          Value
Project1  ABC    Workflow   wf_name   Batch_Table   Table_Name
Project1  ABC    Workflow   wf_name   Batch_Conn    JDBC
Project1  ABC    Mapping    mapp_name BALANCE_Table Bal_Table_Name
Project1  ABC    Mapping    mapp_name Schema        Schema_Name

And I need to convert that into the below XML. Is there any way we can achieve this in SQL Server?

I have attached the desired output.

https://i.stack.imgur.com/Yydr4.png

Body: You can add FOR XML PATH to your query.


问:
Get cursor position (in characters) within a text Input field
How can I get the caret position from within an input field?

I have found a few bits and pieces via Google, but nothing bullet proof.

Basically something like a jQuery plugin would be ideal, so I could simply do

```<code>$("#myinput").caretPosition()
</code>```

答:
const inpT = document.getElementById("text-box");
const inpC = document.getElementById("text-box-content");
// swch gets  inputs .
var swch;
// swch  if corsur is active in inputs defaulte is false .
var isSelect = false;

var crnselect;
// on focus
function setSwitch(e) {
  swch = e;
  isSelect = true;
  console.log("set Switch: " + isSelect);
}
// on click ev
function setEmoji() {
  if (isSelect) {
    console.log("emoji added :)");
    swch.value += ":)";
    swch.setSelectionRange(2,2 );
    isSelect = true;
  }

}
// on not selected on input .
function onout() {
  // الافنت  اون كي اب
  crnselect = inpC.selectionStart;

  // return input select not active after 200 ms .
  var len = swch.value.length;
  setTimeout(() => {
   (len == swch.value.length)? isSelect = false:isSelect = true;
  }, 200);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1> Try it !</h1>

  <input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">
  <input type="text" onfocus = "setSwitch(this)"  onfocusout = "onout()"  id="text-box-content" size="20" value="content">
<button onclick="setEmoji()">emogi :) </button></code>```

Body:
How can I get the caret position from within an input field?

I have found a few bits and pieces via Google, but nothing bullet proof.

Basically something like a jQuery plugin would be ideal, so I could simply do

$("#myinput").caretPosition()

Body:
const inpT = document.getElementById("text-box");
const inpC = document.getElementById("text-box-content");
// swch gets  inputs .
var swch;
// swch  if corsur is active in inputs defaulte is false .
var isSelect = false;

var crnselect;
// on focus
function setSwitch(e) {
  swch = e;
  isSelect = true;
  console.log("set Switch: " + isSelect);
}
// on click ev
function setEmoji() {
  if (isSelect) {
    console.log("emoji added :)");
    swch.value += ":)";
    swch.setSelectionRange(2,2 );
    isSelect = true;
  }

}
// on not selected on input .
function onout() {
  // الافنت  اون كي اب
  crnselect = inpC.selectionStart;

  // return input select not active after 200 ms .
  var len = swch.value.length;
  setTimeout(() => {
   (len == swch.value.length)? isSelect = false:isSelect = true;
  }, 200);
}

<h1> Try it !</h1>

  <input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">
  <input type="text" onfocus = "setSwitch(this)"  onfocusout = "onout()"  id="text-box-content" size="20" value="content">
<button onclick="setEmoji()">emogi :) </button>


问:
Function always missing 1 required positional argument when stored in a list
I want to store functions in a list and then later in a program call those functions from that list with values also stored on that list.

Example:

```<code>import random
import time

ranges = 23,24
my_functions_and_values = [[random.randint, ranges], [time.sleep, 2]]

for i in my_functions_and_values:
    i[0](i[1])
</code>```

But it gives me the following error:

```<code>TypeError: randint() missing 1 required positional argument: 'b'
</code>```

答:
You can store the parameters to functions as tuples (so 2 will become (2, )). Then when you call the function do parameter unpacking with *:

```<code>import random
import time

ranges = 23,24
my_functions_and_values = [[random.randint, ranges], [time.sleep, (2, )]]

for i in my_functions_and_values:
    i[0](*i[1])
</code>```

Body:
I want to store functions in a list and then later in a program call those functions from that list with values also stored on that list.

Example:

import random
import time

ranges = 23,24
my_functions_and_values = [[random.randint, ranges], [time.sleep, 2]]

for i in my_functions_and_values:
    i[0](i[1])

But it gives me the following error:

TypeError: randint() missing 1 required positional argument: 'b'

Body:
You can store the parameters to functions as tuples (so 2 will become (2, )). Then when you call the function do parameter unpacking with *:

import random
import time

ranges = 23,24
my_functions_and_values = [[random.randint, ranges], [time.sleep, (2, )]]

for i in my_functions_and_values:
    i[0](*i[1])


问:
Identify GoogleTv from Android app
Is there a way for an Android app to tell in the Java code if it is running on GoogleTV vs tablets or phones? </p>

答: The following link might help you: Google TV Android Developer's Guide To optimize your app for a Google TV, just add an additional layour for large screens. However, if you want to determine the device that is currently using the app at runtime, you could try the hasSystemFeature() method. With this you can test for certain hardware features that are unique to Google TV (e.g. you could test for FEATURE_TOUCHSCREEN, as any device but Google TV has one <=> if the feature is not supported, the app is probably running on a TV).</p>

Title: Identify GoogleTv from Android app


问:
What is Guild ID in discord?
So I'm trying to get my discord bot to work but a lot of tutorials/posts said to use this thing called guild id and i dont really like just blatantly copying code.

Thanks in advance for helping

答:
As the offical Discord docs explain :

Guilds in Discord represent an isolated collection of users and channels, and are often referred to as "servers" in the UI.

So guilds are basically servers and guildId is a unique server identifier.

Title: What is Guild ID in discord?


问:
Select all occurrences of a word in WebStorm
Simple question: I am looking for the shortcut in WebStorm to select all the occurrences of a word and then replace them

e.g in my CSS file I want to select all the 'phone' variables at once and change them to 'tab-port'

答:
If you want to select all occurrences directly in the code, you can select all of them with the next shortcut:

Ctrl + Cmd + G on Mac OS X or
Ctrl + Alt + Shift + J on Windows

If you want to replace all occurrences, you can make as chazsolo said.


问:
Class members visibility C++
I need to make the initializer of a class invisible for the child classes, but visible for the main(). How can I do it? The only way I see is to make it PUBLIC, but it will be inherited to the child classes. Any ideas?</p>

答:
Making the initializer private (cannot access the initializer even in main), there are many design patterns you can follow for solving your problem. One of the design pattern is Singelton.
The example is given below:

```<code>#include <iostream>

using namespace std;

class A{
    private:
    static A *single_instance;

    //private constructor, cannot be inherited
    A(){

    }

    public:
    //for getting access in main
    static A *getInstance() {
        if (single_instance==NULL){
            single_instance = new A();
        }
        return single_instance;
    }

    void print() {
        cout<<"I'm from A";
    }

};
//initializing with NULL
A *A ::single_instance=NULL;

class B:A {
    //not access to the constructor

    //but access to getInstance()
};

int main()
{
    //now you can access it in main
    A *obj = obj->getInstance();
    obj->print();
    return 0;
}
</code>```

Note that, this design makes sure, only one instance can be created from your class.

Title: Class members visibility C++

Body:
Making the initializer private (cannot access the initializer even in main), there are many design patterns you can follow for solving your problem. One of the design pattern is Singelton.
The example is given below:

#include <iostream>

using namespace std;

class A{
    private:
    static A *single_instance;

    //private constructor, cannot be inherited
    A(){

    }

    public:
    //for getting access in main
    static A *getInstance() {
        if (single_instance==NULL){
            single_instance = new A();
        }
        return single_instance;
    }

    void print() {
        cout<<"I'm from A";
    }

};
//initializing with NULL
A *A ::single_instance=NULL;

class B:A {
    //not access to the constructor

    //but access to getInstance()
};

int main()
{
    //now you can access it in main
    A *obj = obj->getInstance();
    obj->print();
    return 0;
}

Note that, this design makes sure, only one instance can be created from your class.


问:
How to consolidate / eliminate PHP includes for class files
I have multiple files that I keep including individually.  I want to just put them all in one file to decrease file I/O and just have one include.

Update

Ended up using an auto-loader here is the php.net reference.  Now I don't have to explicitly include each file and according to the reference the files are lazy loaded.

答:
While nothing is stopping you from consolidating all of your class objects into a singe file, to do so would be against basic code design philosophies and also eventually create a monolithic file to manage.

If you are thinking about making a single class to require(), I would suggest keeping your individual classes as their own files, and having your consolidate.php look more like this:

```<code><?php
    /** consolidate.php **/
    require( "class.session.php" );
    require( "class.general.php" );
?>
</code>```

As for the PHP handling, calling require() or include() on a file does not actually call any constructing methods on objects. That said, it does include the entirety of the file. For example, including session.php (2KB) and general.php (3KB) would only include 5KB. Including everything could increase that size dramatically depending on your code base.

Body:
While nothing is stopping you from consolidating all of your class objects into a singe file, to do so would be against basic code design philosophies and also eventually create a monolithic file to manage.

If you are thinking about making a single class to require(), I would suggest keeping your individual classes as their own files, and having your consolidate.php look more like this:

<?php
    /** consolidate.php **/
    require( "class.session.php" );
    require( "class.general.php" );
?>

As for the PHP handling, calling require() or include() on a file does not actually call any constructing methods on objects. That said, it does include the entirety of the file. For example, including session.php (2KB) and general.php (3KB) would only include 5KB. Including everything could increase that size dramatically depending on your code base.


问:
How can I forge a DHCP Discovery packet using Bash?
I would like to send via network (LAN) a classic DHCP Discover package using command line, in order to trigger a response from any DHCP server listening, so I could capture it with something like (say my IP address is 192.168.0.30 ):

```<code>tcpdump -i eth0 host 192.168.0.30 -n -s 0 -vvv -w listening.pcap
</code>```

I think about this as a simple method to detect rogue DHCP servers on a network.

How can I do this using Bash ?

Further data:

Other tools allowed, but lets try to keep ti simple: NetCat, sed, grep... etc.

Similar example for forging WOL packet: Bash one-line command to send wake on LAN magic packet without specific tool

答:
Replacement solution - in the name of convenience.

Wouldn't it be easier to scan the network for DHCP servers?

```<code># nmap -sU -p 67 --script=dhcp-discover 192.168.43.0/24 |awk -v RS= '/dhcp-discover/'
</code>```

result:

```<code>Starting Nmap 7.40 ( https://nmap.org ) at 2020-05-29 18:38 UTC
Nmap scan report for 192.168.43.1
Host is up (0.0052s latency).
PORT   STATE SERVICE
67/udp open  dhcps
| dhcp-discover:
|   DHCP Message Type: DHCPACK
|   Server Identifier: 192.168.43.1
|   IP Address Lease Time: 47m22s
|   Subnet Mask: 255.255.255.0
|   Broadcast Address: 192.168.43.255
|   Router: 192.168.43.1
|   Domain Name Server: 192.168.43.1
|_  Vendor Specific Information: ANDROID_METERED
MAC Address: xx:xx:xx:xx:xx:xx (Chiun Mai Communication Systems)
</code>```

Perhaps it would be more sensible to secure yourself with the use of "dhcp snooping" (layer 2 OSI model ) on the switch, which consists in rejecting any DHCP packets that do not come from a trusted interface.

Body:
I would like to send via network (LAN) a classic DHCP Discover package using command line, in order to trigger a response from any DHCP server listening, so I could capture it with something like (say my IP address is 192.168.0.30 ):

tcpdump -i eth0 host 192.168.0.30 -n -s 0 -vvv -w listening.pcap

I think about this as a simple method to detect rogue DHCP servers on a network.

How can I do this using Bash ?

Further data:

Other tools allowed, but lets try to keep ti simple: NetCat, sed, grep... etc.

Similar example for forging WOL packet: Bash one-line command to send wake on LAN magic packet without specific tool

Body:
Replacement solution - in the name of convenience.

Wouldn't it be easier to scan the network for DHCP servers?

# nmap -sU -p 67 --script=dhcp-discover 192.168.43.0/24 |awk -v RS= '/dhcp-discover/'

result:

Starting Nmap 7.40 ( https://nmap.org ) at 2020-05-29 18:38 UTC
Nmap scan report for 192.168.43.1
Host is up (0.0052s latency).
PORT   STATE SERVICE
67/udp open  dhcps
| dhcp-discover:
|   DHCP Message Type: DHCPACK
|   Server Identifier: 192.168.43.1
|   IP Address Lease Time: 47m22s
|   Subnet Mask: 255.255.255.0
|   Broadcast Address: 192.168.43.255
|   Router: 192.168.43.1
|   Domain Name Server: 192.168.43.1
|_  Vendor Specific Information: ANDROID_METERED
MAC Address: xx:xx:xx:xx:xx:xx (Chiun Mai Communication Systems)

Perhaps it would be more sensible to secure yourself with the use of "dhcp snooping" (layer 2 OSI model ) on the switch, which consists in rejecting any DHCP packets that do not come from a trusted interface.


问:
How do you identify questions that the bot could not answer
My organisation is starting to experiment with the Microsoft bot framework. One of the questions our enterprise architect has asked is as follows:

How do we identify questions that the bot was unable to answer?

I've checked the documentation but I'm still unclear. Can anyone elaborate on the techniques that they use to identify unanswered questions? We feel this is important as it identifies opportunities for further growth.

答: Depending of the size and the complexity of your model you will want to use LUIS or qnamaker. If your mother is very simple qnamaker will works. for something a bit more complex especially if you want to make use of entities LUIS is definitely the way to go. Each of them have their own technique and @steviebleeds describe how to do it on qnamaker. For Louis you are going to look at your confidence threshold and you should record that have below the confidence threshold you have set. each time you get a prediction from Lewis it send you a list of intent each of them having a confidence percentage on the predictions. You should assess this confidence percentage and decide depending of your fresh hold if you want or not to answer you users. You also want to look at all questions that have return none intent.</p>


问:
The Use of "Navigate(-1)" Fails to Return to Previous Location in Gatsby
I am trying to create a simple "Back" button in Gatsby that returns the the previous page and retains the scroll position. This already happens when using the browser back button, but I'm struggling to produce a custom one. I've read in the Reach Router docs that you can add -1 as an argument to the navigate function to return to previous locations, but It instead throws the number value into the url and gives me a 404. Can someone give me an idea of what I've done wrong? Or if anyone else has managed to make a functional back button for Gatsby projects?

Here is my code-

```<code>import React from 'react';
import { graphql, navigate } from 'gatsby'
import Img from "gatsby-image"

import "./design.scss"

const designTemplate = (props) => {
  return (
      <section className="design">
        <div className="design__container">
        <h2 className="design__title">
          {props.data.design.title}
        </h2>
        <Img className="design__image" fluid={props.data.design.localImage.childImageSharp.fluid} />
        <p className="design__summary">
          {props.data.design.summary}
        </p>
        </div>
        <button onClick={navigate(-1)}>Go Back</button>
      </section>
  );
}
</code>```

答:
The issue you're having here is just that you didn't define a callback function for your onClick handler.

Instead of this:

```<code><button onClick={navigate(-1)}>Go Back</button>
</code>```

…you want to do this:

```<code><button onClick={() => { navigate(-1) }}>Go Back</button>
</code>```

Body:
I am trying to create a simple "Back" button in Gatsby that returns the the previous page and retains the scroll position. This already happens when using the browser back button, but I'm struggling to produce a custom one. I've read in the Reach Router docs that you can add -1 as an argument to the navigate function to return to previous locations, but It instead throws the number value into the url and gives me a 404. Can someone give me an idea of what I've done wrong? Or if anyone else has managed to make a functional back button for Gatsby projects?

Here is my code-

import React from 'react';
import { graphql, navigate } from 'gatsby'
import Img from "gatsby-image"

import "./design.scss"

const designTemplate = (props) => {
  return (

          {props.data.design.title}

          {props.data.design.summary}

        <button onClick={navigate(-1)}>Go Back</button>

  );
}

Body:
The issue you're having here is just that you didn't define a callback function for your onClick handler.

Instead of this:

<button onClick={navigate(-1)}>Go Back</button>

…you want to do this:

<button onClick={() => { navigate(-1) }}>Go Back</button>


问:
Is there any way to change color after every 7 days after specific date?
I want to change color of div after every 7 days. I have tried changing it using if statements but I want more specific way of doing it (automatically after 7 days add color).

This is what I tried:

```<code>     <div class="hello">
    checking

</div>
<script>
    var currentDate = new Date().getDate()
        console.log(currentDate)
        var hello = document.querySelector(".hello")
        function getMondays() {
            var d = new Date(),
                month = d.getMonth(),
                mondays = [];
            d.setDate(1);
            // Get the first Monday in the month
            while (d.getDay() !== 1) {
                d.setDate(d.getDate() + 1);
            }

            // Get all the other Mondays in the month
            while (d.getMonth() === month) {
              console.log(new Date(d.getTime()))
                mondays.push(new Date(d.getTime()));
                d.setDate(d.getDate() + 7);
            }
            console.log(mondays)

            if(mondays.length === 4 ){
                hello.setAttribute("alt","")
                hello.removeAttribute("src")
                console.log("in 4")
              if(currentDate > 0 && currentDate < mondays[0].getDate()){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[0].getDate() && currentDate < mondays[1].getDate()  ){
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[1].getDate() && currentDate < mondays[2].getDate()  ){
                  hello.style.backgroundColor = "purple"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[2].getDate() && currentDate < mondays[3].getDate()  ){
                  hello.style.backgroundColor = "blue"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[3].getDate() && currentDate <= 31  ){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
            }
            if(mondays.length === 5 ){
              console.log("in 5")
              if(currentDate > 0 && currentDate < mondays[0].getDate()){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[0].getDate() && currentDate < mondays[1].getDate()  ){
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[1].getDate() && currentDate < mondays[2].getDate()  ){
                  hello.style.backgroundColor = "purple"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[2].getDate() && currentDate < mondays[3].getDate()  ){
                  hello.style.backgroundColor = "blue"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[3].getDate() && currentDate < mondays[4].getDate()   ){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[4].getDate() && currentDate <= 31  ){
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
            }
        }
        getMondays()
   </script>
</code>```

in this code I am taking Mondays of the current month and adding color one by one. And I want to add 4 colors.

The issue is when we have 5 weeks: then it will not loop accordingly.

答:
Something on these lines? I think it has bugs but it should give you a gist.

```<code>// Get a date
const date = new Date();
// Todays date ex: 30
const numDate = date.getDate();
// Todays day of week: sunday = 0;monday = 1; so on
const numDay = date.getDay();
// Go to sunday
date.setDate(numDate - numDay);

const weekNum = Math.floor(date.getDate() / 7);

const colors = ["Red", "blue", "green", "orange", "pink"]
const todaysColor = colors[weekNum]
</code>```

Here is the codepen: https://codepen.io/kishin-karra/pen/yLYmYvE
Have updated the codepen as well

Body:
I want to change color of div after every 7 days. I have tried changing it using if statements but I want more specific way of doing it (automatically after 7 days add color).

This is what I tried:

    checking

in this code I am taking Mondays of the current month and adding color one by one. And I want to add 4 colors.

The issue is when we have 5 weeks: then it will not loop accordingly.

Body:
Something on these lines? I think it has bugs but it should give you a gist.

// Get a date
const date = new Date();
// Todays date ex: 30
const numDate = date.getDate();
// Todays day of week: sunday = 0;monday = 1; so on
const numDay = date.getDay();
// Go to sunday
date.setDate(numDate - numDay);

const weekNum = Math.floor(date.getDate() / 7);

const colors = ["Red", "blue", "green", "orange", "pink"]
const todaysColor = colors[weekNum]

Here is the codepen: https://codepen.io/kishin-karra/pen/yLYmYvE
Have updated the codepen as well


问:
".ant does not exist" error building Aibu
I succeeded in building CoffeeShop (https://github.com/lukacu/coffeeshop) using Ant. However, I am unable to build Aibu, an image sequence annotator.

pc-194-6:aibu June$ ant
Buildfile: /Users/liangjun/Documents/aibu/build.xml
```

<p><strong>ivy:</strong></p>

<pre class="lang-none prettyprint-override"><code>BUILD FAILED
/Users/liangjun/Documents/aibu/build.xml:13: /Users/liangjun/.ant does not exist.
</code>```

答:
I had a similar problem building a jar using ant build .
I "solved" it by mkdir ~/.ant/lib
and reran ant compile jar
and it ran successfully.

Seems a bit tacky :-)

Body:
I succeeded in building CoffeeShop (https://github.com/lukacu/coffeeshop) using Ant. However, I am unable to build Aibu, an image sequence annotator.

pc-194-6:aibu June$ ant
Buildfile: /Users/liangjun/Documents/aibu/build.xml

ivy:

BUILD FAILED
/Users/liangjun/Documents/aibu/build.xml:13: /Users/liangjun/.ant does not exist.


问:
Property of a PHP Object itself is another Object of another class
I am pretty sure that we can store reference to an Object's property with an Object of a different class.
But I am stuck with this code.

The __construct() functions of both metro and town assigns the values for $name and $pop of those objects . But I need the __construct() function of the class city to create a new object of either class metro or class town depending on the value of $pop of the object of class city

```<code><?php

class metro
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class town
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class city
{
  public $name;
  public $pop;
  public $derived_city;

  function __construct($name,$pop)
   {
    $this->name = $name;
    $this->pop = $pop;
    if ($this->pop >= 50)
    {
      $derived_city = new metro($this->name,$this->pop);
    }
    else
    {
      $derived_city = new town($this->name,$this->pop);
    }
  }
}

$city1 = new city("Bombay",100);
echo $city1->derived_city->pop;
?>
</code>```

答:
Do this:</p>

```<code>class metro
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class town
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class city
{
  public $name;
  public $pop;
  public $derived_city;

  function __construct($name,$pop)
   {
    $this->name = $name;
    $this->pop = $pop;
    if ($this->pop >= 50)
    {
      $derived_city = new metro($this->name,$this->pop);
    }
    else
    {
      $derived_city = new town($this->name,$this->pop);
    }

    $this->derived_city = $derived_city;
  }
}

$city1 = new city("Bombay",100);
print_r($city1->derived_city);
echo $city1->derived_city->pop;
</code>```

Body:
I am pretty sure that we can store reference to an Object's property with an Object of a different class.
But I am stuck with this code.

The __construct() functions of both metro and town assigns the values for $name and $pop of those objects . But I need the __construct() function of the class city to create a new object of either class metro or class town depending on the value of $pop of the object of class city

<?php

class metro
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class town
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class city
{
  public $name;
  public $pop;
  public $derived_city;

  function __construct($name,$pop)
   {
    $this->name = $name;
    $this->pop = $pop;
    if ($this->pop >= 50)
    {
      $derived_city = new metro($this->name,$this->pop);
    }
    else
    {
      $derived_city = new town($this->name,$this->pop);
    }
  }
}

$city1 = new city("Bombay",100);
echo $city1->derived_city->pop;
?>

Body:
Do this:

class metro
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class town
{
  public $name;
  public $pop;

  function __construct($name,$pop)
  {
    $this->name = $name;
    $this->pop = $pop;
  }
}

class city
{
  public $name;
  public $pop;
  public $derived_city;

  function __construct($name,$pop)
   {
    $this->name = $name;
    $this->pop = $pop;
    if ($this->pop >= 50)
    {
      $derived_city = new metro($this->name,$this->pop);
    }
    else
    {
      $derived_city = new town($this->name,$this->pop);
    }

    $this->derived_city = $derived_city;
  }
}

$city1 = new city("Bombay",100);
print_r($city1->derived_city);
echo $city1->derived_city->pop;


问:
Syntax error on line 6 'if/elif statements' and 'and/or statements'
I am continually getting a syntax error on line 6 when trying to run this code. I've tried messing with the indentation and have browsed related questions on this site to no avail. Any help would be greatly appreciated! Thank you!

```<code>#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if ((input_month == 'March') and (20 <= input_day <= 31))
or ((input_month == 'June') and (1 <= input_day <= 20))
    print('Spring')

#input reading for summer
elif (input_month == 'June') and (21 <= input_day <= 30)
or (input_month == 'September') and (1 <= input_day <= 30)
    print('Summer')

#input reading for Autumn
elif (input_month == 'September') and (22 <= input_day <= 30)
or (input_month == 'December') and (1 <= input_day <= 20)
    print('Autumn')

#input reading for winter
elif (input_month == 'December') and (21 <= input_day <= 31)
or (input_month == 'January') and (1 <= input_day <= 31)
or (input_month == 'February') and (1 <= input_day <= 28)
or (input_month == 'March') and (1 <= input_day <= 19)
    print('Winter')
</code>```

Edit: the error reads 'EOL error' which has in the past meant that I didn't define a variable or didn't write the variable correctly. This doesn't seem to be the case though.

Thank you all for the help!!

Here's the updated, working code including all months:

```<code>#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if input_month == 'March' and 20 <= input_day <= 31\
or input_month == 'April' and 1 <= input_day <= 30\
or input_month == 'May' and 1 <= input_day <= 31\
or input_month == 'June' and 1 <= input_day <= 20:
    print('Spring')

#input reading for summer
elif input_month == 'June' and 21 <= input_day <= 30\
or input_month == 'July' and 1 <= input_day <= 31\
or input_month == 'August' and 1 <= input_day <= 31\
or input_month == 'September' and 1 <= input_day <= 30:
    print('Summer')

#input reading for Autumn
elif input_month == 'September' and 22 <= input_day <= 30\
or input_month == 'October' and 1 <= input_day <= 31\
or input_month == 'November' and 1 <= input_day <= 30\
or input_month == 'December' and 1 <= input_day <= 20:
    print('Autumn')

#input reading for winter
elif input_month == 'December' and 21 <= input_day <= 31\
or input_month == 'January' and 1 <= input_day <= 31\
or input_month == 'February' and 1 <= input_day <= 28\
or input_month == 'March' and 1 <= input_day <= 19:
    print('Winter')

#if input is not valid
else:
    print('Invalid')
</code>```

答:
Here is a syntactically correct code (with backslashes):

```<code>input_month = input()
input_day = int(input())

if input_month == 'March' and 20 <= input_day <= 31 or input_month \
    == 'June' and 1 <= input_day <= 20:
    print('Spring')
elif input_month == 'June' and 21 <= input_day <= 30 or input_month \
    == 'September' and 1 <= input_day <= 30:
    print('Summer')
elif input_month == 'September' and 22 <= input_day <= 30 \
    or input_month == 'December' and 1 <= input_day <= 20:
    print('Autumn')
elif input_month == 'December' and 21 <= input_day <= 31 or input_month \
    == 'January' and 1 <= input_day <= 31 or input_month == 'February' \
    and 1 <= input_day <= 28 or input_month == 'March' and 1 \
    <= input_day <= 19:
    print('Winter')
</code>```

Though, there are ways to make the solution more readable, pythonic and compact. For example, like this:

```<code>MONTHS = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November",
          "December"]

BOUNDARIES = [((3, 20), (6, 20), "Spring"),
              ((6, 21), (9, 21), "Summer"),  # FIXED THE UPPER BOUNDARY
              ((9, 22), (12, 20), "Autumn"),
              ((12, 21), (12, 31), "Winter"),
              ((1, 1), (3, 19), "Winter")]

input_month = input()
input_day = int(input())

input_date = (MONTHS.index(input_month) + 1, input_day)

for lower, upper, season in BOUNDARIES:
    if lower <= input_date <= upper:
        print(season)
        break
</code>```

or (less efficient way) like this:

```<code>SEASONS = {"Spring": [
               ("March", (20, 32)),
               ("June", (1, 21)),
                ],
           "Summer": [
               ("June", (21, 31)),
               ("September", (1, 31)),
                ],
           "Autumn": [
               ("September", (22, 31)),
               ("December", (1, 21)),
                ],
           "Winter": [
               ("December", (21, 32)),
               ("January", (1, 32)),
               ("February", (1, 29)),
               ("March", (1, 20)),
                ]
           }

input_month = input()
input_day = int(input())

for season in SEASONS:
    for month, day_ranges in SEASONS[season]:
        if input_month == month and input_day in range(*day_ranges):
            print(season)
    else:
        continue
    break
</code>```

Body:
I am continually getting a syntax error on line 6 when trying to run this code. I've tried messing with the indentation and have browsed related questions on this site to no avail. Any help would be greatly appreciated! Thank you!

#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if ((input_month == 'March') and (20 <= input_day <= 31))
or ((input_month == 'June') and (1 <= input_day <= 20))
    print('Spring')

#input reading for summer
elif (input_month == 'June') and (21 <= input_day <= 30)
or (input_month == 'September') and (1 <= input_day <= 30)
    print('Summer')

#input reading for Autumn
elif (input_month == 'September') and (22 <= input_day <= 30)
or (input_month == 'December') and (1 <= input_day <= 20)
    print('Autumn')

#input reading for winter
elif (input_month == 'December') and (21 <= input_day <= 31)
or (input_month == 'January') and (1 <= input_day <= 31)
or (input_month == 'February') and (1 <= input_day <= 28)
or (input_month == 'March') and (1 <= input_day <= 19)
    print('Winter')

Edit: the error reads 'EOL error' which has in the past meant that I didn't define a variable or didn't write the variable correctly. This doesn't seem to be the case though.

Thank you all for the help!!

Here's the updated, working code including all months:

#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if input_month == 'March' and 20 <= input_day <= 31\
or input_month == 'April' and 1 <= input_day <= 30\
or input_month == 'May' and 1 <= input_day <= 31\
or input_month == 'June' and 1 <= input_day <= 20:
    print('Spring')

#input reading for summer
elif input_month == 'June' and 21 <= input_day <= 30\
or input_month == 'July' and 1 <= input_day <= 31\
or input_month == 'August' and 1 <= input_day <= 31\
or input_month == 'September' and 1 <= input_day <= 30:
    print('Summer')

#input reading for Autumn
elif input_month == 'September' and 22 <= input_day <= 30\
or input_month == 'October' and 1 <= input_day <= 31\
or input_month == 'November' and 1 <= input_day <= 30\
or input_month == 'December' and 1 <= input_day <= 20:
    print('Autumn')

#input reading for winter
elif input_month == 'December' and 21 <= input_day <= 31\
or input_month == 'January' and 1 <= input_day <= 31\
or input_month == 'February' and 1 <= input_day <= 28\
or input_month == 'March' and 1 <= input_day <= 19:
    print('Winter')

#if input is not valid
else:
    print('Invalid')

Body:
Here is a syntactically correct code (with backslashes):

input_month = input()
input_day = int(input())

if input_month == 'March' and 20 <= input_day <= 31 or input_month \
    == 'June' and 1 <= input_day <= 20:
    print('Spring')
elif input_month == 'June' and 21 <= input_day <= 30 or input_month \
    == 'September' and 1 <= input_day <= 30:
    print('Summer')
elif input_month == 'September' and 22 <= input_day <= 30 \
    or input_month == 'December' and 1 <= input_day <= 20:
    print('Autumn')
elif input_month == 'December' and 21 <= input_day <= 31 or input_month \
    == 'January' and 1 <= input_day <= 31 or input_month == 'February' \
    and 1 <= input_day <= 28 or input_month == 'March' and 1 \
    <= input_day <= 19:
    print('Winter')

Though, there are ways to make the solution more readable, pythonic and compact. For example, like this:

MONTHS = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November",
          "December"]

BOUNDARIES = [((3, 20), (6, 20), "Spring"),
              ((6, 21), (9, 21), "Summer"),  # FIXED THE UPPER BOUNDARY
              ((9, 22), (12, 20), "Autumn"),
              ((12, 21), (12, 31), "Winter"),
              ((1, 1), (3, 19), "Winter")]

input_month = input()
input_day = int(input())

input_date = (MONTHS.index(input_month) + 1, input_day)

for lower, upper, season in BOUNDARIES:
    if lower <= input_date <= upper:
        print(season)
        break

or (less efficient way) like this:

SEASONS = {"Spring": [
               ("March", (20, 32)),
               ("June", (1, 21)),
                ],
           "Summer": [
               ("June", (21, 31)),
               ("September", (1, 31)),
                ],
           "Autumn": [
               ("September", (22, 31)),
               ("December", (1, 21)),
                ],
           "Winter": [
               ("December", (21, 32)),
               ("January", (1, 32)),
               ("February", (1, 29)),
               ("March", (1, 20)),
                ]
           }

input_month = input()
input_day = int(input())

for season in SEASONS:
    for month, day_ranges in SEASONS[season]:
        if input_month == month and input_day in range(*day_ranges):
            print(season)
    else:
        continue
    break


问:
sklearn Pipeline: argument of type 'ColumnTransformer' is not iterable
I am attempting to use a pipeline to feed an ensemble voting classifier as I want the ensemble learner to use models that train on different feature sets. For this purpose, I followed the tutorial available at [1].

Following is the code that I could develop so far.

```<code>y = df1.index
x = preprocessing.scale(df1)

phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])

fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])

pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])

ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])

cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
    x_train, x_test = x[train_index], x[test_index]
    y_train, y_test = y[train_index], y[test_index]
    ens.fit(x_train,y_train)
    print(ens.score(x_test, y_test))
</code>```

However, when running the code, I am getting an error saying TypeError: argument of type 'ColumnTransformer' is not iterable, at the line ens.fit(x_train,y_train).

Following is the complete stack trace that I am receiving.

```<code>Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/ASUS/PycharmProjects/swelltest/enemble.py", line 112, in <module>
    ens.fit(x_train,y_train)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 265, in fit
    return super().fit(X, transformed_y, sample_weight)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 65, in fit
    names, clfs = self._validate_estimators()
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_base.py", line 228, in _validate_estimators
    self._validate_names(names)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in _validate_names
    invalid_names = [name for name in names if '__' in name]
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in <listcomp>
    invalid_names = [name for name in names if '__' in name]
TypeError: argument of type 'ColumnTransformer' is not iterable
</code>```

Following are the values in the names list when the error is occuring.

```<code>1- ColumnTransformer(transformers=[('phy',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['HR', 'RMSSD', 'SCL'])])
2- ColumnTransformer(transformers=[('fa',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['Squality', 'Sneutral', 'Shappy'])])
</code>```

What is the reason for this and how can I fix it?

答:
The estimators parameter of VotingClassifier should be a list of pairs (name, estimator), so e.g.

```<code>ens = VotingClassifier(estimators=[('phy', pipe_phy),
                                   ('fa', pipe_fa)])
</code>```

(In your code, the check is trying to find the second element of the pair, hence the complaint that ColumnTransformer is not iterable.)

Body:
I am attempting to use a pipeline to feed an ensemble voting classifier as I want the ensemble learner to use models that train on different feature sets. For this purpose, I followed the tutorial available at [1].

Following is the code that I could develop so far.

y = df1.index
x = preprocessing.scale(df1)

phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])

fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])

pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])

ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])

cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
    x_train, x_test = x[train_index], x[test_index]
    y_train, y_test = y[train_index], y[test_index]
    ens.fit(x_train,y_train)
    print(ens.score(x_test, y_test))

However, when running the code, I am getting an error saying TypeError: argument of type 'ColumnTransformer' is not iterable, at the line ens.fit(x_train,y_train).

Following is the complete stack trace that I am receiving.

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/ASUS/PycharmProjects/swelltest/enemble.py", line 112, in <module>
    ens.fit(x_train,y_train)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 265, in fit
    return super().fit(X, transformed_y, sample_weight)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 65, in fit
    names, clfs = self._validate_estimators()
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_base.py", line 228, in _validate_estimators
    self._validate_names(names)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in _validate_names
    invalid_names = [name for name in names if '__' in name]
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in <listcomp>
    invalid_names = [name for name in names if '__' in name]
TypeError: argument of type 'ColumnTransformer' is not iterable

Following are the values in the names list when the error is occuring.

1- ColumnTransformer(transformers=[('phy',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['HR', 'RMSSD', 'SCL'])])
2- ColumnTransformer(transformers=[('fa',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['Squality', 'Sneutral', 'Shappy'])])

What is the reason for this and how can I fix it?

Body:
The estimators parameter of VotingClassifier should be a list of pairs (name, estimator), so e.g.

ens = VotingClassifier(estimators=[('phy', pipe_phy),
                                   ('fa', pipe_fa)])

(In your code, the check is trying to find the second element of the pair, hence the complaint that ColumnTransformer is not iterable.)


问:
Rails 3: Nested Attribute presence validation?
I have 3 Deeply nested attraibutes:

Process has many categories,
Categories has many Blocks

How do i place validate_presence_of calls so when a user is creating a new process and attempts to create a category within it without a definition lets say, that he is redirected to the process edit form and told definition can not be left empty empty?

DO i place the validation in process model or category model?

Thanks

答: Validations always go on to the model they are validating. Rails will handle the nesting.</p>


答:
You first forget to use semicolons at end of every if and else statements.
And next things if u want to continue your statement in next line use "\" at line end.
i m mentioning a example below.</p>

```<code>if (input_month == 'June') and (21 <= input_day <= 30) \
  or (input_month == 'September') and (1 <= input_day <= 30):
print('Summer')
</code>```

Title: Syntax error on line 6 'if/elif statements' and 'and/or statements'

Body:
You first forget to use semicolons at end of every if and else statements.
And next things if u want to continue your statement in next line use "\" at line end.
i m mentioning a example below.

if (input_month == 'June') and (21 <= input_day <= 30) \
  or (input_month == 'September') and (1 <= input_day <= 30):
print('Summer')


问:
Performance Issue with Oracle Merge Statements with more than 2 Million records
I am executing the below MERGE statement for Insert Update operation.

It is working fine for 1 to 2 million records but for more than 4 to 5 billion records it takes 6 to 7 hours to complete.

Can anyone suggest some alternative or performance tips for Merge Statement

```<code> merge into employee_payment ep
  using (
     select
        p.pay_id vista_payroll_id,
        p.pay_date pay_dte,
        c.client_id client_id,
        c.company_id company_id,
        case p.uni_ni when 0 then null else u.unit_id end unit_id,
        p.pad_seq pay_dist_seq_nbr,
        ph.payroll_header_id payroll_header_id,
        p.pad_id vista_paydist_id,
        p.pad_beg_payperiod pay_prd_beg_dt,
        p.pad_end_payperiod pay_prd_end_d
     from
        stg_paydist p
        inner join company c on c.vista_company_id = p.emp_ni
        inner join payroll_header ph on ph.vista_payroll_id = p.pay_id
        left outer join unit u on u.vista_unit_id = p.uni_ni
     where ph.deleted = '0'
  ) ps
     on (ps.vista_paydist_id = ep.vista_paydist_id)

  when matched then
  update
     set ep.vista_payroll_id      = ps.vista_payroll_id,
         ep.pay_dte               = ps.pay_dte,
         ep.client_id             = ps.client_id,
         ep.company_id            = ps.company_id,
         ep.unit_id               = ps.unit_id,
         ep.pay_dist_seq_nbr      = ps.pay_dist_seq_nbr,
         ep.payroll_header_id     = ps.payroll_header_id

  when not matched then
  insert (
     ep.employee_payment_id,
     ep.vista_payroll_id,
     ep.pay_dte,
     ep.client_id,
     ep.company_id,
     ep.unit_id,
     ep.pay_dist_seq_nbr,
     ep.payroll_header_id,
     ep.vista_paydist_id
  ) values (
     seq_employee_payments.nextval,
     ps.vista_payroll_id,
     ps.pay_dte,
     ps.client_id,
     ps.company_id,
     ps.unit_id,
     ps.pay_dist_seq_nbr,
     ps.payroll_header_id,
     ps.vista_paydist_id
  ) log errors into errorlog (v_batch || 'EMPLOYEE_PAYMENT') reject limit unlimited;
</code>```

答:
I was working on a similar problem and a good solution i found was to break the query up.
The primary reason big table merges are a bad idea is because of the in memory storage of the result of the using query. Because the PGA gets filled up pretty quickly so the database starts using the temporary table space of sort operations and joins. The temp tablespace being on disk is excruciatingly slow. The use of excessive temp table space can be easily avoided by splitting the query into two queries.
So the below query

```<code>merger into emp e
using (
select a,b,c,d from (/* big query here */)
) ec
on /*conditions*/
when matched then
/* rest of merge logic */
</code>```

can become

```<code>create table temp_big_query as select a,b,c,d from (/* big query here */);
merger into emp e
using (
select a,b,c,d from temp_big_query
) ec
on /*conditions*/
when matched then
/* rest of merge logic */
</code>```

if the using query also has CTEs and sub queries try breaking that query up to use more temp tables like the one shown above. Also avoid using parallel hints because they mostly tend to slow the query down unless the query itself has something that can be done in parallel, try using indexes instead instead as much as possible parallel should be used as the last option for optimization.
I know some references are missing please feel free to comment and add references or point out mistakes in my answer.

Body:
I am executing the below MERGE statement for Insert Update operation.

It is working fine for 1 to 2 million records but for more than 4 to 5 billion records it takes 6 to 7 hours to complete.

Can anyone suggest some alternative or performance tips for Merge Statement

 merge into employee_payment ep
  using (
     select
        p.pay_id vista_payroll_id,
        p.pay_date pay_dte,
        c.client_id client_id,
        c.company_id company_id,
        case p.uni_ni when 0 then null else u.unit_id end unit_id,
        p.pad_seq pay_dist_seq_nbr,
        ph.payroll_header_id payroll_header_id,
        p.pad_id vista_paydist_id,
        p.pad_beg_payperiod pay_prd_beg_dt,
        p.pad_end_payperiod pay_prd_end_d
     from
        stg_paydist p
        inner join company c on c.vista_company_id = p.emp_ni
        inner join payroll_header ph on ph.vista_payroll_id = p.pay_id
        left outer join unit u on u.vista_unit_id = p.uni_ni
     where ph.deleted = '0'
  ) ps
     on (ps.vista_paydist_id = ep.vista_paydist_id)

  when matched then
  update
     set ep.vista_payroll_id      = ps.vista_payroll_id,
         ep.pay_dte               = ps.pay_dte,
         ep.client_id             = ps.client_id,
         ep.company_id            = ps.company_id,
         ep.unit_id               = ps.unit_id,
         ep.pay_dist_seq_nbr      = ps.pay_dist_seq_nbr,
         ep.payroll_header_id     = ps.payroll_header_id

  when not matched then
  insert (
     ep.employee_payment_id,
     ep.vista_payroll_id,
     ep.pay_dte,
     ep.client_id,
     ep.company_id,
     ep.unit_id,
     ep.pay_dist_seq_nbr,
     ep.payroll_header_id,
     ep.vista_paydist_id
  ) values (
     seq_employee_payments.nextval,
     ps.vista_payroll_id,
     ps.pay_dte,
     ps.client_id,
     ps.company_id,
     ps.unit_id,
     ps.pay_dist_seq_nbr,
     ps.payroll_header_id,
     ps.vista_paydist_id
  ) log errors into errorlog (v_batch || 'EMPLOYEE_PAYMENT') reject limit unlimited;

Body:
I was working on a similar problem and a good solution i found was to break the query up.
The primary reason big table merges are a bad idea is because of the in memory storage of the result of the using query. Because the PGA gets filled up pretty quickly so the database starts using the temporary table space of sort operations and joins. The temp tablespace being on disk is excruciatingly slow. The use of excessive temp table space can be easily avoided by splitting the query into two queries.
So the below query

merger into emp e
using (
select a,b,c,d from (/* big query here */)
) ec
on /*conditions*/
when matched then
/* rest of merge logic */

can become

create table temp_big_query as select a,b,c,d from (/* big query here */);
merger into emp e
using (
select a,b,c,d from temp_big_query
) ec
on /*conditions*/
when matched then
/* rest of merge logic */

if the using query also has CTEs and sub queries try breaking that query up to use more temp tables like the one shown above. Also avoid using parallel hints because they mostly tend to slow the query down unless the query itself has something that can be done in parallel, try using indexes instead instead as much as possible parallel should be used as the last option for optimization.
I know some references are missing please feel free to comment and add references or point out mistakes in my answer.


问:
Unable to upload an DataFrame containing mixed-typed data with DolphinDB Python API
I tried to upload a DataFrame with DolphinDB Python API. It contained a column with mixed types.

```<code>import dolphindb as ddb
import pandas as pd

sess = ddb.session('localhost', 8848)
df = DataFrame({'a': [1, 1.0, 'a']})
sess.upload({'df': df})
</code>```

Then I got the following error message:

Traceback (most recent call last):

File "", line 1, in

File "/home/ynwang/.local/lib/python3.6/site-packages/dolphindb/session.py", line 64, in upload

return self.cpp.upload(nameObjectDict)

RuntimeError:  in upload: Failed to read response header from the socket with IO error type 1

And the session just disconnected. I would like to know why this is the case.

答:
Try to first initialize an empty session and then connect to localhost session :</p>

```<code>import dolphindb as ddb
import pandas as pd

conn=ddb.session()
conn.connect( 'localhost', 8848)
df = DataFrame({'a': [1, 1.0, 'a']})
conn.upload({'df': df})
</code>```

Body:
I tried to upload a DataFrame with DolphinDB Python API. It contained a column with mixed types.

import dolphindb as ddb
import pandas as pd

sess = ddb.session('localhost', 8848)
df = DataFrame({'a': [1, 1.0, 'a']})
sess.upload({'df': df})

Then I got the following error message:

Traceback (most recent call last):

File "", line 1, in

File "/home/ynwang/.local/lib/python3.6/site-packages/dolphindb/session.py", line 64, in upload

return self.cpp.upload(nameObjectDict)

RuntimeError:  in upload: Failed to read response header from the socket with IO error type 1

And the session just disconnected. I would like to know why this is the case.

Body:
Try to first initialize an empty session and then connect to localhost session :

import dolphindb as ddb
import pandas as pd

conn=ddb.session()
conn.connect( 'localhost', 8848)
df = DataFrame({'a': [1, 1.0, 'a']})
conn.upload({'df': df})