问:
Magento 1.9 create new Hello World module

 Hello, guys!

I really hope someone will help me with this.

I trying to make new module in magento 1.9.3.2, which show "Hello world!" from phtml file. I  created that step by step by this rules. Module is created, but when I open module (127.0.0.1/magento/helloworld) in browser, nothing appear, just empty this template.
opened module in browser - screenshot

Here is steps by what i guided:

1. Module declaration:
     Create new xml file in  app/etc/modules/M4U_HelloWorld.xml

    <?xml version="1.0"?>
                 <config>
                       <modules>
                          <M4U_HelloWorld>
                               <active>true</active>
                               <codePool>local</codePool>
                          </M4U_HelloWorld>
                       </modules>
                 </config>

Module configuration

    2.1. Create controller class in app/code/local/M4U/HelloWorld/controllers/IndexController.php

class M4U_HelloWorld_IndexController extends  Mage_Core_Controller_Front_Action
                    {
                      public function indexAction()
                      {
                         $this->loadLayout(array('default'));
                         $this->renderLayout();
                      }
                    }

2.2. Create Block class in app/code/local/M4U/HelloWorld/Block/HelloWorld.php

```<code>class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
                  {
                       // necessary methods
                  }
</code>```

2.3. Create configuration xml in app/code/local/M4U/HelloWorld/etc/config.xml

```<code><?xml version="1.0"?>
<config>
<global>
    <modules>
            <m4u_helloworld>
                    <version>0.1.0</version>
            </m4u_helloworld>
    </modules>
<blocks>
        <helloworld>
            <rewrite>
     <helloworld>M4U_HelloWorld_Block_HelloWorld</helloworld>
    </rewrite>
        </helloworld>
 </blocks>
    </global>
   <frontend>
            <routers>
                    <helloworld>
                            <use>standard</use>
                            <args>
                                  <module>M4U_HelloWorld</module>
                                  <frontName>helloworld</frontName>
                            </args>
                    </helloworld>
            </routers>
    <layout>
        <updates>
            <helloworld>
                  <file>helloworld.xml</file>
            </helloworld>
        </updates>
        </layout>
    </frontend>
</code>```

Define frontend template

3.1. Define page layout in app/design/frontend/default/default/layout/helloworld.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">                  <template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>

Create template file in   app/design/frontend/default/default/template/helloworld/helloworld.phtml

答:
TRIED AND TESTED

screenshot here

you can display your helloworld template in your custom module, done some minor modifications to your code.

module declaration:

```<code><?xml version="1.0"?>
 <config>
       <modules>
          <M4U_HelloWorld>
               <active>true</active>
               <codePool>local</codePool>
          </M4U_HelloWorld>
       </modules>
 </config>
</code>```

creating the folder structure and add the files

A. app/code/local/M4U/HelloWorld/etc/config.xml

```<code><config>
    <modules>
        <m4u_helloworld>
            <version>0.1.0</version>
        </m4u_helloworld>
    </modules>
    <frontend>
        <routers>
            <helloworld>
                <use>standard</use>
                <args>
                    <module>M4U_HelloWorld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
        <layout>
            <updates>
                <helloworld module="M4U_HelloWorld">
                    <file>M4U_HelloWorld.xml</file>
                </helloworld>
            </updates>
        </layout>
    </frontend>
    <global>
        <blocks>
            <helloworld>
                <class>M4U_HelloWorld_Block</class>
            </helloworld>
        </blocks>
    </global>
</config>
</code>```

B. app/code/local/M4U/HelloWorld/block/HelloWorld.php

```<code>class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template {

}
</code>```

C. app/code/local/M4U/HelloWorld/controllers/IndexController.php

```<code>class M4U_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action {

    public function indexAction() {
        echo 'hello world';
        $this->loadLayout();  //This function read all layout files and loads them in memory
        $this->renderLayout();
    }

}
</code>```

D. app/design/frontend/ * theme base* / * mytheme * /layout/M4U_HelloWorld.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">
                <template>page/1column.phtml</template>
            </action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>
</code>```

E. app/design/frontend/ * theme base* / * mytheme * /template/helloworld/helloworld.php

```<code>echo 'im a template block';
</code>```

Body:
 Hello, guys!

I really hope someone will help me with this.

I trying to make new module in magento 1.9.3.2, which show "Hello world!" from phtml file. I  created that step by step by this rules. Module is created, but when I open module (127.0.0.1/magento/helloworld) in browser, nothing appear, just empty this template.
opened module in browser - screenshot

Here is steps by what i guided:

1. Module declaration:
     Create new xml file in  app/etc/modules/M4U_HelloWorld.xml

    <?xml version="1.0"?>
                 <config>
                       <modules>
                          <M4U_HelloWorld>
                               <active>true</active>
                               <codePool>local</codePool>
                          </M4U_HelloWorld>
                       </modules>
                 </config>

Module configuration

    2.1. Create controller class in app/code/local/M4U/HelloWorld/controllers/IndexController.php

class M4U_HelloWorld_IndexController extends  Mage_Core_Controller_Front_Action
                    {
                      public function indexAction()
                      {
                         $this->loadLayout(array('default'));
                         $this->renderLayout();
                      }
                    }

2.2. Create Block class in app/code/local/M4U/HelloWorld/Block/HelloWorld.php

class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
                  {
                       // necessary methods
                  }

2.3. Create configuration xml in app/code/local/M4U/HelloWorld/etc/config.xml

<?xml version="1.0"?>
<config>
<global>
    <modules>
            <m4u_helloworld>
                    <version>0.1.0</version>
            </m4u_helloworld>
    </modules>
<blocks>
        <helloworld>
            <rewrite>
     <helloworld>M4U_HelloWorld_Block_HelloWorld</helloworld>
    </rewrite>
        </helloworld>
 </blocks>
    </global>
   <frontend>
            <routers>
                    <helloworld>
                            <use>standard</use>
                            <args>
                                  <module>M4U_HelloWorld</module>
                                  <frontName>helloworld</frontName>
                            </args>
                    </helloworld>
            </routers>
    <layout>
        <updates>
            <helloworld>
                  <file>helloworld.xml</file>
            </helloworld>
        </updates>
        </layout>
    </frontend>

Define frontend template

3.1. Define page layout in app/design/frontend/default/default/layout/helloworld.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">                  <template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>

Create template file in   app/design/frontend/default/default/template/helloworld/helloworld.phtml

Body:
TRIED AND TESTED

screenshot here

you can display your helloworld template in your custom module, done some minor modifications to your code.

module declaration:

<?xml version="1.0"?>
 <config>
       <modules>
          <M4U_HelloWorld>
               <active>true</active>
               <codePool>local</codePool>
          </M4U_HelloWorld>
       </modules>
 </config>

creating the folder structure and add the files

A. app/code/local/M4U/HelloWorld/etc/config.xml

<config>
    <modules>
        <m4u_helloworld>
            <version>0.1.0</version>
        </m4u_helloworld>
    </modules>
    <frontend>
        <routers>
            <helloworld>
                <use>standard</use>
                <args>
                    <module>M4U_HelloWorld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
        <layout>
            <updates>
                <helloworld module="M4U_HelloWorld">
                    <file>M4U_HelloWorld.xml</file>
                </helloworld>
            </updates>
        </layout>
    </frontend>
    <global>
        <blocks>
            <helloworld>
                <class>M4U_HelloWorld_Block</class>
            </helloworld>
        </blocks>
    </global>
</config>

B. app/code/local/M4U/HelloWorld/block/HelloWorld.php

class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template {

}

C. app/code/local/M4U/HelloWorld/controllers/IndexController.php

class M4U_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action {

    public function indexAction() {
        echo 'hello world';
        $this->loadLayout();  //This function read all layout files and loads them in memory
        $this->renderLayout();
    }

}

D. app/design/frontend/ * theme base* / * mytheme * /layout/M4U_HelloWorld.xml

<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">
                <template>page/1column.phtml</template>
            </action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>

E. app/design/frontend/ * theme base* / * mytheme * /template/helloworld/helloworld.php

echo 'im a template block';


来源: stackexchange

问:
Create a calendar day table
I am trying to write a code where i can plug in a date and my table below will populate the expected date table with all the date for the particular month from CD1(Calendar Day 1) all the way to CD30 or CD31 or in February case CD28.  I know i should begin my code with something like

```<code>Declare @startdate as datetime
Set @startdate = '20170401'
</code>```

But after that I get confused with the DateAdd and DatePart code to create this query to produce the results

```date rule  | expected date |
----------------------------
| CD1      | 4/1/2017      |
| CD2      | 4/2/2017      |
| CD3      | 4/3/2017      |
| CD4      | 4/4/2017      |
| CD5      | 4/5/2017      |
| CD6      | 4/6/2017      |
```

Can anyone provide any assistance?

答:
Try this,</p>

```<code>Declare @startdate as datetime
Set @startdate = '20170401'

;with cte as
(
select @startdate dt,1 ruleid
union ALL
select dateadd(day,1,dt)
,ruleid+1
from cte
where
dt<dateadd(day,-1,dateadd(month, datediff(month,0,@startdate)+1,0))
)

select *,'CD'+cast(ruleid as varchar) CalenderRule

 from cte
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create a calendar day table

Body:
I am trying to write a code where i can plug in a date and my table below will populate the expected date table with all the date for the particular month from CD1(Calendar Day 1) all the way to CD30 or CD31 or in February case CD28.  I know i should begin my code with something like

Declare @startdate as datetime
Set @startdate = '20170401'

But after that I get confused with the DateAdd and DatePart code to create this query to produce the results

date rule  | expected date |
----------------------------
| CD1      | 4/1/2017      |
| CD2      | 4/2/2017      |
| CD3      | 4/3/2017      |
| CD4      | 4/4/2017      |
| CD5      | 4/5/2017      |
| CD6      | 4/6/2017      |

Can anyone provide any assistance?

Body:
Try this,

Declare @startdate as datetime
Set @startdate = '20170401'

;with cte as
(
select @startdate dt,1 ruleid
union ALL
select dateadd(day,1,dt)
,ruleid+1
from cte
where
dt<dateadd(day,-1,dateadd(month, datediff(month,0,@startdate)+1,0))
)

select *,'CD'+cast(ruleid as varchar) CalenderRule

 from cte


问:
ExternalLoginConfirmation returns null after facebook successful login
Implementing Facebook login in MVC 5 template, had added the app Id and secret code.

Initially login was failing as it was returning null

```<code>public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    // Crashes on this line
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
}
</code>```

After searching came across a solution which says to replace existing ExternalLoginCallback method with this

```<code>[AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
        if (result == null || result.Identity == null)
        {
            return RedirectToAction("Login");
        }

        var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
        if (idClaim == null)
        {
            return RedirectToAction("Login");
        }

        var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);
        var name = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", "");

        // Sign in the user with this external login provider if the user already has a login
        var user = await UserManager.FindAsync(login);
        if (user != null)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToLocal(returnUrl);
        }
        else
        {
            // If the user does not have an account, then prompt the user to create an account
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.LoginProvider = login.LoginProvider;
            return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = name });
        }
    }
</code>```

Now that issue is solved but when I try to Associate your Facebook account.
You've successfully authenticated with Facebook. Please enter a user name for this site below and click the Register button to finish logging in.

```<code>[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Manage");
        }

        if (ModelState.IsValid)
        {
            // Here comes the error System.NullReferenceException: Object reference not set to an instance of an object.

            var info = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return View("ExternalLoginFailure");
            }
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        ViewBag.ReturnUrl = returnUrl;
        return View(model);
    }
</code>```

On debugging the username come then too can't figure it out that why its throwing exception.

答:
I think when it gets to GetExternalLoginInfoSync that returns null.

I had the same problem and here is how I managed to fix it and get the email from Facebook.

Update following NuGet Pacakges

Microsoft.Owin to version 3.1.0-rc1

Microsoft.Owin.Security to version 3.1.0-rc1

Microsoft.Owin.Security.Cookies to version 3.1.0-rc1

Microsoft.Owin.Security.OAuth to version 3.1.0-rc1

Microsoft.Owin.Security.Facebook to version 3.1.0-rc1

Then add the following code to the Identity Startup class

```<code>var facebookOptions = new FacebookAuthenticationOptions()
        {
            AppId = "your app id",
            AppSecret = "your app secret",
            BackchannelHttpHandler = new FacebookBackChannelHandler(),
            UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            Scope = { "email" }
        };

        app.UseFacebookAuthentication(facebookOptions);
</code>```

This is the definition class for FacebookBackChannelHandler():

```<code>using System;
using System.Net.Http;

public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        System.Threading.CancellationToken cancellationToken)
    {
        // Replace the RequestUri so it's not malformed
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Implementing Facebook login in MVC 5 template, had added the app Id and secret code.

Initially login was failing as it was returning null

public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    // Crashes on this line
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
}

After searching came across a solution which says to replace existing ExternalLoginCallback method with this

[AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
        if (result == null || result.Identity == null)
        {
            return RedirectToAction("Login");
        }

        var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
        if (idClaim == null)
        {
            return RedirectToAction("Login");
        }

        var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);
        var name = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", "");

        // Sign in the user with this external login provider if the user already has a login
        var user = await UserManager.FindAsync(login);
        if (user != null)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToLocal(returnUrl);
        }
        else
        {
            // If the user does not have an account, then prompt the user to create an account
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.LoginProvider = login.LoginProvider;
            return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = name });
        }
    }

Now that issue is solved but when I try to Associate your Facebook account.
You've successfully authenticated with Facebook. Please enter a user name for this site below and click the Register button to finish logging in.

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Manage");
        }

        if (ModelState.IsValid)
        {
            // Here comes the error System.NullReferenceException: Object reference not set to an instance of an object.

            var info = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return View("ExternalLoginFailure");
            }
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        ViewBag.ReturnUrl = returnUrl;
        return View(model);
    }

On debugging the username come then too can't figure it out that why its throwing exception.

Body:
I think when it gets to GetExternalLoginInfoSync that returns null.

I had the same problem and here is how I managed to fix it and get the email from Facebook.

Update following NuGet Pacakges

Microsoft.Owin to version 3.1.0-rc1

Microsoft.Owin.Security to version 3.1.0-rc1

Microsoft.Owin.Security.Cookies to version 3.1.0-rc1

Microsoft.Owin.Security.OAuth to version 3.1.0-rc1

Microsoft.Owin.Security.Facebook to version 3.1.0-rc1

Then add the following code to the Identity Startup class

var facebookOptions = new FacebookAuthenticationOptions()
        {
            AppId = "your app id",
            AppSecret = "your app secret",
            BackchannelHttpHandler = new FacebookBackChannelHandler(),
            UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            Scope = { "email" }
        };

        app.UseFacebookAuthentication(facebookOptions);

This is the definition class for FacebookBackChannelHandler():

using System;
using System.Net.Http;

public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        System.Threading.CancellationToken cancellationToken)
    {
        // Replace the RequestUri so it's not malformed
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        return await base.SendAsync(request, cancellationToken);
    }
}


问:
Why this url pattern is not working?
```<code>from views import login
from django.conf.urls.defaults import *

urlpatterns = patterns('',
  ***  (r'([a-zA-Z0-9]+)/login/$', login, name='login'),

)
</code>```

showing me the syntax error in line ***.

http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it using Django { % url slug login % } tag. But it also not working.

答:
the way u are using the {% url slug login %} is not the correct syntax
you have to write the name which you wrote in your urls for that template,
 i.e {% url login %}
This is according to your url, try this it will work.........</p>

Title: Why this url pattern is not working?

Body:
from views import login
from django.conf.urls.defaults import *

urlpatterns = patterns('',
  ***  (r'([a-zA-Z0-9]+)/login/$', login, name='login'),

)

showing me the syntax error in line ***.

http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it using Django { % url slug login % } tag. But it also not working.

ContentLicense: CC BY-SA 2.5


问:
batch add leading zeroes filename
I've got a script that I'm using for all kinds of things, including renaming and repacking comics. Variants of this script are used by others as well.

I've been seeing a limitation in repacking comics, however; I've found that some comics don't have the leading zeroes at their pages, which makes the pages appear out of order. So, I've added a part that should add leading zeroes.

The file does the following:

loop over all subfolders of the current folder

rename comic archives to their proper extension (so I can see where it is)

loop over all archives, and extract them to a temporary folder

loop over all files in the temporary folder, and add leading zeroes

repack it as a 7zip

rename the file to a comic book extension

Somehow, it's not renaming the files properly, and the name of the archive appears as a subfolder in the archive. For example:
let's repack 'testfolder', which contains images from 1 to 100. It renames, extracts, packs, and renames again, without problem. However, the new archive contains the folder named 'testfolder' in the archive next to the images, which don't have the leading zeroes. I'm not sure what's going on, and I've been fighting with it for a while now, so I thought to put it online (it's a good script to share, anyway). Does anyone have an idea on what's going wrong here?

```<code>@ECHO ON
rem mode con: cols=80 lines=60
for /f "delims=" %%F in ('dir /ad/s/b') do (
    cd %%F

    IF EXIST *.cbr (
        RENAME *.cbr *.rar
    )

    IF EXIST *.cbz (
        RENAME *.cbz *.zip
    )

    IF EXIST *.cb7 (
        RENAME *.cb7 *.7z
    )

    FOR %%I IN (*.RAR, *.ZIP *.7Z) DO (
        ECHO Extracting %%I...
        "C:\Program Files\7-Zip\7z.exe" e "%%I" -oC:\TMPPACKDIR\* -y | FIND /V "ing  "

        echo %%~nI
        cd C:\TMPPACKDIR\%%~nI\

        FOR /f "delims=" %%P IN ('dir *.JPG, *.PNG, *.BMP') DO (
            SET %%N = %%P
            SET %%N = 00%%N
            SET %%N = %%N:~-2%
            echo %%P
            echo %%N
            pause
            rename 'C:\TMPPACKDIR\%%~nI\%%P' %%N
        )

        pause

        echo %%F

        cd %%F

        ECHO Repacking
        "C:\Program Files\7-Zip\7z.exe" a -t7z "%%~nI.7z" "C:\TMPPACKDIR\%%~nI*" -mx=9 | FIND /V "ing  "

        IF %ERRORLEVEL% EQU 0 RD /S /Q C:\TMPPACKDIR

        ECHO Renaming new file
        RENAME *.7z *.CB7

        ECHO Removing original file
        DEL "%%I"
        ECHO File %%I is done
    )
)

REM del /f/q "%~0" | exit
</code>```

答:
I've removed some unnecessary stuff and made a few changes, (the main error being that which aschipfl has already identified).

FOR /F "DELIMS=" %%F IN ('DIR/AD/S/B') DO (
    PUSHD "%%F"
    IF EXIST *.cbr REN *.cbr *.rar
    IF EXIST *.cbz REN *.cbz *.zip
    IF EXIST *.cb7 REN *.cb7 *.7z
    FOR %%I IN (*.RAR, *.ZIP *.7Z) DO (
        ECHO Extracting %%I...
        "%ProgramFiles%\7-Zip\7z.exe" e "%%I" -o"C:\TMPPACKDIR\*" -y
        PUSHD "C:\TMPPACKDIR\%%~nI"
        FOR %%P IN (*.JPG, *.PNG, *.BMP) DO (
            SET "_N=100%%~nP"
            SETLOCAL ENABLEDELAYEDEXPANSION
            SET "_N=!_N:~-2!"
            REN "%%P" "!_N!%%~xP"
            ENDLOCAL
        )
        POPD
        ECHO Repacking
        "%ProgramFiles%\7-Zip\7z.exe" a -t7z "%%~nI.7z" "C:\TMPPACKDIR\%%~nI*" -mx=9
        IF NOT ERRORLEVEL 1 RD/S/Q "C:\TMPPACKDIR\%%~nI"
        ECHO Renaming new file
        REN "%%~nI.7z" "%%~nI.CB7"
        ECHO Removing original file
        DEL "%%I"
        ECHO File %%I is done
    )
    POPD
)
```

Things to look into:
Can 7z.exe not just extract .cbr, .cbz & .cb7 directly without renaming them first. In the same way, when repacking once you've provided the file type, -t7z can the file not be given the name "%%~nI.CB7" directly instead of later renaming it.

Title: batch add leading zeroes filename

Body:
I've got a script that I'm using for all kinds of things, including renaming and repacking comics. Variants of this script are used by others as well.

I've been seeing a limitation in repacking comics, however; I've found that some comics don't have the leading zeroes at their pages, which makes the pages appear out of order. So, I've added a part that should add leading zeroes.

The file does the following:

loop over all subfolders of the current folder

rename comic archives to their proper extension (so I can see where it is)

loop over all archives, and extract them to a temporary folder

loop over all files in the temporary folder, and add leading zeroes

repack it as a 7zip

rename the file to a comic book extension

Somehow, it's not renaming the files properly, and the name of the archive appears as a subfolder in the archive. For example:
let's repack 'testfolder', which contains images from 1 to 100. It renames, extracts, packs, and renames again, without problem. However, the new archive contains the folder named 'testfolder' in the archive next to the images, which don't have the leading zeroes. I'm not sure what's going on, and I've been fighting with it for a while now, so I thought to put it online (it's a good script to share, anyway). Does anyone have an idea on what's going wrong here?

@ECHO ON
rem mode con: cols=80 lines=60
for /f "delims=" %%F in ('dir /ad/s/b') do (
    cd %%F

    IF EXIST *.cbr (
        RENAME *.cbr *.rar
    )

    IF EXIST *.cbz (
        RENAME *.cbz *.zip
    )

    IF EXIST *.cb7 (
        RENAME *.cb7 *.7z
    )

    FOR %%I IN (*.RAR, *.ZIP *.7Z) DO (
        ECHO Extracting %%I...
        "C:\Program Files\7-Zip\7z.exe" e "%%I" -oC:\TMPPACKDIR\* -y | FIND /V "ing  "

        echo %%~nI
        cd C:\TMPPACKDIR\%%~nI\

        FOR /f "delims=" %%P IN ('dir *.JPG, *.PNG, *.BMP') DO (
            SET %%N = %%P
            SET %%N = 00%%N
            SET %%N = %%N:~-2%
            echo %%P
            echo %%N
            pause
            rename 'C:\TMPPACKDIR\%%~nI\%%P' %%N
        )

        pause

        echo %%F

        cd %%F

        ECHO Repacking
        "C:\Program Files\7-Zip\7z.exe" a -t7z "%%~nI.7z" "C:\TMPPACKDIR\%%~nI*" -mx=9 | FIND /V "ing  "

        IF %ERRORLEVEL% EQU 0 RD /S /Q C:\TMPPACKDIR

        ECHO Renaming new file
        RENAME *.7z *.CB7

        ECHO Removing original file
        DEL "%%I"
        ECHO File %%I is done
    )
)

REM del /f/q "%~0" | exit

Body:
I've removed some unnecessary stuff and made a few changes, (the main error being that which aschipfl has already identified).

FOR /F "DELIMS=" %%F IN ('DIR/AD/S/B') DO (
    PUSHD "%%F"
    IF EXIST *.cbr REN *.cbr *.rar
    IF EXIST *.cbz REN *.cbz *.zip
    IF EXIST *.cb7 REN *.cb7 *.7z
    FOR %%I IN (*.RAR, *.ZIP *.7Z) DO (
        ECHO Extracting %%I...
        "%ProgramFiles%\7-Zip\7z.exe" e "%%I" -o"C:\TMPPACKDIR\*" -y
        PUSHD "C:\TMPPACKDIR\%%~nI"
        FOR %%P IN (*.JPG, *.PNG, *.BMP) DO (
            SET "_N=100%%~nP"
            SETLOCAL ENABLEDELAYEDEXPANSION
            SET "_N=!_N:~-2!"
            REN "%%P" "!_N!%%~xP"
            ENDLOCAL
        )
        POPD
        ECHO Repacking
        "%ProgramFiles%\7-Zip\7z.exe" a -t7z "%%~nI.7z" "C:\TMPPACKDIR\%%~nI*" -mx=9
        IF NOT ERRORLEVEL 1 RD/S/Q "C:\TMPPACKDIR\%%~nI"
        ECHO Renaming new file
        REN "%%~nI.7z" "%%~nI.CB7"
        ECHO Removing original file
        DEL "%%I"
        ECHO File %%I is done
    )
    POPD
)

Things to look into:
Can 7z.exe not just extract .cbr, .cbz & .cb7 directly without renaming them first. In the same way, when repacking once you've provided the file type, -t7z can the file not be given the name "%%~nI.CB7" directly instead of later renaming it.


问:
MySQL GROUP_CONCAT Rearranges values
Suppose I have the following table:

```<code>ID|Col1    |Col2
1 |Test1   |Test12
2 |Test2   |Test22
2 |Test3   |Test32
</code>```

When I use a query like:

```<code>SELECT GROUP_CONCAT(Col1) as First, GROUP_CONCAT(Col2) as Second WHERE ID=2 GROUP BY ID
</code>```

It sometimes returns the GROUP_CONCAT's rearranged. For example:

```<code>ID|First      |Second
2 |Test2,Test3|Test32,Test22
</code>```

While I would expect it to return:

```<code>ID|First      |Second
2 |Test2,Test3|Test22,Test32
</code>```

As you can see, it switched the concatenated values in the column named 'Second'. How can I prevent this from happening?

答:
If you want the values in a particular order, then use order by:

```<code>SELECT GROUP_CONCAT(Col1 ORDER BY Col1) as First,
       GROUP_CONCAT(Col2 ORDER BY col2) as Second
FROM t
WHERE ID = 2
GROUP BY ID;
</code>```

In general, SQL deals with unordered sets.  If you want things in a particular order, then you need to explicitly specify the ordering.

Title: MySQL GROUP_CONCAT Rearranges values

Body:
Suppose I have the following table:

ID|Col1    |Col2
1 |Test1   |Test12
2 |Test2   |Test22
2 |Test3   |Test32

When I use a query like:

SELECT GROUP_CONCAT(Col1) as First, GROUP_CONCAT(Col2) as Second WHERE ID=2 GROUP BY ID

It sometimes returns the GROUP_CONCAT's rearranged. For example:

ID|First      |Second
2 |Test2,Test3|Test32,Test22

While I would expect it to return:

ID|First      |Second
2 |Test2,Test3|Test22,Test32

As you can see, it switched the concatenated values in the column named 'Second'. How can I prevent this from happening?

Body:
If you want the values in a particular order, then use order by:

SELECT GROUP_CONCAT(Col1 ORDER BY Col1) as First,
       GROUP_CONCAT(Col2 ORDER BY col2) as Second
FROM t
WHERE ID = 2
GROUP BY ID;

In general, SQL deals with unordered sets.  If you want things in a particular order, then you need to explicitly specify the ordering.


问:
Jquery click event doesn't fire with Handlebars template
I have a problem with Jquery .on() function and Handlebars template. I wroted Handlebars template and add him dynamically in document:

```<code>$('.services-wrapper').append(serviceTemplate({index : ++maxIndex}));
</code>```

This template has a button:

```<code><p>
    <?= Html::buttonInput('Delete', [
    'class' => 'btn btn-danger delete-service',
    'id' => 'js-delete-service',
        'data' => [
        'index' => $index,
    ],
    ]) ?>
</p>
</code>```

So I wroted click handler on this button:

```<code>$('.service').on('click', '.delete-service', function (e) {
    alert('Clicked');
    //$(this).parent().parent().remove();
});
</code>```

When I add this template to document, click event doesn't fire. What is the problem?

答:
You might need a closest parent wrapper as:  </p>

```<code>$('.service-wrapper').on(...);
</code>```

Body:
I have a problem with Jquery .on() function and Handlebars template. I wroted Handlebars template and add him dynamically in document:

$('.services-wrapper').append(serviceTemplate({index : ++maxIndex}));

This template has a button:

    <?= Html::buttonInput('Delete', [
    'class' => 'btn btn-danger delete-service',
    'id' => 'js-delete-service',
        'data' => [
        'index' => $index,
    ],
    ]) ?>

So I wroted click handler on this button:

$('.service').on('click', '.delete-service', function (e) {
    alert('Clicked');
    //$(this).parent().parent().remove();
});

When I add this template to document, click event doesn't fire. What is the problem?

Body:
You might need a closest parent wrapper as:

$('.service-wrapper').on(...);


问:
How to show the selected item of a WPF binding
C#:

```<code>public void SetCompetition(Window wT1)
{
    //Add all the Copetition
    wT1._competition = new List<Competition>();
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test1", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test2", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test3", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test4", IsSelected = false });

        wT1.cboSetupCompetition.ItemsSource = wT1._competition;
        wT1.cboSetupCompetition.Items.Refresh();
    }
</code>```

Data Template:

```<code><UserControl.Resources>
    <System:Double x:Key="Double1">11</System:Double>
    <DataTemplate x:Key="cmbCompetition">
        <WrapPanel  Height="30" >

            <Label Content="{Binding Name}" ></Label>

        </WrapPanel>
    </DataTemplate>

</UserControl.Resources>

<ComboBox x:Name="cboSetupCompetition" ItemTemplate="{DynamicResource     cmbCompetition}" HorizontalAlignment="Left" Margin="29,28,0,0" VerticalAlignment="Top" Width="173" RenderTransformOrigin="0.5,0.591" FontSize="12" Height="22" IsEditable="True"  Background="#FFD8D8D8" SelectionChanged="UpdateCompetitionSelection"/>
</code>```

I have a Combobox with a label and an image and when I select an item I would like to see the same format in the Combobox when it is closed. I am not getting any errors I am seeing the name of the application.Competition(this is my object Model) instead of the values of the image and label.

The SetCopetition is invoked when the application loads.

答:
A TextBox is not able to display a Label and an Image or whatever elements that are in your DataTemplate in it.

Set the IsEditable property of the ComboBox to false and it should work as expected, i.e. your DataTemplate will be applied to the selected item when the ComboBox is closed:

```<code><ComboBox x:Name="cboSetupCompetition" IsEditable="False"  ItemTemplate="{DynamicResource cmbCompetition}" HorizontalAlignment="Left" Margin="29,28,0,0" VerticalAlignment="Top" Width="173" RenderTransformOrigin="0.5,0.591" FontSize="12" Height="22" Background="#FFD8D8D8" SelectionChanged="UpdateCompetitionSelection"/>
</code>```

Your issue has nothing to do with MVVM...

Body:
C#:

public void SetCompetition(Window wT1)
{
    //Add all the Copetition
    wT1._competition = new List<Competition>();
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test1", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test2", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test3", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test4", IsSelected = false });

        wT1.cboSetupCompetition.ItemsSource = wT1._competition;
        wT1.cboSetupCompetition.Items.Refresh();
    }

Data Template:

<UserControl.Resources>
    <System:Double x:Key="Double1">11</System:Double>
    <DataTemplate x:Key="cmbCompetition">
        <WrapPanel  Height="30" >

        </WrapPanel>
    </DataTemplate>

</UserControl.Resources>

<ComboBox x:Name="cboSetupCompetition" ItemTemplate="{DynamicResource     cmbCompetition}" HorizontalAlignment="Left" Margin="29,28,0,0" VerticalAlignment="Top" Width="173" RenderTransformOrigin="0.5,0.591" FontSize="12" Height="22" IsEditable="True"  Background="#FFD8D8D8" SelectionChanged="UpdateCompetitionSelection"/>

I have a Combobox with a label and an image and when I select an item I would like to see the same format in the Combobox when it is closed. I am not getting any errors I am seeing the name of the application.Competition(this is my object Model) instead of the values of the image and label.

The SetCopetition is invoked when the application loads.

Body:
A TextBox is not able to display a Label and an Image or whatever elements that are in your DataTemplate in it.

Set the IsEditable property of the ComboBox to false and it should work as expected, i.e. your DataTemplate will be applied to the selected item when the ComboBox is closed:

<ComboBox x:Name="cboSetupCompetition" IsEditable="False"  ItemTemplate="{DynamicResource cmbCompetition}" HorizontalAlignment="Left" Margin="29,28,0,0" VerticalAlignment="Top" Width="173" RenderTransformOrigin="0.5,0.591" FontSize="12" Height="22" Background="#FFD8D8D8" SelectionChanged="UpdateCompetitionSelection"/>

Your issue has nothing to do with MVVM...


问:
Insert a value to a cell in excel using formula in another cell
I need to insert a value to a cell in excel using formula in another cell.

Say

```<code>A1 = "Test"
B1 = formula to insert A1 to C1
C1 = A1
</code>```

Can I write a formula in B1 to insert value in C1?
I don't need any formulas in C1.
If Yes, What should be the formula?

答:
Without using VBA or formulas in column C you can't achieve this.

A simple solution using formulas:

In cell C1, paste the following formula and drag it down:

```<code>=IF(B1=1;A1;"")
</code>```

So if the content of cell B1 is equal to 1, your cell at column C will display the respective value of the same row at column A.

Body:
I need to insert a value to a cell in excel using formula in another cell.

Say

A1 = "Test"
B1 = formula to insert A1 to C1
C1 = A1

Can I write a formula in B1 to insert value in C1?
I don't need any formulas in C1.
If Yes, What should be the formula?

Body:
Without using VBA or formulas in column C you can't achieve this.

A simple solution using formulas:

In cell C1, paste the following formula and drag it down:

=IF(B1=1;A1;"")

So if the content of cell B1 is equal to 1, your cell at column C will display the respective value of the same row at column A.


问:
Equivalent of 'in' for comparing two Numpy arrays
In pure, unvectorised, Python I can use,

```<code>>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False
</code>```

I would like to do something similar for arrays in Numpy i.e.

```<code>>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, False, False, True, False, True, False, False, False])</code>```

... although this does not work.

Is there a function or method that achieves this? If not what is the easiest way to do this?

答:
You're comparing two very different things. With the pure Python lists, you have an int and a list. With numpy, you have two numpy arrays. If you change a to an int, then it works as expected in numpy.

```<code>>>> a = 9
>>> b = np.array([5, 7, 12])
>>> a in b
False
</code>```

Also note that what you show with two lists is quite an intuitive result. The returned array is showing you, for each value in array a, is it in b? 5 and 7 are, the others are not. Hence the given result.

Body:
In pure, unvectorised, Python I can use,

>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False

I would like to do something similar for arrays in Numpy i.e.

>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, False, False, True, False, True, False, False, False])

... although this does not work.

Is there a function or method that achieves this? If not what is the easiest way to do this?

Body:
You're comparing two very different things. With the pure Python lists, you have an int and a list. With numpy, you have two numpy arrays. If you change a to an int, then it works as expected in numpy.

>>> a = 9
>>> b = np.array([5, 7, 12])
>>> a in b
False

Also note that what you show with two lists is quite an intuitive result. The returned array is showing you, for each value in array a, is it in b? 5 and 7 are, the others are not. Hence the given result.


问:
Javascript function not showing up
I'm making a project for school and my Javascript suddenly stopped showing up. can anyone tell me what's going on?

I'm talking about the scroll back to top button that should appear at the bottom right corner.

jsfiddle: https://jsfiddle.net/u67cea52/

```<code>$(document).ready(function() {
function showItem(evt, itemName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active",     "");
}
document.getElementById(itemName).style.display = "block";
evt.currentTarget.className += " active";
}
$(document).ready(function(){

//kijkt of je verder bent dan de cover pagina, zoja dan verschijnt de knop
$(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }
});

//het event wat ervoor zorgt dat als je op de knop klikt dat je weer     naar boven gaat
    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
});

});
});
</code>```

答:
May be this will help:

HTML:

```<code><div id="content">Hello World</div>
<a href="#" id="back-to-top" title="Back to top">↑</a>
</code>```

CSS:

```<code>#back-to-top {
    position: fixed;
    bottom: 40px;
    right: 40px;
    z-index: 9999;
    width: 32px;
    height: 32px;
    text-align: center;
    line-height: 30px;
    background: #f5f5f5;
    color: #444;
    cursor: pointer;
    border: 0;
    border-radius: 2px;
    text-decoration: none;
    transition: opacity 0.2s ease-out;
    opacity: 0;
}
#back-to-top:hover {
    background: #e9ebec;
}
#back-to-top.show {
    opacity: 1;
}
#content {
    height: 2000px;
}
</code>```

JS:

```<code>if ($('#back-to-top').length) {
    var scrollTrigger = 100, // px
        backToTop = function () {
            var scrollTop = $(window).scrollTop();
            if (scrollTop > scrollTrigger) {
                $('#back-to-top').addClass('show');
            } else {
                $('#back-to-top').removeClass('show');
            }
        };
    backToTop();
    $(window).on('scroll', function () {
        backToTop();
    });
    $('#back-to-top').on('click', function (e) {
        e.preventDefault();
        $('html,body').animate({
            scrollTop: 0
        }, 700);
    });
}
</code>```

Title: Javascript function not showing up

Body:
I'm making a project for school and my Javascript suddenly stopped showing up. can anyone tell me what's going on?

I'm talking about the scroll back to top button that should appear at the bottom right corner.

jsfiddle: https://jsfiddle.net/u67cea52/

$(document).ready(function() {
function showItem(evt, itemName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active",     "");
}
document.getElementById(itemName).style.display = "block";
evt.currentTarget.className += " active";
}
$(document).ready(function(){

//kijkt of je verder bent dan de cover pagina, zoja dan verschijnt de knop
$(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }
});

//het event wat ervoor zorgt dat als je op de knop klikt dat je weer     naar boven gaat
    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
});

});
});

Body:
May be this will help:

HTML:

<div id="content">Hello World</div>
<a href="#" id="back-to-top" title="Back to top">&uarr;</a>

CSS:

#back-to-top {
    position: fixed;
    bottom: 40px;
    right: 40px;
    z-index: 9999;
    width: 32px;
    height: 32px;
    text-align: center;
    line-height: 30px;
    background: #f5f5f5;
    color: #444;
    cursor: pointer;
    border: 0;
    border-radius: 2px;
    text-decoration: none;
    transition: opacity 0.2s ease-out;
    opacity: 0;
}
#back-to-top:hover {
    background: #e9ebec;
}
#back-to-top.show {
    opacity: 1;
}
#content {
    height: 2000px;
}

JS:

if ($('#back-to-top').length) {
    var scrollTrigger = 100, // px
        backToTop = function () {
            var scrollTop = $(window).scrollTop();
            if (scrollTop > scrollTrigger) {
                $('#back-to-top').addClass('show');
            } else {
                $('#back-to-top').removeClass('show');
            }
        };
    backToTop();
    $(window).on('scroll', function () {
        backToTop();
    });
    $('#back-to-top').on('click', function (e) {
        e.preventDefault();
        $('html,body').animate({
            scrollTop: 0
        }, 700);
    });
}


问:
How long does RDD remain in memory?
Considering memory being limited, I had a feeling that spark automatically removes RDD from each node. I'd like to know is this time configurable? How does spark decide when to evict an RDD from memory

Note: I'm not talking about rdd.cache()

答:
In general, that's how Yuval Itzchakov wrote "just like any other object", but...(there's always "but", isn't it?)

In Spark, it's not that obvious since we have shuffle blocks (among the other blocks managed by Spark). They are managed by BlockManagers running on executors. They somehow will have to be notified when an object on the driver gets evicted from memory, right?

That's where ContextCleaner comes to stage. It's Spark Application's Garbage Collector that is responsible for application-wide cleanup of shuffles, RDDs, broadcasts, accumulators and checkpointed RDDs that is aimed at reducing the memory requirements of long-running data-heavy Spark applications.

ContextCleaner runs on the driver. It is created and immediately started when SparkContext starts (and spark.cleaner.referenceTracking Spark property is enabled, which it is by default). It is stopped when SparkContext is stopped.

You can see it working by doing the dump of all the threads in a Spark application using jconsole or jstack. ContextCleaner uses a daemon Spark Context Cleaner thread that cleans RDD, shuffle, and broadcast states.

You can also see its work by enabling INFO or DEBUG logging levels for org.apache.spark.ContextCleaner logger. Just add the following line to conf/log4j.properties:

```<code>log4j.logger.org.apache.spark.ContextCleaner=DEBUG
</code>```

Title: How long does RDD remain in memory?

Body:
In general, that's how Yuval Itzchakov wrote "just like any other object", but...(there's always "but", isn't it?)

In Spark, it's not that obvious since we have shuffle blocks (among the other blocks managed by Spark). They are managed by BlockManagers running on executors. They somehow will have to be notified when an object on the driver gets evicted from memory, right?

That's where ContextCleaner comes to stage. It's Spark Application's Garbage Collector that is responsible for application-wide cleanup of shuffles, RDDs, broadcasts, accumulators and checkpointed RDDs that is aimed at reducing the memory requirements of long-running data-heavy Spark applications.

ContextCleaner runs on the driver. It is created and immediately started when SparkContext starts (and spark.cleaner.referenceTracking Spark property is enabled, which it is by default). It is stopped when SparkContext is stopped.

You can see it working by doing the dump of all the threads in a Spark application using jconsole or jstack. ContextCleaner uses a daemon Spark Context Cleaner thread that cleans RDD, shuffle, and broadcast states.

You can also see its work by enabling INFO or DEBUG logging levels for org.apache.spark.ContextCleaner logger. Just add the following line to conf/log4j.properties:

log4j.logger.org.apache.spark.ContextCleaner=DEBUG


问:
Maven assembly : add different version of the same artifact
I create my application archive with the maven assembly plugin.
All the dependency present in my pom are included without any problem.

Now I need to include two or more version of the same artifact.

If in my pom I put

```<code><dependencies>
        [...]
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.1.0</version>
        </dependency>
</dependencies>
</code>```

Of source the dependenvcy resolver remove the old version and only the 1.1.0 is packaged in the archive

I try to include the jar by using assembly xml descriptor file. And I didn't find any solution.

A possible solution will be to manually put all the needed model.jar inside a folder and tell the assembly to copy it in the archive. But I'm looking for a more configurable solution.

Any idea ?

答: Another ugly solution might be to use WAR file overlays, exploiting the fact that this mechanism pays no attention to the versions of component JAR files when applying the overlays.</p>

Body:
I create my application archive with the maven assembly plugin.
All the dependency present in my pom are included without any problem.

Now I need to include two or more version of the same artifact.

If in my pom I put

<dependencies>
        [...]
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.1.0</version>
        </dependency>
</dependencies>

Of source the dependenvcy resolver remove the old version and only the 1.1.0 is packaged in the archive

I try to include the jar by using assembly xml descriptor file. And I didn't find any solution.

A possible solution will be to manually put all the needed model.jar inside a folder and tell the assembly to copy it in the archive. But I'm looking for a more configurable solution.

Any idea ?


问:
How do i get R data.tree print to show a value for each level?
I have a data frame, struct, showing a hierarchy of things:

```<code># A tibble: 4 × 3
   lev1  lev2  lev3
  <chr> <chr> <chr>
1     A    AA   AAA
2     B    AA   AAA
3     C    BB   BBB
4     D    BB   BBB
</code>```

In another data frame, things, a descriptor, $Code, for each thing:

```<code># A tibble: 8 × 2
  Thing    Code
  <chr>   <chr>
1     A   11-11
2     B   22-22
3     C   33-33
4     D   44-44
5    AA 111-111
6    BB 222-222
7   AAA    <NA>
8   BBB    <NA>
</code>```

I convert struct to a data.tree node:

```<code>struct$pathString <- paste("things",
                       struct$lev3,
                       struct$lev2,
                       struct$lev1,
                       sep = "/")

pfo <- as.Node(struct)
</code>```

The print(pfo) command gives the output:

```<code>1 things
2  ¦--AAA
3  ¦   °--AA
4  ¦       ¦--A
5  ¦       °--B
6  °--BBB
7      °--BB
8          ¦--C
9          °--D
</code>```

What i want to see for each level is the appropriate value from things$Code after each Thing in the printed tree, like this:

```<code>1 things             Code
2  ¦--AAA
3  ¦   °--AA      111-111
4  ¦       ¦--A     11-11
5  ¦       °--B     22-22
6  °--BBB
7      °--BB      222-222
8          ¦--C     33-33
9          °--D     44-44
</code>```

How can i assign these values and print them?

答:
Here's a solution that sorts both Things and the traversal on the tree alphabetically to match the codes:

```<code>#get the nodes corresponding to the struct elements as a traversal
trav <- Traverse(pfo, filterFun = isNotRoot)
#order alphabetically
trav <- trav[order(Get(trav, "name"))]

#also order things alphabetically
codes <- things[order(things$Thing), 2]

#assign codes to nodes
Set(trav, Code = codes$Code)

#print codes
print(pfo, "Code")
</code>```

This will then print as desired:

```<code>      levelName    Code
1 things
2  ¦--AAA
3  ¦   °--AA    111-111
4  ¦       ¦--A   11-11
5  ¦       °--B   22-22
6  °--BBB
7      °--BB    222-222
8          ¦--C   33-33
9          °--D   44-44
</code>```

Body:
I have a data frame, struct, showing a hierarchy of things:

# A tibble: 4 × 3
   lev1  lev2  lev3
  <chr> <chr> <chr>
1     A    AA   AAA
2     B    AA   AAA
3     C    BB   BBB
4     D    BB   BBB

In another data frame, things, a descriptor, $Code, for each thing:

# A tibble: 8 × 2
  Thing    Code
  <chr>   <chr>
1     A   11-11
2     B   22-22
3     C   33-33
4     D   44-44
5    AA 111-111
6    BB 222-222
7   AAA    <NA>
8   BBB    <NA>

I convert struct to a data.tree node:

struct$pathString <- paste("things",
                       struct$lev3,
                       struct$lev2,
                       struct$lev1,
                       sep = "/")

pfo <- as.Node(struct)

The print(pfo) command gives the output:

1 things
2  ¦--AAA
3  ¦   °--AA
4  ¦       ¦--A
5  ¦       °--B
6  °--BBB
7      °--BB
8          ¦--C
9          °--D

What i want to see for each level is the appropriate value from things$Code after each Thing in the printed tree, like this:

1 things             Code
2  ¦--AAA
3  ¦   °--AA      111-111
4  ¦       ¦--A     11-11
5  ¦       °--B     22-22
6  °--BBB
7      °--BB      222-222
8          ¦--C     33-33
9          °--D     44-44

How can i assign these values and print them?

Body:
Here's a solution that sorts both Things and the traversal on the tree alphabetically to match the codes:

#get the nodes corresponding to the struct elements as a traversal
trav <- Traverse(pfo, filterFun = isNotRoot)
#order alphabetically
trav <- trav[order(Get(trav, "name"))]

#also order things alphabetically
codes <- things[order(things$Thing), 2]

#assign codes to nodes
Set(trav, Code = codes$Code)

#print codes
print(pfo, "Code")

This will then print as desired:

      levelName    Code
1 things
2  ¦--AAA
3  ¦   °--AA    111-111
4  ¦       ¦--A   11-11
5  ¦       °--B   22-22
6  °--BBB
7      °--BB    222-222
8          ¦--C   33-33
9          °--D   44-44


问:
Type casting using string for type
I have table settings with columns:
value - varchar type contains setting value and type - enum type contains variable types "int", "string", "float". How can I use string from type column to cast value to this type?

I'm trying to do it in my model but it doesn't work:

```<code>public function getValueAttribute($value){
    return ($this->type)$value;
}
</code>```

答:
You cannot use a dynamic typecasting like that, instead you'll have to use a function for that. settype() takes two arguments, the original value, and the new type you want to typecast it to.

```<code>public function getValueAttribute($value){
    settype($value, $this->type);
    return $value;
}
</code>```

http://php.net/manual/en/function.settype.php

Title: Type casting using string for type

Body:
I have table settings with columns:
value - varchar type contains setting value and type - enum type contains variable types "int", "string", "float". How can I use string from type column to cast value to this type?

I'm trying to do it in my model but it doesn't work:

public function getValueAttribute($value){
    return ($this->type)$value;
}

Body:
You cannot use a dynamic typecasting like that, instead you'll have to use a function for that. settype() takes two arguments, the original value, and the new type you want to typecast it to.

public function getValueAttribute($value){
    settype($value, $this->type);
    return $value;
}

http://php.net/manual/en/function.settype.php


问:
C++ Class wrapper around fundamental types
Many libraries I have seen/used have typedefs to provide portable, fixed size variables, eg int8, uint8, int16, uint16, etc which will be the correct size regardless of platform (and c++11 does it itself with the header stdint.h)

After recently using binary file i/o in a small library I'm writing I can see the benefit of using typedefs in this way to ensure the code is portable.

However, if I'm going to the trouble of typing "namespace::uint32" rather than using built in fundamental types, I may as well make the replacement as useful as possible. Therefore I am considering using classes instead of simple typedefs.

These wrapper classes would implement all normal operators so could be used interchangeably with the fundamental type.

Eg:

```<code>int x = 0;
//do stuff
</code>```

could become

```<code>class intWrapper {
//whatever
};

intWrapper = 0;
//do stuff
</code>```

without having to modify any code in "//do stuff"

The reason I'm considering this approach as opposed to just typedefs is the fact I already have functions that operate on fundamental types, eg

```<code>std::string numberToString(double toConvert);

std::string numberToHexString(double toConvert);

int intToXSignificantPlaces(const int& number,
                               unsigned char numberOfSignificantPlaces);

bool numbersAreApproximatelyEqual(float tollerance);
//etc....
</code>```

Syntactically it would be nicer (and more oop) to do the following:

```<code>intWrapper.toString();
intWrapper.toHexString();
//etc
</code>```

Also it would allow me to implement bigint classes (int128, etc) and have those and the smaller ones (based on fundamental types) use identical interfaces.

Finally each wrapper could have a static instance of itself called max and min, so the nice syntax of int32::max and int32::min would be possible.

However, I have a few concerns that I would like to address before doing this (since it is mostly syntactical sugar and these types would be used so commonly any extra overhead could have a significant performance impact).

1) Is there  any additional function calling overhead when using someClass.operator+(), someClass.operator-() etc over just int a + int b? If so, would inlining operator+() eliminate ALL this overhead?

2) All external functions require the primitive type, eg glVertex3f(float, float, float) could  not simply be passed 3 floatWrapper objects, is there a way to automatically make the compiler cast the floatWrapper to a float? If so, are there performance impacts?

3) Is there any additional memory overhead? I understand(?) that classes with inheritance have some sort of virtual table pointer and so use slightly more memory (or is that just for virtual functions?), but assuming these wrapper classes are not inherited from/are not child classes there isn't any additional memory use using classes instead of fundamental types, is there?

4) Are there any other problems / performance impacts this could cause?

答:
I think the answers are not completely correct - at least for gcc 4 I have observed a significant overhead due to the constructor and operator calls.

The following takes about twice as long as with long:

```<code>typedef intWrapperImpl<long> TestWrapper;
//typedef long TestWrapper;

int main (int argc, char** argv) {
    TestWrapper sum(0);
    TestWrapper test(4);

    for (long i = 0; i < 1000000000L; ++i) {
        sum += test;
    }

    cout << sum << "\n";

    return 0;
}
</code>```

Using different versions of gcc 4 with and with out optimization led to no differences in the performance.

In this case, adding

```<code>intWrapperImpl& operator+=(const intWrapperImpl & v) {value+=v.value; return *this;}
</code>```

gives only a slight improvement.

Using such a wrapper as if they were base-types in performance critical code seems to be a bad idea. Using them locally and thereby invoking the constructor all the time seems even worse.

This really came as a surprise to me, since it should easily be possible to inline everything and optimize it as if it would be a base-type variable.

Any further hints would be greatly appreciated!

Body:
Many libraries I have seen/used have typedefs to provide portable, fixed size variables, eg int8, uint8, int16, uint16, etc which will be the correct size regardless of platform (and c++11 does it itself with the header stdint.h)

After recently using binary file i/o in a small library I'm writing I can see the benefit of using typedefs in this way to ensure the code is portable.

However, if I'm going to the trouble of typing "namespace::uint32" rather than using built in fundamental types, I may as well make the replacement as useful as possible. Therefore I am considering using classes instead of simple typedefs.

These wrapper classes would implement all normal operators so could be used interchangeably with the fundamental type.

Eg:

int x = 0;
//do stuff

could become

class intWrapper {
//whatever
};

intWrapper = 0;
//do stuff

without having to modify any code in "//do stuff"

The reason I'm considering this approach as opposed to just typedefs is the fact I already have functions that operate on fundamental types, eg

std::string numberToString(double toConvert);

std::string numberToHexString(double toConvert);

int intToXSignificantPlaces(const int& number,
                               unsigned char numberOfSignificantPlaces);

bool numbersAreApproximatelyEqual(float tollerance);
//etc....

Syntactically it would be nicer (and more oop) to do the following:

intWrapper.toString();
intWrapper.toHexString();
//etc

Also it would allow me to implement bigint classes (int128, etc) and have those and the smaller ones (based on fundamental types) use identical interfaces.

Finally each wrapper could have a static instance of itself called max and min, so the nice syntax of int32::max and int32::min would be possible.

However, I have a few concerns that I would like to address before doing this (since it is mostly syntactical sugar and these types would be used so commonly any extra overhead could have a significant performance impact).

1) Is there  any additional function calling overhead when using someClass.operator+(), someClass.operator-() etc over just int a + int b? If so, would inlining operator+() eliminate ALL this overhead?

2) All external functions require the primitive type, eg glVertex3f(float, float, float) could  not simply be passed 3 floatWrapper objects, is there a way to automatically make the compiler cast the floatWrapper to a float? If so, are there performance impacts?

3) Is there any additional memory overhead? I understand(?) that classes with inheritance have some sort of virtual table pointer and so use slightly more memory (or is that just for virtual functions?), but assuming these wrapper classes are not inherited from/are not child classes there isn't any additional memory use using classes instead of fundamental types, is there?

4) Are there any other problems / performance impacts this could cause?

Body:
I think the answers are not completely correct - at least for gcc 4 I have observed a significant overhead due to the constructor and operator calls.

The following takes about twice as long as with long:

typedef intWrapperImpl<long> TestWrapper;
//typedef long TestWrapper;

int main (int argc, char** argv) {
    TestWrapper sum(0);
    TestWrapper test(4);

    for (long i = 0; i < 1000000000L; ++i) {
        sum += test;
    }

    cout << sum << "\n";

    return 0;
}

Using different versions of gcc 4 with and with out optimization led to no differences in the performance.

In this case, adding

intWrapperImpl& operator+=(const intWrapperImpl & v) {value+=v.value; return *this;}

gives only a slight improvement.

Using such a wrapper as if they were base-types in performance critical code seems to be a bad idea. Using them locally and thereby invoking the constructor all the time seems even worse.

This really came as a surprise to me, since it should easily be possible to inline everything and optimize it as if it would be a base-type variable.

Any further hints would be greatly appreciated!


问:
amqplib - how to safely check if a queue exists
I'm using the amqplib library for nodejs to work with RabbitMQ. I'm trying to check whether a queue exists by using the function checkQueue:

```<code>mychannel.checkQueue('xxx', function (err, ok) {
    console.log(err);
    console.log(ok)
});
</code>```

But it not only throws an error, but also closes the channel. How can I safely check if the queue exists?

答:
You can't without risking to destroy the channel. The workaround is to create a temporary channel which you can use to do the check.

A comment from amqp.node dev:
(https://github.com/squaremo/amqp.node/issues/280)

The behaviour of checkQueue is dictated by the protocol, but it can be
  worked around. One tactic is to create a "sacrificial" extra channel with
  which to test whether the queue exists. Once you have the answer, you can
  throw the extra channel away, or keep it around for more tests.

Body:
I'm using the amqplib library for nodejs to work with RabbitMQ. I'm trying to check whether a queue exists by using the function checkQueue:

mychannel.checkQueue('xxx', function (err, ok) {
    console.log(err);
    console.log(ok)
});

But it not only throws an error, but also closes the channel. How can I safely check if the queue exists?


问:
Getting error while generating test cases for espresso android
I am following these two links 1 and 2 for espresso test report but getting error while running ./gradlew createDebugCoverageReport. The error will be shown in image given below. Please help me, I am not able to generated report for espresso and ui automation test cases. Now trying to use jacoco but not able to find any solution.

Build.Gradle

```<code>apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.example.project"
        minSdkVersion 18
        targetSdkVersion 24
        versionCode 27
        versionName "1.5"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            testCoverageEnabled true
        }
        debug{
            testCoverageEnabled true
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.github.barteksc:android-pdf-viewer:2.0.3'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.android.support:recyclerview-v7:24.2.1'
    compile 'com.android.support:cardview-v7:24.2.1'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support:support-v4:24.2.1'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-crash:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:support-annotations:24.2.0'
    androidTestCompile 'com.android.support.test:runner:0.2'
    androidTestCompile 'com.android.support.test:rules:0.2'
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0'
    androidTestCompile 'com.android.support:support-annotations:24.2.1'
    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2') {
        exclude group: 'com.android.support', module: 'appcompat'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'support-v7'
        exclude group: 'com.android.support', module: 'design'
        exclude module: 'support-annotations'
        exclude module: 'recyclerview-v7'

    }
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    androidTestCompile "com.android.support.test.espresso:espresso-intents:2.2.2"
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'jacoco'

task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) {

    reports {
        xml.enabled = true
        html.enabled = true
    }

    def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*']
    def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter)
    def mainSrc = "${project.projectDir}/src/main/java"

    sourceDirectories = files([mainSrc])
    classDirectories = files([debugTree])
    executionData = fileTree(dir: "$buildDir", includes: [
            "jacoco/testDebugUnitTest.exec",
            "outputs/code-coverage/connected/*coverage.ec"
    ])
}
</code>```

答:
A few things that got this running:

Make sure that all the requisites are checked, per this other thread: https://stackoverflow.com/a/25525390/3195307

Make sure there is a connected device ready to execute your tests. Emulator, physical device, or cloud device. It should show in 'Select Deployment Target' under 'connected devices' if you play your tests in IDE.

Run Gradlew (project gradle wrapper) from the project directory like so: ./gradlew :app:createDebugCoverageReport

Body:
I am following these two links 1 and 2 for espresso test report but getting error while running ./gradlew createDebugCoverageReport. The error will be shown in image given below. Please help me, I am not able to generated report for espresso and ui automation test cases. Now trying to use jacoco but not able to find any solution.

Build.Gradle

apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.example.project"
        minSdkVersion 18
        targetSdkVersion 24
        versionCode 27
        versionName "1.5"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            testCoverageEnabled true
        }
        debug{
            testCoverageEnabled true
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.github.barteksc:android-pdf-viewer:2.0.3'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.android.support:recyclerview-v7:24.2.1'
    compile 'com.android.support:cardview-v7:24.2.1'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support:support-v4:24.2.1'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-crash:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:support-annotations:24.2.0'
    androidTestCompile 'com.android.support.test:runner:0.2'
    androidTestCompile 'com.android.support.test:rules:0.2'
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0'
    androidTestCompile 'com.android.support:support-annotations:24.2.1'
    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2') {
        exclude group: 'com.android.support', module: 'appcompat'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'support-v7'
        exclude group: 'com.android.support', module: 'design'
        exclude module: 'support-annotations'
        exclude module: 'recyclerview-v7'

    }
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    androidTestCompile "com.android.support.test.espresso:espresso-intents:2.2.2"
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'jacoco'

task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) {

    reports {
        xml.enabled = true
        html.enabled = true
    }

    def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*']
    def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter)
    def mainSrc = "${project.projectDir}/src/main/java"

    sourceDirectories = files([mainSrc])
    classDirectories = files([debugTree])
    executionData = fileTree(dir: "$buildDir", includes: [
            "jacoco/testDebugUnitTest.exec",
            "outputs/code-coverage/connected/*coverage.ec"
    ])
}


问:
is nested yaml inventory file for ansible supported?
I'm trying to use a yaml file as inventory file which looks like below:

- prod:
    webserver:
      hosts:
        example1.com
    db_servers:
      hosts:
        example2.com
        example3.com
- stag:
    webserver:
      hosts:
        example3.com

It doesn't seem to work, and I couldn't find much info on ansible docs arounf yaml inventory file. Is the above supported?

答:
No, this is not supported. You are supposed to have different inventories for production/testing.

You can only define single dependency tree like this:

```<code>webserver:
  hosts:
    example1:
db_servers:
  hosts:
    example2:
    example3:
test:
  children:
    webserver:
    db_servers:
</code>```

In this case group test is a parent of webserver and db_servers.

Body:
No, this is not supported. You are supposed to have different inventories for production/testing.

You can only define single dependency tree like this:

webserver:
  hosts:
    example1:
db_servers:
  hosts:
    example2:
    example3:
test:
  children:
    webserver:
    db_servers:

In this case group test is a parent of webserver and db_servers.