问:
Unfinished verification, Missing method call for verify(mock) while writing a JUnit test case
I am facing

```<code>org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)
</code>```

I have checked for all the parameters and the object as well that is being passed to verify, But not able to figure out what is causing the above exception

The condition I am trying to test,

```<code>if( request.getProcessType() == IPRequest.IPREQUEST_TYPE_DE )
{

     LookInfoIf rdr = new MCLLookInfoReader();

    String origAnatomy = accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
    String origView = accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
    String origPatSize = accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
    String mclPatSize = getMclPatientSize(origPatSize);
    String boneLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPEBONETAG,mclPatSize);
    String tissueLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPESOFTTISSUETAG,mclPatSize);

    params.setProcessingLookBone(boneLook);
    params.setProcessingLookTissue(tissueLook);
        params.setAnatomy(origAnatomy);
        params.setView(origView);
        params.setPatientSize(origPatSize);

}
</code>```

Test case

```<code>@Test
    public void testBuildProcessingInfoIf3() throws Exception
    {
        IPRequest req=new IPRequest(1);//value of IPRequest.IPREQUEST_TYPE_DE

        IPSysParams iPSysParams = Mockito.mock(IPSysParams.class);
        PowerMockito.whenNew(IPSysParams.class).withNoArguments().thenReturn(iPSysParams);

        TagAccessor accessor=Mockito.mock(TagAccessor.class);

        MCLLookInfoReader rdr=Mockito.mock(MCLLookInfoReader.class);
        PowerMockito.whenNew(MCLLookInfoReader.class).withNoArguments().thenReturn(rdr);

        Mockito.when(accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName())).thenReturn("ANATOMY_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName())).thenReturn("VIEW_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName())).thenReturn("PATIENT_SIZE");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All")).thenReturn("boneLook");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All")).thenReturn("tissueLook");

        sysParamsBuilder.buildProcessingInfo(req, info);

        String origAnatomy=accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
        assertEquals("ANATOMY_INFO",origAnatomy);

        String origView=accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
        assertEquals("VIEW_INFO",origView);

        String origPatSize=accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
        assertEquals("PATIENT_SIZE",origPatSize);

        PowerMockito.verifyPrivate(sysParamsBuilder).invoke("getMclPatientSize",origPatSize);//line 241

        String boneLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All");
        assertEquals("boneLook",boneLook);

        String tissueLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All");
        assertEquals("tissueLook",tissueLook);

        Mockito.verify(iPSysParams).setProcessingLookBone(boneLook);//line 244
        Mockito.verify(iPSysParams).setProcessingLookTissue(tissueLook);

        // fill the Anatomy View accrodingly
        Mockito.verify(iPSysParams,Mockito.times(1)).setAnatomy(origAnatomy);
        Mockito.verify(iPSysParams).setView(origView);
        Mockito.verify(iPSysParams).setPatientSize(origPatSize);

    }
</code>```

stack trace

```<code>org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.

    at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:244)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

I have done other test cases in the same way and it has worked but I don't know why its not working here, also all the methods are public. please help me figure It out, Thanks in advance

答:
I don't understand the mockito error here; but my answer goes into a different direction: do not verify like this.

You are following an almost anti-pattern here: you want to use mocking/verify for almost each and any call that happens in your production code. This means that subtle changes in your production code will always directly impact your unit tests. Even when "contract" of your method stays the same, your unit tests break quickly when you are using this style of verification.

My suggestion: instead of verifying that an object sees a lot of setter calls, you could do something along the lines of:

```<code>Params expectedParams = ...
Params actualParams = underTest.whatever();
assertThat(actualParams, is(expectedParams));
</code>```

and if the simple "equals" check that the hamcrest is matcher is doing doesn't work here; you could still create your own matcher.

In other words: stay away from "micro managing" your production code in your unit tests.

Focus on writing code that allows to be tested without caring about how things are done internally. Instead, check the "output" that your methods produce!

Example: assume you do all that mocking verification on some params object as you do above; but then in the end, your method returns some other params object ... then your unit test might be passing; but the whole method is wrong, because it is giving you the wrong result.

Body:
I am facing

org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)

I have checked for all the parameters and the object as well that is being passed to verify, But not able to figure out what is causing the above exception

The condition I am trying to test,

if( request.getProcessType() == IPRequest.IPREQUEST_TYPE_DE )
{

     LookInfoIf rdr = new MCLLookInfoReader();

    String origAnatomy = accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
    String origView = accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
    String origPatSize = accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
    String mclPatSize = getMclPatientSize(origPatSize);
    String boneLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPEBONETAG,mclPatSize);
    String tissueLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPESOFTTISSUETAG,mclPatSize);

    params.setProcessingLookBone(boneLook);
    params.setProcessingLookTissue(tissueLook);
        params.setAnatomy(origAnatomy);
        params.setView(origView);
        params.setPatientSize(origPatSize);

}

Test case

@Test
    public void testBuildProcessingInfoIf3() throws Exception
    {
        IPRequest req=new IPRequest(1);//value of IPRequest.IPREQUEST_TYPE_DE

        IPSysParams iPSysParams = Mockito.mock(IPSysParams.class);
        PowerMockito.whenNew(IPSysParams.class).withNoArguments().thenReturn(iPSysParams);

        TagAccessor accessor=Mockito.mock(TagAccessor.class);

        MCLLookInfoReader rdr=Mockito.mock(MCLLookInfoReader.class);
        PowerMockito.whenNew(MCLLookInfoReader.class).withNoArguments().thenReturn(rdr);

        Mockito.when(accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName())).thenReturn("ANATOMY_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName())).thenReturn("VIEW_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName())).thenReturn("PATIENT_SIZE");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All")).thenReturn("boneLook");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All")).thenReturn("tissueLook");

        sysParamsBuilder.buildProcessingInfo(req, info);

        String origAnatomy=accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
        assertEquals("ANATOMY_INFO",origAnatomy);

        String origView=accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
        assertEquals("VIEW_INFO",origView);

        String origPatSize=accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
        assertEquals("PATIENT_SIZE",origPatSize);

        PowerMockito.verifyPrivate(sysParamsBuilder).invoke("getMclPatientSize",origPatSize);//line 241

        String boneLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All");
        assertEquals("boneLook",boneLook);

        String tissueLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All");
        assertEquals("tissueLook",tissueLook);

        Mockito.verify(iPSysParams).setProcessingLookBone(boneLook);//line 244
        Mockito.verify(iPSysParams).setProcessingLookTissue(tissueLook);

        // fill the Anatomy View accrodingly
        Mockito.verify(iPSysParams,Mockito.times(1)).setAnatomy(origAnatomy);
        Mockito.verify(iPSysParams).setView(origView);
        Mockito.verify(iPSysParams).setPatientSize(origPatSize);

    }

stack trace

org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.

    at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:244)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I have done other test cases in the same way and it has worked but I don't know why its not working here, also all the methods are public. please help me figure It out, Thanks in advance

Body:
I don't understand the mockito error here; but my answer goes into a different direction: do not verify like this.

You are following an almost anti-pattern here: you want to use mocking/verify for almost each and any call that happens in your production code. This means that subtle changes in your production code will always directly impact your unit tests. Even when "contract" of your method stays the same, your unit tests break quickly when you are using this style of verification.

My suggestion: instead of verifying that an object sees a lot of setter calls, you could do something along the lines of:

Params expectedParams = ...
Params actualParams = underTest.whatever();
assertThat(actualParams, is(expectedParams));

and if the simple "equals" check that the hamcrest is matcher is doing doesn't work here; you could still create your own matcher.

In other words: stay away from "micro managing" your production code in your unit tests.

Focus on writing code that allows to be tested without caring about how things are done internally. Instead, check the "output" that your methods produce!

Example: assume you do all that mocking verification on some params object as you do above; but then in the end, your method returns some other params object ... then your unit test might be passing; but the whole method is wrong, because it is giving you the wrong result.


来源: stackexchange

问:
Cookie does not work in Mac Excel
We used to see a bug in Mac Excel 2016 that localStorage does not persist after add-in refresh. So we have adopted a work around by using cookie to store local data.

It works fine until recent Office update. It seems now Cookies does not survive the refresh of add-in. But fortunately localStorage started working.

Does Office team had some fixes to localStorage? But why you are dropping support of Cookies?

答: The localStorage issue was fixed with November release (15.28.0). We did not make any changes with cookies and they are persisting between sessions when I try. Could you provide a repro of the issue? What version of Office, Safari, and Mac OS are you seeing the cookie issue with?</p>

ContentLicense: CC BY-SA 3.0

Title: Cookie does not work in Mac Excel


问:
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Spring Boot
I am working on a spring boot application. I want to achieve sending some json data to a web api. When I try to run it, the following error comes up. After so many attempts, its not getting resolved. Any help will be much appreciated:

Error console:

```<code>2017-03-31 12:00:36.634  WARN 2972 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'oniSavingsApiController': Unsatisfied dependency expressed through field 'oniSavingsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'oniSavingsApiService': Unsatisfied dependency expressed through field 'readSheet'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.oni.excelReader.ReadSheet' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-03-31 12:00:36.634  INFO 2972 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-03-31 12:00:36.654  INFO 2972 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-03-31 12:00:36.798 ERROR 2972 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field readSheet in com.oni.service.OniSavingsApiService required a bean of type 'com.oni.excelReader.ReadSheet' that could not be found.
</code>```

Application

```<code>@SpringBootApplication
@ComponentScan(basePackages = "com.oni.controller, com.oni.service")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

Controller

```<code>@Controller
public class OniSavingsApiController {

    @Autowired
    private OniSavingsApiService oniSavingsService;

    @RequestMapping("/")
    public void home() {
        oniSavingsService.oakRestCall();
    }
}
</code>```

Service

```<code>@Component
public class OniSavingsApiService {

@Autowired
private ReadSheet readSheet;

public static final String CUSTOM_INFO = "custominformation";
public static final String AUTHORIZATION = "Basic";

public void oakRestCall() {

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", AUTHORIZATION);

    ArrayList<ResponseEntity<ResponseData>> responses = new ArrayList<ResponseEntity<ResponseData>>();
    List<ExcelFields> listOfExcelData = readSheet.getFileContent();

    for (ExcelFields ef : listOfExcelData) {
        System.out.println(ef.getId());
        try {
            String json = "";
            String urlString = "";
            /**
            some code here
            **/
        } catch (Exception e) {
        }
    }
}
}
</code>```

答:
Your ComponentScan scans only com.oni.controller and com.oni.service packages to inject the dependencies, so change it to scan through the whole "com.oni" package as shown below:

```<code>@ComponentScan(basePackages = "com.oni")
</code>```

or the other option is include com.oni.excelReader package (in which your ReadSheet class is located) as well:

```<code>@ComponentScan(basePackages = "com.oni.controller,
                           com.oni.service, com.oni.excelReader")
</code>```

P.S.: If you move your Application class to com.oni, you don't need @ComponentScan at all, Spring boot automatically scans all sub-packages of com.oni for you.

Body:
I am working on a spring boot application. I want to achieve sending some json data to a web api. When I try to run it, the following error comes up. After so many attempts, its not getting resolved. Any help will be much appreciated:

Error console:

2017-03-31 12:00:36.634  WARN 2972 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'oniSavingsApiController': Unsatisfied dependency expressed through field 'oniSavingsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'oniSavingsApiService': Unsatisfied dependency expressed through field 'readSheet'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.oni.excelReader.ReadSheet' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-03-31 12:00:36.634  INFO 2972 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-03-31 12:00:36.654  INFO 2972 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-03-31 12:00:36.798 ERROR 2972 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field readSheet in com.oni.service.OniSavingsApiService required a bean of type 'com.oni.excelReader.ReadSheet' that could not be found.

Application

@SpringBootApplication
@ComponentScan(basePackages = "com.oni.controller, com.oni.service")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Controller

@Controller
public class OniSavingsApiController {

    @Autowired
    private OniSavingsApiService oniSavingsService;

    @RequestMapping("/")
    public void home() {
        oniSavingsService.oakRestCall();
    }
}

Service

@Component
public class OniSavingsApiService {

@Autowired
private ReadSheet readSheet;

public static final String CUSTOM_INFO = "custominformation";
public static final String AUTHORIZATION = "Basic";

public void oakRestCall() {

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", AUTHORIZATION);

    ArrayList<ResponseEntity<ResponseData>> responses = new ArrayList<ResponseEntity<ResponseData>>();
    List<ExcelFields> listOfExcelData = readSheet.getFileContent();

    for (ExcelFields ef : listOfExcelData) {
        System.out.println(ef.getId());
        try {
            String json = "";
            String urlString = "";
            /**
            some code here
            **/
        } catch (Exception e) {
        }
    }
}
}

Body:
Your ComponentScan scans only com.oni.controller and com.oni.service packages to inject the dependencies, so change it to scan through the whole "com.oni" package as shown below:

@ComponentScan(basePackages = "com.oni")

or the other option is include com.oni.excelReader package (in which your ReadSheet class is located) as well:

@ComponentScan(basePackages = "com.oni.controller,
                           com.oni.service, com.oni.excelReader")

P.S.: If you move your Application class to com.oni, you don't need @ComponentScan at all, Spring boot automatically scans all sub-packages of com.oni for you.


问:
inner join large table with small table , how to speed up
dear php and mysql expertor
i have two table one large for posts artices 200,000records (index colume: sid) , and one small table (index colume topicid ) for topics has 20 record .. have same topicid

curent im using : ( it took round 0.4s)

+do get last 50 record from table:

SELECT sid, aid, title, time, topic, informant, ihome, alanguage, counter, type, images, chainid FROM veryzoo_stories ORDER BY sid DESC LIMIT 0,50

+then do while loop in each records for find the maching name of topic in each post:

while ( .. ) {
SELECT topicname FROM veryzoo_topics WHERE topicid='$topic'"
....
}

+Now
I going to use Inner Join for speed up process but as my test it took much longer from 1.5s up to 3.5s

SELECT a.sid, a.aid, a.title, a.time, a.topic, a.informant, a.ihome, a.alanguage, a.counter, a.type, a.images, a.chainid, t.topicname FROM veryzoo_stories a INNER JOIN veryzoo_topics t ON a.topic = t.topicid ORDER BY sid DESC LIMIT 0,50

It look like the inner join do all joining 200k records from two table fist then limit result at 50 .. that took long time..

Please help to point me right way doing this..
eg take last 50 records from table one.. then join it to table 2 .. ect

答:
Please try this :

```<code>SELECT *
FROM (
SELECT a.sid, a.aid, a.title, a.time, a.topic, a.informant, a.ihome, a.alanguage, a.counter, a.type, a.images, a.chainid
FROM veryzoo_stories a
ORDER BY sid DESC
LIMIT 0 , 50
)b
INNER JOIN veryzoo_topics t ON b.topic = t.topicid
</code>```

I made a small test and it seems to be faster. It uses a subquery (nested query) to first select the 50 records and then join.

Also make sure that veryzoo_stories.sid, veryzoo_stories.topic and veryzoo_topics.topicid are indexes (and that the relation exists if you use InnoDB). It should improve the performance.

Now it leaves the problem of the ORDER BY LIMIT. It is heavy because it orders the 200,000 records before selecting. I guess it's necessary. The indexes are very important when using ORDER BY.

Here is an article on the problem : ORDER BY … LIMIT Performance Optimization

ContentLicense: CC BY-SA 2.5

Body:
Please try this :

SELECT *
FROM (
SELECT a.sid, a.aid, a.title, a.time, a.topic, a.informant, a.ihome, a.alanguage, a.counter, a.type, a.images, a.chainid
FROM veryzoo_stories a
ORDER BY sid DESC
LIMIT 0 , 50
)b
INNER JOIN veryzoo_topics t ON b.topic = t.topicid

I made a small test and it seems to be faster. It uses a subquery (nested query) to first select the 50 records and then join.

Also make sure that veryzoo_stories.sid, veryzoo_stories.topic and veryzoo_topics.topicid are indexes (and that the relation exists if you use InnoDB). It should improve the performance.

Now it leaves the problem of the ORDER BY LIMIT. It is heavy because it orders the 200,000 records before selecting. I guess it's necessary. The indexes are very important when using ORDER BY.

Here is an article on the problem : ORDER BY … LIMIT Performance Optimization


问:
How to get the array value and in structurized using Mongoose?
I am using MeanStack AngularJS. I stored the values into MongoDB like this:

Data format

```<code>"RoleName" : "Verify",
"IsActive" : true,
"UIList" :
    {
        "UiName": "One",
        "View" : false,
        "Edit" : false
    },
    {
       "UiName": "Two",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Three",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Four",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Five",
        "View" : false,
        "Edit" : false
    }
</code>```

Contoller

```<code>$http.get('/Manage_Datashow').success(function (response) {
    $scope.Manage_Roleser = response;
});
</code>```

Server

```<code>app.get('/Manage_Datashow', function (req, res) {
    db.New_Role.find(function (err, docs) {
        console.log(docs);
        res.json(docs);
    });
});
</code>```

Here I attached my sample code. I want to bind the values in list using ng-repeat.

My code:

```<code><ul ng-repeat=Manage_Rolese in Manage_Roleser >
  <li>{{Manage_Rolese.UIList.UiName}}</li>
  <li>{{Manage_Rolese.UIList.View}}</li>
  <li>{{Manage_Rolese.UIList.Edit}}</li>
</ul>
</code>```

Example:

I need output like this.

答:
First off all you json is not a valid one please check that and go through the below snippest

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.Manage_Roleser =[ {
    "RoleName" : "Verify",
    "IsActive" : true,
    "UIList" : [{
            "UiName": "One",
            "View" : false,
            "Edit" : false
        },
        {
           "UiName": "Two",
            "View" : false,
            "Edit" : false
        },
          {
            "UiName": "Three",
            "View" : false,
            "Edit" : false
        },
         {
            "UiName": "Four",
            "View" : false,
            "Edit" : false
        },
          {
            "UiName": "Five",
            "View" : false,
            "Edit" : false
        }]
       } ]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">

 <div>

     <div  ng-repeat="i in Manage_Roleser[0].UIList">
       {{i.UiName}} | {{i.View}}   {{i.Edit}}

     </div>

 </div>
  </body>

</html></code>```

 Add your headings like as you want.

Body:
I am using MeanStack AngularJS. I stored the values into MongoDB like this:

Data format

"RoleName" : "Verify",
"IsActive" : true,
"UIList" :
    {
        "UiName": "One",
        "View" : false,
        "Edit" : false
    },
    {
       "UiName": "Two",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Three",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Four",
        "View" : false,
        "Edit" : false
    },
    {
        "UiName": "Five",
        "View" : false,
        "Edit" : false
    }

Contoller

$http.get('/Manage_Datashow').success(function (response) {
    $scope.Manage_Roleser = response;
});

Server

app.get('/Manage_Datashow', function (req, res) {
    db.New_Role.find(function (err, docs) {
        console.log(docs);
        res.json(docs);
    });
});

Here I attached my sample code. I want to bind the values in list using ng-repeat.

My code:

{{Manage_Rolese.UIList.UiName}}

{{Manage_Rolese.UIList.View}}

{{Manage_Rolese.UIList.Edit}}

Example:

I need output like this.

Body:
First off all you json is not a valid one please check that and go through the below snippest

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.Manage_Roleser =[ {
    "RoleName" : "Verify",
    "IsActive" : true,
    "UIList" : [{
            "UiName": "One",
            "View" : false,
            "Edit" : false
        },
        {
           "UiName": "Two",
            "View" : false,
            "Edit" : false
        },
          {
            "UiName": "Three",
            "View" : false,
            "Edit" : false
        },
         {
            "UiName": "Four",
            "View" : false,
            "Edit" : false
        },
          {
            "UiName": "Five",
            "View" : false,
            "Edit" : false
        }]
       } ]
});

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">

 <div>

     <div  ng-repeat="i in Manage_Roleser[0].UIList">
       {{i.UiName}} | {{i.View}}   {{i.Edit}}

     </div>

 </div>
  </body>

</html>

 Add your headings like as you want.


问:
how do I store value that is returned by the function without executing the function again?
so getBoundedNumber() is to let the user input some numbers and return the input. My other functions base on the return value and do calculations. I tried to assign it to a global variable outside the function(like var=getBoundedNumber(...)),but instead of storing the value from function, it executes the function again and ask for user to input again. How do I fix this?Thank you!

```<code>def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
            print(ee)
        except ValueError:
            print(' not a valid input')
    exit

return AA
</code>```

This is my main function:

```<code>def MAIN():

while True:

    xx=menu()

    if xx == 'A':
        aa=getBoundedNumber(0.5,4.5,1)

    elif xx == 'N':
        numpoints=getBoundedNumber(10,100000,1)

    elif xx == 'P':

        print('  Parameter a:%20.3f'%aa,'[m]')#console gives me aa not defined
        print('  Number of points:%20d'%numpoints)#console gives me numpoints not defined
        print('  Length:%20.3f'%chainlength(xs,ys),'[m]')#this function requires value from aa and numpoints so it won't execute.
        print('  Angle with support:%20.3f'%anglewithsupport(g_,dd,aa,numpoints))
        print('  Net force:%20.3f'%netforce(),'[N]')

    elif xx == 'Q':
        break
    else:
        print(' not a valid option')

exit
</code>```

This is my menu function

```<code>def menu():
print('Main menu choices')
print('   A - enter chain parameter a' )
print('   N - enter number of points in chain' )
print('   P - calculate and print chain results')
print('   Q - quit program')
while True:
    try:
        SELECTION = input('Enter your selection: ')

        if SELECTION.upper()== 'A':

            break
        elif SELECTION.upper() == 'N':
            break
        elif SELECTION.upper()=='P':
            break
        elif SELECTION.upper()=='Q':
            break

        else:
            print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
    exit
return SELECTION.upper()
</code>```

答:
Declare a global variable and then append the results before the return. Nevertheless you will not append the results because you are calling recursively the MAINMENU function so each execution will have it return value but it will be lost (unless you manage the calls and returns of MAINMENU)

Maybe you can do the same with a while-loop, and keep the values with a global variable.

Body:
so getBoundedNumber() is to let the user input some numbers and return the input. My other functions base on the return value and do calculations. I tried to assign it to a global variable outside the function(like var=getBoundedNumber(...)),but instead of storing the value from function, it executes the function again and ask for user to input again. How do I fix this?Thank you!

def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
            print(ee)
        except ValueError:
            print(' not a valid input')
    exit

return AA

This is my main function:

def MAIN():

while True:

    xx=menu()

    if xx == 'A':
        aa=getBoundedNumber(0.5,4.5,1)

    elif xx == 'N':
        numpoints=getBoundedNumber(10,100000,1)

    elif xx == 'P':

        print('  Parameter a:%20.3f'%aa,'[m]')#console gives me aa not defined
        print('  Number of points:%20d'%numpoints)#console gives me numpoints not defined
        print('  Length:%20.3f'%chainlength(xs,ys),'[m]')#this function requires value from aa and numpoints so it won't execute.
        print('  Angle with support:%20.3f'%anglewithsupport(g_,dd,aa,numpoints))
        print('  Net force:%20.3f'%netforce(),'[N]')

    elif xx == 'Q':
        break
    else:
        print(' not a valid option')

exit

This is my menu function

def menu():
print('Main menu choices')
print('   A - enter chain parameter a' )
print('   N - enter number of points in chain' )
print('   P - calculate and print chain results')
print('   Q - quit program')
while True:
    try:
        SELECTION = input('Enter your selection: ')

        if SELECTION.upper()== 'A':

            break
        elif SELECTION.upper() == 'N':
            break
        elif SELECTION.upper()=='P':
            break
        elif SELECTION.upper()=='Q':
            break

        else:
            print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
    exit
return SELECTION.upper()


问:
How to save an image in the gallery when the image is stored in firebase?
I am very new to android programming. I want to design an app which will download an image in the phone's gallery and the image has already been stored in the firebase.
The image is getting downloaded and is being set in the imageview also but unfortunately i can not find it in the phone gallery.I have also added write external storage permission in the manifest file.Here is my DownloadActivity.java:

```<code> package com.example.android.myapplication;

/**
 * Created by Krishnendu on 25-03-2017.
 */

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static android.R.attr.src;

public class DownloadActivity extends RootActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        final ImageView imageView = (ImageView)findViewById(R.id.image);
        View btnDownloadByteArray = findViewById(R.id.btn_download_byte);
        btnDownloadByteArray.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FirebaseStorage storage = FirebaseStorage.getInstance();
                StorageReference storageRef = storage.getReferenceFromUrl("gs://test1-a7e81.appspot.com").child("as.jpg");
                final long ONE_MEGABYTE = 1024 * 1024;

                //download file as a byte array
                storageRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
                    @Override
                    public void onSuccess(byte[] bytes) {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        imageView.setImageBitmap(bitmap);
                        showToast("Download successful!");
                    }
                });
            }
        });

        View btnDownloadAsFile = findViewById(R.id.btn_download_file);
        btnDownloadAsFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FirebaseStorage storage = FirebaseStorage.getInstance();
                final StorageReference storageRef = storage.getReferenceFromUrl("gs://test1-a7e81.appspot.com").child("as.jpg");

                //get download file url
                storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        Log.i("Main", "File uri: " + uri.toString());
                    }
                });

                //download the file
                try {
                    showProgressDialog("Download File", "Downloading File...");
                    final File localFile = File.createTempFile("images","jpg");

                    storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {

                        @Override
                        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                            Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                            imageView.setImageBitmap(bitmap);
                            dismissProgressDialog();
                            showToast("Download successful!");
                            Log.i("path",localFile.getPath());
                            Log.i("parent",localFile.getParent());

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            dismissProgressDialog();
                            showToast("Download Failed!");
                        }
                    });
                } catch (Exception e ) {
                    e.printStackTrace();
                    Log.e("Main", "IOE Exception");
                }
            }
        });
    }
}
</code>```

This is my RootActivity.java file:`

```<code>    package com.example.android.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class RootActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    protected void showProgressDialog(String title, String msg) {
        progressDialog = ProgressDialog.show(this, title, msg, true);
    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void dismissProgressDialog() {
        progressDialog.dismiss();
    }
}
</code>```

This is my activity_main.xml file:`

```<code> <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="495dp">

        <Button
            android:id="@+id/btn_download_byte"
            android:text="Download as byte Array"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn_download_file"
            android:text="Download as File"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_gravity="center"
            android:layout_centerHorizontal="true"
            android:contentDescription="@null" />

    </LinearLayout>
</code>```

This is my manifest file:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.myapplication">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".DownloadActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
You cannot store image files in the Gallery as the Gallery app is no storage place but just an app that shows all image files on your device. To know which image files are on your device the Gallery app queries the MediaStore. The MediaStore will have indexed the image files on your device.

If you create a new file you should inform the MediaStore about it. Otherwise the Gallery app will not 'see' it.

Body:
I am very new to android programming. I want to design an app which will download an image in the phone's gallery and the image has already been stored in the firebase.
The image is getting downloaded and is being set in the imageview also but unfortunately i can not find it in the phone gallery.I have also added write external storage permission in the manifest file.Here is my DownloadActivity.java:

 package com.example.android.myapplication;

/**
 * Created by Krishnendu on 25-03-2017.
 */

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static android.R.attr.src;

public class DownloadActivity extends RootActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        final ImageView imageView = (ImageView)findViewById(R.id.image);
        View btnDownloadByteArray = findViewById(R.id.btn_download_byte);
        btnDownloadByteArray.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FirebaseStorage storage = FirebaseStorage.getInstance();
                StorageReference storageRef = storage.getReferenceFromUrl("gs://test1-a7e81.appspot.com").child("as.jpg");
                final long ONE_MEGABYTE = 1024 * 1024;

                //download file as a byte array
                storageRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
                    @Override
                    public void onSuccess(byte[] bytes) {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        imageView.setImageBitmap(bitmap);
                        showToast("Download successful!");
                    }
                });
            }
        });

        View btnDownloadAsFile = findViewById(R.id.btn_download_file);
        btnDownloadAsFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FirebaseStorage storage = FirebaseStorage.getInstance();
                final StorageReference storageRef = storage.getReferenceFromUrl("gs://test1-a7e81.appspot.com").child("as.jpg");

                //get download file url
                storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        Log.i("Main", "File uri: " + uri.toString());
                    }
                });

                //download the file
                try {
                    showProgressDialog("Download File", "Downloading File...");
                    final File localFile = File.createTempFile("images","jpg");

                    storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {

                        @Override
                        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                            Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                            imageView.setImageBitmap(bitmap);
                            dismissProgressDialog();
                            showToast("Download successful!");
                            Log.i("path",localFile.getPath());
                            Log.i("parent",localFile.getParent());

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            dismissProgressDialog();
                            showToast("Download Failed!");
                        }
                    });
                } catch (Exception e ) {
                    e.printStackTrace();
                    Log.e("Main", "IOE Exception");
                }
            }
        });
    }
}

This is my RootActivity.java file:`

    package com.example.android.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class RootActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    protected void showProgressDialog(String title, String msg) {
        progressDialog = ProgressDialog.show(this, title, msg, true);
    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void dismissProgressDialog() {
        progressDialog.dismiss();
    }
}

This is my activity_main.xml file:`

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="495dp">

        <Button
            android:id="@+id/btn_download_byte"
            android:text="Download as byte Array"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn_download_file"
            android:text="Download as File"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_gravity="center"
            android:layout_centerHorizontal="true"
            android:contentDescription="@null" />

    </LinearLayout>

This is my manifest file:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.myapplication">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".DownloadActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
Chrome dev tools lose syntax highlighting for TypeScript
I'm not sure if there if a way around this, or if maybe there is an issue when using mapped TypeScript files, but in many cases (larger files), I seem to lose the syntax highlighting..

As can be seen on the above image, it is ok until line 102, and from then on the rest of the file is just in red.

The above is from an Ionic 2 / Angular 2 project.

Appears to happen after the use of backtick string (but not always after the use of these)

It is not the end of the world, but the highlighting does make it easier to read. Anyone else experience this, and perhaps know a work around?

答:
experiencing this problem all the time working with TS sourcemaps.
that's chromium engine trouble, there is also bug report about this problem
(link to report)
I gave up for this and using oldschool string concatenation.</p>


问:
Remove method using linq
How do I implement the following method (preferably without fetching the items from the database first):

```<code>public void Remove(Expression<Func<TEntity, bool>> query)
{
  _session.XXXXXXX
}
</code>```

It's for my repository class.

答:
I'm afraid that's not currently possible, as Linq in NH is only supported for data-retrieving queries, not updates.

An alternative is using HQL updates: http://nhibernate.info/doc/nh/en/index.html#batch-direct

The end result is the same: HQL queries are type-safe and compiled (by NHibernate)

Title: Remove method using linq

Body:
How do I implement the following method (preferably without fetching the items from the database first):

public void Remove(Expression<Func<TEntity, bool>> query)
{
  _session.XXXXXXX
}

It's for my repository class.


问:
Adding events to google calendar in ios 10
I am trying to add events to google calendar but in ios 10 i am getting following error even i login my gmail account in settings --> calendar.

I am using the following code

```<code>    GTLServiceCalendar *_calendarService = [[GTLServiceCalendar alloc] init];

    _calendarService.authorizer = [GTMOAuth2ViewControllerTouch
                                   authForGoogleFromKeychainForName:kGoogleAPIKeychainItemName
                                   clientID:kGoogleAPIClientID
                                   clientSecret:nil];

    if (!_calendarService.authorizer.canAuthorize)
        //if([auth canAuthorize])
    {
        [self launchGoogleAuthenticationView];
    }
    else {

        [self addEventToGoogleCalendar];
    }
  - (void)launchGoogleAuthenticationView {
_didCancelGoogleAuthentication = NO;

GTMOAuth2ViewControllerTouch *authController;

// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeCalendar, nil];

authController = [[GTMOAuth2ViewControllerTouch alloc]
                  initWithScope:[scopes componentsJoinedByString:@" "]
                  clientID:kGoogleAPIClientID
                  clientSecret:nil
                  keychainItemName:kGoogleAPIKeychainItemName
                  delegate:self
                  finishedSelector:@selector(googleAuthenticationViewController:finishedWithAuth:error:)];

UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];

[closeButton setTitle:@"Cancel" forState:UIControlStateNormal];

[closeButton setBackgroundColor:appredcolor];

[closeButton addTarget:self
                action:@selector(didTapCloseButton:)
      forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *closeButtonItem = [[UIBarButtonItem alloc]
                                    initWithCustomView:closeButton];

[closeButtonItem setTintColor:appredcolor];

[authController.navigationItem setLeftBarButtonItem:closeButtonItem];

UINavigationController *navController = [[UINavigationController alloc]
                                         initWithRootViewController:authController];

 [myappDelegate.navCont.viewControllers.lastObject presentViewController:navController animated:YES completion:nil];
 }
- (void)addEventToGoogleCalendar {

NSString *appdatestr =[[CTManager sharedInstance] getAppointmentForId:cardict.carsIdentifier];

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"dd-MMM-yy, hh:mm a"];

_calendarEvent = [[GTLCalendarEvent alloc] init];

[_calendarEvent setSummary:@"Fathik"];
[_calendarEvent setDescriptionProperty:@"Adding event in UCR"];

NSDate *startDate = [outputFormatter dateFromString:appdatestr];
NSDate *endDate = [startDate dateByAddingTimeInterval:60*60];

if (endDate == nil) {
    endDate = [startDate dateByAddingTimeInterval:(60 * 60)];
}

GTLDateTime *startTime = [GTLDateTime dateTimeWithDate:startDate
                                              timeZone:[NSTimeZone systemTimeZone]];

[_calendarEvent setStart:[GTLCalendarEventDateTime object]];
[_calendarEvent.start setDateTime:startTime];

GTLDateTime *endTime = [GTLDateTime dateTimeWithDate:endDate
                                            timeZone:[NSTimeZone systemTimeZone]];

[_calendarEvent setEnd:[GTLCalendarEventDateTime object]];
[_calendarEvent.end setDateTime:endTime];

GTLQueryCalendar *insertQuery = [GTLQueryCalendar queryForEventsInsertWithObject:_calendarEvent
                                                                      calendarId:kGoogleAPICalendarID];
//[self showAlertWithTitle:nil
//     andMessage:NSLocalizedString(@"Adding Event…", nil)];

[_calendarService executeQuery:insertQuery
             completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
                 if (error == nil) {
                     NSLog(@"event added");
                     [myappDelegate.navCont.view makeToast:@"Event added to your Calender"
                                                  duration:2.0
                                                  position:CSToastPositionBottom
                                                     title:nil];
                 } else {
                     NSLog(@"event added failed --- %@",[error description]);
                 }
             }];

}
</code>```

Please suggest any idea.Thanks in advance

答:
Add this few line of code in your viewDidLoad()
I was facing same issue, After a great pursuing the problem I got the following given solution.
*Thanks For Mr. Adnan Ameen*

// set default useragent

```<code>NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
</code>```

Body:
I am trying to add events to google calendar but in ios 10 i am getting following error even i login my gmail account in settings --> calendar.

I am using the following code

    GTLServiceCalendar *_calendarService = [[GTLServiceCalendar alloc] init];

    _calendarService.authorizer = [GTMOAuth2ViewControllerTouch
                                   authForGoogleFromKeychainForName:kGoogleAPIKeychainItemName
                                   clientID:kGoogleAPIClientID
                                   clientSecret:nil];

    if (!_calendarService.authorizer.canAuthorize)
        //if([auth canAuthorize])
    {
        [self launchGoogleAuthenticationView];
    }
    else {

        [self addEventToGoogleCalendar];
    }
  - (void)launchGoogleAuthenticationView {
_didCancelGoogleAuthentication = NO;

GTMOAuth2ViewControllerTouch *authController;

// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeCalendar, nil];

authController = [[GTMOAuth2ViewControllerTouch alloc]
                  initWithScope:[scopes componentsJoinedByString:@" "]
                  clientID:kGoogleAPIClientID
                  clientSecret:nil
                  keychainItemName:kGoogleAPIKeychainItemName
                  delegate:self
                  finishedSelector:@selector(googleAuthenticationViewController:finishedWithAuth:error:)];

UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];

[closeButton setTitle:@"Cancel" forState:UIControlStateNormal];

[closeButton setBackgroundColor:appredcolor];

[closeButton addTarget:self
                action:@selector(didTapCloseButton:)
      forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *closeButtonItem = [[UIBarButtonItem alloc]
                                    initWithCustomView:closeButton];

[closeButtonItem setTintColor:appredcolor];

[authController.navigationItem setLeftBarButtonItem:closeButtonItem];

UINavigationController *navController = [[UINavigationController alloc]
                                         initWithRootViewController:authController];

 [myappDelegate.navCont.viewControllers.lastObject presentViewController:navController animated:YES completion:nil];
 }
- (void)addEventToGoogleCalendar {

NSString *appdatestr =[[CTManager sharedInstance] getAppointmentForId:cardict.carsIdentifier];

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"dd-MMM-yy, hh:mm a"];

_calendarEvent = [[GTLCalendarEvent alloc] init];

[_calendarEvent setSummary:@"Fathik"];
[_calendarEvent setDescriptionProperty:@"Adding event in UCR"];

NSDate *startDate = [outputFormatter dateFromString:appdatestr];
NSDate *endDate = [startDate dateByAddingTimeInterval:60*60];

if (endDate == nil) {
    endDate = [startDate dateByAddingTimeInterval:(60 * 60)];
}

GTLDateTime *startTime = [GTLDateTime dateTimeWithDate:startDate
                                              timeZone:[NSTimeZone systemTimeZone]];

[_calendarEvent setStart:[GTLCalendarEventDateTime object]];
[_calendarEvent.start setDateTime:startTime];

GTLDateTime *endTime = [GTLDateTime dateTimeWithDate:endDate
                                            timeZone:[NSTimeZone systemTimeZone]];

[_calendarEvent setEnd:[GTLCalendarEventDateTime object]];
[_calendarEvent.end setDateTime:endTime];

GTLQueryCalendar *insertQuery = [GTLQueryCalendar queryForEventsInsertWithObject:_calendarEvent
                                                                      calendarId:kGoogleAPICalendarID];
//[self showAlertWithTitle:nil
//     andMessage:NSLocalizedString(@"Adding Event…", nil)];

[_calendarService executeQuery:insertQuery
             completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
                 if (error == nil) {
                     NSLog(@"event added");
                     [myappDelegate.navCont.view makeToast:@"Event added to your Calender"
                                                  duration:2.0
                                                  position:CSToastPositionBottom
                                                     title:nil];
                 } else {
                     NSLog(@"event added failed --- %@",[error description]);
                 }
             }];

}

Please suggest any idea.Thanks in advance

Body:
Add this few line of code in your viewDidLoad()
I was facing same issue, After a great pursuing the problem I got the following given solution.
*Thanks For Mr. Adnan Ameen*

// set default useragent

NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];


问:
How to Replace Bad Words in a Comment with Asterisks Using PHP

Hope All Of You are Fine.

I have a File in Of Bad Words, I want to Replace Bad Words in a Comments with Asterisks.

Bad Words URL : https://gist.githubusercontent.com/anonymous/e8e6798137b1ff4836d6ebcf73fef7dc/raw/415dfc8cbab13fa6033fbb4d4ce9eae7a9dbe7cd/Bad_Words.txt

I wrote Below Lines Of Code But It's not Working :(

Kindly Help.

```<code><?php
$abusive_words = file_get_contents('Bad_Words.txt');
$abusive_words = explode("\n", $abusive_words);
$input_string = 'Catch that bastard, Idiot .... !!';
$fixed = str_ireplace($abusive_words,'*****',$input_string);
echo "Input String <br> $input_string <br><br><hr><br>Input String Fixed <br> $fixed";
?>
</code>```

答:
Here I am sharing example where we just have to set replace with character and it will replace characters of string.

for ex. Bitch will replace with ***** (5 stars) and for crap it will show **** (4 starts).

```<code>$abusive_words = ['bitch', 'crap', 'bastard'];
$input_string = 'Catch that bastard, Idiot .... !!';
$replaceWith = '*';

$replace = array();
$replace['a'] = '(a|a\.|a\-|4|@|Á|á|À|Â|à|Â|â|Ä|ä|Ã|ã|Å|å|α|Δ|Λ|λ)';
$replace['b'] = '(b|b\.|b\-|8|\|3|ß|Β|β)';
$replace['c'] = '(c|c\.|c\-|Ç|ç|¢|€|<|\(|{|©)';
$replace['d'] = '(d|d\.|d\-|∂|\|\)|Þ|þ|Ð|ð)';
$replace['e'] = '(e|e\.|e\-|3|€|È|è|É|é|Ê|ê|∑)';
$replace['f'] = '(f|f\.|f\-|ƒ)';
$replace['g'] = '(g|g\.|g\-|6|9)';
$replace['h'] = '(h|h\.|h\-|Η)';
$replace['i'] = '(i|i\.|i\-|!|\||\]\[|]|1|∫|Ì|Í|Î|Ï|ì|í|î|ï)';
$replace['j'] = '(j|j\.|j\-)';
$replace['k'] = '(k|k\.|k\-|Κ|κ)';
$replace['l'] = '(l|1\.|l\-|!|\||\]\[|]|£|∫|Ì|Í|Î|Ï)';
$replace['m'] = '(m|m\.|m\-)';
$replace['n'] = '(n|n\.|n\-|η|Ν|Π)';
$replace['o'] = '(o|o\.|o\-|0|Ο|ο|Φ|¤|°|ø)';
$replace['p'] = '(p|p\.|p\-|ρ|Ρ|¶|þ)';
$replace['q'] = '(q|q\.|q\-)';
$replace['r'] = '(r|r\.|r\-|®)';
$replace['s'] = '(s|s\.|s\-|5|\$|§)';
$replace['t'] = '(t|t\.|t\-|Τ|τ)';
$replace['u'] = '(u|u\.|u\-|υ|µ)';
$replace['v'] = '(v|v\.|v\-|υ|ν)';
$replace['w'] = '(w|w\.|w\-|ω|ψ|Ψ)';
$replace['x'] = '(x|x\.|x\-|Χ|χ)';
$replace['y'] = '(y|y\.|y\-|¥|γ|ÿ|ý|Ÿ|Ý)';
$replace['z'] = '(z|z\.|z\-|Ζ)';

$replacement = array();
$whiteListCount = count($abusive_words);

for ($x = 0; $x < $whiteListCount; $x++) {
    $replacement[$x] = str_repeat($replaceWith, strlen($abusive_words[$x]));
    $abusive_words[$x] = '/' . str_ireplace(array_keys($replace), array_values($replace), $abusive_words[$x]) . '/i';
}
echo preg_replace($abusive_words, $replacement, $input_string);
</code>```

You can move main logic bunch of codes in separate function and used in any files where you want to replace bad words from content of any length.

Body:
Hope All Of You are Fine.

I have a File in Of Bad Words, I want to Replace Bad Words in a Comments with Asterisks.

Bad Words URL : https://gist.githubusercontent.com/anonymous/e8e6798137b1ff4836d6ebcf73fef7dc/raw/415dfc8cbab13fa6033fbb4d4ce9eae7a9dbe7cd/Bad_Words.txt

I wrote Below Lines Of Code But It's not Working :(

Kindly Help.

<?php
$abusive_words = file_get_contents('Bad_Words.txt');
$abusive_words = explode("\n", $abusive_words);
$input_string = 'Catch that bastard, Idiot .... !!';
$fixed = str_ireplace($abusive_words,'*****',$input_string);
echo "Input String
 $input_string

Input String Fixed
 $fixed";
?>

Body:
Here I am sharing example where we just have to set replace with character and it will replace characters of string.

for ex. Bitch will replace with ***** (5 stars) and for crap it will show **** (4 starts).

$abusive_words = ['bitch', 'crap', 'bastard'];
$input_string = 'Catch that bastard, Idiot .... !!';
$replaceWith = '*';

$replace = array();
$replace['a'] = '(a|a\.|a\-|4|@|Á|á|À|Â|à|Â|â|Ä|ä|Ã|ã|Å|å|α|Δ|Λ|λ)';
$replace['b'] = '(b|b\.|b\-|8|\|3|ß|Β|β)';
$replace['c'] = '(c|c\.|c\-|Ç|ç|¢|€|<|\(|{|©)';
$replace['d'] = '(d|d\.|d\-|&part;|\|\)|Þ|þ|Ð|ð)';
$replace['e'] = '(e|e\.|e\-|3|€|È|è|É|é|Ê|ê|∑)';
$replace['f'] = '(f|f\.|f\-|ƒ)';
$replace['g'] = '(g|g\.|g\-|6|9)';
$replace['h'] = '(h|h\.|h\-|Η)';
$replace['i'] = '(i|i\.|i\-|!|\||\]\[|]|1|∫|Ì|Í|Î|Ï|ì|í|î|ï)';
$replace['j'] = '(j|j\.|j\-)';
$replace['k'] = '(k|k\.|k\-|Κ|κ)';
$replace['l'] = '(l|1\.|l\-|!|\||\]\[|]|£|∫|Ì|Í|Î|Ï)';
$replace['m'] = '(m|m\.|m\-)';
$replace['n'] = '(n|n\.|n\-|η|Ν|Π)';
$replace['o'] = '(o|o\.|o\-|0|Ο|ο|Φ|¤|°|ø)';
$replace['p'] = '(p|p\.|p\-|ρ|Ρ|¶|þ)';
$replace['q'] = '(q|q\.|q\-)';
$replace['r'] = '(r|r\.|r\-|®)';
$replace['s'] = '(s|s\.|s\-|5|\$|§)';
$replace['t'] = '(t|t\.|t\-|Τ|τ)';
$replace['u'] = '(u|u\.|u\-|υ|µ)';
$replace['v'] = '(v|v\.|v\-|υ|ν)';
$replace['w'] = '(w|w\.|w\-|ω|ψ|Ψ)';
$replace['x'] = '(x|x\.|x\-|Χ|χ)';
$replace['y'] = '(y|y\.|y\-|¥|γ|ÿ|ý|Ÿ|Ý)';
$replace['z'] = '(z|z\.|z\-|Ζ)';

$replacement = array();
$whiteListCount = count($abusive_words);

for ($x = 0; $x < $whiteListCount; $x++) {
    $replacement[$x] = str_repeat($replaceWith, strlen($abusive_words[$x]));
    $abusive_words[$x] = '/' . str_ireplace(array_keys($replace), array_values($replace), $abusive_words[$x]) . '/i';
}
echo preg_replace($abusive_words, $replacement, $input_string);

You can move main logic bunch of codes in separate function and used in any files where you want to replace bad words from content of any length.


问:
Powershell Click Through Transparent
I need to make a window click through-able when transparent.

```<code>$form.Transparencykey = "Red"
$form.BackColour = "Red"
</code>```

This allows me to see through the form, but not click objects through the transparent window.
I can't find any examples anywhere of ways to do this in PowerShell. Is there a way to make the window transparent but not allow clicks to be transferred to the windows below?

答:
Okay so I found the problem and its the colour I selected was a system colour.

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/199a4ca5-38c2-4ade-aad4-31d1a30a1334/interesting-some-color-as-transparentkey-makes-form-not-clickthrough?forum=winforms

this article explains. so now I have modified the colour to "Silver" I can click through. If you set to say "Red" you can't.

Title: Powershell Click Through Transparent

Body:
I need to make a window click through-able when transparent.

$form.Transparencykey = "Red"
$form.BackColour = "Red"

This allows me to see through the form, but not click objects through the transparent window.
I can't find any examples anywhere of ways to do this in PowerShell. Is there a way to make the window transparent but not allow clicks to be transferred to the windows below?


问:
SQL Stored procedure- Must declare the scalar variable "@user_name"
I am getting the following error while I execute it.

Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "@user_name".

(1 row(s) affected)

```<code>USE [qcsl]
GO
/****** Object:  StoredProcedure [dbo].[UserAdvancedSearch]    Script Date: 3/31/2017 12:09:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UserAdvancedSearch]
    -- Add the parameters for the stored procedure here
    (
    @user_name varchar(50) = NULL,
    @role_id int = 2,
    @user_status int = 1

    )
    AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
DECLARE @query varchar(2000);
SET @query = 'select * from user_main
where (CONCAT(user_first_name,user_last_name) like  CONCAT(@user_name) OR CONCAT(CONCAT(user_first_name,user_last_name) IS NULL)
AND
(user_role_id_ref=@role_id OR user_role_id_ref IS NULL)
AND
(user_status = @user_status OR user_status IS NULL)';
EXEC(@query)
END
</code>```

答:
Since you have parameters in dynamic query so modify your execute query like below and try.

```<code>EXEC SP_EXECUTESQL @query,N' @user_name varchar(50),@role_id  INT,@user_status int',@user_name=@user_name,@role_id=@role_id,@user_status=user_status
</code>```

Also, modify your line of code

```<code>DECLARE @query varchar(2000);
</code>```

to

DECLARE @query nvarchar(2000);

Body:
I am getting the following error while I execute it.

Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "@user_name".

(1 row(s) affected)

USE [qcsl]
GO
/****** Object:  StoredProcedure [dbo].[UserAdvancedSearch]    Script Date: 3/31/2017 12:09:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UserAdvancedSearch]
    -- Add the parameters for the stored procedure here
    (
    @user_name varchar(50) = NULL,
    @role_id int = 2,
    @user_status int = 1

    )
    AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
DECLARE @query varchar(2000);
SET @query = 'select * from user_main
where (CONCAT(user_first_name,user_last_name) like  CONCAT(@user_name) OR CONCAT(CONCAT(user_first_name,user_last_name) IS NULL)
AND
(user_role_id_ref=@role_id OR user_role_id_ref IS NULL)
AND
(user_status = @user_status OR user_status IS NULL)';
EXEC(@query)
END

Body:
Since you have parameters in dynamic query so modify your execute query like below and try.

EXEC SP_EXECUTESQL @query,N' @user_name varchar(50),@role_id  INT,@user_status int',@user_name=@user_name,@role_id=@role_id,@user_status=user_status

Also, modify your line of code

DECLARE @query varchar(2000);

to

DECLARE @query nvarchar(2000);


问:
Getter for private member object in Java
Say I have a class called Truck and one of the private member variables is of class Wheel. A getter for the Wheel variable, getWheel, would return a reference to it, as follows:

```<code>class Truck{
    private Wheel wheel;

    Truck(){
        wheel=new Wheel();

    }

    Wheel getWheel(){
        return this.wheel;
    }
}

class Wheel{
    int color;
}
</code>```

Now, whoever calls getWheel will be able to modify the private member object at will:

```<code>class me{
    public static void main(String[] args){
        Truck ye=new Truck();
        Wheel v=ye.getWheel();

        v.color=2;
    }
}
</code>```

This would defeat encapsulation, wouldn't it?

What would be the right remedy for this?

答:
The usual approaches are:

Make a defensive copy (e.g., return a copy of Wheel)

Make Wheel immutable (any time you want to change it, you create a new one instead, constructed with the new color)

Don't return Wheel, return an immutable interface on Wheel that only exposes getters, no mutation operations

As Sandeep said, make the setter more restricted than the getter, say, package-private for the setter and public for the getter. Then classes within the package could set the color of Wheel, but classes outside the package cannot. (I prefer #3 in this situation for the clear separation, but this works too if you're crossing a visibility boundary.)

That third option is one of the reasons why making instance variables (fields) non-private is often considered poor practice.

Here's #3 in more depth, just because it's more complicated than #1 and #2, not because it's necessarily better (it isn't, design choices are made in context).

A read-only interface, typically public or package-private depending on how you're going to use all of this stuff:

```<code>public interface Wheel {
    int getColor();
}
</code>```

The concrete class, typically package-private (could be a private static nested class within Truck if that's the only place it's used):

```<code>class WheelImplementation implements Wheel {
    private int color;

    WheelImplementation(int color) {
        this.color = color;
    }

    public int getColor() {
        return this.color;
    }

    void setColor(int color) {
        this.color = color;
    }
}
</code>```

Truck, typically same visibility as Wheel:

```<code>public class Truck {
    private WheelImplementation wheel;

    Truck(){
        this.wheel = new WheelImplementation(/*...initial color...*/);
    }

    Wheel getWheel() {
        return this.wheel;
    }
}
</code>```

Sure, that can be defeated through reflection, but generally you design an  API for use, rather than for abuse. :-)

Body:
Say I have a class called Truck and one of the private member variables is of class Wheel. A getter for the Wheel variable, getWheel, would return a reference to it, as follows:

class Truck{
    private Wheel wheel;

    Truck(){
        wheel=new Wheel();

    }

    Wheel getWheel(){
        return this.wheel;
    }
}

class Wheel{
    int color;
}

Now, whoever calls getWheel will be able to modify the private member object at will:

class me{
    public static void main(String[] args){
        Truck ye=new Truck();
        Wheel v=ye.getWheel();

        v.color=2;
    }
}

This would defeat encapsulation, wouldn't it?

What would be the right remedy for this?

Body:
The usual approaches are:

Make a defensive copy (e.g., return a copy of Wheel)

Make Wheel immutable (any time you want to change it, you create a new one instead, constructed with the new color)

Don't return Wheel, return an immutable interface on Wheel that only exposes getters, no mutation operations

As Sandeep said, make the setter more restricted than the getter, say, package-private for the setter and public for the getter. Then classes within the package could set the color of Wheel, but classes outside the package cannot. (I prefer #3 in this situation for the clear separation, but this works too if you're crossing a visibility boundary.)

That third option is one of the reasons why making instance variables (fields) non-private is often considered poor practice.

Here's #3 in more depth, just because it's more complicated than #1 and #2, not because it's necessarily better (it isn't, design choices are made in context).

A read-only interface, typically public or package-private depending on how you're going to use all of this stuff:

public interface Wheel {
    int getColor();
}

The concrete class, typically package-private (could be a private static nested class within Truck if that's the only place it's used):

class WheelImplementation implements Wheel {
    private int color;

    WheelImplementation(int color) {
        this.color = color;
    }

    public int getColor() {
        return this.color;
    }

    void setColor(int color) {
        this.color = color;
    }
}

Truck, typically same visibility as Wheel:

public class Truck {
    private WheelImplementation wheel;

    Truck(){
        this.wheel = new WheelImplementation(/*...initial color...*/);
    }

    Wheel getWheel() {
        return this.wheel;
    }
}

Sure, that can be defeated through reflection, but generally you design an  API for use, rather than for abuse. :-)


问:
Generating Multiple Columns Based On The Column Content
I am in need of generating a result which joins two user related tables - Users and Usermeta. These are from a Wordpress MySQL DB.

User Table -

```<code>ID user_email
1  abc@gmail.com
2  xyz@gmail.com
3  1sf@email.com
</code>```

Usermeta Table -

```<code>Umeta_ID user_id meta_key          meta_value
1000     1       billing_phone     9876443100
1001     1       billing_postcode  670001
1002     1       billing_address   Somewhere here, Delhi
1003     2       billing_phone     9876345188
1004     2       billing_postcode  650021
1005     2       billing_address   7th Lane, Bangalore
1003     3       billing_phone     7852562100
1004     3       billing_postcode  400521
1005     3       billing_address   Fancy Area, Mumbai
</code>```

As you can the user_id column in Usermeta table refers the ID column from the User table.

I am in dire need of a MYSQL query which gives out the result in this manner -

```<code>ID user_email     billing_phone billing_postcode billing_address
1  abc@gmail.com  9876443100    670001           Somewhere here, Delhi
2  abc@gmail.com  9876345188    650021           7th Lane, Bangalore
3  1sf@gmail.com  7852562100    400521           Fancy Area, Mumbai
</code>```

I tried doing an UNION on two joins like this

```<code>SELECT 6ft_users.ID, 6ft_usermeta.meta_value as PHONE_NUMBER
FROM 6ft_users
INNER JOIN 6ft_usermeta
ON 6ft_users.ID=6ft_usermeta.user_id
WHERE 6ft_usermeta.meta_key LIKE 'billing_phone'
UNION
SELECT 6ft_users.ID, 6ft_usermeta.meta_value as POSTCODE
FROM 6ft_users
INNER JOIN 6ft_usermeta
ON 6ft_users.ID=6ft_usermeta.user_id
WHERE 6ft_usermeta.meta_key LIKE 'billing_postcode';
</code>```

But this is not helping as I get only one column - PHONE_NUMBER. I tried a few other things but to no avail. Please help me out.
Thanks in advance!

答:
Try this: </p>

```<code>SELECT U.ID,
       U.user_email,
       MAX(IF(UM.meta_key = 'billing_phone', UM.meta_value, '')) AS billing_phone,
       MAX(IF(UM.meta_key = 'billing_postcode', UM.meta_value, '')) AS billing_postcode,
       MAX(IF(UM.meta_key = 'billing_address', UM.meta_value, '')) AS billing_address
FROM 6ft_users U
LEFT JOIN 6ft_usermeta UM ON U.ID = UM.user_id
GROUP BY U.ID
</code>```

Body:
I am in need of generating a result which joins two user related tables - Users and Usermeta. These are from a Wordpress MySQL DB.

User Table -

ID user_email
1  abc@gmail.com
2  xyz@gmail.com
3  1sf@email.com

Usermeta Table -

Umeta_ID user_id meta_key          meta_value
1000     1       billing_phone     9876443100
1001     1       billing_postcode  670001
1002     1       billing_address   Somewhere here, Delhi
1003     2       billing_phone     9876345188
1004     2       billing_postcode  650021
1005     2       billing_address   7th Lane, Bangalore
1003     3       billing_phone     7852562100
1004     3       billing_postcode  400521
1005     3       billing_address   Fancy Area, Mumbai

As you can the user_id column in Usermeta table refers the ID column from the User table.

I am in dire need of a MYSQL query which gives out the result in this manner -

ID user_email     billing_phone billing_postcode billing_address
1  abc@gmail.com  9876443100    670001           Somewhere here, Delhi
2  abc@gmail.com  9876345188    650021           7th Lane, Bangalore
3  1sf@gmail.com  7852562100    400521           Fancy Area, Mumbai

I tried doing an UNION on two joins like this

SELECT 6ft_users.ID, 6ft_usermeta.meta_value as PHONE_NUMBER
FROM 6ft_users
INNER JOIN 6ft_usermeta
ON 6ft_users.ID=6ft_usermeta.user_id
WHERE 6ft_usermeta.meta_key LIKE 'billing_phone'
UNION
SELECT 6ft_users.ID, 6ft_usermeta.meta_value as POSTCODE
FROM 6ft_users
INNER JOIN 6ft_usermeta
ON 6ft_users.ID=6ft_usermeta.user_id
WHERE 6ft_usermeta.meta_key LIKE 'billing_postcode';

But this is not helping as I get only one column - PHONE_NUMBER. I tried a few other things but to no avail. Please help me out.
Thanks in advance!

Body:
Try this:

SELECT U.ID,
       U.user_email,
       MAX(IF(UM.meta_key = 'billing_phone', UM.meta_value, '')) AS billing_phone,
       MAX(IF(UM.meta_key = 'billing_postcode', UM.meta_value, '')) AS billing_postcode,
       MAX(IF(UM.meta_key = 'billing_address', UM.meta_value, '')) AS billing_address
FROM 6ft_users U
LEFT JOIN 6ft_usermeta UM ON U.ID = UM.user_id
GROUP BY U.ID


问:
loading gif image display another frame. use jquery

please look at the above html frame.

if i click menu on [Menu] frame,

then loading gif image will display [Load page] frame.

but gif image display only [Menu] frame......

$("#mmeload").click(function() {
  $('#loader').show();
  $setTimeout(function() {
    $('#loader').hide();
  }, 6500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.loader {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, .8)url('/images/default.gif') no-repeat 50%
}</code>```

<!DOCTYPE html>

    MME Info

```

if click menu, then show gif image, and hide after 6500 micro sec..

how can i displaying anohter page...?

i already use post, load function...

答:
Please check the following code and I guess your issue will be cleared.

$("#mmeload").click(function() {
  $('#loader').show();
  setTimeout(function() {
    $('#loader').hide();
  }, 6500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.loader {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, .8)url('/images/default.gif') no-repeat 50%
}</code>```

<!DOCTYPE html>

    MME Info

```

Body:
please look at the above html frame.

if i click menu on [Menu] frame,

then loading gif image will display [Load page] frame.

but gif image display only [Menu] frame......

$("#mmeload").click(function() {
  $('#loader').show();
  $setTimeout(function() {
    $('#loader').hide();
  }, 6500);
});

.loader {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, .8)url('/images/default.gif') no-repeat 50%
}

<!DOCTYPE html>

    MME Info

if click menu, then show gif image, and hide after 6500 micro sec..

how can i displaying anohter page...?

i already use post, load function...

Body:
Please check the following code and I guess your issue will be cleared.

$("#mmeload").click(function() {
  $('#loader').show();
  setTimeout(function() {
    $('#loader').hide();
  }, 6500);
});

.loader {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, .8)url('/images/default.gif') no-repeat 50%
}

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <div class="dTree">
    <div class="loader" id="loader" style="display:none"></div>
    <a href="setup/mmeContextView.php" id="mmeload" target="view">MME Info</a>
  </div>
</body>

</html>


问:
React-bootstrap-router LinkContainer doesn't route anywhere
I use react-bootstrap-router where I want to link to /logout which logs out the user and routes them to the front-page(automatically, from the backend). I simply need to make what is essentially a href to it.

But LinkContainer doesnt appear to work?

Here's my sourcecode:

```<code>import { LinkContainer } from 'react-router-bootstrap';

<Dropdown id="dropdown-custom-1">
    <Dropdown.Toggle>
        <Glyphicon glyph="cog" />
    </Dropdown.Toggle>
    <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
        <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}
            </div>
        </MenuItem>
        <MenuItem divider />
        <LinkContainer to="/logout" activeClassName="active"> // It doesn't do anythign here?
            <MenuItem className="u-graph-text">
                log out
            </MenuItem>
        </LinkContainer>
    </Dropdown.Menu>
</Dropdown>
</code>```

Nothing changes in the URL of the browser.

答:
You can try to use Link instead of LinkContainer or try to update to the latest version of react-router-bootstrap  because I think there is some version compatibility issues here and earlier versions of LinkContainer were not compatible with MenuItem.

```<code>import { Link } from 'react-router';

<Dropdown id="dropdown-custom-1">
    <Dropdown.Toggle>
        <Glyphicon glyph="cog" />
    </Dropdown.Toggle>
    <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
        <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}
            </div>
        </MenuItem>
        <MenuItem divider />

            <MenuItem className="u-graph-text">
                <Link to="/logout">log out</Link>
            </MenuItem>
    </Dropdown.Menu>
</Dropdown>
</code>```

Body:
I use react-bootstrap-router where I want to link to /logout which logs out the user and routes them to the front-page(automatically, from the backend). I simply need to make what is essentially a href to it.

But LinkContainer doesnt appear to work?

Here's my sourcecode:

import { LinkContainer } from 'react-router-bootstrap';

<Dropdown id="dropdown-custom-1">
    <Dropdown.Toggle>
        <Glyphicon glyph="cog" />
    </Dropdown.Toggle>
    <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
        <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}

        </MenuItem>
        <MenuItem divider />
        <LinkContainer to="/logout" activeClassName="active"> // It doesn't do anythign here?
            <MenuItem className="u-graph-text">
                log out
            </MenuItem>
        </LinkContainer>
    </Dropdown.Menu>
</Dropdown>

Nothing changes in the URL of the browser.

Body:
You can try to use Link instead of LinkContainer or try to update to the latest version of react-router-bootstrap  because I think there is some version compatibility issues here and earlier versions of LinkContainer were not compatible with MenuItem.

import { Link } from 'react-router';

<Dropdown id="dropdown-custom-1">
    <Dropdown.Toggle>
        <Glyphicon glyph="cog" />
    </Dropdown.Toggle>
    <Dropdown.Menu style={{textAlign: "left", right: "0", left: "auto"}}>
        <MenuItem className='disabled u-graph-text'>
            <Glyphicon glyph="user" style={{paddingRight: "10px"}}/>
            {this.state.data.username}
            </div>
        </MenuItem>
        <MenuItem divider />

            <MenuItem className="u-graph-text">
                <Link to="/logout">log out</Link>
            </MenuItem>
    </Dropdown.Menu>
</Dropdown>


问:
Get number of sets in array
```<code>Sub test()
    Dim Relevant_Sheets As Variant
    Set Relevant_Sheets = Sheets(Array("btw.facturen", "btw.filelist", "btw.controle", "intervat", "voorblad", "medecontractanten", "Vak 01", "Vak 03", "Vak 45", "Vak 54", "Vak 55", "Vak 56", "Vak 59", "Vak 81", "Vak 82", "Vak 83", "Vak 84", "Vak 85", "Vak 86", "Vak 88"))
    Number_of_Relevant_Sheets = 20
End Sub
</code>```

This is an extract of my code. Relevant_Sheets gets used multiple times afterwards, and I use it so that I only have to set which pages to use once.

I would like Number_of_Relevant_Sheets to count the number of sheets in Relevant_Sheets (in this case 20), so that I don't have to manually change it when I add or remove a sheet from the list.

If anyone could point me in the right direction?

答:
Maybe I went a little "overkill" here, but I would go with something like the code below (so you can use all variables and objects later in your code):</p>

```<code>Option Explicit

Sub test()

    Dim Relevant_Sheet()    As Worksheet
    Dim SheetNameArr        As Variant
    Dim Number_of_Relevant_Sheets As Long
    Dim i As Long

    SheetNameArr = Array("btw.facturen", "btw.filelist", "btw.controle", "intervat", "voorblad", "medecontractanten", "Vak 01", "Vak 03", "Vak 45", "Vak 54", "Vak 55", "Vak 56", "Vak 59", "Vak 81", "Vak 82", "Vak 83", "Vak 84", "Vak 85", "Vak 86", "Vak 88")
    Number_of_Relevant_Sheets = UBound(SheetNameArr) + 1 '<-- add 1 because the array start at 0
    ReDim Relevant_Sheet(0 To UBound(SheetNameArr)) ' <-- resize worksheet array

    For i = 0 To UBound(SheetNameArr) ' <-- loop though all elements in the array, and set the relevant sheet
        Set Relevant_Sheet(i) = Sheets(SheetNameArr(i))
    Next i

End Sub
</code>```

Title: Get number of sets in array

Body:
Sub test()
    Dim Relevant_Sheets As Variant
    Set Relevant_Sheets = Sheets(Array("btw.facturen", "btw.filelist", "btw.controle", "intervat", "voorblad", "medecontractanten", "Vak 01", "Vak 03", "Vak 45", "Vak 54", "Vak 55", "Vak 56", "Vak 59", "Vak 81", "Vak 82", "Vak 83", "Vak 84", "Vak 85", "Vak 86", "Vak 88"))
    Number_of_Relevant_Sheets = 20
End Sub

This is an extract of my code. Relevant_Sheets gets used multiple times afterwards, and I use it so that I only have to set which pages to use once.

I would like Number_of_Relevant_Sheets to count the number of sheets in Relevant_Sheets (in this case 20), so that I don't have to manually change it when I add or remove a sheet from the list.

If anyone could point me in the right direction?

Body:
Maybe I went a little "overkill" here, but I would go with something like the code below (so you can use all variables and objects later in your code):

Option Explicit

Sub test()

    Dim Relevant_Sheet()    As Worksheet
    Dim SheetNameArr        As Variant
    Dim Number_of_Relevant_Sheets As Long
    Dim i As Long

    SheetNameArr = Array("btw.facturen", "btw.filelist", "btw.controle", "intervat", "voorblad", "medecontractanten", "Vak 01", "Vak 03", "Vak 45", "Vak 54", "Vak 55", "Vak 56", "Vak 59", "Vak 81", "Vak 82", "Vak 83", "Vak 84", "Vak 85", "Vak 86", "Vak 88")
    Number_of_Relevant_Sheets = UBound(SheetNameArr) + 1 '<-- add 1 because the array start at 0
    ReDim Relevant_Sheet(0 To UBound(SheetNameArr)) ' <-- resize worksheet array

    For i = 0 To UBound(SheetNameArr) ' <-- loop though all elements in the array, and set the relevant sheet
        Set Relevant_Sheet(i) = Sheets(SheetNameArr(i))
    Next i

End Sub


问:
Reversing single linked list
I tried to revert single linkied list as follows:

```<code>public class MutableLst<T> {
    public T current;
    public MutableLst<T> next;

    private MutableLst(T current){
        this.current = current;
    }

    public static <T> MutableLst<T> create(T current){
        return new MutableLst<T>(current);
    }

    public void reverse(){
        MutableLst<T> newNext = null;
        MutableLst<T> nxt = next;
        next = newNext;
        while(nxt != null) {
            newNext = this;  //<------- cycle is here
            current = nxt.current;
            next = newNext;
            nxt = nxt.next;
        }
    }
</code>```

But this implementation does not work. When I assign to this I got a cycle. How to fix it?

答:
You are reversing only the list, so I don't know why do you want to do something with "this" object. Anyway I think you should just use this:
https://www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/api/list/MutableList.html#reverseThis--</p>

Title: Reversing single linked list

Body:
I tried to revert single linkied list as follows:

public class MutableLst<T> {
    public T current;
    public MutableLst<T> next;

    private MutableLst(T current){
        this.current = current;
    }

    public static <T> MutableLst<T> create(T current){
        return new MutableLst<T>(current);
    }

    public void reverse(){
        MutableLst<T> newNext = null;
        MutableLst<T> nxt = next;
        next = newNext;
        while(nxt != null) {
            newNext = this;  //<------- cycle is here
            current = nxt.current;
            next = newNext;
            nxt = nxt.next;
        }
    }

But this implementation does not work. When I assign to this I got a cycle. How to fix it?


问:
javascript: how to judge a function name exists?
Is it possible to judge if a function names exists before calling it?</p>

答:
You an check typeof for the function, for example:

```<code>if(typeof this["functionName"] != "undefined") {
  alert("uh oh, doesn't exist");
}
</code>```

If you need to check if it exists and is a function to be extra sure:

```<code>if(typeof this["functionName"] == "function") {
  this["functionName"](); //it exists, call it
}
</code>```

Or the more relaxed version:

```<code>if(this["functionName"]) this["functionName"]();
</code>```

If the name doesn't change (e.g. I misinterpreted the question) just use dot notation, like this:

```<code>if(this.functionName) this.functionName();
</code>```

Or course it doesn't have to be this...whatever object you're checking on, use that, if it's a global function use window.

Body:
You an check typeof for the function, for example:

if(typeof this["functionName"] != "undefined") {
  alert("uh oh, doesn't exist");
}

If you need to check if it exists and is a function to be extra sure:

if(typeof this["functionName"] == "function") {
  this["functionName"](); //it exists, call it
}

Or the more relaxed version:

if(this["functionName"]) this["functionName"]();

If the name doesn't change (e.g. I misinterpreted the question) just use dot notation, like this:

if(this.functionName) this.functionName();

Or course it doesn't have to be this...whatever object you're checking on, use that, if it's a global function use window.