问:
Boostrap nav menu immediately disappearing on click on mobile/small screen size
I have recently noticed that, when my bootstrap navbar for my layout file switches to the mobile-friendly, collapsed variant, that the button for expanding/showing the navigation links is acting very strangely, and in doing so, it is completely unusable.

When I click on the button to expand the menu, it expands, shows the animation for opening up long enough to display every item in the list, and then immediately shuts itself.

A second click simply displays a short animation with a white line appearing - my best guess is that this is the closing animation playing, but without a menu to close.

After the second click, the behavior repeats in that same pattern.

I'm not sure what I would have changed that could be causing this, other than perhaps messing up the ordering of my javascript/css loading, but the searches I've done on that front seem to be consistent with what I am doing in my bundles, here:

```<code>public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
            "~/Scripts/modernizr-*",
            "~/Scripts/jquery-3.1.1.min.js",
            "~/Scripts/bootstrap.min.js",
            "~/Scripts/respond.min.js",
            "~/Scripts/jquery.validate.min.js*",
            "~/Scripts/jquery.validate.unobtrusive.min.js",
            "~/Scripts/jquery.unobtrusive-ajax.min.js",
            "~/Scripts/navbarLinksCurrentColor.js",
            "~/Scripts/ajaxCallWithLoadingIcon.js"
            ));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.min.css",
                  "~/Content/styles.css"));

        BundleTable.EnableOptimizations = true;
    }
}
</code>```

The bundle configuration is loaded in the standard manner, inside of Global.asax:

```<code>    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        if (!File.Exists(LogFilePath))
            File.Create(LogFilePath);
    }
</code>```

These bundles are loading in this manner in my layout view, here:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/scripts")
</head>
<body>
    <header>
        @{Html.RenderPartial("NavigationMenu");}
    </header>
    <div class="body-content container-fluid">
        @RenderBody()
    </div>
    <footer>
    </footer>
    <div id="processing"
         class="processingIcon">
        <h2>Loading...</h2>
    </div>
    @RenderSection("scripts", required: false)
</body>
</html>
</code>```

As you can see, the layout view calls a partial view to render the navigation menu:

```<code><nav class="navbar navbar-default navbar-fixed-top">
    <div class="container-fluid">
        <div class="navbar-header">
        @*I originally was using the 4-span style that I've seen
        commonly for the collapse button, but switched to a glyphicon
        approach to simplify things as well as see if it would fix the
        issue - it did not, so I don't think it is relevant to this issue*@
            <button type="button" class="navbar-toggle collapsed glyphicon glyphicon-menu-hamburger"
            data-toggle="collapse" data-target="#navbarLinks"></button>
            <a class="navbar-brand" href="/">Hire Right Testing</a>
        </div>
        <div class="collapse navbar-collapse" id="navbarLinks">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("New Clients", "NewClients", "Client")</li>
                <li>@Html.ActionLink("Build a Custom Test", "Index", "CustomSolutions")</li>
                @*More links here...*@
            </ul>
        </div>
    </div>
</nav>
</code>```

The issue was occurring prior to me migrating this out into its own file, so I don't believe that is the cause of the strange behavior.

The only other case which seemed similar to this was a case where the solution ended up being a mismatch between the Bootstrap css and js files, which I don't think is the case as I have uninstalled and then reinstalled the Bootstrap nuget package (currently using version 3.3.7, the current latest version).

Package Versions:
Bootstrap - 3.3.7 (also tried: 3.3.5)

jQuery - 3.1.1 (also tried: 1.12.4, 2.0.0, 2.2.4, 3.0.0.1)

jQuery.Validation - 1.16.0 (also tried: 1.15.1)

Final thought: Not sure if the _references.js file would matter for this at all, but here is that file, as well:

```<code>/// <reference path="jquery-3.1.1.js" />
/// <autosync enabled="true" />
/// <reference path="ajaxcallwithloadingicon.js" />
/// <reference path="bootstrap.min.js" />
/// <reference path="customsolutions/categoryfilterpartial.js" />
/// <reference path="customsolutions/customsolutionspartial.js" />
/// <reference path="customsolutions/index.js" />
/// <reference path="jquery.unobtrusive-ajax.min.js" />
/// <reference path="jquery.validate.min.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
/// <reference path="jquery-3.1.1.min.js" />
/// <reference path="jquery-3.1.1.slim.min.js" />
/// <reference path="modernizr-2.8.3.js" />
/// <reference path="navbarlinkscurrentcolor.js" />
/// <reference path="orderdetailsupdates.js" />
/// <reference path="replacingdivcontents.js" />
/// <reference path="respond.matchmedia.addlistener.min.js" />
/// <reference path="respond.min.js" />
/// <reference path="showhidediv.js" />
/// <reference path="toggledivsandbuttons.js" />
</code>```

答:
I did manage to find the part of my code which was causing this issue. I got to this answer by creating a new .NET MVC application using the template and experimenting with code copied over from the application which had the issue. None of the scripting/bundling appeared to be the issue, the actual problem was part of my css.

Some time back, I had apparently placed this block inside my main .scss file:

```<code>.navbar-collapse.collapse {
    display: none!important;
}
</code>```

I do not remember why I placed this inside my css - but it was the sole cause of the nav menu issues.

Body:
I have recently noticed that, when my bootstrap navbar for my layout file switches to the mobile-friendly, collapsed variant, that the button for expanding/showing the navigation links is acting very strangely, and in doing so, it is completely unusable.

When I click on the button to expand the menu, it expands, shows the animation for opening up long enough to display every item in the list, and then immediately shuts itself.

A second click simply displays a short animation with a white line appearing - my best guess is that this is the closing animation playing, but without a menu to close.

After the second click, the behavior repeats in that same pattern.

I'm not sure what I would have changed that could be causing this, other than perhaps messing up the ordering of my javascript/css loading, but the searches I've done on that front seem to be consistent with what I am doing in my bundles, here:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
            "~/Scripts/modernizr-*",
            "~/Scripts/jquery-3.1.1.min.js",
            "~/Scripts/bootstrap.min.js",
            "~/Scripts/respond.min.js",
            "~/Scripts/jquery.validate.min.js*",
            "~/Scripts/jquery.validate.unobtrusive.min.js",
            "~/Scripts/jquery.unobtrusive-ajax.min.js",
            "~/Scripts/navbarLinksCurrentColor.js",
            "~/Scripts/ajaxCallWithLoadingIcon.js"
            ));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.min.css",
                  "~/Content/styles.css"));

        BundleTable.EnableOptimizations = true;
    }
}

The bundle configuration is loaded in the standard manner, inside of Global.asax:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        if (!File.Exists(LogFilePath))
            File.Create(LogFilePath);
    }

These bundles are loading in this manner in my layout view, here:

<!DOCTYPE html>

    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/scripts")

        @{Html.RenderPartial("NavigationMenu");}

        @RenderBody()

Loading...

    @RenderSection("scripts", required: false)

As you can see, the layout view calls a partial view to render the navigation menu:

        @*I originally was using the 4-span style that I've seen
        commonly for the collapse button, but switched to a glyphicon
        approach to simplify things as well as see if it would fix the
        issue - it did not, so I don't think it is relevant to this issue*@
            <button type="button" class="navbar-toggle collapsed glyphicon glyphicon-menu-hamburger"
            data-toggle="collapse" data-target="#navbarLinks"></button>
            Hire Right Testing

@Html.ActionLink("New Clients", "NewClients", "Client")

@Html.ActionLink("Build a Custom Test", "Index", "CustomSolutions")

                @*More links here...*@

The issue was occurring prior to me migrating this out into its own file, so I don't believe that is the cause of the strange behavior.

The only other case which seemed similar to this was a case where the solution ended up being a mismatch between the Bootstrap css and js files, which I don't think is the case as I have uninstalled and then reinstalled the Bootstrap nuget package (currently using version 3.3.7, the current latest version).

Package Versions:
Bootstrap - 3.3.7 (also tried: 3.3.5)

jQuery - 3.1.1 (also tried: 1.12.4, 2.0.0, 2.2.4, 3.0.0.1)

jQuery.Validation - 1.16.0 (also tried: 1.15.1)

Final thought: Not sure if the _references.js file would matter for this at all, but here is that file, as well:

/// <reference path="jquery-3.1.1.js" />
/// <autosync enabled="true" />
/// <reference path="ajaxcallwithloadingicon.js" />
/// <reference path="bootstrap.min.js" />
/// <reference path="customsolutions/categoryfilterpartial.js" />
/// <reference path="customsolutions/customsolutionspartial.js" />
/// <reference path="customsolutions/index.js" />
/// <reference path="jquery.unobtrusive-ajax.min.js" />
/// <reference path="jquery.validate.min.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
/// <reference path="jquery-3.1.1.min.js" />
/// <reference path="jquery-3.1.1.slim.min.js" />
/// <reference path="modernizr-2.8.3.js" />
/// <reference path="navbarlinkscurrentcolor.js" />
/// <reference path="orderdetailsupdates.js" />
/// <reference path="replacingdivcontents.js" />
/// <reference path="respond.matchmedia.addlistener.min.js" />
/// <reference path="respond.min.js" />
/// <reference path="showhidediv.js" />
/// <reference path="toggledivsandbuttons.js" />

Body:
I did manage to find the part of my code which was causing this issue. I got to this answer by creating a new .NET MVC application using the template and experimenting with code copied over from the application which had the issue. None of the scripting/bundling appeared to be the issue, the actual problem was part of my css.

Some time back, I had apparently placed this block inside my main .scss file:

.navbar-collapse.collapse {
    display: none!important;
}

I do not remember why I placed this inside my css - but it was the sole cause of the nav menu issues.


来源: stackexchange

问:
NodeJS inspect 0.0.0.0 not hitting breakpoints
I'm on Ubuntu 16 on a droplet on Digital Ocean, installed nodejs and am trying to remote debug.

I have nginx proxying port 80 traffic to the localhost:3000 app and all works well when I access the droplets IP.

I start the app like so

```<code>node --inspect=0.0.0.0:9229 app.js
</code>```

I get a message like this.

```<code>Debugger listening on ws://0.0.0.0:9229/5f583ab2-4ebf-4f73-84de-01500c38d31f
For help see https://nodejs.org/en/docs/inspector
✓ App is running at http://localhost:3000 in development mode
   Press CTRL-C to stop
</code>```

In Chrome I have the NiM setup on my host and port.

The window opens automatically whenever I start the app, but that's when the fun stops.

No breakpoints are being hit and no logging is happening in the dev tools console and every few minutes it says "disconnected" and I have to hit reconnect. Is --inspect not built to be remote debugged like this?

答: Turns out it was the chrome plugin Node Inspector Manager that was the issue. Not anything else to do with nodejs itself. Once I visited chrome:://inspect , added the remote host of domain:port, it popped up to inspect when I started the process and I clicked "Open Dedicated Devtools for Node" and voila alls well in the debugging world.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm on Ubuntu 16 on a droplet on Digital Ocean, installed nodejs and am trying to remote debug.

I have nginx proxying port 80 traffic to the localhost:3000 app and all works well when I access the droplets IP.

I start the app like so

node --inspect=0.0.0.0:9229 app.js

I get a message like this.

Debugger listening on ws://0.0.0.0:9229/5f583ab2-4ebf-4f73-84de-01500c38d31f
For help see https://nodejs.org/en/docs/inspector
✓ App is running at http://localhost:3000 in development mode
   Press CTRL-C to stop

In Chrome I have the NiM setup on my host and port.

The window opens automatically whenever I start the app, but that's when the fun stops.

No breakpoints are being hit and no logging is happening in the dev tools console and every few minutes it says "disconnected" and I have to hit reconnect. Is --inspect not built to be remote debugged like this?


问:
JDBC transactions rollback() still updating table
I have a table that contains an id column, a bids column and a cost column. I am using transactions in jdbc. I set auto commit to false, executed some queries to update that table and then called the rollback method, which should undo changes made in the transaction and revert the table back to its previous state. However, the table is still being updated.

Here is my code:

```<code>public class JdbcTransactions {
public static void main(String[] args) {
    Connection myConn = null;
    Statement myStmt = null;

    try {
        myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tutorialdatabase", "student", "student");

        myConn.setAutoCommit(false);

        myStmt = myConn.createStatement();
        myStmt.executeUpdate("UPDATE items SET bids = 0 WHERE id <= 5");
        myStmt.executeUpdate("UPDATE items SET cost = cost + 100 WHERE id <= 5");

        myConn.rollback();

    }catch(SQLException e) {
        System.err.println("Something went wrong: ");
        e.printStackTrace();

    } finally {
        try {
            myStmt.close();
            myConn.close();
        }catch(SQLException e) {

        }
    }
}
</code>```

}

I want to update the items table in tutorialdatabase to set the bids to 0 and cost to increment by 100 for the first 5 rows(all rows with id 1 - 5)

答:
Try to put autocommit off on db
SET autocommit=0;</p>

Body:
I have a table that contains an id column, a bids column and a cost column. I am using transactions in jdbc. I set auto commit to false, executed some queries to update that table and then called the rollback method, which should undo changes made in the transaction and revert the table back to its previous state. However, the table is still being updated.

Here is my code:

public class JdbcTransactions {
public static void main(String[] args) {
    Connection myConn = null;
    Statement myStmt = null;

    try {
        myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tutorialdatabase", "student", "student");

        myConn.setAutoCommit(false);

        myStmt = myConn.createStatement();
        myStmt.executeUpdate("UPDATE items SET bids = 0 WHERE id <= 5");
        myStmt.executeUpdate("UPDATE items SET cost = cost + 100 WHERE id <= 5");

        myConn.rollback();

    }catch(SQLException e) {
        System.err.println("Something went wrong: ");
        e.printStackTrace();

    } finally {
        try {
            myStmt.close();
            myConn.close();
        }catch(SQLException e) {

        }
    }
}

}

I want to update the items table in tutorialdatabase to set the bids to 0 and cost to increment by 100 for the first 5 rows(all rows with id 1 - 5)


问:
Interpolation in locale-specific error messages
I am trying to modify an existing Spring Boot application to support multilingual error messages. I have changed the annotation on the property as follows:

```<code>@Size(min = 2, max = 75, message = "Book.name.Size")
private String name;
</code>```

My messages_en.properties looks like:

Book.name.Size = The name must be between {min} and {max} characters

The MessageSource config is as follows:

```<code>@Configuration
public class MessageSourceConfig extends WebMvcConfigurerAdapter {

    @Bean
    public MessageSource messageSource() {

        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(600);

        return messageSource;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");

        return localeChangeInterceptor;
    }

    @Bean
    public LocaleResolver localeResolver() {

        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);

        return sessionLocaleResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(localeChangeInterceptor());
    }

    @Bean
    public LocalValidatorFactoryBean validator()
    {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setValidationMessageSource(messageSource());

        return localValidatorFactoryBean;
    }
}
</code>```

If a value is entered that is too small/large the error message returned does not contain the interpolated min/max values so the user sees exactly:

The name must be between {min} and {max} characters

I tried changing the annotation on the property to include curly braces:

```<code>@Size(min = 2, max = 75, message = "{Book.name.Size}")
private String name;
</code>```

But now I receive an error instead:

org.springframework.context.NoSuchMessageException: No message found under code 'The name must be between 2 and 75 characters' for locale 'en'

It must be an issue with the configuration but I don't know where the problem lies...

答:
You have to add the following to your GreetingController :

```<code>@Autowired
private LocalValidatorFactoryBean validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}
</code>```

Body:
I am trying to modify an existing Spring Boot application to support multilingual error messages. I have changed the annotation on the property as follows:

@Size(min = 2, max = 75, message = "Book.name.Size")
private String name;

My messages_en.properties looks like:

Book.name.Size = The name must be between {min} and {max} characters

The MessageSource config is as follows:

@Configuration
public class MessageSourceConfig extends WebMvcConfigurerAdapter {

    @Bean
    public MessageSource messageSource() {

        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(600);

        return messageSource;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");

        return localeChangeInterceptor;
    }

    @Bean
    public LocaleResolver localeResolver() {

        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);

        return sessionLocaleResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(localeChangeInterceptor());
    }

    @Bean
    public LocalValidatorFactoryBean validator()
    {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setValidationMessageSource(messageSource());

        return localValidatorFactoryBean;
    }
}

If a value is entered that is too small/large the error message returned does not contain the interpolated min/max values so the user sees exactly:

The name must be between {min} and {max} characters

I tried changing the annotation on the property to include curly braces:

@Size(min = 2, max = 75, message = "{Book.name.Size}")
private String name;

But now I receive an error instead:

org.springframework.context.NoSuchMessageException: No message found under code 'The name must be between 2 and 75 characters' for locale 'en'

It must be an issue with the configuration but I don't know where the problem lies...

Body:
You have to add the following to your GreetingController :

@Autowired
private LocalValidatorFactoryBean validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}


问:
.Net Core Serialize an Object with IEnumerables<T> to Save as XML
I am using .net Core 1.1 and writing a console application. I need to Serialize an Object with some basic properties of strings and int as well as some IEnumerable Objects and serialize it as XML so I can save it to a "data.xml" file.

I receive the Exception:
System.Runtime.Serialization.SerializationException: 'Type 'System.Collections.Generic.List`1[[CorpsDataExtractor.ViewModels.LegacyView, CorpsDataExtractor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfLegacyView:http://schemas.datacontract.org/2004/07/CorpsDataExtractor.ViewModels' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'

I currently am able to serialize my Object as JSON, but am having trouble utilizing the DataContractSerializer. I Added the Known Type List that the exception states I am missing but it still fails.

```<code>// This List isretrieved using Entity Framework Core
      List<LegacyView> legacyData = await _corpsRepo.ListLegacyData();

// The Below Line will write to a JSON File. No Error and works
        File.WriteAllText(@"E:\\CorporationsDataLegacy.json", JsonConvert.SerializeObject(legacyData));

// This Creates a Known Type List for the DataContractSerializer
        var knownTypeList = new List<Type>
        {
            typeof(LegacyView),
            typeof(People),
            typeof(DocumentType)
        };

        FileStream writer = new FileStream(@"E:\\data.xml", FileMode.Create);
        var ser = new DataContractSerializer(typeof(LegacyView), knownTypeList );
// When Debugging I Receive The stated exception at this line
        ser.WriteObject(writer, legacyData);
</code>```

Below Are my Class ViewModels:

Legacy View

```<code>[DataContract]
public class LegacyView
{
    [DataMember]
    public string Ubi { get; set; }
    [DataMember]
    public IEnumerable<Person> People{ get; set; }
    [DataMember]
    public IEnumerable<DocumentType> DocumentTypes { get; set; }
}
</code>```

Person

```<code>[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string MiddleName { get; set; }
}
</code>```

Documents

```<code>[DataContract]
public class DocumentType
{
    [DataMember]
    public string Document { get; set; }
    [DataMember]
    public DateTime? CompletedDate { get; set; }
}
</code>```

Any Direction on what I am missing?

答:
By using a Both Gusman and LB2 comments I was able to solve the issue. As LB2 states "with IEnumerable as the type, deserializer wouldn't know what class to actually instantiate to back the interface during deserialization."

This is why the error was occurring, however the problem did not exist at the Class LegacyView [DataMember] level, it existed at the known Types that were being passed into the DataContractSerializer.

Gusman was correct that I needed to tell the DataContractSerializer that these were going to be an enumerable type.

```<code>// I needed to tell the DataContractSerializer what the types were
    var knownTypeList = new List<Type>
    {
        typeof(List<LegacyView>),
        typeof(List<People>),
        typeof(List<DocumentType>)
    };

    using (var writer = new FileStream(@"E:\\myTestExample.xml", FileMode.Create))
    {
        var ser = new DataContractSerializer(typeof(LegacyView), knownTypeList);
        ser.WriteObject(writer, legacyData);
    }
</code>```

Body:
I am using .net Core 1.1 and writing a console application. I need to Serialize an Object with some basic properties of strings and int as well as some IEnumerable Objects and serialize it as XML so I can save it to a "data.xml" file.

I receive the Exception:
System.Runtime.Serialization.SerializationException: 'Type 'System.Collections.Generic.List`1[[CorpsDataExtractor.ViewModels.LegacyView, CorpsDataExtractor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfLegacyView:http://schemas.datacontract.org/2004/07/CorpsDataExtractor.ViewModels' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'

I currently am able to serialize my Object as JSON, but am having trouble utilizing the DataContractSerializer. I Added the Known Type List that the exception states I am missing but it still fails.

// This List isretrieved using Entity Framework Core
      List<LegacyView> legacyData = await _corpsRepo.ListLegacyData();

// The Below Line will write to a JSON File. No Error and works
        File.WriteAllText(@"E:\\CorporationsDataLegacy.json", JsonConvert.SerializeObject(legacyData));

// This Creates a Known Type List for the DataContractSerializer
        var knownTypeList = new List<Type>
        {
            typeof(LegacyView),
            typeof(People),
            typeof(DocumentType)
        };

        FileStream writer = new FileStream(@"E:\\data.xml", FileMode.Create);
        var ser = new DataContractSerializer(typeof(LegacyView), knownTypeList );
// When Debugging I Receive The stated exception at this line
        ser.WriteObject(writer, legacyData);

Below Are my Class ViewModels:

Legacy View

[DataContract]
public class LegacyView
{
    [DataMember]
    public string Ubi { get; set; }
    [DataMember]
    public IEnumerable<Person> People{ get; set; }
    [DataMember]
    public IEnumerable<DocumentType> DocumentTypes { get; set; }
}

Person

[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string MiddleName { get; set; }
}

Documents

[DataContract]
public class DocumentType
{
    [DataMember]
    public string Document { get; set; }
    [DataMember]
    public DateTime? CompletedDate { get; set; }
}

Any Direction on what I am missing?

Body:
By using a Both Gusman and LB2 comments I was able to solve the issue. As LB2 states "with IEnumerable as the type, deserializer wouldn't know what class to actually instantiate to back the interface during deserialization."

This is why the error was occurring, however the problem did not exist at the Class LegacyView [DataMember] level, it existed at the known Types that were being passed into the DataContractSerializer.

Gusman was correct that I needed to tell the DataContractSerializer that these were going to be an enumerable type.

// I needed to tell the DataContractSerializer what the types were
    var knownTypeList = new List<Type>
    {
        typeof(List<LegacyView>),
        typeof(List<People>),
        typeof(List<DocumentType>)
    };

    using (var writer = new FileStream(@"E:\\myTestExample.xml", FileMode.Create))
    {
        var ser = new DataContractSerializer(typeof(LegacyView), knownTypeList);
        ser.WriteObject(writer, legacyData);
    }

ContentLicense: CC BY-SA 4.0


问:
Is there a windows utility similar to HTML Tidy for Javascript?
I want to cleanup some javascript files and reformat them with nice indents, etc,
Are there recommendations for utilities to do this under Windows?</p>

答:
Beautify Javascript is a good, simple option.

(Oops. Thought I grabbed the link for the app, not the home page.) ;)

OwnerDisplayName: Noah

LastEditorDisplayName: Noah

OwnerDisplayName: Jonathan Lonowski

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Lonowski


问:
What is the OR operator in emacs regexps?
The manual says to use '\|', as in a\|b matches a or b. But when I use it with regexp builder or align-regexp e.g. with, "True\|False", it doesn't recognize "True" or "False". I get the following message:

```<code>Wrong argument type: integer-or-marker-p, nil
</code>```

What am I doing wrong?

答:
For further details, see the discussion of '\' and strings in the elisp manual section 34.3.1.1 "Special Characters in Regular Expressions"

M-: (info "(elisp) Regexp Special") RET

Body:
The manual says to use '\|', as in a\|b matches a or b. But when I use it with regexp builder or align-regexp e.g. with, "True\|False", it doesn't recognize "True" or "False". I get the following message:

Wrong argument type: integer-or-marker-p, nil

What am I doing wrong?


问:
Title Screen Not Running Pygame
I'm trying to create a title screen for a game I'm making, but when I run the program it's just a black canvas. Without the title, everything works fine and the game (which is a maze) runs perfectly, but if I try to add my title fcn everything messes up.
When running my program I'm calling:

```<code>game_intro()
game_loop() #the fcn that stores my game code
</code>```

This is my title fcn code:

```<code>def game_intro():
    intro = True
    while intro == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

    screen.fill((WHITE))
    largeText = pygame.font.Font(None, 115)
    TextSurf, TextRect = text_objects("H&D: Hedges and Dragons", largeText)
    TextRect.center = ((DISPLAY_WIDTH/2), (DISPLAY_HEIGHT/2))
    screen.blit(TextSurf, TextRect)
    pygame.display.update()
    clock.tick(FPS)
</code>```

I appreciate any help or advice!

答:
You need to initialize pygame right before the while loop:</p>

```<code>def game_intro():
    pygame.init()
    screen = pygame.display.set_mode((1000, 900))
    intro = True
    while intro: #do not need intro == True
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               pygame.quit()
               quit()

    screen.fill((WHITE))
    largeText = pygame.font.Font(None, 115)
    TextSurf, TextRect = text_objects("H&D: Hedges and Dragons", largeText)
    TextRect.center = ((DISPLAY_WIDTH/2), (DISPLAY_HEIGHT/2))
    screen.blit(TextSurf, TextRect)
    pygame.display.update()
    clock.tick(FPS)
</code>```

Title: Title Screen Not Running Pygame

Body:
I'm trying to create a title screen for a game I'm making, but when I run the program it's just a black canvas. Without the title, everything works fine and the game (which is a maze) runs perfectly, but if I try to add my title fcn everything messes up.
When running my program I'm calling:

game_intro()
game_loop() #the fcn that stores my game code

This is my title fcn code:

def game_intro():
    intro = True
    while intro == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

    screen.fill((WHITE))
    largeText = pygame.font.Font(None, 115)
    TextSurf, TextRect = text_objects("H&D: Hedges and Dragons", largeText)
    TextRect.center = ((DISPLAY_WIDTH/2), (DISPLAY_HEIGHT/2))
    screen.blit(TextSurf, TextRect)
    pygame.display.update()
    clock.tick(FPS)

I appreciate any help or advice!

Body:
You need to initialize pygame right before the while loop:

def game_intro():
    pygame.init()
    screen = pygame.display.set_mode((1000, 900))
    intro = True
    while intro: #do not need intro == True
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               pygame.quit()
               quit()

    screen.fill((WHITE))
    largeText = pygame.font.Font(None, 115)
    TextSurf, TextRect = text_objects("H&D: Hedges and Dragons", largeText)
    TextRect.center = ((DISPLAY_WIDTH/2), (DISPLAY_HEIGHT/2))
    screen.blit(TextSurf, TextRect)
    pygame.display.update()
    clock.tick(FPS)


问:
ERROR: config_template is not a legal parameter in an Ansible task or handler
I am trying to install Openstack through Ansible for a single node using All IN ONE.

When I run setup-everything.yml file, I am receiving following error:

ERROR: config_template is not a legal parameter in an Ansible task or handler

Can you please help on the issue?

答:
I know that this answer is a little late but I found this and thought to try and help others out should they run into this.

It's very likely that the system was not bootstrapped. We see this error from time to time when the action plugin is not present on the system. With OpenStack-Ansible you will need to retrieve the roles and plugins from the ansible-role-requirements.txt file. After you've cloned the software the first step in deployment is usually running ./scripts/bootstrap-ansible.sh which would install Ansible into a venv, retrieve your roles, libraries, & plugins, and then create the openstack-ansible CLI wrapper. You can also simply use the ansible-galaxy command with the ansible-role-requirements.txt if you don't want to run that script. After you have the roles and libs you will likely no longer see that error. More documentation on getting started can be found here: https://docs.openstack.org/developer/openstack-ansible/developer-docs/quickstart-aio.html

You can get access to the config_template module source code here: https://github.com/openstack/openstack-ansible-plugins/blob/master/action/_v2_config_template.py should you have issues specifically with the module or jump into the #openstack-ansible channel on freenode where there's generally someone available to help out.


问:
`docker run` on a remote host
is it possible (using the docker command or the docker-py API directly) to start a container from a remote host?

Lets assume I have two machines that have different architectures:
- A is an x86 machine
- B is an ARM machine

I would like to run a container on the B machine using my A machine. At first, I thought it was possible using this command:

```<code>[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker run hello-from-B
</code>```

But this command actually pulls the image hello-from-B and tries to run it on the machine A which ends up on some exec format error cause obviously you can't run images that are specific to ARM to an x86 machine.

Communication between machine A and B is working well. I can run commands like images or ps and it gives me the expected results:

```<code>[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
hello-from-B              <none>              fd5059044831        13 hours ago        1.26GB
</code>```

I've heard about docker-machine and haven't tried it yet, but from my understanding, this won't solve my problem.

Is there any way to achieve that using docker directly. A workaround might be to using ssh to connect to the remote host and use the docker client directly from the remote host, but I'd like to avoid this solution as much as possible.

Thanks in advance,

TL;DR;

How can DOCKER_HOST=... docker run something runs something on the DOCKER_HOST rather than running it on my local machine.

答:
This article explains the concept very well: https://docs.docker.com/engine/reference/commandline/dockerd/#bind-docker-to-another-hostport-or-a-unix-socket

Considering the huge warning on the page, I suggest you resort to using a secure connection via SSH ie. ssh user@host 'docker run hello-from-B'

Warning: Changing the default docker daemon binding to a TCP port or Unix docker user group will increase your security risks by
  allowing non-root users to gain root access on the host. Make sure you
  control access to docker. If you are binding to a TCP port, anyone
  with access to that port has full Docker access; so it is not
  advisable on an open network.

With -H it is possible to make the Docker daemon to listen on a
  specific IP and port. By default, it will listen on
  unix:///var/run/docker.sock to allow only local connections by the
  root user. You could set it to 0.0.0.0:2375 or a specific host IP to
  give access to everybody, but that is not recommended because then it
  is trivial for someone to gain root access to the host where the
  daemon is running.

Similarly, the Docker client can use -H to connect to a custom port.
  The Docker client will default to connecting to
  unix:///var/run/docker.sock on Linux, and tcp://127.0.0.1:2376 on
  Windows.

-H accepts host and port assignment in the following format:

tcp://[host]:[port][path] or unix://path

You can use multiple -H, for example, if you want to listen on both
  TCP and a Unix socket

```<code># Run docker in daemon mode
$ sudo <path to>/dockerd -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock &
# Download an ubuntu image, use default Unix socket
$ docker pull ubuntu
# OR use the TCP port
$ docker -H tcp://127.0.0.1:2375 pull ubuntu
</code>```

Title: `docker run` on a remote host

Body:
is it possible (using the docker command or the docker-py API directly) to start a container from a remote host?

Lets assume I have two machines that have different architectures:
- A is an x86 machine
- B is an ARM machine

I would like to run a container on the B machine using my A machine. At first, I thought it was possible using this command:

[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker run hello-from-B

But this command actually pulls the image hello-from-B and tries to run it on the machine A which ends up on some exec format error cause obviously you can't run images that are specific to ARM to an x86 machine.

Communication between machine A and B is working well. I can run commands like images or ps and it gives me the expected results:

[A]$> DOCKER_HOST=$MACHINE_B_IP:$MACHIN_B_PORT docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
hello-from-B              <none>              fd5059044831        13 hours ago        1.26GB

I've heard about docker-machine and haven't tried it yet, but from my understanding, this won't solve my problem.

Is there any way to achieve that using docker directly. A workaround might be to using ssh to connect to the remote host and use the docker client directly from the remote host, but I'd like to avoid this solution as much as possible.

Thanks in advance,

TL;DR;

How can DOCKER_HOST=... docker run something runs something on the DOCKER_HOST rather than running it on my local machine.

Body:
This article explains the concept very well: https://docs.docker.com/engine/reference/commandline/dockerd/#bind-docker-to-another-hostport-or-a-unix-socket

Considering the huge warning on the page, I suggest you resort to using a secure connection via SSH ie. ssh user@host 'docker run hello-from-B'

Warning: Changing the default docker daemon binding to a TCP port or Unix docker user group will increase your security risks by
  allowing non-root users to gain root access on the host. Make sure you
  control access to docker. If you are binding to a TCP port, anyone
  with access to that port has full Docker access; so it is not
  advisable on an open network.

With -H it is possible to make the Docker daemon to listen on a
  specific IP and port. By default, it will listen on
  unix:///var/run/docker.sock to allow only local connections by the
  root user. You could set it to 0.0.0.0:2375 or a specific host IP to
  give access to everybody, but that is not recommended because then it
  is trivial for someone to gain root access to the host where the
  daemon is running.

Similarly, the Docker client can use -H to connect to a custom port.
  The Docker client will default to connecting to
  unix:///var/run/docker.sock on Linux, and tcp://127.0.0.1:2376 on
  Windows.

-H accepts host and port assignment in the following format:

tcp://[host]:[port][path] or unix://path

You can use multiple -H, for example, if you want to listen on both
  TCP and a Unix socket

# Run docker in daemon mode
$ sudo <path to>/dockerd -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock &
# Download an ubuntu image, use default Unix socket
$ docker pull ubuntu
# OR use the TCP port
$ docker -H tcp://127.0.0.1:2375 pull ubuntu


问:
Mule Facebook Connector error: "Could not extract OAuth verifier."
I tried to build very simple application via Mule to connect to Facebook.
I followed this demo: enter link description here

The final components will be like this:

The Problem once I run application and hit the URL: http://localhost:1111/auth
I got the following message in the browser:

```<code>Could not extract OAuth verifier.
</code>```

Also I get the following error in the console:

```<code>Root Exception stack trace:
org.mule.security.oauth.exception.AuthorizationCodeNotFoundException
    at org.mule.security.oauth.processor.ExtractAuthorizationCodeMessageProcessor.extractAuthorizationCode(ExtractAuthorizationCodeMessageProcessor.java:56)
    at org.mule.security.oauth.processor.ExtractAuthorizationCodeMessageProcessor.process(ExtractAuthorizationCodeMessageProcessor.java:39)
    at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
    at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:108)
    at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
</code>```

The complete configuration XML

```<code><?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:facebook="http://www.mulesoft.org/schema/mule/facebook" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/facebook http://www.mulesoft.org/schema/mule/facebook/current/mule-facebook.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
    <http:listener-config name="HTTP_Listener_Configuration1111" host="localhost" port="1111" doc:name="HTTP Listener Configuration"/>
    <facebook:config-with-oauth name="Facebook" consumerKey="111974699389920" consumerSecret="7406759445e528542668752d135c422a" doc:name="Facebook">
        <facebook:oauth-callback-config domain="localhost" localPort="1111" remotePort="1111" path="/*"/>
    </facebook:config-with-oauth>
    <flow name="facebookFlow">
        <http:listener config-ref="HTTP_Listener_Configuration1111" path="/auth" doc:name="HTTP"/>
        <facebook:authorize config-ref="Facebook" doc:name="Facebook"/>
        <choice doc:name="Choice">
            <when expression="#[flowVars.OAuthAccessTokenId != null]">
                <logger level="INFO" doc:name="Logger" message="Authorization is done succefully"/>
                <set-payload doc:name="Set Payload" value="Facebook Authorization Successful"/>
                <json:object-to-json-transformer doc:name="Object to JSON"/>
            </when>
            <otherwise>
                <logger level="INFO" doc:name="Logger" message="Authorization Failed"/>
                <set-payload doc:name="Set Payload" value="Facebook Authorization Failed"/>
            </otherwise>
        </choice>
    </flow>
</mule>
</code>```

What is the cause of this problem?? how to avoid it??

答:
You have to hit http listener url not the callback url.

listener URL :  http://localhost:1111  -- use this after running application.
callback url :  http://localhost:1111/auth

Please let me know if it helps !

Aman.

Body:
I tried to build very simple application via Mule to connect to Facebook.
I followed this demo: enter link description here

The final components will be like this:

The Problem once I run application and hit the URL: http://localhost:1111/auth
I got the following message in the browser:

Could not extract OAuth verifier.

Also I get the following error in the console:

Root Exception stack trace:
org.mule.security.oauth.exception.AuthorizationCodeNotFoundException
    at org.mule.security.oauth.processor.ExtractAuthorizationCodeMessageProcessor.extractAuthorizationCode(ExtractAuthorizationCodeMessageProcessor.java:56)
    at org.mule.security.oauth.processor.ExtractAuthorizationCodeMessageProcessor.process(ExtractAuthorizationCodeMessageProcessor.java:39)
    at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
    at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:108)
    at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)

The complete configuration XML

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:facebook="http://www.mulesoft.org/schema/mule/facebook" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/facebook http://www.mulesoft.org/schema/mule/facebook/current/mule-facebook.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
    <http:listener-config name="HTTP_Listener_Configuration1111" host="localhost" port="1111" doc:name="HTTP Listener Configuration"/>
    <facebook:config-with-oauth name="Facebook" consumerKey="111974699389920" consumerSecret="7406759445e528542668752d135c422a" doc:name="Facebook">
        <facebook:oauth-callback-config domain="localhost" localPort="1111" remotePort="1111" path="/*"/>
    </facebook:config-with-oauth>
    <flow name="facebookFlow">
        <http:listener config-ref="HTTP_Listener_Configuration1111" path="/auth" doc:name="HTTP"/>
        <facebook:authorize config-ref="Facebook" doc:name="Facebook"/>
        <choice doc:name="Choice">
            <when expression="#[flowVars.OAuthAccessTokenId != null]">
                <logger level="INFO" doc:name="Logger" message="Authorization is done succefully"/>
                <set-payload doc:name="Set Payload" value="Facebook Authorization Successful"/>
                <json:object-to-json-transformer doc:name="Object to JSON"/>
            </when>
            <otherwise>
                <logger level="INFO" doc:name="Logger" message="Authorization Failed"/>
                <set-payload doc:name="Set Payload" value="Facebook Authorization Failed"/>
            </otherwise>
        </choice>
    </flow>
</mule>

What is the cause of this problem?? how to avoid it??


问:
Help with converting bool to integer
I keep getting an error saying "Cannot implicitly covert type bool to int" I cannot figure out what to do with this. I get the error on: DisplayIndex = columns[i].Visible,

Code:

```<code>    private void SaveColumnOrder()
    {
        if (dgPortStatus.CanUserReorderColumns == true)
        {
            List<ColumnOrderItem> columnOrder = new List<ColumnOrderItem>();
            DataGridViewColumnCollection columns = this.Columns;
            for (int i = 0; i < columns.Count; i++)
            {
                columnOrder.Add(new ColumnOrderItem
                {
                    ColumnIndex = i,
                    DisplayIndex = columns[i].Visible,
                    Width = columns[i].Width
                });

            }

            portalDataGridViewSetting.Default.ColumnOrder[this.Name] = columnOrder;
            portalDataGridViewSetting.Default.Save();
        }
    }
</code>```

Code:

```<code> public sealed class ColumnOrderItem
    {
        public int DisplayIndex { get; set; }
        public int Width { get; set; }
        public bool Visible  { get; set; }
        public int ColumnIndex { get; set; }
    }
</code>```

答:
The only possible interpretation I can make of this is:</p>

```<code>        int displayIndex = 0;
        for (int i = 0; i < columns.Count; i++)
        {
            columnOrder.Add(new ColumnOrderItem
            {
                ColumnIndex = i,
                DisplayIndex = displayIndex;
                Width = columns[i].Width
            });

            if (columns[i].Visible) displayIndex++;
        }
</code>```

Title: Help with converting bool to integer

Body:
I keep getting an error saying "Cannot implicitly covert type bool to int" I cannot figure out what to do with this. I get the error on: DisplayIndex = columns[i].Visible,

Code:

    private void SaveColumnOrder()
    {
        if (dgPortStatus.CanUserReorderColumns == true)
        {
            List<ColumnOrderItem> columnOrder = new List<ColumnOrderItem>();
            DataGridViewColumnCollection columns = this.Columns;
            for (int i = 0; i < columns.Count; i++)
            {
                columnOrder.Add(new ColumnOrderItem
                {
                    ColumnIndex = i,
                    DisplayIndex = columns[i].Visible,
                    Width = columns[i].Width
                });

            }

            portalDataGridViewSetting.Default.ColumnOrder[this.Name] = columnOrder;
            portalDataGridViewSetting.Default.Save();
        }
    }

Code:

 public sealed class ColumnOrderItem
    {
        public int DisplayIndex { get; set; }
        public int Width { get; set; }
        public bool Visible  { get; set; }
        public int ColumnIndex { get; set; }
    }

Body:
The only possible interpretation I can make of this is:

        int displayIndex = 0;
        for (int i = 0; i < columns.Count; i++)
        {
            columnOrder.Add(new ColumnOrderItem
            {
                ColumnIndex = i,
                DisplayIndex = displayIndex;
                Width = columns[i].Width
            });

            if (columns[i].Visible) displayIndex++;
        }


问:
smartcard probing with different SC families : command to clean the SC state
I wish to read some basic info from a bunch of smartcard from different vendors, different usage, different APDUs.
For example : national identification smartcard, EMV (payment), cellphone SIM, javacard, etc ...

I wrote a Java application.
Let me call the SC families A B C D E and with the same names the 5 subroutines, each one with the correct APDUs to read the basic info for one specific family of SC.

Unfortunately the order I issue the routines biases the successful results.

Example : with the subroutine order A B C D E, I can read SC of type A B C D, not E.

If I change the execution order to E A B C D, I can read E but now I fail with SC of type C.

I understand : some SC discard foreign APDUs ... other SC "hangs".

Is there a basic command to clean the state of smartcard ( and reader ) ?

So the order of execution of the subroutines doesn't change the output ?

A reset B reset C reset D reset etc...

Is it ATR ? Is it mandatory on each kind of SC ?

答:
You can use the Card.disconnect() method to reset card (beware of this).

But (IMHO) the best way is to use card ATR (as given by Card.getATR()) for guessing the correct card family (if possible). This way is also much faster. I used this approach for a demo handling several distinct contactless card products and it worked very well.

Some additional (random) notes:

Study the documentation for all families -- definitely there must be a reason for such behavior. Try to skip some subroutines and/or their APDU commands to pin it down.

In addition some APDUs might cause problems when sent accidentally (e.g. locked secret codes or locked authentication attempts). You should know what you are doing.

Most of product families have some way to be reliably detected -- see the documentation if you have it.

If any previously called subroutine uses SELECT to change selected application/file and succeeds it stays selected. Consider using explicit SELECT at the beginning of each of your subroutine (e.g. select expected AID or master file).

DESFire cards leave native mode and enter wrapped mode upon receiving non-native command APDU (which probably is not your case as you usually ISO wrap commands when using javax.smartcardio).

Good luck!


问:
Inverting a 4x4 matrix
I am looking for a sample code implementation on how to invert a 4x4 matrix. I know there is Gaussian eleminiation, LU decomposition, etc., but instead of looking at them in detail I am really just looking for the code to do this.

Language ideally C++, data is available in array of 16 floats in column-major order.

Title: Inverting a 4x4 matrix

Body:
If anyone looking for more costumized code and "easier to read", then I got this

var A2323 = m.m22 * m.m33 - m.m23 * m.m32 ;
var A1323 = m.m21 * m.m33 - m.m23 * m.m31 ;
var A1223 = m.m21 * m.m32 - m.m22 * m.m31 ;
var A0323 = m.m20 * m.m33 - m.m23 * m.m30 ;
var A0223 = m.m20 * m.m32 - m.m22 * m.m30 ;
var A0123 = m.m20 * m.m31 - m.m21 * m.m30 ;
var A2313 = m.m12 * m.m33 - m.m13 * m.m32 ;
var A1313 = m.m11 * m.m33 - m.m13 * m.m31 ;
var A1213 = m.m11 * m.m32 - m.m12 * m.m31 ;
var A2312 = m.m12 * m.m23 - m.m13 * m.m22 ;
var A1312 = m.m11 * m.m23 - m.m13 * m.m21 ;
var A1212 = m.m11 * m.m22 - m.m12 * m.m21 ;
var A0313 = m.m10 * m.m33 - m.m13 * m.m30 ;
var A0213 = m.m10 * m.m32 - m.m12 * m.m30 ;
var A0312 = m.m10 * m.m23 - m.m13 * m.m20 ;
var A0212 = m.m10 * m.m22 - m.m12 * m.m20 ;
var A0113 = m.m10 * m.m31 - m.m11 * m.m30 ;
var A0112 = m.m10 * m.m21 - m.m11 * m.m20 ;

var det = m.m00 * ( m.m11 * A2323 - m.m12 * A1323 + m.m13 * A1223 )
    - m.m01 * ( m.m10 * A2323 - m.m12 * A0323 + m.m13 * A0223 )
    + m.m02 * ( m.m10 * A1323 - m.m11 * A0323 + m.m13 * A0123 )
    - m.m03 * ( m.m10 * A1223 - m.m11 * A0223 + m.m12 * A0123 ) ;
det = 1 / det;

return new Matrix4x4() {
   m00 = det *   ( m.m11 * A2323 - m.m12 * A1323 + m.m13 * A1223 ),
   m01 = det * - ( m.m01 * A2323 - m.m02 * A1323 + m.m03 * A1223 ),
   m02 = det *   ( m.m01 * A2313 - m.m02 * A1313 + m.m03 * A1213 ),
   m03 = det * - ( m.m01 * A2312 - m.m02 * A1312 + m.m03 * A1212 ),
   m10 = det * - ( m.m10 * A2323 - m.m12 * A0323 + m.m13 * A0223 ),
   m11 = det *   ( m.m00 * A2323 - m.m02 * A0323 + m.m03 * A0223 ),
   m12 = det * - ( m.m00 * A2313 - m.m02 * A0313 + m.m03 * A0213 ),
   m13 = det *   ( m.m00 * A2312 - m.m02 * A0312 + m.m03 * A0212 ),
   m20 = det *   ( m.m10 * A1323 - m.m11 * A0323 + m.m13 * A0123 ),
   m21 = det * - ( m.m00 * A1323 - m.m01 * A0323 + m.m03 * A0123 ),
   m22 = det *   ( m.m00 * A1313 - m.m01 * A0313 + m.m03 * A0113 ),
   m23 = det * - ( m.m00 * A1312 - m.m01 * A0312 + m.m03 * A0112 ),
   m30 = det * - ( m.m10 * A1223 - m.m11 * A0223 + m.m12 * A0123 ),
   m31 = det *   ( m.m00 * A1223 - m.m01 * A0223 + m.m02 * A0123 ),
   m32 = det * - ( m.m00 * A1213 - m.m01 * A0213 + m.m02 * A0113 ),
   m33 = det *   ( m.m00 * A1212 - m.m01 * A0212 + m.m02 * A0112 ),
};

I don't write the code, but my program did. I made a small program to make a program that calculate the determinant and inverse of any N-matrix.

I do it because once in the past I need a code that inverses 5x5 matrix, but nobody in the earth have done this so I made one.

Take a look about the program here.

EDIT: The matrix layout is row-by-row (meaning m01 is in the first row and second column). Also the language is C#, but should be easy to convert into C.


问:
How To store form data in cookies OctoberCMS
I have been searching through the docs and can't seem to find an example of how to store cookies. I have a simple form with two inputs that I would like to store the values of when the user returns to the website after a selected amount of time. While the docs are thorough I can seem to find working example of certain thing as in Laravel. Loving this CMS so far, any suggestions would be appreciated.</p>

答:
Use the Cookie service facade to read and write cookies.

https://octobercms.com/docs/services/request-input#cookies

Retrieving a cookie value

```<code>$value = Cookie::get('name');
</code>```

Queue the cookie with the next page response

```<code>Cookie::queue($name, $value, $minutes);
</code>```

Body:
Use the Cookie service facade to read and write cookies.

https://octobercms.com/docs/services/request-input#cookies

Retrieving a cookie value

$value = Cookie::get('name');

Queue the cookie with the next page response

Cookie::queue($name, $value, $minutes);


问:
apache mod_rewrite equivalent for node.js?
Is there an equivalent module for Node.js that does what Apache's mod_rewrite does? or is there a standard language construct that provides equivalent functionality?

I'm just getting started with Node and looking to convert my server to this platform.

答:
There is a rewrite module. And when used with another proxy module in the middleware, they work together as a Reverse Proxy.

I use them while developing Single Page Applications in my local box (so I dont have to configure apache/nginx locally)

This in order to avoid CORS and send all pages (except js/css/images) to index.html for the SPA to work.

```<code>var connect = require('connect');
var modRewrite = require('connect-modrewrite');
var proxy = require('proxy-middleware');
var url = require('url');

var app = connect()
  .use(modRewrite([
    "^\/api\/(.*)        /send-to-api/api/$1    [L]",
    "^(.*)\/css\/(.*)    /send-to-ui/css/$2     [L]",
    "^(.*)\/js\/(.*)     /send-to-ui/js/$2      [L]",
    "^(.*)\/images\/(.*) /send-to-ui/images/$2  [L]",
    "^(.*)\/fonts\/(.*)  /send-to-ui/fonts/$2   [L]",
    "^(.*)               /send-to-ui/index.html [L]"
  ]))
  .use('/send-to-api', proxy(url.parse('http://api.server.dev/'))) // Don't forget the last backslash
  .use('/send-to-ui',  proxy(url.parse('http://ui.server.dev/' ))) // Don't forget the last backslash
  .listen(9000)
</code>```

Check that I use [L] flag because I want it to rewrite and skip the rest of the rules.

In this case, only the /api urls get proxied to api.server.dev, the rest goes to ui.server.dev.
The url prefixes /send-to-api and /send-to-ui are temporary and I use them to differentiate what will go where, it is removed by the connect before sent to their respective servers.

And yes, in case of redirects, proxy-middleware will change the Location header to be localhost:9000

Body:
There is a rewrite module. And when used with another proxy module in the middleware, they work together as a Reverse Proxy.

I use them while developing Single Page Applications in my local box (so I dont have to configure apache/nginx locally)

This in order to avoid CORS and send all pages (except js/css/images) to index.html for the SPA to work.

var connect = require('connect');
var modRewrite = require('connect-modrewrite');
var proxy = require('proxy-middleware');
var url = require('url');

var app = connect()
  .use(modRewrite([
    "^\/api\/(.*)        /send-to-api/api/$1    [L]",
    "^(.*)\/css\/(.*)    /send-to-ui/css/$2     [L]",
    "^(.*)\/js\/(.*)     /send-to-ui/js/$2      [L]",
    "^(.*)\/images\/(.*) /send-to-ui/images/$2  [L]",
    "^(.*)\/fonts\/(.*)  /send-to-ui/fonts/$2   [L]",
    "^(.*)               /send-to-ui/index.html [L]"
  ]))
  .use('/send-to-api', proxy(url.parse('http://api.server.dev/'))) // Don't forget the last backslash
  .use('/send-to-ui',  proxy(url.parse('http://ui.server.dev/' ))) // Don't forget the last backslash
  .listen(9000)

Check that I use [L] flag because I want it to rewrite and skip the rest of the rules.

In this case, only the /api urls get proxied to api.server.dev, the rest goes to ui.server.dev.
The url prefixes /send-to-api and /send-to-ui are temporary and I use them to differentiate what will go where, it is removed by the connect before sent to their respective servers.

And yes, in case of redirects, proxy-middleware will change the Location header to be localhost:9000


问:
Calculate distance between latitude and longitude in dataframe
I have 4 columns in my dataframe containing the following data:

```<code>Start_latitude<br>
Start_longitude<br>
Stop_latitude<br>
Stop_longitude<br>
</code>```

I need to compute distance between the latitude longitude pair and create a new column with the distance computed.

I came across a package (geopy) which can do this for me. But I need to pass a tuple to geopy. How do i apply this function (geopy) across the dataframe in pandas for all the records?

答:
From the documentation of geopy: https://pypi.python.org/pypi/geopy. You can do this by doing:

```<code>from geopy.distance import vincenty

# Define the two points
start = (start_latitute, start_longitude)
stop = (stop_latitude, stop_longitude)

# Print the vincenty distance
print(vincenty(start, stop).meters)

# Print the great circle distance
print(great_circle(start, stop).meters)
</code>```

Combining this with Pandas. Assuming you have a dataframe df. We first create the function:

```<code>def distance_calc (row):
    start = (row['start_latitute'], row['start_longitude'])
    stop = (row['stop_latitude'], row['stop_longitude'])

    return vincenty(start, stop).meters
</code>```

And then apply it to the dataframe:

```<code>df['distance'] = df.apply (lambda row: distance_calc (row),axis=1)
</code>```

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level.

Body:
I have 4 columns in my dataframe containing the following data:

Start_latitude

Start_longitude

Stop_latitude

Stop_longitude

I need to compute distance between the latitude longitude pair and create a new column with the distance computed.

I came across a package (geopy) which can do this for me. But I need to pass a tuple to geopy. How do i apply this function (geopy) across the dataframe in pandas for all the records?

Body:
From the documentation of geopy: https://pypi.python.org/pypi/geopy. You can do this by doing:

from geopy.distance import vincenty

# Define the two points
start = (start_latitute, start_longitude)
stop = (stop_latitude, stop_longitude)

# Print the vincenty distance
print(vincenty(start, stop).meters)

# Print the great circle distance
print(great_circle(start, stop).meters)

Combining this with Pandas. Assuming you have a dataframe df. We first create the function:

def distance_calc (row):
    start = (row['start_latitute'], row['start_longitude'])
    stop = (row['stop_latitude'], row['stop_longitude'])

    return vincenty(start, stop).meters

And then apply it to the dataframe:

df['distance'] = df.apply (lambda row: distance_calc (row),axis=1)

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level.


问:
Revealing board in minesweeper
Im working on a minesweeper program and i would like a little help with revealing the whole board after the player has clicked on a bomb . Here is the code :

```<code>package narkalieutis;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javafx.scene.control.MenuBar;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;

public class Narkalieutis extends Application {

private int TILE_SIZE = 50;
private static final int W = 500;
private static final int H = 500;

private int X_TILES = W / TILE_SIZE;
private int Y_TILES = H / TILE_SIZE;
private final String[] gameType = {"Easy", "Medium", "Hard", "Very Hard"};
private String difficulty;

@FXML
private Menu gameMenu;

private Tile[][] grid = new Tile[X_TILES][Y_TILES];
private Scene scene;

public MenuBar menu() {
    gameMenu = new Menu("Difficulty");
    for(String game : gameType){
        MenuItem menuItem = new MenuItem(game);
        menuItem.setUserData(game);
        menuItem.setOnAction((ActionEvent event) -> {
            selectGame(event);
        });
        gameMenu.getItems().add(menuItem);
    }
    MenuBar menuBar = new MenuBar(gameMenu);
    return menuBar;
}

private void selectGame(ActionEvent event) {
    MenuItem menuItem = (MenuItem)event.getSource();
    difficulty = (String)menuItem.getUserData();
    switch (difficulty) {
        case "Easy":
            TILE_SIZE = 2*TILE_SIZE;
            break;
        case "Medium":
            TILE_SIZE = 100;
            break;
        case "Hard":
            TILE_SIZE = 50;
            break;
        case "Very Hard":
            TILE_SIZE = 40;
            break;
        default:
            break;
    }
}

private Parent createContent() {
    VBox root = new VBox();
    Pane content = new Pane();
    content.setPrefSize(W, H);

    for (int y = 0; y < Y_TILES; y++) {
        for (int x = 0; x < X_TILES; x++) {
            Tile tile = new Tile(x, y, Math.random() < 0.2);

            grid[x][y] = tile;
            content.getChildren().add(tile);
        }
    }

    for (int y = 0; y < Y_TILES; y++) {
        for (int x = 0; x < X_TILES; x++) {
            Tile tile = grid[x][y];

            if (tile.hasBomb)
                continue;

            long bombs = getNeighbors(tile).stream().filter(t ->      t.hasBomb).count();

            if (bombs > 0)
                tile.text.setText(String.valueOf(bombs));
        }
    }
    root.getChildren().addAll(menu(), content);

    return root;
}

private List<Tile> getNeighbors(Tile tile) {
    List<Tile> neighbors = new ArrayList<>();

    int[] points = new int[] {
          -1, -1,
          -1, 0,
          -1, 1,
          0, -1,
          0, 1,
          1, -1,
          1, 0,
          1, 1
    };

    for (int i = 0; i < points.length; i++) {
        int dx = points[i];
        int dy = points[++i];

        int newX = tile.x + dx;
        int newY = tile.y + dy;

        if (newX >= 0 && newX < X_TILES
                && newY >= 0 && newY < Y_TILES) {
            neighbors.add(grid[newX][newY]);
        }
    }

    return neighbors;
}

private class Tile extends StackPane {
    private int x, y;
    private boolean hasBomb;
    private boolean isOpen = false;

    private Rectangle board = new Rectangle(TILE_SIZE - 2, TILE_SIZE - 2);
    private Text text = new Text();

  Alert alert = new Alert(AlertType.CONFIRMATION);

    public Tile(int x, int y, boolean hasBomb) {
        this.x = x;
        this.y = y;
        this.hasBomb = hasBomb;

        board.setStroke(Color.LIGHTGRAY);

        text.setFont(Font.font(18));
        text.setText(hasBomb ? "X" : "");
        text.setVisible(false);

        getChildren().addAll(board, text);

        setTranslateX(x * TILE_SIZE);
        setTranslateY(y * TILE_SIZE);

        setOnMouseClicked(e -> open());
    }

    public void open() {
        if (isOpen)
            return;

        if (hasBomb) {
    board.setVisible(true);
        Optional<ButtonType> result = alert.showAndWait();
            if (result.isPresent() && result.get() == ButtonType.OK) {
                scene.setRoot(createContent());
            }
           return;
        }

        isOpen = true;
        text.setVisible(true);
        board.setFill(null);

        if (text.getText().isEmpty()) {
            getNeighbors(this).forEach(Tile::open);
        }

        switch (text.getText()) {
            case "1":
                text.setFill(Color.BLUE);
                break;
            case "2":
                text.setFill(Color.FORESTGREEN);
                break;
            case "3":
                text.setFill(Color.RED);
                break;
            case "4":
                text.setFill(Color.DARKBLUE);
                break;
            case "5":
                text.setFill(Color.MAROON);
                break;
            case "6":
                text.setFill(Color.AQUAMARINE);
                break;
            case "7":
                text.setFill(Color.BLACK);
                break;
            case "8":
                text.setFill(Color.GRAY);
                break;
            default:
                break;
        }
    }
}

@Override
public void start(Stage stage) throws Exception {
    scene = new Scene(createContent());

    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch(args);
    }
}
</code>```

Im trying to make it so that when the player loses the content of all the tiles is revealed .

答:
You haven't explained exactly what problem you're having.  Based on what you've already achieved, it should be well within your ability to reveal all the tiles.

In createContent(), you already have nested for loops, one for x and one for y, that cover the entire board.  In this case they set the value of the tiles.

You simply need to do the same thing, but instead of set the tile value you simply reveal the tile, however you're doing that.  I imagine this would be replacing the grey tile with the icon representing what's inside it.

Title: Revealing board in minesweeper

Body:
Im working on a minesweeper program and i would like a little help with revealing the whole board after the player has clicked on a bomb . Here is the code :

package narkalieutis;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javafx.scene.control.MenuBar;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;

public class Narkalieutis extends Application {

private int TILE_SIZE = 50;
private static final int W = 500;
private static final int H = 500;

private int X_TILES = W / TILE_SIZE;
private int Y_TILES = H / TILE_SIZE;
private final String[] gameType = {"Easy", "Medium", "Hard", "Very Hard"};
private String difficulty;

@FXML
private Menu gameMenu;

private Tile[][] grid = new Tile[X_TILES][Y_TILES];
private Scene scene;

public MenuBar menu() {
    gameMenu = new Menu("Difficulty");
    for(String game : gameType){
        MenuItem menuItem = new MenuItem(game);
        menuItem.setUserData(game);
        menuItem.setOnAction((ActionEvent event) -> {
            selectGame(event);
        });
        gameMenu.getItems().add(menuItem);
    }
    MenuBar menuBar = new MenuBar(gameMenu);
    return menuBar;
}

private void selectGame(ActionEvent event) {
    MenuItem menuItem = (MenuItem)event.getSource();
    difficulty = (String)menuItem.getUserData();
    switch (difficulty) {
        case "Easy":
            TILE_SIZE = 2*TILE_SIZE;
            break;
        case "Medium":
            TILE_SIZE = 100;
            break;
        case "Hard":
            TILE_SIZE = 50;
            break;
        case "Very Hard":
            TILE_SIZE = 40;
            break;
        default:
            break;
    }
}

private Parent createContent() {
    VBox root = new VBox();
    Pane content = new Pane();
    content.setPrefSize(W, H);

    for (int y = 0; y < Y_TILES; y++) {
        for (int x = 0; x < X_TILES; x++) {
            Tile tile = new Tile(x, y, Math.random() < 0.2);

            grid[x][y] = tile;
            content.getChildren().add(tile);
        }
    }

    for (int y = 0; y < Y_TILES; y++) {
        for (int x = 0; x < X_TILES; x++) {
            Tile tile = grid[x][y];

            if (tile.hasBomb)
                continue;

            long bombs = getNeighbors(tile).stream().filter(t ->      t.hasBomb).count();

            if (bombs > 0)
                tile.text.setText(String.valueOf(bombs));
        }
    }
    root.getChildren().addAll(menu(), content);

    return root;
}

private List<Tile> getNeighbors(Tile tile) {
    List<Tile> neighbors = new ArrayList<>();

    int[] points = new int[] {
          -1, -1,
          -1, 0,
          -1, 1,
          0, -1,
          0, 1,
          1, -1,
          1, 0,
          1, 1
    };

    for (int i = 0; i < points.length; i++) {
        int dx = points[i];
        int dy = points[++i];

        int newX = tile.x + dx;
        int newY = tile.y + dy;

        if (newX >= 0 && newX < X_TILES
                && newY >= 0 && newY < Y_TILES) {
            neighbors.add(grid[newX][newY]);
        }
    }

    return neighbors;
}

private class Tile extends StackPane {
    private int x, y;
    private boolean hasBomb;
    private boolean isOpen = false;

    private Rectangle board = new Rectangle(TILE_SIZE - 2, TILE_SIZE - 2);
    private Text text = new Text();

  Alert alert = new Alert(AlertType.CONFIRMATION);

    public Tile(int x, int y, boolean hasBomb) {
        this.x = x;
        this.y = y;
        this.hasBomb = hasBomb;

        board.setStroke(Color.LIGHTGRAY);

        text.setFont(Font.font(18));
        text.setText(hasBomb ? "X" : "");
        text.setVisible(false);

        getChildren().addAll(board, text);

        setTranslateX(x * TILE_SIZE);
        setTranslateY(y * TILE_SIZE);

        setOnMouseClicked(e -> open());
    }

    public void open() {
        if (isOpen)
            return;

        if (hasBomb) {
    board.setVisible(true);
        Optional<ButtonType> result = alert.showAndWait();
            if (result.isPresent() && result.get() == ButtonType.OK) {
                scene.setRoot(createContent());
            }
           return;
        }

        isOpen = true;
        text.setVisible(true);
        board.setFill(null);

        if (text.getText().isEmpty()) {
            getNeighbors(this).forEach(Tile::open);
        }

        switch (text.getText()) {
            case "1":
                text.setFill(Color.BLUE);
                break;
            case "2":
                text.setFill(Color.FORESTGREEN);
                break;
            case "3":
                text.setFill(Color.RED);
                break;
            case "4":
                text.setFill(Color.DARKBLUE);
                break;
            case "5":
                text.setFill(Color.MAROON);
                break;
            case "6":
                text.setFill(Color.AQUAMARINE);
                break;
            case "7":
                text.setFill(Color.BLACK);
                break;
            case "8":
                text.setFill(Color.GRAY);
                break;
            default:
                break;
        }
    }
}

@Override
public void start(Stage stage) throws Exception {
    scene = new Scene(createContent());

    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch(args);
    }
}

Im trying to make it so that when the player loses the content of all the tiles is revealed .


问:
SKLearn Naive Bayes: add feature after tfidf vectorization
So I have been tasked with training a model on phone call transcripts. The following code does this. A little background info:
- x is a list of strings, each ith element is an entire transcript
- y is a list of booleans, stating the outcome of a call being positive or negative.

The following code works, but here is my issue. I want to include call duration as a feature to train on. I'd assume after the TFIDF transformer that vectorizes the transcripts, I would just concatenate the call duration feature to the TFIDF output right? Maybe this is easier than I think, but I have the transcripts and the durations all in the pandas data frame you see at the beginning of the code. So if I have that data frame column (numpy array) of durations, what do I need to do to add that feature into my model?

Additional Questions:

Am I missing a fundamental assumption about Naive Bayes model that limits me to vectorized strings?

At which step in my pipeline do I add the new feature?

Can this even be done in a pipeline or do I have to break it apart to do something like this?

Code:

```<code>import numpy as np
import pandas as pd
import random
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDClassifier
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import cross_val_score
from sklearn.feature_selection import SelectPercentile
from sklearn.metrics import roc_auc_score
from sklearn.feature_selection import chi2

def main():
filename = 'QA_training.pkl'
splitRatio = 0.67
dataframe = loadData(filename)
x, y = getTrainingData(dataframe)
print len(x), len(y)

x_train, x_test = splitDataset(x, splitRatio)
y_train, y_test = splitDataset(y, splitRatio)

#x_train = np.asarray(x_train)

percentiles = [10, 15, 20, 25, 30, 35, 40, 45, 50]

MNNB_pipe = Pipeline([('vec', CountVectorizer()),('tfidf', TfidfTransformer()),('select', SelectPercentile(score_func=chi2)),('clf', MultinomialNB())])
MNNB_param_grid = {
#'vec__max_features': (10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000),
'tfidf__use_idf': (True, False),
'tfidf__sublinear_tf': (True, False),
'vec__binary': (True, False),
'tfidf__norm': ('l1', 'l2'),
'clf__alpha': (1, 0.1, 0.01, 0.001, 0.0001, 0.00001),
'select__percentile': percentiles
}
MNNB_search = GridSearchCV(MNNB_pipe, param_grid=MNNB_param_grid, cv=10, scoring='roc_auc', n_jobs=-1, verbose=1)
MNNB_search = MNNB_search.fit(x_train, y_train)
MNNB_search_best_cv = cross_val_score(MNNB_search.best_estimator_, x_train, y_train, cv=10, scoring='roc_auc', n_jobs=-1, verbose=10)

SGDC_pipe = Pipeline([('vec', CountVectorizer()),('tfidf', TfidfTransformer()),('select', SelectPercentile(score_func=chi2)),('clf', SGDClassifier())])
SGDC_param_grid = {
#'vec__max_features': [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
'tfidf__use_idf': [True, False],
'tfidf__sublinear_tf': [True, False],
'vec__binary': [True, False],
'tfidf__norm': ['l1', 'l2'],
'clf__loss': ['modified_huber','log'],
'clf__penalty': ['l1','l2'],
'clf__alpha': [1e-3],
'clf__n_iter': [5,10],
'clf__random_state': [42],
'select__percentile': percentiles
}
SGDC_search = GridSearchCV(SGDC_pipe, param_grid=SGDC_param_grid, cv=10, scoring='roc_auc', n_jobs=-1, verbose=1)
SGDC_search = SGDC_search.fit(x_train, y_train)
SGDC_search_best_cv = cross_val_score(SGDC_search.best_estimator_, x_train, y_train, cv=10, scoring='roc_auc', n_jobs=-1, verbose=10)

# pre_SGDC = SGDC_clf.predict(x_test)
# print (np.mean(pre_SGDC == y_test))

mydata = [{'model': MNNB_search.best_estimator_.named_steps['clf'],'features': MNNB_search.best_estimator_.named_steps['select'], 'mean_cv_scores': MNNB_search_best_cv.mean()},
          #{'model': GNB_search.best_estimator_.named_steps['classifier'],'features': GNB_search.best_estimator_.named_steps['select'], 'mean_cv_scores': GNB_search_best_cv.mean()},
          {'model': SGDC_search.best_estimator_.named_steps['clf'],'features': SGDC_search.best_estimator_.named_steps['select'], 'mean_cv_scores': SGDC_search_best_cv.mean()}]
model_results_df = pd.DataFrame(mydata)
model_results_df.to_csv("best_model_results.csv")
</code>```

答:
As far as I'm aware, sklearn pipelines are API driven -- There's no real magic that happens in the pipeline itself.  So, from that perspective, you should be able to create your own wrapper around TfidfVectorizer that does what you want it to do.  For example, let's assume that you have a DataFrame that looks like this:

```<code>df = pd.DataFrame({'text': ['foo text', 'bar text'], 'duration': [1, 2]})
</code>```

you could probably implement your transform as follows:

```<code>class MyVectorizer(object):
    def __init__(self, tfidf_kwargs=None):
        self._tfidf = TfidfVectorizer(**(tfidf_kwargs or None))

    def fit(self, X, y=None):
        self._tfidf.fit(X['text'], y)
        return self

    def fit_transform(self, X, y=None):
        self.fit(X)
        return self.transform(X, copy=False)

    def transform(self, X, copy=True):
        result = self._tfidf.transform(X['text'], copy=copy)
        # result is a sparse matrix.  I'm not sure of a clean way
        # to add a column to a sparse matrix.  If you have the
        # memory, you can use a dense matrix instead...
        return np.column_stack((result, X['duration']))
</code>```

And then I think you should be all set to use this instead of the original tfidf vectorizer.

Body:
So I have been tasked with training a model on phone call transcripts. The following code does this. A little background info:
- x is a list of strings, each ith element is an entire transcript
- y is a list of booleans, stating the outcome of a call being positive or negative.

The following code works, but here is my issue. I want to include call duration as a feature to train on. I'd assume after the TFIDF transformer that vectorizes the transcripts, I would just concatenate the call duration feature to the TFIDF output right? Maybe this is easier than I think, but I have the transcripts and the durations all in the pandas data frame you see at the beginning of the code. So if I have that data frame column (numpy array) of durations, what do I need to do to add that feature into my model?

Additional Questions:

Am I missing a fundamental assumption about Naive Bayes model that limits me to vectorized strings?

At which step in my pipeline do I add the new feature?

Can this even be done in a pipeline or do I have to break it apart to do something like this?

Code:

import numpy as np
import pandas as pd
import random
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDClassifier
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import cross_val_score
from sklearn.feature_selection import SelectPercentile
from sklearn.metrics import roc_auc_score
from sklearn.feature_selection import chi2

def main():
filename = 'QA_training.pkl'
splitRatio = 0.67
dataframe = loadData(filename)
x, y = getTrainingData(dataframe)
print len(x), len(y)

x_train, x_test = splitDataset(x, splitRatio)
y_train, y_test = splitDataset(y, splitRatio)

#x_train = np.asarray(x_train)

percentiles = [10, 15, 20, 25, 30, 35, 40, 45, 50]

MNNB_pipe = Pipeline([('vec', CountVectorizer()),('tfidf', TfidfTransformer()),('select', SelectPercentile(score_func=chi2)),('clf', MultinomialNB())])
MNNB_param_grid = {
#'vec__max_features': (10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000),
'tfidf__use_idf': (True, False),
'tfidf__sublinear_tf': (True, False),
'vec__binary': (True, False),
'tfidf__norm': ('l1', 'l2'),
'clf__alpha': (1, 0.1, 0.01, 0.001, 0.0001, 0.00001),
'select__percentile': percentiles
}
MNNB_search = GridSearchCV(MNNB_pipe, param_grid=MNNB_param_grid, cv=10, scoring='roc_auc', n_jobs=-1, verbose=1)
MNNB_search = MNNB_search.fit(x_train, y_train)
MNNB_search_best_cv = cross_val_score(MNNB_search.best_estimator_, x_train, y_train, cv=10, scoring='roc_auc', n_jobs=-1, verbose=10)

SGDC_pipe = Pipeline([('vec', CountVectorizer()),('tfidf', TfidfTransformer()),('select', SelectPercentile(score_func=chi2)),('clf', SGDClassifier())])
SGDC_param_grid = {
#'vec__max_features': [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
'tfidf__use_idf': [True, False],
'tfidf__sublinear_tf': [True, False],
'vec__binary': [True, False],
'tfidf__norm': ['l1', 'l2'],
'clf__loss': ['modified_huber','log'],
'clf__penalty': ['l1','l2'],
'clf__alpha': [1e-3],
'clf__n_iter': [5,10],
'clf__random_state': [42],
'select__percentile': percentiles
}
SGDC_search = GridSearchCV(SGDC_pipe, param_grid=SGDC_param_grid, cv=10, scoring='roc_auc', n_jobs=-1, verbose=1)
SGDC_search = SGDC_search.fit(x_train, y_train)
SGDC_search_best_cv = cross_val_score(SGDC_search.best_estimator_, x_train, y_train, cv=10, scoring='roc_auc', n_jobs=-1, verbose=10)

# pre_SGDC = SGDC_clf.predict(x_test)
# print (np.mean(pre_SGDC == y_test))

mydata = [{'model': MNNB_search.best_estimator_.named_steps['clf'],'features': MNNB_search.best_estimator_.named_steps['select'], 'mean_cv_scores': MNNB_search_best_cv.mean()},
          #{'model': GNB_search.best_estimator_.named_steps['classifier'],'features': GNB_search.best_estimator_.named_steps['select'], 'mean_cv_scores': GNB_search_best_cv.mean()},
          {'model': SGDC_search.best_estimator_.named_steps['clf'],'features': SGDC_search.best_estimator_.named_steps['select'], 'mean_cv_scores': SGDC_search_best_cv.mean()}]
model_results_df = pd.DataFrame(mydata)
model_results_df.to_csv("best_model_results.csv")

Body:
As far as I'm aware, sklearn pipelines are API driven -- There's no real magic that happens in the pipeline itself.  So, from that perspective, you should be able to create your own wrapper around TfidfVectorizer that does what you want it to do.  For example, let's assume that you have a DataFrame that looks like this:

df = pd.DataFrame({'text': ['foo text', 'bar text'], 'duration': [1, 2]})

you could probably implement your transform as follows:

class MyVectorizer(object):
    def __init__(self, tfidf_kwargs=None):
        self._tfidf = TfidfVectorizer(**(tfidf_kwargs or None))

    def fit(self, X, y=None):
        self._tfidf.fit(X['text'], y)
        return self

    def fit_transform(self, X, y=None):
        self.fit(X)
        return self.transform(X, copy=False)

    def transform(self, X, copy=True):
        result = self._tfidf.transform(X['text'], copy=copy)
        # result is a sparse matrix.  I'm not sure of a clean way
        # to add a column to a sparse matrix.  If you have the
        # memory, you can use a dense matrix instead...
        return np.column_stack((result, X['duration']))

And then I think you should be all set to use this instead of the original tfidf vectorizer.


问:
General ASP.NET Session questions
I have some questions in regards to Session in ASP.NET

As we need to manually create cookie, does Session automatically created by the application when the application starts?

Is it just only one Session object to store all users'information? Or there is new Session object for every user?

There is Timeout attribute for Session, can I use this attribute instead of setting expiry time for cookie?

答:
Session Start is its own part of the lifecycle. Each user gets their own session.

Not sure why you would want to link the cookies and sessions in that way. If you just want something alive during the session, just store it in the session.

Title: General ASP.NET Session questions


问:
Is it possible to mock in Django Behave tests?
I have seen a lot of articles on unit tests with mocking.

I have a simple checkout form which submits card details to a payment gateway. Is it possible to mock the payment gateway response in Behave tests?

```<code>@then(u'I submitted checkout form')
def submit_checkout_form(context):
    "Mock your response Do not send/post request to payment gateway, but create order"

@then(u'I see my order successfully created')
def inspect_order_page(context):
    "Thank you page: check product & price"
</code>```

I am wondering, is it possible to mock in Behave tests?

答:
You can try:</p>

```<code>@then(u'I submitted checkout form')
def submit_checkout_form(context):
    with mock.patch('path.module', mock.Mock(return_value=None)):
        **type here**
</code>```

Body:
I have seen a lot of articles on unit tests with mocking.

I have a simple checkout form which submits card details to a payment gateway. Is it possible to mock the payment gateway response in Behave tests?

@then(u'I submitted checkout form')
def submit_checkout_form(context):
    "Mock your response Do not send/post request to payment gateway, but create order"

@then(u'I see my order successfully created')
def inspect_order_page(context):
    "Thank you page: check product & price"

I am wondering, is it possible to mock in Behave tests?

Body:
You can try:

@then(u'I submitted checkout form')
def submit_checkout_form(context):
    with mock.patch('path.module', mock.Mock(return_value=None)):
        **type here**


问:
How to provide an initial plotting platform to add additional plots in R?
I'm trying to use a for loop to draw 3 side by side curves in R but without getting any error message nothing shows?

I suspect something should provide an initial plotting platform for the first curve, and then the second and the third plots can be added. Can the initial plotting platform be plot.new() for example?

Note: I'm definitely trying to avoid using long if else statements as a solution.

Here is my R code:

```<code>for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
   col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )

}
</code>```

答:
Since you'd like to avoid if statements, how about

```<code>p = c(.1, .5, .9)
col = c("red3", "green3", "blue")

for(i in 1:3) curve(dbinom(x, size = 100, prob = p[i]), add = i!=1,
    ty = "h", xlim = c(0, 100), col = col[i],
    xlab = "Number of Agreements", ylab = "Probability", las = 1 )
</code>```

Body:
I'm trying to use a for loop to draw 3 side by side curves in R but without getting any error message nothing shows?

I suspect something should provide an initial plotting platform for the first curve, and then the second and the third plots can be added. Can the initial plotting platform be plot.new() for example?

Note: I'm definitely trying to avoid using long if else statements as a solution.

Here is my R code:

for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
   col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )

}

Body:
Since you'd like to avoid if statements, how about

p = c(.1, .5, .9)
col = c("red3", "green3", "blue")

for(i in 1:3) curve(dbinom(x, size = 100, prob = p[i]), add = i!=1,
    ty = "h", xlim = c(0, 100), col = col[i],
    xlab = "Number of Agreements", ylab = "Probability", las = 1 )


问:
How can I get specific object and its index that was changed from $watch Angular
I get array of objects from API that is updated every 2 seconds. I have $watch that is looking for any changes in this array. I need to know what is element or elements are changed and their index, in order to set background color to these elements which were changed.
Thanks in advance.

```<code>$scope.$watch('recentUpdates', function(newValue, oldValue) {
  if(oldValue != newValue && newValue != null){
    $scope.recentUpdates= newValue;
    console.log(newValue)
    setColor(newValue) ;
}else{
    console.log('hey, value is not changed!');
}
</code>```

});

SetColor function need to get object and index of an element in order to update its color.

答:
I presume there can be more than one change per cycle.  So, you can just cycle through the array looking for changes.  I also assume that the length of the array doesn't change.

```<code>$scope.$watch('recentUpdates', function(newValue, oldValue) {
  for (var i=0; i < newValue.length; i++) {
    if (newValue[i] !== oldValue[i]) {
      console.log(newValue[i]);
      setColor(newValue[i], i) ;
    }
  }
});
</code>```

You then pass the new value and the position to your setColor function.  I also removed $scope.recentUpdates= newValue; as there was no reason to do this.

You could also use angular.forEach to loop through the array if you preferred.

Body:
I get array of objects from API that is updated every 2 seconds. I have $watch that is looking for any changes in this array. I need to know what is element or elements are changed and their index, in order to set background color to these elements which were changed.
Thanks in advance.

$scope.$watch('recentUpdates', function(newValue, oldValue) {
  if(oldValue != newValue && newValue != null){
    $scope.recentUpdates= newValue;
    console.log(newValue)
    setColor(newValue) ;
}else{
    console.log('hey, value is not changed!');
}

});

SetColor function need to get object and index of an element in order to update its color.

Body:
I presume there can be more than one change per cycle.  So, you can just cycle through the array looking for changes.  I also assume that the length of the array doesn't change.

$scope.$watch('recentUpdates', function(newValue, oldValue) {
  for (var i=0; i < newValue.length; i++) {
    if (newValue[i] !== oldValue[i]) {
      console.log(newValue[i]);
      setColor(newValue[i], i) ;
    }
  }
});

You then pass the new value and the position to your setColor function.  I also removed $scope.recentUpdates= newValue; as there was no reason to do this.

You could also use angular.forEach to loop through the array if you preferred.


问:
Equivalent of angular.equals in angular2
I am working on migration of angular 1 project to angular 2 . In angular 1 project I was using angular.equals for object comparison angular.equals($ctrl.obj1, $ctrl.newObj); , I searched online for equivalent method in angular 2 but could not find any matching result.

答:
Instead of writing a function to iterate through the objects, you could just use JSON.stringify and compare the two strings?

Example:

```<code>var obj1 = {
  title: 'title1',
  tags: []
}

var obj2 = {
  title: 'title1',
  tags: ['r']
}

console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));

console.log(JSON.stringify(obj1) === JSON.stringify(obj2));
</code>```

Body:
Instead of writing a function to iterate through the objects, you could just use JSON.stringify and compare the two strings?

Example:

var obj1 = {
  title: 'title1',
  tags: []
}

var obj2 = {
  title: 'title1',
  tags: ['r']
}

console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));

console.log(JSON.stringify(obj1) === JSON.stringify(obj2));