问:
Registering a .NET assembly in a COM+ application outside of the GAC
I developed a .NET assembly (.NET 4.0, strong-named) which exposes two Serviced Components. The assembly (dll) is supposed to be hosted in a COM+ application and it is decorated with the COM+ attributes (assembly & component levels). For example, the assembly level attributes:

```<code>//COM+ Attributes
[assembly: ApplicationID("MY_APP_GUID")] //GUID of the COM+ app
[assembly: ApplicationName("MyComPlusAppName")] //Name of the COM+ app
[assembly: ApplicationActivation(ActivationOption.Server)] //The app is hosted in it own dllhost process (out-of-process)
[assembly: ApplicationAccessControl(AccessChecksLevel = AccessChecksLevelOption.ApplicationComponent, Authentication = AuthenticationOption.None, ImpersonationLevel = ImpersonationLevelOption.Delegate, Value = false)]
[assembly: Description("COM+ app description")]
</code>```

Currently (development reasons), I've been running the following script to create the COM+ application and register the assembly (with all of its components):

```<code>%windir%\Microsoft.NET\Framework\v4.0.30319\RegSvcs.exe /appdir:"%CD%" MyComPlusAssembly.dll
</code>```

The above batch file will create (in a single run) the COM+ application according to the assembly decorating attributes, register the MyComPlusAssembly.dll file in the COM+ app and register all ComVisible components in it, so everything is visible and configured as expected in dcomcnfg. This command will also generate a fresh new TLB file.
The assembly is built using AnyCPU, so on x64 versions of Windows the dllhost.exe process will run as 64bit and on a x86 version of Windows it will run as 32bit. Also, my dll file should NOT be placed in the GAC (this is why I'm using the /appdir switch of the RegSvcs.exe command-line utility). All is working as expected when installing the COM+ assembly with the above batch file.

I started writing a Wix (v3.6) deployment project for my app which is supposed to do the same, that is: Create the COM+ application, register the .NET assembly and all ComVisible components. Please note that this time I'm relying on the fact that the TLB file is shipped with the installer (*.msi). The TLB was generated by the build process (VS 2010).
To achieve the above I've added the following Wix component (inspired by the Wix COM+ Extension docs - WixComPlusExtension):

```<code>   <DirectoryRef Id="INSTALLDIR_SERVER">
      <Component Id="cmp_MyComPlusAssembly.dll" Guid="COMPONENT_DLL_GUID">
        <File Id="MyComPlusAssembly.dll" Name="MyComPlusAssembly.dll" DiskId="1" Source="..\install\$(var.Configuration)\Server\MyComPlusAssembly.dll" KeyPath="yes"/>
        <CreateFolder>
          <util:PermissionEx GenericAll="yes" User="NT AUTHORITY\LocalService"/>
        </CreateFolder>
        <complus:ComPlusApplication Id="ComPlusServerApp"
                                    AccessChecksLevel="applicationComponentLevel"
                                    Activation="local"
                                    ApplicationAccessChecksEnabled="no"
                                    ApplicationDirectory="[INSTALLDIR_SERVER]"
                                    ApplicationId="MyComPlusAssembly.dll"
                                    Authentication="none"
                                    Description="MyComPlusAssembly.dll"
                                    Identity="NT AUTHORITY\LocalService"
                                    ImpersonationLevel="delegate"
                                    IsEnabled="yes"
                                    RunForever="yes"
                                    Name="MyComPlusApp"
                                    Deleteable="yes">
          <complus:ComPlusAssembly Id="ComPlusServerAssembley"
                                   DllPath="[#MyComPlusAssembly.dll]"
                                   TlbPath="[#MyComPlusAssembly.tlb]"
                                   Type=".net"
                                   DllPathFromGAC="no">

            <complus:ComPlusComponent Id="COMObject_1"
                                      CLSID="COM_OBJ_1_GUID"
                                      Description="Object 1"
                                      IsEnabled="yes"/>

            <complus:ComPlusComponent Id="COMObject_2"
                                      CLSID="COM_OBJ_2_GUID"
                                      Description="Object 2"
                                      IsEnabled="yes"/>

          </complus:ComPlusAssembly>
        </complus:ComPlusApplication>

      </Component>
      </Component>

      <Component Id="cmp_MyComPlusAssembly.tlb" Guid="COMPONENT_TLB_GUID">
        <File Id="cmp_MyComPlusAssembly.tlb" Name="cmp_MyComPlusAssembly.tlb" DiskId="1" Source="..\install\$(var.Configuration)\Server\cmp_MyComPlusAssembly.tlb" KeyPath="yes"/>
      </Component>

    </DirectoryRef>
</code>```

The MSI project builds successfully but the installation process fails and is rolled back immediately after trying to register the dll.
The following error can be found in the log (for BOTH x86 & x64 versions):

```<code>Action 16:33:37: RegisterComPlusAssemblies. Registering COM+ components
RegisterComPlusAssemblies: DLL: C:\Program Files\MyApp\Server\MyComPlusAssembly.dll
ComPlusInstallExecute:  Registering assembly, key: ComPlusServerAssembley
ComPlusInstallExecute:  ExceptionInfo: Code='0', Source='System.EnterpriseServices', Description='Failed to load assembly 'c:\program files\myapp\server\MyComPlusAssembly.dll'.', HelpFile='', HelpContext='0'
ComPlusInstallExecute:  Error 0x80020009: Failed to invoke RegistrationHelper.InstallAssembly() method
ComPlusInstallExecute:  Error 0x80020009: Failed to register .NET assembly
ComPlusInstallExecute:  Error 0x80020009: Failed to register assembly, key: ComPlusServerAssembley
ComPlusInstallExecute:  Error 0x80020009: Failed to register assemblies
</code>```

The above error can mean that the dll being registered in the COM+ app is missing, that is, the file is not on the disk.
Although the installation process is fast, I've never seen the MyComPlusAssembly.dll file being copied to the disk (to [INSTALLDIR_SERVER]), all other files are on the disk when the installation starts rolling back (including the TLB). Is this a timing issue?

Observations:

This happens for both versions of the installer (x64 & x86).

When removing the "<complus:ComPlusAssembly...>" tag (including the
nested components), the installation succeeds and an (empty)
application is created, that is - only the container", without any
assembly or COM+ hosted components.

I tried adding a third "<Component.../>" which creates a simple
registry key and move all of the
"<complus:ComPlusApplication.../>" code to it. This component will be
executed after all files are copied. Same result (error) as log
above.

What am I missing here?

答:
I changed COM+ assembly's target platform to 3.5 and it worked.

The issue is around System.EnterpriseServices.dll version called from WixComPlusExtension. There are several version of the library, at least: 2.0.xxxx and 4.0.xxxx.
WixComPlusExtension calls RegisterDotNetAssembly (cpasmexec.cpp) method that uses System.EnterpriseServices.RegistrationHelper class to register an assembly. The fact is when you call RegistrationHelper.InstallAssembly from System.EnterpriseServices of version 2.0.xxxx against a .net COM+ library built for framework 4 or higher, you get "Failed to load assembly" error.

Any ideas how to tweak WixComPlusExtension (it's open source) to make it call System.EnterpriseServices for framework 4?

Body:
I developed a .NET assembly (.NET 4.0, strong-named) which exposes two Serviced Components. The assembly (dll) is supposed to be hosted in a COM+ application and it is decorated with the COM+ attributes (assembly & component levels). For example, the assembly level attributes:

//COM+ Attributes
[assembly: ApplicationID("MY_APP_GUID")] //GUID of the COM+ app
[assembly: ApplicationName("MyComPlusAppName")] //Name of the COM+ app
[assembly: ApplicationActivation(ActivationOption.Server)] //The app is hosted in it own dllhost process (out-of-process)
[assembly: ApplicationAccessControl(AccessChecksLevel = AccessChecksLevelOption.ApplicationComponent, Authentication = AuthenticationOption.None, ImpersonationLevel = ImpersonationLevelOption.Delegate, Value = false)]
[assembly: Description("COM+ app description")]

Currently (development reasons), I've been running the following script to create the COM+ application and register the assembly (with all of its components):

%windir%\Microsoft.NET\Framework\v4.0.30319\RegSvcs.exe /appdir:"%CD%" MyComPlusAssembly.dll

The above batch file will create (in a single run) the COM+ application according to the assembly decorating attributes, register the MyComPlusAssembly.dll file in the COM+ app and register all ComVisible components in it, so everything is visible and configured as expected in dcomcnfg. This command will also generate a fresh new TLB file.
The assembly is built using AnyCPU, so on x64 versions of Windows the dllhost.exe process will run as 64bit and on a x86 version of Windows it will run as 32bit. Also, my dll file should NOT be placed in the GAC (this is why I'm using the /appdir switch of the RegSvcs.exe command-line utility). All is working as expected when installing the COM+ assembly with the above batch file.

I started writing a Wix (v3.6) deployment project for my app which is supposed to do the same, that is: Create the COM+ application, register the .NET assembly and all ComVisible components. Please note that this time I'm relying on the fact that the TLB file is shipped with the installer (*.msi). The TLB was generated by the build process (VS 2010).
To achieve the above I've added the following Wix component (inspired by the Wix COM+ Extension docs - WixComPlusExtension):

   <DirectoryRef Id="INSTALLDIR_SERVER">
      <Component Id="cmp_MyComPlusAssembly.dll" Guid="COMPONENT_DLL_GUID">
        <File Id="MyComPlusAssembly.dll" Name="MyComPlusAssembly.dll" DiskId="1" Source="..\install\$(var.Configuration)\Server\MyComPlusAssembly.dll" KeyPath="yes"/>
        <CreateFolder>
          <util:PermissionEx GenericAll="yes" User="NT AUTHORITY\LocalService"/>
        </CreateFolder>
        <complus:ComPlusApplication Id="ComPlusServerApp"
                                    AccessChecksLevel="applicationComponentLevel"
                                    Activation="local"
                                    ApplicationAccessChecksEnabled="no"
                                    ApplicationDirectory="[INSTALLDIR_SERVER]"
                                    ApplicationId="MyComPlusAssembly.dll"
                                    Authentication="none"
                                    Description="MyComPlusAssembly.dll"
                                    Identity="NT AUTHORITY\LocalService"
                                    ImpersonationLevel="delegate"
                                    IsEnabled="yes"
                                    RunForever="yes"
                                    Name="MyComPlusApp"
                                    Deleteable="yes">
          <complus:ComPlusAssembly Id="ComPlusServerAssembley"
                                   DllPath="[#MyComPlusAssembly.dll]"
                                   TlbPath="[#MyComPlusAssembly.tlb]"
                                   Type=".net"
                                   DllPathFromGAC="no">

            <complus:ComPlusComponent Id="COMObject_1"
                                      CLSID="COM_OBJ_1_GUID"
                                      Description="Object 1"
                                      IsEnabled="yes"/>

            <complus:ComPlusComponent Id="COMObject_2"
                                      CLSID="COM_OBJ_2_GUID"
                                      Description="Object 2"
                                      IsEnabled="yes"/>

          </complus:ComPlusAssembly>
        </complus:ComPlusApplication>

      </Component>
      </Component>

      <Component Id="cmp_MyComPlusAssembly.tlb" Guid="COMPONENT_TLB_GUID">
        <File Id="cmp_MyComPlusAssembly.tlb" Name="cmp_MyComPlusAssembly.tlb" DiskId="1" Source="..\install\$(var.Configuration)\Server\cmp_MyComPlusAssembly.tlb" KeyPath="yes"/>
      </Component>

    </DirectoryRef>

The MSI project builds successfully but the installation process fails and is rolled back immediately after trying to register the dll.
The following error can be found in the log (for BOTH x86 & x64 versions):

Action 16:33:37: RegisterComPlusAssemblies. Registering COM+ components
RegisterComPlusAssemblies: DLL: C:\Program Files\MyApp\Server\MyComPlusAssembly.dll
ComPlusInstallExecute:  Registering assembly, key: ComPlusServerAssembley
ComPlusInstallExecute:  ExceptionInfo: Code='0', Source='System.EnterpriseServices', Description='Failed to load assembly 'c:\program files\myapp\server\MyComPlusAssembly.dll'.', HelpFile='', HelpContext='0'
ComPlusInstallExecute:  Error 0x80020009: Failed to invoke RegistrationHelper.InstallAssembly() method
ComPlusInstallExecute:  Error 0x80020009: Failed to register .NET assembly
ComPlusInstallExecute:  Error 0x80020009: Failed to register assembly, key: ComPlusServerAssembley
ComPlusInstallExecute:  Error 0x80020009: Failed to register assemblies

The above error can mean that the dll being registered in the COM+ app is missing, that is, the file is not on the disk.
Although the installation process is fast, I've never seen the MyComPlusAssembly.dll file being copied to the disk (to [INSTALLDIR_SERVER]), all other files are on the disk when the installation starts rolling back (including the TLB). Is this a timing issue?

Observations:

This happens for both versions of the installer (x64 & x86).

When removing the "<complus:ComPlusAssembly...>" tag (including the
nested components), the installation succeeds and an (empty)
application is created, that is - only the container", without any
assembly or COM+ hosted components.

I tried adding a third "<Component.../>" which creates a simple
registry key and move all of the
"<complus:ComPlusApplication.../>" code to it. This component will be
executed after all files are copied. Same result (error) as log
above.

What am I missing here?


来源: stackexchange

问:
How to recreate a virtual env in python
I have installed virtualenv and virtualenvwrapper on Ubuntu 16.04
I have created one enviroment named env1

```<code>$ sudo apt-get install python-pip
$ pip install virtualenv
$ pip install --upgrade pip
$ pip install virtualenvwrapper
$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1
</code>```

Once in (env1) I have installed several packages

```<code>(env1) $ pip install numpy
(env1) $ pip install scipy
(env1) $ pip install matplotlib
(env1) $ apt-get install python-tk
</code>```

I have also installed opencv3 (I am not copying how because is too long)

I am using env1 for a specific project.

Now I want to start another project using the same packages, but I also want to add other packages.

I have created env2, and I was wondering if it is possible to copy env1 to env2 without the need to re-install everything again from scratch.

答:
Your best option is to do this:

virtualenv-1:

```<code>pip freeze > requirements.txt
</code>```

virtualenv-2:

```<code>pip install -r requirements.txt
</code>```

Assuming they are both the on the same system and use the same Python, it is somewhat possible to just copy the site-packages:

```<code>cp -Rp /environments/virtualenv-1/lib/python2.7/site-packages \
       /environments/virtualenv-2/lib/python2.7/site-packages
</code>```

This won't necessarily work though:

some packages will install dependencies and other things into /bin/ or elsewhere.  most don't, but many do.

if the python versions for the virtualenvs differ -- even on a minor version -- that can break libraries that use c extensions.

So your best bet is to pip freeze and reinstall from that file.

ContentLicense: CC BY-SA 3.0

Title: How to recreate a virtual env in python

Body:
I have installed virtualenv and virtualenvwrapper on Ubuntu 16.04
I have created one enviroment named env1

$ sudo apt-get install python-pip
$ pip install virtualenv
$ pip install --upgrade pip
$ pip install virtualenvwrapper
$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1

Once in (env1) I have installed several packages

(env1) $ pip install numpy
(env1) $ pip install scipy
(env1) $ pip install matplotlib
(env1) $ apt-get install python-tk

I have also installed opencv3 (I am not copying how because is too long)

I am using env1 for a specific project.

Now I want to start another project using the same packages, but I also want to add other packages.

I have created env2, and I was wondering if it is possible to copy env1 to env2 without the need to re-install everything again from scratch.

Body:
Your best option is to do this:

virtualenv-1:

pip freeze > requirements.txt

virtualenv-2:

pip install -r requirements.txt

Assuming they are both the on the same system and use the same Python, it is somewhat possible to just copy the site-packages:

cp -Rp /environments/virtualenv-1/lib/python2.7/site-packages \
       /environments/virtualenv-2/lib/python2.7/site-packages

This won't necessarily work though:

some packages will install dependencies and other things into /bin/ or elsewhere.  most don't, but many do.

if the python versions for the virtualenvs differ -- even on a minor version -- that can break libraries that use c extensions.

So your best bet is to pip freeze and reinstall from that file.


问:
Not able to click on a link a java link on a site using powershell
After opening the site there is a frame inside that frame menubar is their and in that menubar 5 button are their for example:-

Search (with e underlined and a drop down arrow also with search) and Window (with W underlined a drop down arrow also with window) I want to click on search.

I tried using href,id but unable to click on search.

```<code>        $Url = “some site”
        $Username=”xxx”
        $Password=”xxx”

       $IE = New-Object -com internetexplorer.application;
       $IE.visible = $true;
       $IE.navigate($url);
       while ($IE.Busy -eq $true)

      {

      Start-Sleep -Milliseconds 2000;

      }

        $IE.Document.getElementById(“USERNAME”).value = $Username
         $IE.Document.getElementByID(“PIN”).value=$Password
        $IE.Document.getElementById(“HardcodedSub”).Click()

        while($ie.busy) {sleep 5}

        $Link = $ie.Document.getElementsByTagName("a") | where-object {$_.id -eq     'menu_2'}
         $Link.click()

error:-You cannot call a method on a null-valued expression.
At line:25 char:1
+ $Link.click()
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

inspect element:-

<a id="menu_2" tabindex="2" class="menu_unselected_text" href="javascript:window.parent.role_main.cai_main.setActKeyMenuState(2)">S<u>e</u>arch<img border="0" src="/CAisd/img/arrow_asc_bk.png" width="15" height="10"></a>
</code>```

答:
Why cant below line use the same GetElementById().

```<code>$Link = $ie.Document.getElementById("menu_2")
</code>```

And its good to debug in PowerShell ISE or execute line by line and see the page loads completely before you call a method.

Regards,

Kvprasoon

Body:
After opening the site there is a frame inside that frame menubar is their and in that menubar 5 button are their for example:-

Search (with e underlined and a drop down arrow also with search) and Window (with W underlined a drop down arrow also with window) I want to click on search.

I tried using href,id but unable to click on search.

        $Url = “some site”
        $Username=”xxx”
        $Password=”xxx”

       $IE = New-Object -com internetexplorer.application;
       $IE.visible = $true;
       $IE.navigate($url);
       while ($IE.Busy -eq $true)

      {

      Start-Sleep -Milliseconds 2000;

      }

        $IE.Document.getElementById(“USERNAME”).value = $Username
         $IE.Document.getElementByID(“PIN”).value=$Password
        $IE.Document.getElementById(“HardcodedSub”).Click()

        while($ie.busy) {sleep 5}

        $Link = $ie.Document.getElementsByTagName("a") | where-object {$_.id -eq     'menu_2'}
         $Link.click()

error:-You cannot call a method on a null-valued expression.
At line:25 char:1
+ $Link.click()
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

inspect element:-

Search

Body:
Why cant below line use the same GetElementById().

$Link = $ie.Document.getElementById("menu_2")

And its good to debug in PowerShell ISE or execute line by line and see the page loads completely before you call a method.

Regards,

Kvprasoon


问:
Microsoft Graph API - Email sent to new users
We're using the MS Graph API to create users on our Office 365 tenant which is a domain managed outside of Office 365. (e.g. users.ourcompany.com)

Since we're autogenerating the password for the users, we would like them to be aware of that password that they could use to login for the first time and reset it.

Does this API automatically trigger an email (containing their username and password) to the address as specified by the userPrincipalName user attribute? If not, is there a way to do it explicitly?

答: Assuming the admin creating a new user has an Exchange Online mailbox provisioned, you could send an email from that account using Graph. </p>


问:
Why does cURL return error "(23) Failed writing body"?
It works ok as a single tool:

```<code>curl "someURL"
curl -o - "someURL"
</code>```

but it doesn't work in a pipeline:

```<code>curl "someURL" | tr -d '\n'
curl -o - "someURL" | tr -d '\n'
</code>```

it returns:

```<code>(23) Failed writing body
</code>```

What is the problem with piping the cURL output? How to buffer the whole cURL output and then handle it?

答: I had the same error but from different reason. In my case I had (tmpfs) partition with only 1GB space and I was downloading big file which finally filled all memory on that partition and I got the same error as you.

ContentLicense: CC BY-SA 4.0

Body:
It works ok as a single tool:

curl "someURL"
curl -o - "someURL"

but it doesn't work in a pipeline:

curl "someURL" | tr -d '\n'
curl -o - "someURL" | tr -d '\n'

it returns:

(23) Failed writing body

What is the problem with piping the cURL output? How to buffer the whole cURL output and then handle it?


问:
How to expand/collapse bootstrap accordion on panel-heading click event?
I try to Expand/Collapse 'panel-body' on 'panel-heading' on click event instead of   on click (default), but it's not working.

Here is my html markup:

```

                  Portal Design

<input type="radio" name="web_design" data-price="15000" value="Website Design">Website design required

<input type="radio" name="web_design" data-price="7000" value="Website Re-Design">Re-Design existing website

<input type="radio" name="web_design" data-price="0" value="Not Required">Website design not required

                  Recharge API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                <input type="radio" name="api-mobile" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                <input type="radio" name="api-mobile" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                <input type="radio" name="api-mobile" data-price="150000" value="Enterprise">

                    Utility Bill Payment API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="150000" value="Enterprise">

                    Travel API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-travel" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-travel" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-travel" data-price="150000" value="Enterprise">

                    Money Transfer API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-dmr" data-price="9600" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-dmr" data-price="10500" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-dmr" data-price="25000" value="Enterprise">

                    Additional Services

<input type="checkbox" name="sms_gateway" data-price="5000" value="SMS Gateway"> SMS Gateway

<input type="checkbox" name="long_code" data-price="1300" value="Long Code"> Long Code

                    Others

No other service available

```

Here the live: http://jsfiddle.net/8yaurtxr/

I have try to add data-toggle="collapse" but it's not working.

答:
```<code><div class="panel-heading" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
<h4 class="panel-title">
    <a>Collapsible Group Item #1</a>
</h4></div>
</code>```

Body:
I try to Expand/Collapse 'panel-body' on 'panel-heading' on click event instead of   on click (default), but it's not working.

Here is my html markup:

                  Portal Design

<input type="radio" name="web_design" data-price="15000" value="Website Design">Website design required

<input type="radio" name="web_design" data-price="7000" value="Website Re-Design">Re-Design existing website

<input type="radio" name="web_design" data-price="0" value="Not Required">Website design not required

                  Recharge API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                <input type="radio" name="api-mobile" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                <input type="radio" name="api-mobile" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                <input type="radio" name="api-mobile" data-price="150000" value="Enterprise">

                    Utility Bill Payment API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="150000" value="Enterprise">

                    Travel API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-travel" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-travel" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-travel" data-price="150000" value="Enterprise">

                    Money Transfer API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-dmr" data-price="9600" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-dmr" data-price="10500" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-dmr" data-price="25000" value="Enterprise">

                    Additional Services

<input type="checkbox" name="sms_gateway" data-price="5000" value="SMS Gateway"> SMS Gateway

<input type="checkbox" name="long_code" data-price="1300" value="Long Code"> Long Code

                    Others

No other service available

Here the live: http://jsfiddle.net/8yaurtxr/

I have try to add data-toggle="collapse" but it's not working.


问:
Send Table Data Using PHPMailer
I have a record which can be fetched from the database. I want to be able to send this tabulated report to email using PHPMailer.The issue now is: When the mail is sent, it shows only the header section of the table and the content is not shown. See my code below, maybe someone can tell me what i am missing or better approach:

```<code>$mail->Body    =  "<p>Please find below the Action Plan for Routine Report that is generated based on today's Check.</p><br/>".
                  "<table width='100%' border='1' style='margin-top:15px;' align='left class='table table-striped'>".
                  "<thead><tr>".
                  "<th>SN</th>".
                  "<th nowrap='nowrap'>Mainlocation</th>".
                  "<th nowrap='nowrap'>Sub-Loaction</th>".
                  "<th nowrap='nowrap'>Issue</th>".
                  "<th nowrap='nowrap'>Current Plan</th>".
                  "<th nowrap='nowrap'>Who</th>".
                  "<th nowrap='nowrap'>When</th>".
                  "</tr></thead><tbody>".
                  $qq = mysqli_query($con,"SELECT * FROM tab_trans WHERE transid='$transid' ORDER BY subloc");
                  $d =0;
                  while($c = mysqli_fetch_array($qq)){ $d++;
                  "<tr>".
                  "<td nowrap='nowrap'>".$d."</td>".
                  "<td nowrap='nowrap'> ".$c['mainloc']."</td>".
                  "<td nowrap='nowrap'> ".$c['subloc']."</td>".
                  "<td nowrap='nowrap'> ".$c['issue']."</td>".
                  "<td nowrap='nowrap'> ".$c['what']."</td>".
                  "<td nowrap='nowrap'> ".$c['who']."</td>".
                  "<td nowrap='nowrap'> ".$c['period']."</td></tr>";
                  }
                  "</tbody></table>";
</code>```

I have truncated the previous section of the phpmailer function. ie the  settings. Thanks

答:
Thanks all. The solution is this: The loop is the one having issue. It is not able to get the result. Hence, concantenating the $mail->body  and little modification solves the problem:</p>

```<code>$mail->Body    =  "<p>Please find below the Action Plan for Routine Report that is generated based on today's Check.</p><br/>".

                     "<table width='100%' border='1' style='margin-top:15px;' align='left class='table table-striped'>".
                      "<thead><tr>".
                      "<th>SN</th>".
                      "<th nowrap='nowrap'>Mainlocation</th>".
                      "<th nowrap='nowrap'>Sub-Loaction</th>".
                      "<th nowrap='nowrap'>Issue</th>".
                      "<th nowrap='nowrap'>Current Plan</th>".
                      "<th nowrap='nowrap'>Who</th>".
                      "<th nowrap='nowrap'>When</th>".
                      "</tr></thead><tbody>";
                      $qq = mysqli_query($con,"SELECT * FROM tab_trans WHERE transid='$transid' ORDER BY subloc");
                      $d =0;
                      while($c = mysqli_fetch_array($qq)){ $d++;
  $mail->Body.=       "<tr>".
                      "<td nowrap='nowrap'>".$d."</td>".
                      "<td nowrap='nowrap'> ".$c['mainloc']."</td>".
                      "<td nowrap='nowrap'> ".$c['subloc']."</td>".
                      "<td nowrap='nowrap'> ".$c['issue']."</td>".
                      "<td nowrap='nowrap'> ".$c['what']."</td>".
                      "<td nowrap='nowrap'> ".$c['who']."</td>".
                      "<td nowrap='nowrap'> ".$c['period']."</td></tr>";
                      }
$mail->Body.=       "</tbody></table>";
</code>```

Title: Send Table Data Using PHPMailer

Body:
I have a record which can be fetched from the database. I want to be able to send this tabulated report to email using PHPMailer.The issue now is: When the mail is sent, it shows only the header section of the table and the content is not shown. See my code below, maybe someone can tell me what i am missing or better approach:

$mail->Body    =  "
Please find below the Action Plan for Routine Report that is generated based on today's Check.

".
                  "
".
                  "

".
                  "SN	".
                  "Mainlocation	".
                  "Sub-Loaction	".
                  "Issue	".
                  "Current Plan	".
                  "Who	".
                  "When	".
                  "

".
                  $qq = mysqli_query($con,"SELECT * FROM tab_trans WHERE transid='$transid' ORDER BY subloc");
                  $d =0;
                  while($c = mysqli_fetch_array($qq)){ $d++;
                  "
".
                  "".$d."	".
                  " ".$c['mainloc']."	".
                  " ".$c['subloc']."	".
                  " ".$c['issue']."	".
                  " ".$c['what']."	".
                  " ".$c['who']."	".
                  " ".$c['period']."
";
                  }
                  "

";

I have truncated the previous section of the phpmailer function. ie the  settings. Thanks

Body:
Thanks all. The solution is this: The loop is the one having issue. It is not able to get the result. Hence, concantenating the $mail->body  and little modification solves the problem:

$mail->Body    =  "<p>Please find below the Action Plan for Routine Report that is generated based on today's Check.</p><br/>".

                     "<table width='100%' border='1' style='margin-top:15px;' align='left class='table table-striped'>".
                      "<thead><tr>".
                      "<th>SN</th>".
                      "<th nowrap='nowrap'>Mainlocation</th>".
                      "<th nowrap='nowrap'>Sub-Loaction</th>".
                      "<th nowrap='nowrap'>Issue</th>".
                      "<th nowrap='nowrap'>Current Plan</th>".
                      "<th nowrap='nowrap'>Who</th>".
                      "<th nowrap='nowrap'>When</th>".
                      "</tr></thead><tbody>";
                      $qq = mysqli_query($con,"SELECT * FROM tab_trans WHERE transid='$transid' ORDER BY subloc");
                      $d =0;
                      while($c = mysqli_fetch_array($qq)){ $d++;
  $mail->Body.=       "<tr>".
                      "<td nowrap='nowrap'>".$d."</td>".
                      "<td nowrap='nowrap'> ".$c['mainloc']."</td>".
                      "<td nowrap='nowrap'> ".$c['subloc']."</td>".
                      "<td nowrap='nowrap'> ".$c['issue']."</td>".
                      "<td nowrap='nowrap'> ".$c['what']."</td>".
                      "<td nowrap='nowrap'> ".$c['who']."</td>".
                      "<td nowrap='nowrap'> ".$c['period']."</td></tr>";
                      }
$mail->Body.=       "</tbody></table>";


问:
Count rows within a group, but also from global result set: performance issue
I have a table with log records. Each log record is represented by a status (open or closed) and a date:

```<code>CREATE TABLE logs (
  id          BIGSERIAL PRIMARY KEY,
  status      VARCHAR NOT NULL,
  inserted_at DATE NOT NULL
);
</code>```

I need to get a daily report with a following information:

how many log records with status = open were created,

how many log records with status = closed were created,

how many log records with status = open exist to this day, including this day.

Here's a sample report output:

```<code>    day     | created | closed | total_open
------------+---------+--------+------------
 2017-01-01 |       2 |      0 |          2
 2017-01-02 |       2 |      1 |          3
 2017-01-03 |       1 |      1 |          3
 2017-01-04 |       1 |      0 |          4
 2017-01-05 |       1 |      0 |          5
 2017-01-06 |       1 |      0 |          6
 2017-01-07 |       1 |      0 |          7
 2017-01-08 |       0 |      1 |          6
 2017-01-09 |       0 |      0 |          6
 2017-01-10 |       0 |      0 |          6
(10 rows)
</code>```

I solved this in a very "dirty" way:

```<code>INSERT INTO logs (status, inserted_at) VALUES
  ('created', '2017-01-01'),
  ('created', '2017-01-01'),
  ('closed', '2017-01-02'),
  ('created', '2017-01-02'),
  ('created', '2017-01-02'),
  ('created', '2017-01-03'),
  ('closed', '2017-01-03'),
  ('created', '2017-01-04'),
  ('created', '2017-01-05'),
  ('created', '2017-01-06'),
  ('created', '2017-01-07'),
  ('closed', '2017-01-08');

  SELECT days.day,
         count(case when logs.inserted_at  = days.day AND logs.status = 'created' then 1 end) as created,
         count(case when logs.inserted_at  = days.day AND logs.status = 'closed' then 1 end) as closed,
         count(case when logs.inserted_at <= days.day AND logs.status = 'created' then 1 end) -
         count(case when logs.inserted_at <= days.day AND logs.status = 'closed' then 1 end) as total
    FROM (SELECT day::date FROM generate_series('2017-01-01'::date, '2017-01-10'::date, '1 day'::interval) day) days,
         logs
GROUP BY days.day
ORDER BY days.day;
</code>```

Also (posted it on gist for brevity), and would like to improve the solution.

Right now explain for my query reveals some ridiculous cost numbers that that I would like to minimize (I don't have indexes yet).

How an efficient query to achieve the report above would look like?

答:
A possible solution is to use window functions:

```<code>select s.*, sum(created - closed) over (order by inserted_at)
from   (select    inserted_at,
                  count(status) filter (where status = 'created') created,
                  count(status) filter (where status = 'closed')  closed
        from      (select d::date inserted_at
                   from   generate_series('2017-01-01'::date, '2017-01-10'::date, '1 day'::interval) d) d
        left join logs using (inserted_at)
        group by  inserted_at) s
</code>```

http://rextester.com/GFRRP71067

Also, an index on (inserted_at, status) could help you a lot with this query.

Note: count(...) filter (where ...) is really just a fancy way to write count(case when ... then ... [else null] end).

Body:
I have a table with log records. Each log record is represented by a status (open or closed) and a date:

CREATE TABLE logs (
  id          BIGSERIAL PRIMARY KEY,
  status      VARCHAR NOT NULL,
  inserted_at DATE NOT NULL
);

I need to get a daily report with a following information:

how many log records with status = open were created,

how many log records with status = closed were created,

how many log records with status = open exist to this day, including this day.

Here's a sample report output:

    day     | created | closed | total_open
------------+---------+--------+------------
 2017-01-01 |       2 |      0 |          2
 2017-01-02 |       2 |      1 |          3
 2017-01-03 |       1 |      1 |          3
 2017-01-04 |       1 |      0 |          4
 2017-01-05 |       1 |      0 |          5
 2017-01-06 |       1 |      0 |          6
 2017-01-07 |       1 |      0 |          7
 2017-01-08 |       0 |      1 |          6
 2017-01-09 |       0 |      0 |          6
 2017-01-10 |       0 |      0 |          6
(10 rows)

I solved this in a very "dirty" way:

INSERT INTO logs (status, inserted_at) VALUES
  ('created', '2017-01-01'),
  ('created', '2017-01-01'),
  ('closed', '2017-01-02'),
  ('created', '2017-01-02'),
  ('created', '2017-01-02'),
  ('created', '2017-01-03'),
  ('closed', '2017-01-03'),
  ('created', '2017-01-04'),
  ('created', '2017-01-05'),
  ('created', '2017-01-06'),
  ('created', '2017-01-07'),
  ('closed', '2017-01-08');

  SELECT days.day,
         count(case when logs.inserted_at  = days.day AND logs.status = 'created' then 1 end) as created,
         count(case when logs.inserted_at  = days.day AND logs.status = 'closed' then 1 end) as closed,
         count(case when logs.inserted_at <= days.day AND logs.status = 'created' then 1 end) -
         count(case when logs.inserted_at <= days.day AND logs.status = 'closed' then 1 end) as total
    FROM (SELECT day::date FROM generate_series('2017-01-01'::date, '2017-01-10'::date, '1 day'::interval) day) days,
         logs
GROUP BY days.day
ORDER BY days.day;

Also (posted it on gist for brevity), and would like to improve the solution.

Right now explain for my query reveals some ridiculous cost numbers that that I would like to minimize (I don't have indexes yet).

How an efficient query to achieve the report above would look like?

Body:
A possible solution is to use window functions:

select s.*, sum(created - closed) over (order by inserted_at)
from   (select    inserted_at,
                  count(status) filter (where status = 'created') created,
                  count(status) filter (where status = 'closed')  closed
        from      (select d::date inserted_at
                   from   generate_series('2017-01-01'::date, '2017-01-10'::date, '1 day'::interval) d) d
        left join logs using (inserted_at)
        group by  inserted_at) s

http://rextester.com/GFRRP71067

Also, an index on (inserted_at, status) could help you a lot with this query.

Note: count(...) filter (where ...) is really just a fancy way to write count(case when ... then ... [else null] end).


问:
react setState does not update the state us expected
I have a react component that looks like this:

```<code>class MyComponent extends Component {
  incrementQty = () => {
    // calls this.setState({....})
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}
</code>```

My problem is that the state does not be updated until the last call in the loop, I knew that setState is asynchronous and I can't use redux here to rerender the component after an action is dispatched.

Has anyone has a solution, and thanks.

答:
State should be updated as little as possible, if you update quickly within a loop it will cause issues as it tries to re-render based on state change.

If you are updating state based on the current state in 'incrementQty' this will also cause issues as the render cycle has not yet finished and the current state will not be updated on each loop.

To fix this, calculate the new quantity first and then update state:

class MyComponent extends Component {
  setQty (qty) => {
    let newQuantity = 0; //or this.state.quantity?
    for (....) {
      newQuantity++;
    }
    this.setState({quantity:newQuantity}
  }
}```

P.s. it seems you're passing qty to setQty anyway, are you sure you don't just want to use 'this.setState({quantity:qty});'?

Body:
I have a react component that looks like this:

class MyComponent extends Component {
  incrementQty = () => {
    // calls this.setState({....})
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}

My problem is that the state does not be updated until the last call in the loop, I knew that setState is asynchronous and I can't use redux here to rerender the component after an action is dispatched.

Has anyone has a solution, and thanks.

Body:
State should be updated as little as possible, if you update quickly within a loop it will cause issues as it tries to re-render based on state change.

If you are updating state based on the current state in 'incrementQty' this will also cause issues as the render cycle has not yet finished and the current state will not be updated on each loop.

To fix this, calculate the new quantity first and then update state:

class MyComponent extends Component {
  setQty (qty) => {
    let newQuantity = 0; //or this.state.quantity?
    for (....) {
      newQuantity++;
    }
    this.setState({quantity:newQuantity}
  }
}

P.s. it seems you're passing qty to setQty anyway, are you sure you don't just want to use 'this.setState({quantity:qty});'?


问:
Ruby: writing binary string (7zip) to file. file gets corrupted
We're building an application on Ruby on Rails 4 and it's going really fluently, except for this pain-giving issue

In our application we get a Multipart Response from a SOAP request. This response comes from an external party and sends us a 7zip compressed file.  The response has 2 parts, where the second contains a application/octet-stream.

The parts are of the Mail:part type.

When I save the contents of 'part.body.decoded' to a file, I can't open the file with 7zip, because it says the file is damaged.

When I open the generated file in the hex-editor the first lines seem ok.

```<code>p part.body.decoded.encoding.name # gives => "ASCII-8BIT"

File.open("file.7z", "wb") do |f|
 f.write(part.body.decoded)
end
</code>```

Here are the first HEX lines.

```<code>37 7A BC AF 27 1C 00 03 EF F2 1B 17 EA FA 03 00
00 00 00 00 68 00 00 00 00 00 00 00 BD D9 66 08
00 1E 10 88 27 43 3B A7 F5 C7 75 19 5D F6 A6 E0
</code>```

As a test I created a 7z file myself and read it in a string and wrote it back to a file. This works and gives me a valid 7zip.

Any ideas on how to tackle this?

Update: when I put the contents of part.body.decoded in a string
str = part.body.decoded #and put the string
p str # I get the string as below (I've deleted the middle section of the string because it has to many characters to post it here)

```<code>"7z\xBC\xAF'\x1C\x00\x03\xFCpd\x01\xEA\xFA\x03\x00\x00\x00\x00\x00h\x00\x00\x00\x00\x00\x00\x006E\x91\x1F\x00\x1E\x10\x88'C;\xA7\xF5\xC7u\x19]\xF6\xA6\xE0\xACC\xD9\xA4\xA0:,4\xE9\xA1\xAD%\x05\\a\xFBq\xA4Z\xEC7\xCC\x8C\x91\xBC?\x80H)\xFBa\xB8\xB8u\xBE\xB2\x1C|`\xA7P|\xC3\xA9\x82\xB3\r\n\xA2\x15\xA2\xDAn\xBB\xB9
</code>```

答:
Solved :-) The Savon 2 Soap Gem depends on the Mail Gem (max. version 2.5). In the Mail gem there is a bug, which touches the raw binary reponse (it ads line-ends). I've forked the Mail gem and made adaptions (to be found in the higher version of Mail (which Savon doesn't use)) and added 'my' Mail gem to my gemfile.
Thnx to all commenters for their tips!</p>

Body:
We're building an application on Ruby on Rails 4 and it's going really fluently, except for this pain-giving issue

In our application we get a Multipart Response from a SOAP request. This response comes from an external party and sends us a 7zip compressed file.  The response has 2 parts, where the second contains a application/octet-stream.

The parts are of the Mail:part type.

When I save the contents of 'part.body.decoded' to a file, I can't open the file with 7zip, because it says the file is damaged.

When I open the generated file in the hex-editor the first lines seem ok.

p part.body.decoded.encoding.name # gives => "ASCII-8BIT"

File.open("file.7z", "wb") do |f|
 f.write(part.body.decoded)
end

Here are the first HEX lines.

37 7A BC AF 27 1C 00 03 EF F2 1B 17 EA FA 03 00
00 00 00 00 68 00 00 00 00 00 00 00 BD D9 66 08
00 1E 10 88 27 43 3B A7 F5 C7 75 19 5D F6 A6 E0

As a test I created a 7z file myself and read it in a string and wrote it back to a file. This works and gives me a valid 7zip.

Any ideas on how to tackle this?

Update: when I put the contents of part.body.decoded in a string
str = part.body.decoded #and put the string
p str # I get the string as below (I've deleted the middle section of the string because it has to many characters to post it here)

"7z\xBC\xAF'\x1C\x00\x03\xFCpd\x01\xEA\xFA\x03\x00\x00\x00\x00\x00h\x00\x00\x00\x00\x00\x00\x006E\x91\x1F\x00\x1E\x10\x88'C;\xA7\xF5\xC7u\x19]\xF6\xA6\xE0\xACC\xD9\xA4\xA0:,4\xE9\xA1\xAD%\x05\\a\xFBq\xA4Z\xEC7\xCC\x8C\x91\xBC?\x80H)\xFBa\xB8\xB8u\xBE\xB2\x1C|`\xA7P|\xC3\xA9\x82\xB3\r\n\xA2\x15\xA2\xDAn\xBB\xB9


问:
Sorting a schedule to show activities for the day
```<code>#!/usr/bin/env python3.4
#March 27th 2017
#Class

import time

class DayPlanner:
    def __init__(self):
        self.schedule = []

    def add(self, datetime, activity):
        tt = time.strptime(datetime, '%Y-%m-%d %H:%M')
        self.schedule.append( [time.mktime(tt), activity] )

    def delete(self, datetime, activity):
        tt = time.mktime(time.strptime(datetime, '%Y-%m-%d %H:%M'))
        print("\n")
        for i in range(len(self.schedule)):
            if activity == self.schedule[i][1] and tt == self.schedule[i][0]:
                print("[[Match Found]]")
                print("\n")
                del self.schedule[i]
                break

    def show(self):
        for i in sorted(self.schedule):
            print('{:s}  {:s}'.format(time.ctime(i[0]), i[1]) )
#-------

sched = DayPlanner()

while True:
    date = input('date and time? ')
    if date == '':
        break
    act = input('activity? ')
    sched.add(date, act)
print("\n")
sched.show()

print("\n")

while True:
    date = input('Which date and time should I delete? ')
    if date == '':
        break
    act = input('which activity should I delete? ')
    sched.delete(date,act)
print("\n")
print("New Schedule")
sched.show()

print("\n")
print("\n")

while True:
    date = input('Which Date should I show the schedule for?')
    if date == '':
        break
    print("\n")
    print("Schedule for the day")

    sched.show()
</code>```

So, I have a good setup for adding and removing my entries, even though the time format is crazy when typing it all out.

To add to the schedule you need to type the exact format such as 2017-5-5 3:00.

My main question is how would I format that last sched.show to only show the schedule of the day?

I know I would need to make changes to the def show().

Should I create a new def and have it specifically show the day?

I am drawing a blank here and would love some help!

答:
```<code>def showday(self,day):
    for i in sorted(self.schedule):
        sec = i[0]
        tt1=time.localtime(sec)
        stt=time.strptime(day,'%Y-%m-%d')
        if stt.tm_year == tt1.tm_year and stt.tm_mon == tt1.tm_mon and stt.tm_mday == tt1.tm_mday:
            print(time.ctime(sec), i[1])
</code>```

<p>I used this def to fix my issue. My greatest resource was jupyter to find some help regarding time. I wont lie it took a bit but I got it all figured out and it works pretty well. Posting my solution for archive just in case someone else comes up with something similar. </p>

Body:
#!/usr/bin/env python3.4
#March 27th 2017
#Class

import time

class DayPlanner:
    def __init__(self):
        self.schedule = []

    def add(self, datetime, activity):
        tt = time.strptime(datetime, '%Y-%m-%d %H:%M')
        self.schedule.append( [time.mktime(tt), activity] )

    def delete(self, datetime, activity):
        tt = time.mktime(time.strptime(datetime, '%Y-%m-%d %H:%M'))
        print("\n")
        for i in range(len(self.schedule)):
            if activity == self.schedule[i][1] and tt == self.schedule[i][0]:
                print("[[Match Found]]")
                print("\n")
                del self.schedule[i]
                break

    def show(self):
        for i in sorted(self.schedule):
            print('{:s}  {:s}'.format(time.ctime(i[0]), i[1]) )
#-------

sched = DayPlanner()

while True:
    date = input('date and time? ')
    if date == '':
        break
    act = input('activity? ')
    sched.add(date, act)
print("\n")
sched.show()

print("\n")

while True:
    date = input('Which date and time should I delete? ')
    if date == '':
        break
    act = input('which activity should I delete? ')
    sched.delete(date,act)
print("\n")
print("New Schedule")
sched.show()

print("\n")
print("\n")

while True:
    date = input('Which Date should I show the schedule for?')
    if date == '':
        break
    print("\n")
    print("Schedule for the day")

    sched.show()

So, I have a good setup for adding and removing my entries, even though the time format is crazy when typing it all out.

To add to the schedule you need to type the exact format such as 2017-5-5 3:00.

My main question is how would I format that last sched.show to only show the schedule of the day?

I know I would need to make changes to the def show().

Should I create a new def and have it specifically show the day?

I am drawing a blank here and would love some help!

Body:
def showday(self,day):
    for i in sorted(self.schedule):
        sec = i[0]
        tt1=time.localtime(sec)
        stt=time.strptime(day,'%Y-%m-%d')
        if stt.tm_year == tt1.tm_year and stt.tm_mon == tt1.tm_mon and stt.tm_mday == tt1.tm_mday:
            print(time.ctime(sec), i[1])

I used this def to fix my issue. My greatest resource was jupyter to find some help regarding time. I wont lie it took a bit but I got it all figured out and it works pretty well. Posting my solution for archive just in case someone else comes up with something similar.


问:
Call google chart from partial view in mvc
I'm trying to call google chart from a partial view to a view but the chart is not loading. It was working fine in the view, but when converted to partial view it is not rendering. Anyone please check and help me if anything wrong.

My View

```<code>@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#ChartTypes').change(function () {

            var selectedID = $(this).val();
            $.ajax({
                url: '/charts/GetChart/4',
                type: 'GET',
                success: function (result) {
                    debugger;
                    var res = JSON.stringify(result);
                    $('#div-Graph').append(res);
                    alert($('#div-Graph').html());
                }
            });

        });
    });
</script>
<div>

    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>
    <div id="div-Graph">

    </div>
</div>
</code>```

My PartialView

```<code>@model IEnumerable<HeathAppDesign.Model.ChartModel>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });

</script>
<script type="text/javascript">
    $(function () {

        chartsdata = '@Model'
        alert(chartsdata);
        google.charts.load('current', { 'packages': ['bar'] });
        google.charts.setOnLoadCallback(drawStuff);

        function drawStuff() {
            var data = new google.visualization.DataTable();

            data.addColumn('string', '');
            data.addColumn('number', '');

            for (var i = 0; i < chartsdata.length; i++) {
                data.addRow([chartsdata[i].XCoordinates, chartsdata[i].YCoordinates]);
            }

            var options = {
                title: 'Paid/Allowed Ratio by Plan',
                width: 500,
                legend: { position: 'none' },
                trendlines: { 0: {} },
                bars: 'vertical', // Required for Material Bar Charts
                vAxis: { viewWindow: { min: 90, max: 100 }, gridlines: { count: 11} },

                bar: { groupWidth: "20%" }
            };

            var chart = new google.charts.Bar(document.getElementById('chartdiv'));
            chart.draw(data, options);
        };

    });

</script>
<h2>
    Chart5</h2>
<div id="chartdiv" style="width: 600px; height: 350px; margin: 0 auto;">
</div>
</code>```

My ActionMethod

```<code> [HttpGet]
        public ActionResult GetChart(int id)
        {
            return PartialView("_PaidOrAllowedRatio",
                      objChartService.GetChartCoordinates(ChartTypes.PaidOrAllowedRatioByPlan));
        }
</code>```

My result is like this

"\r\n\r\n
\r\n Chart5

\r\n
\r\n
\r\n"
Design table Area

I have multiple charts in the same view and that is why using partial view.

Anyone please help?

答:
I see few problems with your code

Issue 1

In your partial view, this line

```<code>var chartsdata = '@Model';
</code>```

When razor executes this code, It generates code like below (you can see this if you check view source of the generated page.(check response tab of your ajax call))

```<code>var chartsdata = 'System.Collections.Generic.List`1[YourNamespace.ChartModel]';
</code>```

This is a string. So basically in your for loop below you are looping until the length of this string , which is obviously  wrong! Your Model is a collection of ChartModel. So you should set the same collection/array as it is to this chartsdata  variable which you can loop through later and use it for adding the data for the graph.

You can use JsonConvert.SerializeObject with Html.Raw to convert your model object to a javascript array.

```<code>var chartsdata = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
</code>```

This will store an array (of ChartModel objects(js version)) to the chartsdata variable.

Now your looping code is good

```<code>for (var i = 0; i < chartsdata.length; i++) {
   data.addRow([chartsdata[i].XCoordinates, chartsdata[i].YCoordinates]);
}
</code>```

Issue 2

Next problem is, you are using a wrong variable to update the DOM when you get the ajax call response.

```<code>success: function (result) {
                $('#div-Graph').append(res);   // WHAT IS "res" ?????
            }
</code>```

The fix is simple

```<code>success: function (result) {
                $('#div-Graph').append(result);
            }
</code>```

Once you fix these issues, the charts will appear on the SELECT element change event ,assuming you do not have any other js errors in the page.

Body:
I'm trying to call google chart from a partial view to a view but the chart is not loading. It was working fine in the view, but when converted to partial view it is not rendering. Anyone please check and help me if anything wrong.

My View

@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}

    Index

    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>

My PartialView

@model IEnumerable<HeathAppDesign.Model.ChartModel>

    Chart5

My ActionMethod

 [HttpGet]
        public ActionResult GetChart(int id)
        {
            return PartialView("_PaidOrAllowedRatio",
                      objChartService.GetChartCoordinates(ChartTypes.PaidOrAllowedRatioByPlan));
        }

My result is like this

"\r\n\r\n
\r\n Chart5

\r\n
\r\n
\r\n"
Design table Area

I have multiple charts in the same view and that is why using partial view.

Anyone please help?

Body:
I see few problems with your code

Issue 1

In your partial view, this line

var chartsdata = '@Model';

When razor executes this code, It generates code like below (you can see this if you check view source of the generated page.(check response tab of your ajax call))

var chartsdata = 'System.Collections.Generic.List`1[YourNamespace.ChartModel]';

This is a string. So basically in your for loop below you are looping until the length of this string , which is obviously  wrong! Your Model is a collection of ChartModel. So you should set the same collection/array as it is to this chartsdata  variable which you can loop through later and use it for adding the data for the graph.

You can use JsonConvert.SerializeObject with Html.Raw to convert your model object to a javascript array.

var chartsdata = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));

This will store an array (of ChartModel objects(js version)) to the chartsdata variable.

Now your looping code is good

for (var i = 0; i < chartsdata.length; i++) {
   data.addRow([chartsdata[i].XCoordinates, chartsdata[i].YCoordinates]);
}

Issue 2

Next problem is, you are using a wrong variable to update the DOM when you get the ajax call response.

success: function (result) {
                $('#div-Graph').append(res);   // WHAT IS "res" ?????
            }

The fix is simple

success: function (result) {
                $('#div-Graph').append(result);
            }

Once you fix these issues, the charts will appear on the SELECT element change event ,assuming you do not have any other js errors in the page.


问:
How to prevent entry of a disabled date in bootstrap-datepicker
I am running uxsolutions / bootstrap-datepicker (https://github.com/uxsolutions/bootstrap-datepicker).

I have disabled dates in the popup calendar widget just fine (see code below). Yet in the date's textbox, I can enter a disabled date (screen shot below).

How can I get the date box to recognize disabled dates and prevent them from being able to be input?

```<code>  $('#eventDate-container .input-group.date').datepicker({
    weekStart: 1, // calendar starts on Monday
    autoclose: true,
    todayHighlight: true,
    startDate: "4/10/2017", // disables all dates prior to this date
    datesDisabled: ['01/01/1970', '12/31/2099'] // placeholder sample for possible future use
  });
</code>```

答:
I know this is not the plugin you are using (Bootstrap 3 Date/Time Picker) but this might help...
I have been doing the same today, i started out with the exact plugin you are using, but then went to Bootstrap 3 Date/Time Picker because it has more options

Disable manual entry of date in , force selection via picker. #212

Body:
I am running uxsolutions / bootstrap-datepicker (https://github.com/uxsolutions/bootstrap-datepicker).

I have disabled dates in the popup calendar widget just fine (see code below). Yet in the date's textbox, I can enter a disabled date (screen shot below).

How can I get the date box to recognize disabled dates and prevent them from being able to be input?

  $('#eventDate-container .input-group.date').datepicker({
    weekStart: 1, // calendar starts on Monday
    autoclose: true,
    todayHighlight: true,
    startDate: "4/10/2017", // disables all dates prior to this date
    datesDisabled: ['01/01/1970', '12/31/2099'] // placeholder sample for possible future use
  });


问:
Sqoop is failing to get data from teradata with java.IO exception
Here is my sqoop import that I'm using to pull data from Teradata

```<code>     sqoop import -libjars jars --driver drivers --connect connection_url -m 1 --hive-overwrite --hive-import --hive-database hivedatabase --hive-table hivetable --target-dir '/user/hive/warehouse/database.db/table_name' --as-parquetfile --query "select c1,c2,c3, to_char(SOURCE_ACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_ACTIVATION_DT,to_char(SOURCE_DEACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_DEACTIVATION_DT,to_char(EFF_DT,'YYYY-MM-DD HH24:MI:SS') as EFF_DT,to_char(EXP_DT,'YYYY-MM-DD HH24:MI:SS') as EXP_DT,to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_UPDATE_DTM,to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_LOAD_DTM from source_schema.table_name WHERE to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS')> '2017-03-30 10:00:00' OR to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') > '2017-03-30 10:00:00' AND \$CONDITIONS"
</code>```

Below is the error I'm getting, this was running fine for two days and started returning the below error recently.

```<code>17/03/29 20:07:53 INFO mapreduce.Job:  map 0% reduce 0%
17/03/29 20:56:46 INFO mapreduce.Job: Task Id : attempt_1487033963691_263120_m_000000_0, Status : FAILED
Error: java.io.IOException: SQLException in nextKeyValue
    at org.apache.sqoop.mapreduce.db.DBRecordReader.nextKeyValue(DBRecordReader.java:277)
    at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.nextKeyValue(MapTask.java:556)
    at org.apache.hadoop.mapreduce.task.MapContextImpl.nextKeyValue(MapContextImpl.java:80)
    at org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.nextKeyValue(WrappedMapper.java:91)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:144)
    at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1693)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
Caused by: java.sql.SQLException: [Teradata JDBC Driver] [TeraJDBC 15.10.00.14] [Error 1005] [SQLState HY000] Unexpected parcel kind received: 9
    at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDriverJDBCException(ErrorFactory.java:94)
    at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDriverJDBCException(ErrorFactory.java:69)
    at com.teradata.jdbc.jdbc_4.statemachine.ReceiveRecordSubState.action(ReceiveRecordSubState.java:195)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:311)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:200)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:137)
    at com.teradata.jdbc.jdbc_4.statemachine.PreparedStatementController.run(PreparedStatementController.java:46)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementController.fetchRows(StatementController.java:360)
    at com.teradata.jdbc.jdbc_4.TDResultSet.goToRow(TDResultSet.java:374)
    at com.teradata.jdbc.jdbc_4.TDResultSet.next(TDResultSet.java:657)
    at org.apache.sqoop.mapreduce.db.DBRecordReader.nextKeyValue(DBRecordReader.java:237)
    ... 12 more
</code>```

When i googled around I've seen people getting same errors for different errors, I know this is something related to the time i'm using in where clause, but not sure what exactly i have to change.

Thanks in advance...!!

答:
Sqoop uses $CONDITIONS to fetch metadata and data.

Metadata - It replaces $CONDITIONS with 1=0. So, no data will be fetched using this condition but only metadata.

Data in case of 1 mapper: It replaces $CONDITIONS with 1=1. So, all the data is fetched.

Data in case of multiple mapper: It replaces $CONDITIONS with some range condition.

Try these queries in JDBC client:

select c1,c2,c3, to_char(SOURCE_ACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_ACTIVATION_DT,to_char(SOURCE_DEACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_DEACTIVATION_DT,to_char(EFF_DT,'YYYY-MM-DD HH24:MI:SS') as EFF_DT,to_char(EXP_DT,'YYYY-MM-DD HH24:MI:SS') as EXP_DT,to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_UPDATE_DTM,to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_LOAD_DTM from source_schema.table_name WHERE to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS')> '2017-03-30 10:00:00' OR to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') > '2017-03-30 10:00:00' AND 1=0"

select c1,c2,c3, to_char(SOURCE_ACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_ACTIVATION_DT,to_char(SOURCE_DEACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_DEACTIVATION_DT,to_char(EFF_DT,'YYYY-MM-DD HH24:MI:SS') as EFF_DT,to_char(EXP_DT,'YYYY-MM-DD HH24:MI:SS') as EXP_DT,to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_UPDATE_DTM,to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_LOAD_DTM from source_schema.table_name WHERE to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS')> '2017-03-30 10:00:00' OR to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') > '2017-03-30 10:00:00' AND 1=1"

If these are not working, your sqoop command with this query can never run.

Body:
Here is my sqoop import that I'm using to pull data from Teradata

     sqoop import -libjars jars --driver drivers --connect connection_url -m 1 --hive-overwrite --hive-import --hive-database hivedatabase --hive-table hivetable --target-dir '/user/hive/warehouse/database.db/table_name' --as-parquetfile --query "select c1,c2,c3, to_char(SOURCE_ACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_ACTIVATION_DT,to_char(SOURCE_DEACTIVATION_DT,'YYYY-MM-DD HH24:MI:SS') as SOURCE_DEACTIVATION_DT,to_char(EFF_DT,'YYYY-MM-DD HH24:MI:SS') as EFF_DT,to_char(EXP_DT,'YYYY-MM-DD HH24:MI:SS') as EXP_DT,to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_UPDATE_DTM,to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') as SYS_LOAD_DTM from source_schema.table_name WHERE to_char(SYS_UPDATE_DTM,'YYYY-MM-DD HH24:MI:SS')> '2017-03-30 10:00:00' OR to_char(SYS_LOAD_DTM,'YYYY-MM-DD HH24:MI:SS') > '2017-03-30 10:00:00' AND \$CONDITIONS"

Below is the error I'm getting, this was running fine for two days and started returning the below error recently.

17/03/29 20:07:53 INFO mapreduce.Job:  map 0% reduce 0%
17/03/29 20:56:46 INFO mapreduce.Job: Task Id : attempt_1487033963691_263120_m_000000_0, Status : FAILED
Error: java.io.IOException: SQLException in nextKeyValue
    at org.apache.sqoop.mapreduce.db.DBRecordReader.nextKeyValue(DBRecordReader.java:277)
    at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.nextKeyValue(MapTask.java:556)
    at org.apache.hadoop.mapreduce.task.MapContextImpl.nextKeyValue(MapContextImpl.java:80)
    at org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.nextKeyValue(WrappedMapper.java:91)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:144)
    at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1693)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
Caused by: java.sql.SQLException: [Teradata JDBC Driver] [TeraJDBC 15.10.00.14] [Error 1005] [SQLState HY000] Unexpected parcel kind received: 9
    at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDriverJDBCException(ErrorFactory.java:94)
    at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDriverJDBCException(ErrorFactory.java:69)
    at com.teradata.jdbc.jdbc_4.statemachine.ReceiveRecordSubState.action(ReceiveRecordSubState.java:195)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:311)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:200)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:137)
    at com.teradata.jdbc.jdbc_4.statemachine.PreparedStatementController.run(PreparedStatementController.java:46)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementController.fetchRows(StatementController.java:360)
    at com.teradata.jdbc.jdbc_4.TDResultSet.goToRow(TDResultSet.java:374)
    at com.teradata.jdbc.jdbc_4.TDResultSet.next(TDResultSet.java:657)
    at org.apache.sqoop.mapreduce.db.DBRecordReader.nextKeyValue(DBRecordReader.java:237)
    ... 12 more

When i googled around I've seen people getting same errors for different errors, I know this is something related to the time i'm using in where clause, but not sure what exactly i have to change.

Thanks in advance...!!


问:
Python Recursive Example Explanation
So currently working through MIT's OpenCourseWare computer science course online and I am having trouble trying to understand one of the recursive examples.

```<code>def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            return f(e)
return result
</code>```

When the following input is given:

```<code>print f([1, [[2, 'a'], ['a','b']], (3, 4)])
</code>```

The output is:

```<code>[2, 'a']
</code>```

I am having trouble trying to understand how this function actually works or what it is doing. Shouldn't the function eventually be adding every string or int into the result list? I just need help with trying to understand how this function "winds up" and "unwinds"

I feel like the output should be:

```<code>[1,2,'a','a','b',3,4]
</code>```

Any help would be appreciated thanks!

答:
so by your suggested answer I see that you understand about the idea of the code. It digs deeper and deeper until it finds an element. But look about the back-step to the upper levels:

When it reaches the deepest point for the first time (the elements of the [2,'a'] list) it finish the loop on this level and returns the results 2 and a. And here is a RETURN statement ... that means the loop is stoped and thus no other elements are found.

The open question is now, why it is not showing 1 as part of result ? For the same reason, the RETURN is the result of the lower levels (2,a) and the result of the upper level. If you change "result" to a global variable, the outcome will be [1, 2, 'a']

best regards

Title: Python Recursive Example Explanation

Body:
So currently working through MIT's OpenCourseWare computer science course online and I am having trouble trying to understand one of the recursive examples.

def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            return f(e)
return result

When the following input is given:

print f([1, [[2, 'a'], ['a','b']], (3, 4)])

The output is:

[2, 'a']

I am having trouble trying to understand how this function actually works or what it is doing. Shouldn't the function eventually be adding every string or int into the result list? I just need help with trying to understand how this function "winds up" and "unwinds"

I feel like the output should be:

[1,2,'a','a','b',3,4]

Any help would be appreciated thanks!


问:
creating local push notification using react-native
I am developing android app using react-native. I want to create local push notification by clicking on button. how can I do this? which all the libraries I need to import?  prasanna</p>

答:
You can use react-native-fcm plugin for local notification and scheduled notification.

Code snippet

```<code>_onLocalNotification(){
    if(Platform.OS  === "android"){
        FCM.presentLocalNotification({
            id: "UNIQ_ID_STRING",                               // (optional for instant notification)
            title: this.state.content,                     // as FCM payload
            body: this.state.content,                    // as FCM payload (required)
            sound: "default",                                   // as FCM payload
            priority: "high",                                   // as FCM payload
            click_action: "ACTION",                             // as FCM payload
            badge: 10,                                          // as FCM payload IOS only, set 0 to clear badges
            number: 10,                                         // Android only
            ticker: "My Notification Ticker",                   // Android only
            auto_cancel: true,                                  // Android only (default true)
            large_icon: "ic_launcher",                           // Android only
            icon: "ic_launcher",                                // as FCM payload, you can relace this with custom icon you put in mipmap
            big_text: "Show when notification is expanded",     // Android only
            sub_text: "This is a subText",                      // Android only
            color: "red",                                       // Android only
            vibrate: 300,                                       // Android only default: 300, no vibration if you pass null
            tag: 'some_tag',                                    // Android only
            group: "group",                                     // Android only
            my_custom_data:'my_custom_field_value',             // extra data you want to throw
            lights: true,                                       // Android only, LED blinking (default false)
            show_in_foreground: true                                  // notification when app is in foreground (local & remote)
        });
    }
   else{
        FCM.scheduleLocalNotification({
            fire_date: new Date().getTime() + 1000,      //RN's converter is used, accept epoch time and whatever that converter supports
            id: '1111',
            body: this.state.content,
            repeat_interval: 'day',
            count: 3,
            show_in_foreground: true
        })
    }

}

_onScheduledNotification(){
    FCM.scheduleLocalNotification({
        fire_date: new Date().getTime() + 5000,      //RN's converter is used, accept epoch time and whatever that converter supports
        id: '1111',
        body: this.state.content,
        repeat_interval: 'day',
        count: 3,
        show_in_foreground: true
    })
}
</code>```

Please check and let me know if you face any issue.
Note - Solution provided in question's comment uses react-native-push-notification plugin.

Body:
You can use react-native-fcm plugin for local notification and scheduled notification.

Code snippet

_onLocalNotification(){
    if(Platform.OS  === "android"){
        FCM.presentLocalNotification({
            id: "UNIQ_ID_STRING",                               // (optional for instant notification)
            title: this.state.content,                     // as FCM payload
            body: this.state.content,                    // as FCM payload (required)
            sound: "default",                                   // as FCM payload
            priority: "high",                                   // as FCM payload
            click_action: "ACTION",                             // as FCM payload
            badge: 10,                                          // as FCM payload IOS only, set 0 to clear badges
            number: 10,                                         // Android only
            ticker: "My Notification Ticker",                   // Android only
            auto_cancel: true,                                  // Android only (default true)
            large_icon: "ic_launcher",                           // Android only
            icon: "ic_launcher",                                // as FCM payload, you can relace this with custom icon you put in mipmap
            big_text: "Show when notification is expanded",     // Android only
            sub_text: "This is a subText",                      // Android only
            color: "red",                                       // Android only
            vibrate: 300,                                       // Android only default: 300, no vibration if you pass null
            tag: 'some_tag',                                    // Android only
            group: "group",                                     // Android only
            my_custom_data:'my_custom_field_value',             // extra data you want to throw
            lights: true,                                       // Android only, LED blinking (default false)
            show_in_foreground: true                                  // notification when app is in foreground (local & remote)
        });
    }
   else{
        FCM.scheduleLocalNotification({
            fire_date: new Date().getTime() + 1000,      //RN's converter is used, accept epoch time and whatever that converter supports
            id: '1111',
            body: this.state.content,
            repeat_interval: 'day',
            count: 3,
            show_in_foreground: true
        })
    }

}

_onScheduledNotification(){
    FCM.scheduleLocalNotification({
        fire_date: new Date().getTime() + 5000,      //RN's converter is used, accept epoch time and whatever that converter supports
        id: '1111',
        body: this.state.content,
        repeat_interval: 'day',
        count: 3,
        show_in_foreground: true
    })
}

Please check and let me know if you face any issue.
Note - Solution provided in question's comment uses react-native-push-notification plugin.


问:
If one checkbox is checked, set the other to unchecked
I have two checkboxes on my form; chkBuried and chkAboveGround. I want to set it up so if one is checked, the other is unchecked. How can I do this?

I have tried the CheckChanged property:

```<code>private void chkBuried_CheckedChanged(object sender, EventArgs e)
{
    chkAboveGround.Checked = false;
}
private void chkAboveGround_CheckedChanged(object sender, EventArgs e)
{
    chkBuried.Checked = false;
}
</code>```

And it works, just not as well as I hoped. That is, when I check chkBuried, then check chkAboveGround, both boxes become unchecked before I can check another one again.

答:
Better version, allows the user to uncheck boxes.

        private void chkOne_CheckedChanged(object sender, EventArgs e)
        {
            if (chkTwo.Checked == true)
            {
                chkTwo.Checked = !chkOne.Checked;
            }
        }

        private void chkTwo_CheckedChanged(object sender, EventArgs e)
        {
            if (chkOne.Checked == true)
            {
                chkOne.Checked = !chkTwo.Checked;
            }
        }
```

Body:
I have two checkboxes on my form; chkBuried and chkAboveGround. I want to set it up so if one is checked, the other is unchecked. How can I do this?

I have tried the CheckChanged property:

private void chkBuried_CheckedChanged(object sender, EventArgs e)
{
    chkAboveGround.Checked = false;
}
private void chkAboveGround_CheckedChanged(object sender, EventArgs e)
{
    chkBuried.Checked = false;
}

And it works, just not as well as I hoped. That is, when I check chkBuried, then check chkAboveGround, both boxes become unchecked before I can check another one again.


问:
Angular 2/4: How to show all navigation entries of children modules in the parent level navigation bar?
In the first version of the UI design of my project, there are two levels of navigations. The root level, only 4 links: feature groups A, B, C, and D. Each feature group has its own features: A1, A2...B1, B2....D1, D2. When a user click link "A" on the app root page, then all the features of group A will show on a sub navigation bar.

I implemented the app like this: created 4 feature modules A, B, C and D. Each module has its own routing config (e.g: a-routing.module.ts under folder A). The second level navigation bar is written in each feature modules's component template, e.g.: a.component.html. Everything has been fine.

Now the team has changed the GUI design. There is a dropdown menu on the root level navigation bar. Links to all feature pages are assembled in this dropdown menu bar. What is the best way to refactor my implementation to fit this new dropdown menu bar? (I will have to push all the 2-level navi links to 1-level navi template now. app.component.html has be changed to contain all these links. But do I have to refactor other files too? And how?)

Angular 2 is relatively new to me, I'm still learning, many thanks in advance for any help.

Current app.component.html looks like this:

My App

      Dashboard
      Service Catalog
      Administration
      Profile

<router-outlet></router-outlet>```
</div>
</div>
</p>

<p>Current app-routing.module.ts looks like this (sans imports):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const routes: Routes = [
    { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  declarations: [ PageNotFoundComponent ],
  exports: [ RouterModule ]
})

export class AppRoutingModule {}</code>```

Component template of one of the children module looks like this:

Dashboard

Service Status

Service
   Usage

System
   Status

 {{item.caption}}

<router-outlet></router-outlet>```
</div>
</div>
</p>

<p>The corresponding child routing config looks like this (sans imports):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const monitoringRoutes: Routes = [
    {
        path: 'dashboard',
        component: MonitoringComponent,
        children: [
            { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
            { path: 'dashboard', component: DashboardComponent },
            { path: 'service-status', component: ServiceStatusComponent },
            { path: 'service-usage', component: ServiceUsageComponent },
            { path: 'system-status', component: SystemStatusComponent },
            { path: 'binded-ui/:uri', component: UIBindingComponent }
        ]
    }
];

@NgModule({
  imports: [ RouterModule.forChild(monitoringRoutes) ],
  exports: [ RouterModule ]
})
export class MonitoringRoutingModule {}</code>```

答:
I just tried. It is relatively straightforward. Basically I only need to move the entries in the module html to the root html, and make some slight change to the routerLink. For example, this line:

Service Status
```
</div>
</div>
</p>

<p>when moved to app.component.html, changed be changed to </p>

```
Service Status

```

Basically that's it. The other typescript files do not need change in my case. But if there was some router guard, maybe change will be needed. I don't know. I'm building router guard into the migrated code now.

Body:
In the first version of the UI design of my project, there are two levels of navigations. The root level, only 4 links: feature groups A, B, C, and D. Each feature group has its own features: A1, A2...B1, B2....D1, D2. When a user click link "A" on the app root page, then all the features of group A will show on a sub navigation bar.

I implemented the app like this: created 4 feature modules A, B, C and D. Each module has its own routing config (e.g: a-routing.module.ts under folder A). The second level navigation bar is written in each feature modules's component template, e.g.: a.component.html. Everything has been fine.

Now the team has changed the GUI design. There is a dropdown menu on the root level navigation bar. Links to all feature pages are assembled in this dropdown menu bar. What is the best way to refactor my implementation to fit this new dropdown menu bar? (I will have to push all the 2-level navi links to 1-level navi template now. app.component.html has be changed to contain all these links. But do I have to refactor other files too? And how?)

Angular 2 is relatively new to me, I'm still learning, many thanks in advance for any help.

Current app.component.html looks like this:

My App

      Dashboard
      Service Catalog
      Administration
      Profile

<router-outlet></router-outlet>

Current app-routing.module.ts looks like this (sans imports):

const routes: Routes = [
    { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  declarations: [ PageNotFoundComponent ],
  exports: [ RouterModule ]
})

export class AppRoutingModule {}

Component template of one of the children module looks like this:

Dashboard

Service Status

Service
   Usage

System
   Status

 {{item.caption}}

<router-outlet></router-outlet>

The corresponding child routing config looks like this (sans imports):

const monitoringRoutes: Routes = [
    {
        path: 'dashboard',
        component: MonitoringComponent,
        children: [
            { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
            { path: 'dashboard', component: DashboardComponent },
            { path: 'service-status', component: ServiceStatusComponent },
            { path: 'service-usage', component: ServiceUsageComponent },
            { path: 'system-status', component: SystemStatusComponent },
            { path: 'binded-ui/:uri', component: UIBindingComponent }
        ]
    }
];

@NgModule({
  imports: [ RouterModule.forChild(monitoringRoutes) ],
  exports: [ RouterModule ]
})
export class MonitoringRoutingModule {}

Body:
I just tried. It is relatively straightforward. Basically I only need to move the entries in the module html to the root html, and make some slight change to the routerLink. For example, this line:

<li><a routerLink="service-status" routerLinkActive="active">Service Status</a></li>

when moved to app.component.html, changed be changed to

<li><a routerLink="/dashboard/service-status" routerLinkActive="active">Service Status</a></li>

Basically that's it. The other typescript files do not need change in my case. But if there was some router guard, maybe change will be needed. I don't know. I'm building router guard into the migrated code now.


问:
C# read string from back to end
I have a string. For example :

```<code>string a = "abcdef098403248";
</code>```

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

```<code>string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";
</code>```

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

```<code>string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Or:

```<code>string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Regardless, thanks.

答:
```<code>string str = "3333333a224444";
var reversedStr = str.Reverse();
string result= new String(reversedStr.TakeWhile(Char.IsDigit).ToArray());
</code>```

Title: C# read string from back to end

Body:
I have a string. For example :

string a = "abcdef098403248";

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";

Or:

string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";

Regardless, thanks.


问:
JavaScript ES6 - console.log with template literal
I'm writing node's script that connect to the mongo database.

I noticed that printing error response is different by small change in console.log syntax. Below example should be more meaningful.

```<code>#!/usr/bin/env node

const mongoose = require("mongoose");
const config = require("./config");

mongoose.connect(config.dbURI, (err) => {
    if (err) {
        console.log(`${err}`); // First console.log
        console.log(err); // Second console.log
    } else {
        console.log(`Database connection successful`)
    }
});
</code>```

Example output of the first console.log

```<code>MongoError: Authentication failed.
</code>```

Example output of the second console.log

```<code>{ MongoError: Authentication failed.
    at Function.MongoError.create (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/error.js:31:11)
    at /Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:489:72
    at authenticateStragglers (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:435:16)
    at Connection.messageHandler (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:469:5)
    at Socket.<anonymous> (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/connection.js:321:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:563:20)
  name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  code: 18,
  errmsg: 'Authentication failed.' }
</code>```

Where comes from this difference?

答:
${err} (or '' + err for that matter) will interpolate the err object with a string which will also change your Error object into a string  - which is equivalent to calling err.toString(). However directly logging err will pass it to the console as an object and display it in that manner.

This is called "implicit coercion" - if you would like to know more about this subject I can highly recommend reading You Don't Know JS: Types & Grammar (Chapter 4: Coercion) for a deep dive.

Body:
I'm writing node's script that connect to the mongo database.

I noticed that printing error response is different by small change in console.log syntax. Below example should be more meaningful.

#!/usr/bin/env node

const mongoose = require("mongoose");
const config = require("./config");

mongoose.connect(config.dbURI, (err) => {
    if (err) {
        console.log(`${err}`); // First console.log
        console.log(err); // Second console.log
    } else {
        console.log(`Database connection successful`)
    }
});

Example output of the first console.log

MongoError: Authentication failed.

Example output of the second console.log

{ MongoError: Authentication failed.
    at Function.MongoError.create (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/error.js:31:11)
    at /Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:489:72
    at authenticateStragglers (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:435:16)
    at Connection.messageHandler (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:469:5)
    at Socket.<anonymous> (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/connection.js:321:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:563:20)
  name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  code: 18,
  errmsg: 'Authentication failed.' }

Where comes from this difference?