问:
Importing functions from in the same file as declared
I would like to place a function at the end of a script which is used in the script. This, of course, does not work as the function is not known yet.
Can I therefore import this funtion in the same script?

If I do it like the following, I get the error " ImportError: cannot import name:'subfunction' "

```<code>from the_script_in_use import subfuction

a=subfunction(b)

def subfunction(value)
    do something
    return a
</code>```

答:
You may use the statement :

```<code>if __name__ == '__main__':
</code>```

Which will be executed if you run this file as a script. In your case:

```<code>def main_function()
    a=subfunction(b)

def subfunction(value)
    do something
    return a

if __name__ == '__main__':
    main_function()
</code>```

Note there is no need to import your function.
Doing so you can order your fonction the way you want.

Body:
I would like to place a function at the end of a script which is used in the script. This, of course, does not work as the function is not known yet.
Can I therefore import this funtion in the same script?

If I do it like the following, I get the error " ImportError: cannot import name:'subfunction' "

from the_script_in_use import subfuction

a=subfunction(b)

def subfunction(value)
    do something
    return a

Body:
You may use the statement :

if __name__ == '__main__':

Which will be executed if you run this file as a script. In your case:

def main_function()
    a=subfunction(b)

def subfunction(value)
    do something
    return a

if __name__ == '__main__':
    main_function()

Note there is no need to import your function.
Doing so you can order your fonction the way you want.


来源: stackexchange

问:
How can I make a checkbox readonly? not disabled?
I have a form where I have to post form values to my action class. In this form I have a checkbox that needs to be readonly. I tried setting disabled="true" but that doesn't work when posting to the action class.

So please advice??

答:
Through CSS:

```<code><label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>
</code>```

pointer-events not supported in IE<10

https://jsfiddle.net/fl4sh/3r0v8pug/2/

ContentLicense: CC BY-SA 3.0

Body:
Through CSS:

<label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>

pointer-events not supported in IE<10

https://jsfiddle.net/fl4sh/3r0v8pug/2/


问:
Format XMLGregorianCalendar in java
i have a date String which looks just like this.

2017-12-06T17:39:00Z

What i would like to do is to convert this String to XMLGregorianCalendar but using the same format.

What i do at the moment is:

```<code>String choosenDate = 2017-12-06T17:39:00Z;

GregorianCalendar c = new GregorianCalendar();

DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
TemporalAccessor accessor = timeFormatter.parse(dateChoisie);

Date date = Date.from(Instant.from(accessor));
c.setTime(date);
System.err.println("choosenDate: " + dateChoisie);
System.err.println("date : " + date);
XMLGregorianCalendar dateXMLGreg = null;
try
{
    dateXMLGreg = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    System.err.println("dateXMLGreg: " + dateXMLGreg);
}
catch (DatatypeConfigurationException e)
{
    messages.addMessage(new MessageBuilder().error().code("webservice.failure").build());
}
</code>```

which gives me the following output:

10:47:45,957 ERROR [stderr] (default task-47) choosenDate:
  2017-12-06T17:39:03Z

10:47:45,957 ERROR [stderr] (default task-47) date : Wed Dec 06
  18:39:03 CET 2017

10:47:45,958 ERROR [stderr] (default task-47) dateXMLGreg:
  2017-12-06T18:39:03.000+01:00

So how can i do so i have my XMLGregorianCalendar dateXMLGreg to look like:

2017-12-06T17:39:03Z

答:
like this.</p>

```<code>    private XMLGregorianCalendar change(String dateStr) {
    XMLGregorianCalendar xmlDate = null;

    try {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date date = format.parse(dateStr);

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
        System.out.println(xmlDate.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return xmlDate;
}
</code>```

Title: Format XMLGregorianCalendar in java

Body:
i have a date String which looks just like this.

2017-12-06T17:39:00Z

What i would like to do is to convert this String to XMLGregorianCalendar but using the same format.

What i do at the moment is:

String choosenDate = 2017-12-06T17:39:00Z;

GregorianCalendar c = new GregorianCalendar();

DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
TemporalAccessor accessor = timeFormatter.parse(dateChoisie);

Date date = Date.from(Instant.from(accessor));
c.setTime(date);
System.err.println("choosenDate: " + dateChoisie);
System.err.println("date : " + date);
XMLGregorianCalendar dateXMLGreg = null;
try
{
    dateXMLGreg = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    System.err.println("dateXMLGreg: " + dateXMLGreg);
}
catch (DatatypeConfigurationException e)
{
    messages.addMessage(new MessageBuilder().error().code("webservice.failure").build());
}

which gives me the following output:

10:47:45,957 ERROR [stderr] (default task-47) choosenDate:
  2017-12-06T17:39:03Z

10:47:45,957 ERROR [stderr] (default task-47) date : Wed Dec 06
  18:39:03 CET 2017

10:47:45,958 ERROR [stderr] (default task-47) dateXMLGreg:
  2017-12-06T18:39:03.000+01:00

So how can i do so i have my XMLGregorianCalendar dateXMLGreg to look like:

2017-12-06T17:39:03Z

Body:
like this.

    private XMLGregorianCalendar change(String dateStr) {
    XMLGregorianCalendar xmlDate = null;

    try {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date date = format.parse(dateStr);

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
        System.out.println(xmlDate.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return xmlDate;
}


问:
Draggable text elements with overflow (GSAP)
In the Codepen I am trying to make a draggable list of items that contain text. Each item must have overflow: auto so that the content can scroll. However, on touch devices in Chrome the pointer event gets caught in the item and it does not drag smoothly.

To replicate, launch in Chrome and enter responsive mode via dev tools. Dragging in between the elements works as expected, but dragging on the elements does not work correctly.

I have tried various draggable options and also laying out without flexbox, but none seem to work. I have also tried toggling a dragging/not-dragging css class that sets overflow:hidden / auto , but that does not have the required effect.

https://codepen.io/motionimaging/pen/efbf92943645bf108e720c9b7b640abd#0

答:
Thanks to @jack for the answer. More details are here: https://greensock.com/forums/topic/17546-draggable-text-elements-with-overflow/

This does seem to be a browser bug. In my case I fixed it using

```<code>.item {
  touch-action: pan-y;
}
</code>```

As using touch-action: none; results in not being able to scroll the content. pan-y limits the movement to the y-axis only, meaning you can drag left to right unhindered.

Body:
Thanks to @jack for the answer. More details are here: https://greensock.com/forums/topic/17546-draggable-text-elements-with-overflow/

This does seem to be a browser bug. In my case I fixed it using

.item {
  touch-action: pan-y;
}

As using touch-action: none; results in not being able to scroll the content. pan-y limits the movement to the y-axis only, meaning you can drag left to right unhindered.


问:
Angular2 + Jasmine Event Object
I have this simple method which needs to be tested:

```<code>  public onLayerContainerClick(event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    if (event.srcElement.classList.contains('dpm-info__layerContainer')) {
     this.closeInfoLayer(event);
    }
  }
</code>```

My objective is actually to increase code coverage for the component. If I test is like this:

```<code>  it( 'should close on info container click', () => {
    spyOn( component, 'onLayerContainerClick' );
    const el: DebugElement = fixture.debugElement.query( By.css( '.dpm-info__layerContainer' ) );
    el.triggerEventHandler( 'click', null );
    expect( component.onLayerContainerClick ).toHaveBeenCalled();
  } );
</code>```

the test is OK, but instanbul says "function not covered". So I guess, I need to call the function explicitly? To do that, I need to have a full event object, including (at least) srcTarget property. How do I define such an event within the unit test?

答:
You have to call the function with a mocked event in the test.
component.onLayerContainerClick({ srcElement: { value: 'mock_value' } });

And then write what you expect

expect( component.closeInfoLayer ).toHaveBeenCalled();

Maybe this https://angular.io/guide/testing#triggereventhandler might help as well

Title: Angular2 + Jasmine Event Object

Body:
I have this simple method which needs to be tested:

  public onLayerContainerClick(event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    if (event.srcElement.classList.contains('dpm-info__layerContainer')) {
     this.closeInfoLayer(event);
    }
  }

My objective is actually to increase code coverage for the component. If I test is like this:

  it( 'should close on info container click', () => {
    spyOn( component, 'onLayerContainerClick' );
    const el: DebugElement = fixture.debugElement.query( By.css( '.dpm-info__layerContainer' ) );
    el.triggerEventHandler( 'click', null );
    expect( component.onLayerContainerClick ).toHaveBeenCalled();
  } );

the test is OK, but instanbul says "function not covered". So I guess, I need to call the function explicitly? To do that, I need to have a full event object, including (at least) srcTarget property. How do I define such an event within the unit test?


问:
Temp procedure messes up collation
Issue:
i have a procedure (simplified), created by .NET application:

```<code>create procedure #SaveData
@InValue varchar(128)
as
begin
    insert into Production.TargetTable (PREFIX_Value) select @InValue
end
</code>```

Problem is, the database uses SQL_SLOVAK_CP1250_CI_AS collation.
TempDB uses default SQL_Latin1_General_CP1_CI_AS collation.

Problem simplified:

```<code>-- this doesnt work, returns RTC
create procedure #SaveData
@InValue varchar(128)
as
begin
    select @InValue
end

-- this doesnt work, returns RTC
create procedure #SaveData
@InValue varchar(128)
as
begin
    select @InValue collate SQL_SLOVAK_CP1250_CI_AS
end

-- this does work, returns ŘŤČ
create procedure SaveData
@InValue varchar(128)
as
begin
    select @InValue
end
</code>```

Which causes that instead for instead of test string ŘŤČ, RTC is saved.
When i remove the # from the Procedure name and dont create it as a temp procedure, everything works.

Now, one fix found to work, is to change the param type from varchar to nvarchar. But this would be a lot of work (many different procedures). Is there any global approach that could work?

Thank you and have a nice day

答:
The problem is in column collation. Any value passed to it will have its collation changed to column collation:

```<code>declare @table table(txt varchar(10) collate SQL_Latin1_General_CP1_CI_AS)
insert into @table values ('ŘŤČ' collate SQL_SLOVAK_CP1250_CI_AS)
--result will be changed, even with explicit collation
select * from @table
go

declare @table table(txt varchar(10) collate SQL_SLOVAK_CP1250_CI_AS)
insert into @table values ('ŘŤČ')
--correct output
select * from @table
go
</code>```

So you have to change collation in column:

```<code>alter table TABLE_NAME alter column TextCol varchar(...) collate SQL_SLOVAK_CP1250_CI_AS
</code>```

Title: Temp procedure messes up collation

Body:
Issue:
i have a procedure (simplified), created by .NET application:

create procedure #SaveData
@InValue varchar(128)
as
begin
    insert into Production.TargetTable (PREFIX_Value) select @InValue
end

Problem is, the database uses SQL_SLOVAK_CP1250_CI_AS collation.
TempDB uses default SQL_Latin1_General_CP1_CI_AS collation.

Problem simplified:

-- this doesnt work, returns RTC
create procedure #SaveData
@InValue varchar(128)
as
begin
    select @InValue
end

-- this doesnt work, returns RTC
create procedure #SaveData
@InValue varchar(128)
as
begin
    select @InValue collate SQL_SLOVAK_CP1250_CI_AS
end

-- this does work, returns ŘŤČ
create procedure SaveData
@InValue varchar(128)
as
begin
    select @InValue
end

Which causes that instead for instead of test string ŘŤČ, RTC is saved.
When i remove the # from the Procedure name and dont create it as a temp procedure, everything works.

Now, one fix found to work, is to change the param type from varchar to nvarchar. But this would be a lot of work (many different procedures). Is there any global approach that could work?

Thank you and have a nice day

Body:
The problem is in column collation. Any value passed to it will have its collation changed to column collation:

declare @table table(txt varchar(10) collate SQL_Latin1_General_CP1_CI_AS)
insert into @table values ('ŘŤČ' collate SQL_SLOVAK_CP1250_CI_AS)
--result will be changed, even with explicit collation
select * from @table
go

declare @table table(txt varchar(10) collate SQL_SLOVAK_CP1250_CI_AS)
insert into @table values ('ŘŤČ')
--correct output
select * from @table
go

So you have to change collation in column:

alter table TABLE_NAME alter column TextCol varchar(...) collate SQL_SLOVAK_CP1250_CI_AS


问:
What is the expected behavior when setting `security.oauth2.resource.jwk.key-set-uri` in spring boot
In spring boot, upon configuring a Resource server we have the option to set the security.oauth2.resource.jwk.key-set-uri property if the access tokens will be JWTs and the issuer provides an endpoint for clients to acquire the public RSA key for verification in JWK format.

What is the expected behavior to initiate a keystore from this JWK? The property is being loaded in the ResourceServerProperties.JWK but then what. Should spring boot call this URI and fetch the jwks then create a store for me to use in verification?

I am following this tutorial to setup the configuration of the keystore http://www.baeldung.com/spring-security-oauth-jwt

```<code>    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        Resource resource = new ClassPathResource("public.txt");
        String publicKey = null;
        try {
            publicKey = IOUtils.toString(resource.getInputStream());
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifierKey(publicKey);
        return converter;
    }
</code>```

But instead of loading a .pem public key I think I want to load it from a jwk.

答:
The main goal of this implementation would be to verify a JWT locally using the corresponding JWK(JSON WEB TOKEN KEY SET). The JWK used for verification is matched using the kid header parameter of the JWT and the kid attribute of the JWK.

The server can validate this token locally without making any network requests, talking to a database, etc. This can potentially make session management faster because instead of needing to load the user from a database (or cache) on every request, you just need to run a small bit of local code. This is probably the single biggest reason people like using JWTs: they are stateless.

Body:
In spring boot, upon configuring a Resource server we have the option to set the security.oauth2.resource.jwk.key-set-uri property if the access tokens will be JWTs and the issuer provides an endpoint for clients to acquire the public RSA key for verification in JWK format.

What is the expected behavior to initiate a keystore from this JWK? The property is being loaded in the ResourceServerProperties.JWK but then what. Should spring boot call this URI and fetch the jwks then create a store for me to use in verification?

I am following this tutorial to setup the configuration of the keystore http://www.baeldung.com/spring-security-oauth-jwt

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        Resource resource = new ClassPathResource("public.txt");
        String publicKey = null;
        try {
            publicKey = IOUtils.toString(resource.getInputStream());
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifierKey(publicKey);
        return converter;
    }

But instead of loading a .pem public key I think I want to load it from a jwk.


问:
error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR
I get the error error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR  with a simple class like this:

BLOCK.h

```<code>#pragma once
#include "helpful.h"

class WORLD;

class BLOCK
{
    public:
        short int type;

        void Render();

        BLOCK();
        ~BLOCK(void);
};
</code>```

BLOCK.cpp

```<code>#include "BLOCK.h"
#include "WORLD.h"

BLOCK::BLOCK(void)
{
}
void BLOCK::Render()
{
}
BLOCK::~BLOCK(void)
{
}
</code>```

But the BLOCK class is defined, no?

答: I found my mistake: The call to BLOCK's constructor was in another file, but the header for BLOCK wasn't included, all I had was class BLOCK;. Changed it instead to #include BLOCK.h, problem solved.

Body:
I get the error error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR  with a simple class like this:

BLOCK.h

#pragma once
#include "helpful.h"

class WORLD;

class BLOCK
{
    public:
        short int type;

        void Render();

        BLOCK();
        ~BLOCK(void);
};

BLOCK.cpp

#include "BLOCK.h"
#include "WORLD.h"

BLOCK::BLOCK(void)
{
}
void BLOCK::Render()
{
}
BLOCK::~BLOCK(void)
{
}

But the BLOCK class is defined, no?


问:
Azure Alert not triggered WebHook for Azure WebJobs
I'm trying to find what is wrong in my Template Deployment for Azure Alert. I want to Send Email and triggered a WebHook in Azure WebJobs with Basic Authentification.

```<code>{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {

  },
  "variables": {
  },
  "resources": [
    {
      "type": "Microsoft.Insights/alertRules",
      "name": "tesTalert",
      "location": "westeurope",
      "apiVersion": "2014-04-01",
      "properties": {
        "name": "test",
        "isEnabled": true,
      "condition": {
          "odata.type": "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition",
          "dataSource": {
              "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource",
              "operationName": "RunFinished",
              "status": "Failed",
              "subStatus": "FailedExecution"
          }
        },
        "action": {
        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction",
        "serviceUri": "https://$myUserName:MyPassWord@MyWebsite.scm.azurewebsites.net/api/triggeredwebjobs/WebJobName/run",
        "properties": {}
        }
      }
    }
  ]
}
</code>```

i have also try with this template with email and it's working but not for the webhook. Maybe the problem is from the api version , so i try different version. Nothing happend.

```<code>{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": { },
    "resources": [
        {
            "type": "microsoft.insights/alertrules",
            "name": "ADFAlertsSlice",
            "apiVersion": "2015-01-01",
            "location": "westeurope",
            "properties": {
                "name": "ADFAlertsSlice",
                "description": "One or more of the data slices for the Azure Data Factory has failed processing.",
                "isEnabled": true,
                "condition": {
                    "odata.type": "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition",
                    "dataSource": {
                        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource",
                        "operationName": "RunFinished",
                        "status": "Failed",
                        "subStatus": "FailedExecution"
                    }

                },
                "actions": [
                       {
                        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction",
                         "serviceUri": "https://$myUserName:MyPassWord@MyWebsite.scm.azurewebsites.net/api/triggeredwebjobs/WebJobName/run",
                        "properties": {}
                    },
                    {
                        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
                        "customEmails": [
                         "MyEmail@email.com"
                        ]
                    }
                ]
            }
        }
    ]
}
</code>```

I can't find what is wrong. thanks for your help.

答:
According to Microsoft docs, webhooks from metric alert rules can only use token authentication.

Authenticating the webhook
The webhook can authenticate using token-based authorization. The webhook URI is saved with a token ID, eg.

```<code>https://mysamplealert/webcallback?tokenid=sometokenid&someparameter=somevalue
</code>```

https://learn.microsoft.com/en-us/azure/monitoring-and-diagnostics/insights-webhooks-alerts
And if you scroll down to the comments other ahve the same issue as you do, they even started a feature request with MS.
https://feedback.azure.com/forums/602299-azure-alert-management/suggestions/19711606-enable-user-password-authentication-to-webhooks

Body:
I'm trying to find what is wrong in my Template Deployment for Azure Alert. I want to Send Email and triggered a WebHook in Azure WebJobs with Basic Authentification.

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {

  },
  "variables": {
  },
  "resources": [
    {
      "type": "Microsoft.Insights/alertRules",
      "name": "tesTalert",
      "location": "westeurope",
      "apiVersion": "2014-04-01",
      "properties": {
        "name": "test",
        "isEnabled": true,
      "condition": {
          "odata.type": "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition",
          "dataSource": {
              "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource",
              "operationName": "RunFinished",
              "status": "Failed",
              "subStatus": "FailedExecution"
          }
        },
        "action": {
        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction",
        "serviceUri": "https://$myUserName:MyPassWord@MyWebsite.scm.azurewebsites.net/api/triggeredwebjobs/WebJobName/run",
        "properties": {}
        }
      }
    }
  ]
}

i have also try with this template with email and it's working but not for the webhook. Maybe the problem is from the api version , so i try different version. Nothing happend.

{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": { },
    "resources": [
        {
            "type": "microsoft.insights/alertrules",
            "name": "ADFAlertsSlice",
            "apiVersion": "2015-01-01",
            "location": "westeurope",
            "properties": {
                "name": "ADFAlertsSlice",
                "description": "One or more of the data slices for the Azure Data Factory has failed processing.",
                "isEnabled": true,
                "condition": {
                    "odata.type": "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition",
                    "dataSource": {
                        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource",
                        "operationName": "RunFinished",
                        "status": "Failed",
                        "subStatus": "FailedExecution"
                    }

                },
                "actions": [
                       {
                        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction",
                         "serviceUri": "https://$myUserName:MyPassWord@MyWebsite.scm.azurewebsites.net/api/triggeredwebjobs/WebJobName/run",
                        "properties": {}
                    },
                    {
                        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
                        "customEmails": [
                         "MyEmail@email.com"
                        ]
                    }
                ]
            }
        }
    ]
}

I can't find what is wrong. thanks for your help.

Body:
According to Microsoft docs, webhooks from metric alert rules can only use token authentication.

Authenticating the webhook
The webhook can authenticate using token-based authorization. The webhook URI is saved with a token ID, eg.

https://mysamplealert/webcallback?tokenid=sometokenid&someparameter=somevalue

https://learn.microsoft.com/en-us/azure/monitoring-and-diagnostics/insights-webhooks-alerts
And if you scroll down to the comments other ahve the same issue as you do, they even started a feature request with MS.
https://feedback.azure.com/forums/602299-azure-alert-management/suggestions/19711606-enable-user-password-authentication-to-webhooks


问:
Node.js issues with exporting functions
I have a few questions about the nature of exporting functions in NodeJS:

Firstly this is an acceptable way to export a function:

```<code>exports.bread = function bread() {
  return 'bread: 2';
};
</code>```

However, it is not possible (maybe?) to export a function using this method:

```<code>function pullData(pair) {
  console.log(pair);
}

module.exports = pullData;
</code>```

The only problem with this second method is that the function is not hoisted and limits its' use elsewhere?

Another method for exporting variables is to include the variables within an object and export that object. However, in this case, the functions within the module have a limited scope...

So is there any easy way to export declarative functions and use them, or is doing so not something I should strive to achieve?

Screenshots from project:

答:
Try putting pullData in curly brackets:

```<code>module.exports = {pullData}
</code>```

and when you require it, do this:

```<code>const {pullData} = require("./getTicker");
</code>```

Hope it'll work.

Title: Node.js issues with exporting functions

Body:
I have a few questions about the nature of exporting functions in NodeJS:

Firstly this is an acceptable way to export a function:

exports.bread = function bread() {
  return 'bread: 2';
};

However, it is not possible (maybe?) to export a function using this method:

function pullData(pair) {
  console.log(pair);
}

module.exports = pullData;

The only problem with this second method is that the function is not hoisted and limits its' use elsewhere?

Another method for exporting variables is to include the variables within an object and export that object. However, in this case, the functions within the module have a limited scope...

So is there any easy way to export declarative functions and use them, or is doing so not something I should strive to achieve?

Screenshots from project:

Body:
Try putting pullData in curly brackets:

module.exports = {pullData}

and when you require it, do this:

const {pullData} = require("./getTicker");

Hope it'll work.


问:
Window BAT - Loop Exit Without Continue
I am try to loop all the source file in array and make sure it is exits in the folder with the file path I have set, below is my code

```<code>@echo OFF

setlocal EnableExtensions EnableDelayedExpansion
set "string_list=A.txt B.txt C.txt D.txt"

set count=0
For %%j in (%string_list%) Do Set /A count+=1
rem echo.Total count: %count%

set current_count=0
REM for %%s in (%string_list%) do (
for %%s in (%string_list%) do (
set "var=C:\Users\ABC\Desktop\TESTING\%%s"
rem echo "!var!"

:START
if not exist "!var!" GOTO WAIT
GOTO COPY

:WAIT
timeout 5
ECHO "MISSING !var!, WAITING SOURCE FILE TO LOAD IN"
GOTO START

:COPY
ECHO "!var! FILES IS AVAIALBLE"

set /A current_count+=1
if /I %current_count%==%count% (
    echo "ALL THE FILE IS IS AVAILABLE"
) else (
    echo "CONTINUE CHECK FOR OTHER FILE"
)
)
rem echo %current_count%
pause
</code>```

It will exit the loop once it found the first file. The code is to check and make sure all the files are in the folder, if one of the file is not there then continue loop until the file is there.

I am not sure can the function add in the FOR loop.

I'm expecting this:

C:\Users\ABC\Desktop\TESTING\A.txt FILES IS AVAILABLE <- A.txt is in the folder

Waiting for 0 seconds, press a key to continue ...

But I'm getting this:

MISSING C:\Users\ABC\Desktop\TESTING\B.txt, WAITING SOURCE FILE TO LOAD IN <- B.txt is not in the folder for the first time.

C:\Users\ABC\Desktop\TESTING\B.txt FILES IS AVAIALBLE <- B.txt is in the folder for the second loop

C:\Users\ABC\Desktop\TESTING\C.txt FILES IS AVAIALBLE <- C.txt is in the folder

C:\Users\ABC\Desktop\TESTING\D.txt FILES IS AVAIALBLE <- D.txt is in the folder

The loop should only exit if all the files are in the folder, or else it will continue loop.

答:
as I said in comment goto breaks for loop please refer

Batch script for loop not working

use subroutine to get what you want. I have modified following script and it works for you case :

```<code>@echo OFF

setlocal EnableExtensions EnableDelayedExpansion
set string_list=A.txt B.txt C.txt D.txt
set count=0
For %%j in (%string_list%) Do Set /A count+=1
echo.Total count: %count%
set current_count=0
FOR %%s in (%string_list%) DO call :workProc %%s
exit /b
:workProc
set "var=%1"
echo "hey"
echo "!var!"
:START
if not exist !var! GOTO WAIT
GOTO COPY
:WAIT
timeout 5
ECHO "MISSING !var!, WAITING SOURCE FILE TO LOAD IN"
GOTO START
:COPY
ECHO "!var! FILES IS AVAIALBLE"
set /A current_count+=1
if /I %current_count%==%count% (
    echo "ALL THE FILE IS IS AVAILABLE"
) else (
    echo "CONTINUE CHECK FOR OTHER FILE"
    pause )
)
exit /b
rem echo %current_count%
</code>```

Title: Window BAT - Loop Exit Without Continue

Body:
I am try to loop all the source file in array and make sure it is exits in the folder with the file path I have set, below is my code

@echo OFF

setlocal EnableExtensions EnableDelayedExpansion
set "string_list=A.txt B.txt C.txt D.txt"

set count=0
For %%j in (%string_list%) Do Set /A count+=1
rem echo.Total count: %count%

set current_count=0
REM for %%s in (%string_list%) do (
for %%s in (%string_list%) do (
set "var=C:\Users\ABC\Desktop\TESTING\%%s"
rem echo "!var!"

:START
if not exist "!var!" GOTO WAIT
GOTO COPY

:WAIT
timeout 5
ECHO "MISSING !var!, WAITING SOURCE FILE TO LOAD IN"
GOTO START

:COPY
ECHO "!var! FILES IS AVAIALBLE"

set /A current_count+=1
if /I %current_count%==%count% (
    echo "ALL THE FILE IS IS AVAILABLE"
) else (
    echo "CONTINUE CHECK FOR OTHER FILE"
)
)
rem echo %current_count%
pause

It will exit the loop once it found the first file. The code is to check and make sure all the files are in the folder, if one of the file is not there then continue loop until the file is there.

I am not sure can the function add in the FOR loop.

I'm expecting this:

C:\Users\ABC\Desktop\TESTING\A.txt FILES IS AVAILABLE <- A.txt is in the folder

Waiting for 0 seconds, press a key to continue ...

But I'm getting this:

MISSING C:\Users\ABC\Desktop\TESTING\B.txt, WAITING SOURCE FILE TO LOAD IN <- B.txt is not in the folder for the first time.

C:\Users\ABC\Desktop\TESTING\B.txt FILES IS AVAIALBLE <- B.txt is in the folder for the second loop

C:\Users\ABC\Desktop\TESTING\C.txt FILES IS AVAIALBLE <- C.txt is in the folder

C:\Users\ABC\Desktop\TESTING\D.txt FILES IS AVAIALBLE <- D.txt is in the folder

The loop should only exit if all the files are in the folder, or else it will continue loop.

Body:
as I said in comment goto breaks for loop please refer

Batch script for loop not working

use subroutine to get what you want. I have modified following script and it works for you case :

@echo OFF

setlocal EnableExtensions EnableDelayedExpansion
set string_list=A.txt B.txt C.txt D.txt
set count=0
For %%j in (%string_list%) Do Set /A count+=1
echo.Total count: %count%
set current_count=0
FOR %%s in (%string_list%) DO call :workProc %%s
exit /b
:workProc
set "var=%1"
echo "hey"
echo "!var!"
:START
if not exist !var! GOTO WAIT
GOTO COPY
:WAIT
timeout 5
ECHO "MISSING !var!, WAITING SOURCE FILE TO LOAD IN"
GOTO START
:COPY
ECHO "!var! FILES IS AVAIALBLE"
set /A current_count+=1
if /I %current_count%==%count% (
    echo "ALL THE FILE IS IS AVAILABLE"
) else (
    echo "CONTINUE CHECK FOR OTHER FILE"
    pause )
)
exit /b
rem echo %current_count%


问:
Error using boolean results in new method - expects string, found boolean
I have created some methods in Java to test the results of a string based on length, characters and digits. However I also need to create a new method to check all those results and produce a boolean result based on if they were all true. But I'm not sure I'm calling the other methods correctly within my IF/ELSE loop and when I compile I'm getting an error stating that it's expecting a String result, but found Boolean. Any ideas where I'm going wrong?

The code for the new method is currently:

```<code>public boolean isValidAccountNum(String s)
{
  if ( isValidLength(true) && isValidStart(true) && hasValidDigits(true) ){
        return true;
     } else
     {
        return false;
     }
}
</code>```

The other methods are:

```<code>public boolean isValidLength(String s)
{
  accountNum = s;
  int accountInt = s.length();

  if(accountInt == 6){
     return true;
  }
  else {
     return false;
  }
}

public boolean isValidStart(String s)
{
  if(Character.isUpperCase(s.charAt(0))){
     return true;
  }
  else {
     return false;
  }
}

public boolean hasValidDigits(String s)
{
  for (int i = 0; i < s.length(); i++) {
     if (Character.isLetter(s.charAt(i))){
        return false;
     } else
     {
        return true;
     }
  }
}
</code>```

答:
isValidLength(true) && isValidStart(true) && hasValidDigits(true), these methods have no boolean in their parameters.

The answer of the question is:

Changing this:

```<code>if(isValidLength(true) && isValidStart(true) && hasValidDigits(true)) {}
</code>```

To this:

```<code>if(isValidLength(s) && isValidStart(s) && hasValidDigits(s)) {}
</code>```

or

```<code>return isValidLength(s) && isValidStart(s) && hasValidDigits(s);
</code>```

Body:
I have created some methods in Java to test the results of a string based on length, characters and digits. However I also need to create a new method to check all those results and produce a boolean result based on if they were all true. But I'm not sure I'm calling the other methods correctly within my IF/ELSE loop and when I compile I'm getting an error stating that it's expecting a String result, but found Boolean. Any ideas where I'm going wrong?

The code for the new method is currently:

public boolean isValidAccountNum(String s)
{
  if ( isValidLength(true) && isValidStart(true) && hasValidDigits(true) ){
        return true;
     } else
     {
        return false;
     }
}

The other methods are:

public boolean isValidLength(String s)
{
  accountNum = s;
  int accountInt = s.length();

  if(accountInt == 6){
     return true;
  }
  else {
     return false;
  }
}

public boolean isValidStart(String s)
{
  if(Character.isUpperCase(s.charAt(0))){
     return true;
  }
  else {
     return false;
  }
}

public boolean hasValidDigits(String s)
{
  for (int i = 0; i < s.length(); i++) {
     if (Character.isLetter(s.charAt(i))){
        return false;
     } else
     {
        return true;
     }
  }
}

Body:
isValidLength(true) && isValidStart(true) && hasValidDigits(true), these methods have no boolean in their parameters.

The answer of the question is:

Changing this:

if(isValidLength(true) && isValidStart(true) && hasValidDigits(true)) {}

To this:

if(isValidLength(s) && isValidStart(s) && hasValidDigits(s)) {}

or

return isValidLength(s) && isValidStart(s) && hasValidDigits(s);


问:
svn 1.7 error E200009 Could not add all targets because some targets are already versioned
I did a clean checkout of a repository then every day I have an hudson job that runs a script to backup the configuration. Part of the script is to add *.xml

```<code>$ svn add *.xml
svn: warning: W150002: '/data/hudson/config.xml' is already under version control
svn: E200009: Could not add all targets because some targets are already versioned
svn: E200009: Illegal target for the requested operation
</code>```

The warning is fine because some of the xml files are already under version control but I don't understand why I get the E200009 error. If there is nothing to add, there should be no error.

答: svn add something --force will solve the error E200009. In your case, svn add *.xml --force will solve your problem

Body:
I did a clean checkout of a repository then every day I have an hudson job that runs a script to backup the configuration. Part of the script is to add *.xml

$ svn add *.xml
svn: warning: W150002: '/data/hudson/config.xml' is already under version control
svn: E200009: Could not add all targets because some targets are already versioned
svn: E200009: Illegal target for the requested operation

The warning is fine because some of the xml files are already under version control but I don't understand why I get the E200009 error. If there is nothing to add, there should be no error.


问:
Add subtitle under the title in navigation bar controller in Xcode
So I'm wanting to add a "subtitle" under the title in the navigation bar in navigation controller.

Mostly everything I look up so far wants me to use CGRect. I don't know a whole lot what that is and it sounds like its wanting me to create an entire new view which is not what I am wanting to do.

My question is, is there a dot method to adding a subtitle view easily?

The closest thing I found was posted on stack overflow and here is the link:

Create a subtitle in navigationbar

Apparently last year this worked but now I am getting errors and it's in my viewDidLoad...

I tried this:

self.navigationController?.navigationItem.prompt = "Subtitle Here"

It's the only thing that won't show any errors but still doesn't work. It literally does nothing. At least nothing visible at run time.

On a side note, swift is preferred. Thanks!

答:
Another solution, using only one label and NSAttributedString to differentiate between title and subtitle (with different font sizes, weights, colors, etc.) instead. Removes the problem of different label alignment.

```<code>extension UIViewController {
    func setTitle(_ title: String, subtitle: String) {
        let rect = CGRect(x: 0, y: 0, width: 400, height: 50)
        let titleSize: CGFloat = 20     // adjust as needed
        let subtitleSize: CGFloat = 15

        let label = UILabel(frame: rect)
        label.backgroundColor = .clear
        label.numberOfLines = 2
        label.textAlignment = .center
        label.textColor = .black

        let text = NSMutableAttributedString()
        text.append(NSAttributedString(string: title, attributes: [.font : UIFont.boldSystemFont(ofSize: titleSize)]))
        text.append(NSAttributedString(string: "\n\(subtitle)", attributes: [.font : UIFont.systemFont(ofSize: subtitleSize)]))
        label.attributedText = text
        self.navigationItem.titleView = label
    }
}
</code>```

Custom titleView based in part on https://stackoverflow.com/a/34298491/3918865

ContentLicense: CC BY-SA 4.0

Body:
Another solution, using only one label and NSAttributedString to differentiate between title and subtitle (with different font sizes, weights, colors, etc.) instead. Removes the problem of different label alignment.

extension UIViewController {
    func setTitle(_ title: String, subtitle: String) {
        let rect = CGRect(x: 0, y: 0, width: 400, height: 50)
        let titleSize: CGFloat = 20     // adjust as needed
        let subtitleSize: CGFloat = 15

        let label = UILabel(frame: rect)
        label.backgroundColor = .clear
        label.numberOfLines = 2
        label.textAlignment = .center
        label.textColor = .black

        let text = NSMutableAttributedString()
        text.append(NSAttributedString(string: title, attributes: [.font : UIFont.boldSystemFont(ofSize: titleSize)]))
        text.append(NSAttributedString(string: "\n\(subtitle)", attributes: [.font : UIFont.systemFont(ofSize: subtitleSize)]))
        label.attributedText = text
        self.navigationItem.titleView = label
    }
}

Custom titleView based in part on https://stackoverflow.com/a/34298491/3918865


问:
How to resolve "Error: No provider for AngularFireDatabase"
I'm trying to build a proto chat application using Angular & Firebase.

the foll are my routes:

```<code>export const appRoutes: Routes = [
    { path: 'signup', component: SignupFormComponent },
    { path: 'login', component: LoginFormComponent },
    { path: 'chat', component: ChatroomComponent },
    { path: '', redirectTo: '/login', pathMatch: 'full'},
];
</code>```

But when i route to /chat, i get the foll error. I'm not sure what is it that i am missing here in order to fix this error. any guidance is appreciated.

I have looked at the foll link, but i have included all the import stated in the answers:
No provider for AngularFireDatabase, AngularFireAuth

```<code>ERROR Error: Uncaught (in promise): Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!
Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!
</code>```

the foll is my chat-service.ts file:

```<code>import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../services/auth.service';
import * as firebase from 'firebase/app';

import { ChatMessage } from '../models/chat-message.model';

@Injectable()
export class ChatService {
  user: firebase.User;
  chatMessages: FirebaseListObservable<ChatMessage[]>;
  chatMessage: ChatMessage;
  userName: Observable<string>;

  constructor(
    private db: AngularFireDatabase,
    private afAuth: AngularFireAuth
    ) {
        /*this.afAuth.authState.subscribe(auth => {
          if (auth !== undefined && auth !== null) {
            this.user = auth; // the user object is only going to be set if we are authenticated
          }

        });*/
    }

   sendMessage(msg: string) { //per all the properties defined in the chat-message model
    const timestamp = this.getTimeStamp();
  //  const email = this.user.email;
    const email = "test@gmail.com";
    this.chatMessages = this.getMessages();
    this.chatMessages.push({
      message: msg,
      timeSent: timestamp,
      //userName: this.userName,
      userName: "test-user",
      email: email });

      console.log('called send');
  }

  getMessages(): FirebaseListObservable<ChatMessage[]> {
    // query to create our message feed binding
    return this.db.list('messages', {
      query: {
        limitToLast: 25,
        orderByKey: true
      }
    });
  }

  getTimeStamp() {
    const now = new Date();
    const date = now.getUTCFullYear() + '/' +
                 (now.getUTCMonth() + 1) + '/' +
                 now.getUTCDate();
    const time = now.getUTCHours() + ':' +
                 now.getUTCMinutes() + ':' +
                 now.getUTCSeconds();

    return (date + ' ' + time);
  }
}
</code>```

the foll is my app.module.ts file:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AppComponent } from './app.component';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';

import { appRoutes } from '../routes';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    ChatFormComponent,
    ChatroomComponent,
    FeedComponent,
    MessageComponent,
    LoginFormComponent,
    SignupFormComponent,
    NavbarComponent,
    UserListComponent,
    UserItemComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    AngularFireModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebase),

  ],
  providers: [AuthService, ChatService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
add in app.module.ts

import { AngularFireDatabase } from 'angularfire2/database-deprecated';

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AppComponent } from './app.component';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';

import { appRoutes } from '../routes';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    ChatFormComponent,
    ChatroomComponent,
    FeedComponent,
    MessageComponent,
    LoginFormComponent,
    SignupFormComponent,
    NavbarComponent,
    UserListComponent,
    UserItemComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    AngularFireModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebase),

  ],
  providers: [AuthService, ChatService,AngularFireDatabase],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Body:
I'm trying to build a proto chat application using Angular & Firebase.

the foll are my routes:

export const appRoutes: Routes = [
    { path: 'signup', component: SignupFormComponent },
    { path: 'login', component: LoginFormComponent },
    { path: 'chat', component: ChatroomComponent },
    { path: '', redirectTo: '/login', pathMatch: 'full'},
];

But when i route to /chat, i get the foll error. I'm not sure what is it that i am missing here in order to fix this error. any guidance is appreciated.

I have looked at the foll link, but i have included all the import stated in the answers:
No provider for AngularFireDatabase, AngularFireAuth

ERROR Error: Uncaught (in promise): Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!
Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!

the foll is my chat-service.ts file:

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../services/auth.service';
import * as firebase from 'firebase/app';

import { ChatMessage } from '../models/chat-message.model';

@Injectable()
export class ChatService {
  user: firebase.User;
  chatMessages: FirebaseListObservable<ChatMessage[]>;
  chatMessage: ChatMessage;
  userName: Observable<string>;

  constructor(
    private db: AngularFireDatabase,
    private afAuth: AngularFireAuth
    ) {
        /*this.afAuth.authState.subscribe(auth => {
          if (auth !== undefined && auth !== null) {
            this.user = auth; // the user object is only going to be set if we are authenticated
          }

        });*/
    }

   sendMessage(msg: string) { //per all the properties defined in the chat-message model
    const timestamp = this.getTimeStamp();
  //  const email = this.user.email;
    const email = "test@gmail.com";
    this.chatMessages = this.getMessages();
    this.chatMessages.push({
      message: msg,
      timeSent: timestamp,
      //userName: this.userName,
      userName: "test-user",
      email: email });

      console.log('called send');
  }

  getMessages(): FirebaseListObservable<ChatMessage[]> {
    // query to create our message feed binding
    return this.db.list('messages', {
      query: {
        limitToLast: 25,
        orderByKey: true
      }
    });
  }

  getTimeStamp() {
    const now = new Date();
    const date = now.getUTCFullYear() + '/' +
                 (now.getUTCMonth() + 1) + '/' +
                 now.getUTCDate();
    const time = now.getUTCHours() + ':' +
                 now.getUTCMinutes() + ':' +
                 now.getUTCSeconds();

    return (date + ' ' + time);
  }
}

the foll is my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AppComponent } from './app.component';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';

import { appRoutes } from '../routes';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    ChatFormComponent,
    ChatroomComponent,
    FeedComponent,
    MessageComponent,
    LoginFormComponent,
    SignupFormComponent,
    NavbarComponent,
    UserListComponent,
    UserItemComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    AngularFireModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebase),

  ],
  providers: [AuthService, ChatService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
add in app.module.ts

import { AngularFireDatabase } from 'angularfire2/database-deprecated';

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AppComponent } from './app.component';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';

import { appRoutes } from '../routes';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    ChatFormComponent,
    ChatroomComponent,
    FeedComponent,
    MessageComponent,
    LoginFormComponent,
    SignupFormComponent,
    NavbarComponent,
    UserListComponent,
    UserItemComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    AngularFireModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebase),

  ],
  providers: [AuthService, ChatService,AngularFireDatabase],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Issue with Powermock
I am trying to use Powermockito in my test cases to test a void delete()method inside of a legacy public final ClassToTest but its throwing this exception when I am calling mockStatic on ClassToTest

Here is the exception :

```<code>java.lang.NoClassDefFoundError:

org/mockito/internal/creation/instance/InstantationException
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:121)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:71)
    at nl.naturalis.nba.etl.ClassToTestTest.testLogDuration(ClassToTestTest.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    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:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: java.lang.ClassNotFoundException: org.mockito.internal.creation.instance.InstantationException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 37 more
</code>```

My ivy.xml for dependencies looks like this:

```<code><dependency org="junit" name="junit" rev="4.11"/>
<dependency org="org.mockito" name="mockito-all" rev="1.9.5"/>
<dependency org="org.powermock" name="powermock-module-junit4" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-api-mockito" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-core" rev="1.7.3"/>
</code>```

Inside the test method i m using these annotation :

```<code>@RunWith( PowerMockRunner.class )
@PrepareForTest( ClassToTest.class )
@PowerMockIgnore( {"javax.management.*"})
</code>```

I did a debug to find to find that it fails exactly at this point when it tries to load this class :

```<code>org.powermock.api.mockito.repackaged.ClassImposterizer
</code>```

Is there is something I m missing in the dependencies? or something else i am doing wrong?

答: Mockito's 1.9.5 is a very old version. Can you try to change it with the latest stable- 1.10.19. </p>

Title: Issue with Powermock

Body:
I am trying to use Powermockito in my test cases to test a void delete()method inside of a legacy public final ClassToTest but its throwing this exception when I am calling mockStatic on ClassToTest

Here is the exception :

java.lang.NoClassDefFoundError:

org/mockito/internal/creation/instance/InstantationException
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:121)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:71)
    at nl.naturalis.nba.etl.ClassToTestTest.testLogDuration(ClassToTestTest.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    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:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: java.lang.ClassNotFoundException: org.mockito.internal.creation.instance.InstantationException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 37 more

My ivy.xml for dependencies looks like this:

<dependency org="junit" name="junit" rev="4.11"/>
<dependency org="org.mockito" name="mockito-all" rev="1.9.5"/>
<dependency org="org.powermock" name="powermock-module-junit4" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-api-mockito" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-core" rev="1.7.3"/>

Inside the test method i m using these annotation :

@RunWith( PowerMockRunner.class )
@PrepareForTest( ClassToTest.class )
@PowerMockIgnore( {"javax.management.*"})

I did a debug to find to find that it fails exactly at this point when it tries to load this class :

org.powermock.api.mockito.repackaged.ClassImposterizer

Is there is something I m missing in the dependencies? or something else i am doing wrong?


问:
What is the Entropy of Android's Dot Password System?
How many permutations of the androids dot login system are possible?   I know for a fact the solution to this lies in Discrete Math,  specifically Permutations Without Repetition,  If your answer doesn't use permutations or combinations you are incorrect.

The length of passwords is between 4 and 9 dots,  There are a total of 9 dots to permute though.  so my initial equation is:

```<code>9P4+9P5+9P6+9P7+9P8+9P9
</code>```

However,  I know this equation is incomplete because it does not take into consideration all of the rules.  Each dot is distinct because of is position so if you assign a number to each dot as follows:

```<code>123
456
789
</code>```

The password "1397" is impossible,  if you attempt to use this password you will in fact have entered in "1236987" because the numbers in-between are automatically selected.  Another equation needs to be created to account for these limitations and then subtract off from my nPr equation above.

This link has a great video of someone using the android login.  It also goes into greater detail into the rules.  The math on that page is completely incorrect,  he is not even close to a real solution.

答: Omnifarious was definitely accurate in his posting - there are 389,112 combinations. I posted a HUGE thing about the whole process of determining this algorithm, along with a text file listing every single combo from 1-9 length (which seems to be possible, from what I could tell on my girlfriend's phone). The link to this content is this: http://bit.ly/hEHcBJ</p>

ContentLicense: CC BY-SA 2.5

Body:
How many permutations of the androids dot login system are possible?   I know for a fact the solution to this lies in Discrete Math,  specifically Permutations Without Repetition,  If your answer doesn't use permutations or combinations you are incorrect.

The length of passwords is between 4 and 9 dots,  There are a total of 9 dots to permute though.  so my initial equation is:

9P4+9P5+9P6+9P7+9P8+9P9

However,  I know this equation is incomplete because it does not take into consideration all of the rules.  Each dot is distinct because of is position so if you assign a number to each dot as follows:

123
456
789

The password "1397" is impossible,  if you attempt to use this password you will in fact have entered in "1236987" because the numbers in-between are automatically selected.  Another equation needs to be created to account for these limitations and then subtract off from my nPr equation above.

This link has a great video of someone using the android login.  It also goes into greater detail into the rules.  The math on that page is completely incorrect,  he is not even close to a real solution.


问:
How to detect a circle using SteamVR SDK?
I am involved in a virtual-reality project using the HTC Vive device, Unity and the SteamVR SDK used to communicate with the Vive.

Thanks to the joysticks, the final user must draw some shapes (for example a circle) and the movements begin when he presses a joysticks' button.

From all the generated data (output from the joysticks), how could I detect a circle ?

Do you have some documentation on this ?

答:
Please correct me if I understand your concern incorrectly here:

You use joysticks to draw some shapes like circles in some apps like steamvr home,
and you want to detect what you have drawn using software. And maybe you want to show the result in real time in screen or save to a file.

That means you need the ability to get rendered images, and detect image content using algorithms like deep learning.
HTC Vive device are compatible with openVR SDK:
https://github.com/ValveSoftware/openvr

You can use openVR SDK to DIY a steamVR driver,and get images in real time using direct mode component in the SDK. It has lot of works to do even before adding the detection algorithm, because you need a steamvr driver that can used to execute steamVR.


问:
What does Spark recover the data from a failed node?
Suppose we have an RDD, which is being used multiple times. So to save the computations again and again, we persisted this RDD using the rdd.persist() method.

So when we are persisting this RDD, the nodes computing the RDD will be storing their partitions.

So now suppose, the node containing this persisted partition of RDD fails, then what will happen? How will spark recover the lost data? Is there any replication mechanism? Or some other mechanism?

答:
When you do rdd.persist, rdd doesn't materialize the content. It does when you perform an action on the rdd. It follows the same lazy evaluation principle.

Now an RDD knows the partition on which it should operate and the DAG associated with it. With the DAG it is perfectly capable of recreating the materialized partition.

So, when a node fails the driver spawn another executor in some other node and provides it the Data partition on which it was supposed to work and the DAG associated with it in a closure. Now with this information it can recompute the data and materialize it.

In the mean time the cached data in the RDD won't have all the data in memory, the data of the lost nodes it has to fetch from the disk it will take so little more time.

On the replication, yes spark supports in memory replication. You need to set StorageLevel.MEMORY_DISK_2 when you persist.

```<code>rdd.persist(StorageLevel.MEMORY_DISK_2)
</code>```

This ensures the data is replicated twice.

Body:
When you do rdd.persist, rdd doesn't materialize the content. It does when you perform an action on the rdd. It follows the same lazy evaluation principle.

Now an RDD knows the partition on which it should operate and the DAG associated with it. With the DAG it is perfectly capable of recreating the materialized partition.

So, when a node fails the driver spawn another executor in some other node and provides it the Data partition on which it was supposed to work and the DAG associated with it in a closure. Now with this information it can recompute the data and materialize it.

In the mean time the cached data in the RDD won't have all the data in memory, the data of the lost nodes it has to fetch from the disk it will take so little more time.

On the replication, yes spark supports in memory replication. You need to set StorageLevel.MEMORY_DISK_2 when you persist.

rdd.persist(StorageLevel.MEMORY_DISK_2)

This ensures the data is replicated twice.


问:
get ltpatoken2 expiry time
I am currently testing a web application deployed on IBM Websphere Application Server. I understand that I can set the LTPAToken timeout via the console configuration. However, is there any way I can retrieve the timeout duration or a listener in JAVA to indicate that the ltpatoken has expired?</p>

答:
You can get the token expiration time in your Java code like this (this will give you credential expiration time)

```<code>   Subject callerSubject = WSSubject.getCallerSubject();
   Set<WSCredential> credentials = callerSubject.getPublicCredentials(WSCredential.class);

   // should contain only one credential
   int credSize = credentials.size();
   if( credSize != 1)
        throw new RuntimeException("Invalid credential number: "+credSize);
    WSCredential cred = credentials.iterator().next();
    System.out.println("getExpiration: " + cred.getExpiration()+" date: " + new Date(cred.getExpiration()) + "<BR>");
</code>```

if you are interested in particular in ltpatoken, you need to extend it a bit (but probably credential will be enough for you):

```<code>Set tokens = callerSubject.getPrivateCredentials();

for (Object o : tokens) {
    if(o instanceof SingleSignonToken) {
        SingleSignonToken ssoToken = (SingleSignonToken)o;
        System.out.println("getName: " + ssoToken.getName()+"<BR>");
        if("LtpaToken".equals(ssoToken.getName())){
            System.out.println("getExpiration: " + ssoToken.getExpiration()+"<BR>");
        }
    }
}
</code>```

Title: get ltpatoken2 expiry time

Body:
You can get the token expiration time in your Java code like this (this will give you credential expiration time)

   Subject callerSubject = WSSubject.getCallerSubject();
   Set<WSCredential> credentials = callerSubject.getPublicCredentials(WSCredential.class);

   // should contain only one credential
   int credSize = credentials.size();
   if( credSize != 1)
        throw new RuntimeException("Invalid credential number: "+credSize);
    WSCredential cred = credentials.iterator().next();
    System.out.println("getExpiration: " + cred.getExpiration()+" date: " + new Date(cred.getExpiration()) + "<BR>");

if you are interested in particular in ltpatoken, you need to extend it a bit (but probably credential will be enough for you):

Set tokens = callerSubject.getPrivateCredentials();

for (Object o : tokens) {
    if(o instanceof SingleSignonToken) {
        SingleSignonToken ssoToken = (SingleSignonToken)o;
        System.out.println("getName: " + ssoToken.getName()+"<BR>");
        if("LtpaToken".equals(ssoToken.getName())){
            System.out.println("getExpiration: " + ssoToken.getExpiration()+"<BR>");
        }
    }
}


问:
Sharing large datasets between Matlab and R
I need a relatively efficient way to share data between Matlab and R.

I have checked SaveR and MATLAB R-link, but SaveR formats Matlab's binary data as text strings first and then prints them to an ASCII file, which is not efficient for large datasets, and MATLAB R-link only works on Windows (it uses a COM-based interface).

Update:

Dirk has posted a list of what seem to be better solutions to this problem than SaveR and Matlab R-link. I also learned recently about RAM disks (see here and here for some implementation examples), and thought that they might facilitate the task of sharing large datasets between Matlab and R (or similar computational environments) further. This leads me to the following questions:

Assumming that the data fits in the machines' memory in Matlab's or R's native data containers:

Are any of the solutions listed so
far a better fit for RAM disks?

Are there any additional
considerations to be taken into
account when dealing with RAM disks
instead of with secundary-storage
solutions?

Thanks!

答:
Couple of ideas, and with the caveat that I know more about the R side of things:

Tthe R.matlab package on CRAN can help: This package provides methods to read and write MAT files. It also makes it possible to communicate (evaluate code, send and retrieve objects etc.) with Matlab v6 or higher running locally or on a remote host

HDF5, as you suggested, is a possibility but I heard  that the R support in CRAN package hdf5 is somewhat basic

NetCDF may be an alternative; CRAN has packages RNetCDF, ncdf and  ncdf4

Use a database, especially a light and file-based one like SQLite or H4 both of which have R support

Use a common serialization / de-serialization format; R has support for Google Protocol Buffers via RProtoBuf and Google points to protobuf-matlab for Matlab

Write your own!  Especially when you only need something basic like large rectangular matrices then nothing will beat a direct binary write; I did this once years ago for Octave (which is close to Matlab). You can extend Matab via mex files; R has its API and helpers like Rcpp.  The larger your data sets, the more attractive this may look as you save the conversions.


问:
How to get real Hexadecimal number from Hex as String
How do I get the proper Hexadecimal number from a Hexadecimal string?

For example:

```<code><?php
$a = 'C8';
$b = 0xC8;
$c = doWhatHere($a);
$b === $c; // true
</code>```

答:
Thanks to @Ryan.

This does the Trick:

```<code><?php
$a = 'C8';
$b = 0xC8;
$c = intval($a, 16);
$b === $c; // true
</code>```

Body:
How do I get the proper Hexadecimal number from a Hexadecimal string?

For example:

<?php
$a = 'C8';
$b = 0xC8;
$c = doWhatHere($a);
$b === $c; // true

Body:
Thanks to @Ryan.

This does the Trick:

<?php
$a = 'C8';
$b = 0xC8;
$c = intval($a, 16);
$b === $c; // true