问:
WCF in IIS, using MSMQ in workgroup mode
I've been trying out MSMQ with WCF, but I can't seem to get it to work properly. I've got the client (which sends messages to the queue) working, by using WCF and a service reference. The code that does this is more or less this:

```<code>static void Main(string[] args)
{
    var client = new MsmqServiceReference.MsmqContractClient();
    client.SendMessage("TEST");
    client.Close();
    Console.ReadKey();
}
</code>```

Where MsmqContractClient is a proxy generated by visual studio when I add a service reference. The endpoint in the app.config is pointing to a msmqueue:

```<code><client>
  <endpoint
    address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
    binding="netMsmqBinding"
    bindingConfiguration="MsmqBindingNonTransactionalNoSecurity"
    contract="MsmqServiceReference.IMsmqContract" name="MsmqService" />
</client>
</code>```

This works, messages are being posted to the queue.

Now I am trying to actually get the service to work, but I keep getting this error:

Binding validation failed because the
  binding's MsmqAuthenticationMode
  property is set to WindowsDomain but
  MSMQ is installed with Active
  Directory integration disabled. The
  channel factory or service host cannot
  be opened.

Things I've tried are:

give everyone full access (including anonymous logon) to the queue

configuring the app to use a specific binding from the config file using:

```<code><bindings>
  <netMsmqBinding>
     <binding name="MsmqBindingNonTransactionalNoSecurity"
              deadLetterQueue="Custom"
              exactlyOnce="false">
       <security mode="None" />
     </binding>
  </netMsmqBinding>
</bindings>
</code>```

I tried running the app pool in IIS (7) under my own account and administrator account

What stumps me is that it keeps trying to convince me that I am trying to run it with WindowsDomain authentication. I stated that I DIDN'T want to do that with the security mode set to none, right?

My app at the moment is simply a webforms asp.net site with a WCF service added to it.

If someone could at least point me into the right direction I'll be very grateful, as I've spent too much time on this already.

It seems as if the configuration is being ignored, or overridden. The full error message:

```<code>WebHost failed to process a request.
 Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/63721755
 Exception: System.ServiceModel.ServiceActivationException: The service '/MsmqService/MsmqService.svc' cannot be activated due to an exception during compilation.  The exception message is: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.. ---> System.InvalidOperationException: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.
   at System.ServiceModel.Channels.MsmqVerifier.VerifySecurity(MsmqTransportSecurity security, Nullable`1 useActiveDirectory)
   at System.ServiceModel.Channels.MsmqVerifier.VerifyReceiver(MsmqReceiveParameters receiveParameters, Uri listenUri)
   at System.ServiceModel.Channels.MsmqTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
   at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
   at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnBeginOpen()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open()
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   --- End of inner exception stack trace ---
   at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
 Process Name: w3wp
 Process ID: 5660
</code>```

I tried figuring out what happens using Reflector, but it simply seems that somehow a MsmqTransportBindingElement is passed into the channel building process, which is convinced it has to use WindowsDomain as a security measure. However, I have security set to none in my config file. Any ideas on where this override behavior comes from?

Resolution:

I feel really stupid on one hand, but I feel there's room for improvement on the other hand.
The short version is that I messed up the value in the 'name' attribute on the service element:

```<code><services>
  <service name="WcfService.MsmqService">
    <!--        <endpoint binding="mexHttpBinding" contract="IMetadataExchange" />-->
    <endpoint name="msmq"
            address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
            binding="netMsmqBinding"
            bindingConfiguration="NoSecurity"
            contract="WcfService.IMsmqContract" />
  </service>
</services>
</code>```

The name was the same as on my client, however, the client had bindings generated by visual studio. I gave it a different name (MsmqService), so the name value was 'MsmqService.MsmqService'.

What kinda bothers me is that I didn't get any warning whatsoever that I was configuring a non-existing service, or any indication I am using the default configuration for the service. It would be really nice if the framework would at least generate a warning somewhere that I am using defaults, or an option to turn on some form of strict mode. Either way, thanks for all your input, and I am going to bang my head against the wall a few more times.

And yes, you may now point and laugh ;-)

答:
Not sure if this is going to solve your concrete problem here, but there's a really good three-part blog post series by Tom Hollander:

MSMQ, WCF and IIS: Getting them to play nice (part 1 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 2 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 3 of 3)

Also, since the Active Directory stuff seems to be the problem, have you tried to tell your MSMQ binding to not use AD ??

```<code><bindings>
  <netMsmqBinding>
     <binding name="MsmqBindingNonTransactionalNoSecurity"
              deadLetterQueue="Custom" exactlyOnce="false"
              useActiveDirectory="false">   <== try this setting here!
        <security mode="None" />
     </binding>
  </netMsmqBinding>
</bindings>
</code>```

Body:
I've been trying out MSMQ with WCF, but I can't seem to get it to work properly. I've got the client (which sends messages to the queue) working, by using WCF and a service reference. The code that does this is more or less this:

static void Main(string[] args)
{
    var client = new MsmqServiceReference.MsmqContractClient();
    client.SendMessage("TEST");
    client.Close();
    Console.ReadKey();
}

Where MsmqContractClient is a proxy generated by visual studio when I add a service reference. The endpoint in the app.config is pointing to a msmqueue:

<client>
  <endpoint
    address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
    binding="netMsmqBinding"
    bindingConfiguration="MsmqBindingNonTransactionalNoSecurity"
    contract="MsmqServiceReference.IMsmqContract" name="MsmqService" />
</client>

This works, messages are being posted to the queue.

Now I am trying to actually get the service to work, but I keep getting this error:

Binding validation failed because the
  binding's MsmqAuthenticationMode
  property is set to WindowsDomain but
  MSMQ is installed with Active
  Directory integration disabled. The
  channel factory or service host cannot
  be opened.

Things I've tried are:

give everyone full access (including anonymous logon) to the queue

configuring the app to use a specific binding from the config file using:

<bindings>
  <netMsmqBinding>
     <binding name="MsmqBindingNonTransactionalNoSecurity"
              deadLetterQueue="Custom"
              exactlyOnce="false">
       <security mode="None" />
     </binding>
  </netMsmqBinding>
</bindings>

I tried running the app pool in IIS (7) under my own account and administrator account

What stumps me is that it keeps trying to convince me that I am trying to run it with WindowsDomain authentication. I stated that I DIDN'T want to do that with the security mode set to none, right?

My app at the moment is simply a webforms asp.net site with a WCF service added to it.

If someone could at least point me into the right direction I'll be very grateful, as I've spent too much time on this already.

It seems as if the configuration is being ignored, or overridden. The full error message:

WebHost failed to process a request.
 Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/63721755
 Exception: System.ServiceModel.ServiceActivationException: The service '/MsmqService/MsmqService.svc' cannot be activated due to an exception during compilation.  The exception message is: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.. ---> System.InvalidOperationException: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.
   at System.ServiceModel.Channels.MsmqVerifier.VerifySecurity(MsmqTransportSecurity security, Nullable`1 useActiveDirectory)
   at System.ServiceModel.Channels.MsmqVerifier.VerifyReceiver(MsmqReceiveParameters receiveParameters, Uri listenUri)
   at System.ServiceModel.Channels.MsmqTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
   at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
   at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnBeginOpen()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open()
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   --- End of inner exception stack trace ---
   at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
 Process Name: w3wp
 Process ID: 5660

I tried figuring out what happens using Reflector, but it simply seems that somehow a MsmqTransportBindingElement is passed into the channel building process, which is convinced it has to use WindowsDomain as a security measure. However, I have security set to none in my config file. Any ideas on where this override behavior comes from?

Resolution:

I feel really stupid on one hand, but I feel there's room for improvement on the other hand.
The short version is that I messed up the value in the 'name' attribute on the service element:

<services>
  <service name="WcfService.MsmqService">

    <endpoint name="msmq"
            address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
            binding="netMsmqBinding"
            bindingConfiguration="NoSecurity"
            contract="WcfService.IMsmqContract" />
  </service>
</services>

The name was the same as on my client, however, the client had bindings generated by visual studio. I gave it a different name (MsmqService), so the name value was 'MsmqService.MsmqService'.

What kinda bothers me is that I didn't get any warning whatsoever that I was configuring a non-existing service, or any indication I am using the default configuration for the service. It would be really nice if the framework would at least generate a warning somewhere that I am using defaults, or an option to turn on some form of strict mode. Either way, thanks for all your input, and I am going to bang my head against the wall a few more times.

And yes, you may now point and laugh ;-)

Body:
Not sure if this is going to solve your concrete problem here, but there's a really good three-part blog post series by Tom Hollander:

MSMQ, WCF and IIS: Getting them to play nice (part 1 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 2 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 3 of 3)

Also, since the Active Directory stuff seems to be the problem, have you tried to tell your MSMQ binding to not use AD ??

<bindings>
  <netMsmqBinding>
     <binding name="MsmqBindingNonTransactionalNoSecurity"
              deadLetterQueue="Custom" exactlyOnce="false"
              useActiveDirectory="false">   <== try this setting here!
        <security mode="None" />
     </binding>
  </netMsmqBinding>
</bindings>


来源: stackexchange

问:
Using JSON files to initialize static class
I have a class thats acts as a properties/configurations class. In addition to this, I also have a JSON file which contains the properties.

Right now, in my main class, I am instantiating a property object and then using the gson's fromJson method to read in the JSON file into this object. I am then passing this to my other classes so that they will be able to access the properties.

I want to refactor my design so that this property class will have static variables and methods, so that I don't have to instantiate it in order to access the properties.

I am wondering if this is possible using gson, or if this design is a good idea.

Thank you!

答:
Feel free to ignore the people saying "don't do that".  You know your code and requirements better than we do.

What you're looking for is called "reflection" in java.  You can loop over your JSON key/value pairs, then look up the field using reflection, then set the field w/ the value.

This question has a good breakdown on how to do that.

Then use a static initialize block start your import function.

Good luck!

EDIT:

Some example code to show this isn't some crazy, complicated, unreadable horrible, no-good, very-bad idea that only James Gosling should ever attempt.  :)

```<code>import java.lang.reflect.*;
import net.sf.json.*;

public class Test {
    public static String hello = null;

    static JSONObject readConfig() {
        // fake read a config file
        String settings = "{\"hello\": \"world\"}";
        JSONObject obj = (JSONObject)JSONSerializer.toJSON(settings);
        return obj;
    }

    static {
        // load config into static variables
        JSONObject config = Test.readConfig();
        for (Object key : config.keySet()) {
          String value = config.getString((String)key);
          try {
              Field field = Test.class.getDeclaredField((String)key);
              field.set(null, value);
              System.out.println("Set '"+ key +"' to '"+ value +"'.");
          } catch (Exception e) {
             System.err.println("Could not set unknown prop '"+ key +"' because "+ e +".");
          }
        }
    }

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

And it running:

```<code>$ javac -cp .:/usr/share/java/* Test.java
$ java -cp .:/usr/share/java/* Test
Set 'hello' to 'world'.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Feel free to ignore the people saying "don't do that".  You know your code and requirements better than we do.

What you're looking for is called "reflection" in java.  You can loop over your JSON key/value pairs, then look up the field using reflection, then set the field w/ the value.

This question has a good breakdown on how to do that.

Then use a static initialize block start your import function.

Good luck!

EDIT:

Some example code to show this isn't some crazy, complicated, unreadable horrible, no-good, very-bad idea that only James Gosling should ever attempt.  :)

import java.lang.reflect.*;
import net.sf.json.*;

public class Test {
    public static String hello = null;

    static JSONObject readConfig() {
        // fake read a config file
        String settings = "{\"hello\": \"world\"}";
        JSONObject obj = (JSONObject)JSONSerializer.toJSON(settings);
        return obj;
    }

    static {
        // load config into static variables
        JSONObject config = Test.readConfig();
        for (Object key : config.keySet()) {
          String value = config.getString((String)key);
          try {
              Field field = Test.class.getDeclaredField((String)key);
              field.set(null, value);
              System.out.println("Set '"+ key +"' to '"+ value +"'.");
          } catch (Exception e) {
             System.err.println("Could not set unknown prop '"+ key +"' because "+ e +".");
          }
        }
    }

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

And it running:

$ javac -cp .:/usr/share/java/* Test.java
$ java -cp .:/usr/share/java/* Test
Set 'hello' to 'world'.


问:
Add View - Cannot retrieve Metadata
I am still new to MVC, but I am starting to get a feel for the general picture however I still mixup things like namespace, or using and I THINK that may be the case here where I am mis-referencing something.

Question: I am trying to add an EmployeeInfo View, with a List template, with Model class: EmployeeInfo, with data context class: MoviesEntities

The auto-generation will not execute. When I right-click in Controller's method EmployeeInfo. I select the option "Add View", fill in the information, then hit add and during the scaffolding load screen it gives me the error as follows.

There was an error running the selected code generator: 'Unable to
  retrieve metadata for 'WebApplication2.Models.EmployeeInfo'.'

My controller

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Entities;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class MoviesController : Controller
    {
        private MoviesEntities db = new MoviesEntities();

        // GET: /Movies/
        public ActionResult Index()
        {
            return View(db.Movies.ToList());
        }

        public ActionResult EmployeeInfo()
        {
            var query =
            from m in db.Movies
            join me in db.MovieEmployees
            on m.ID equals me.movieID
            join e in db.Employees
            on me.employeeID equals e.ID
            join r in db.Roles
            on me.roleID equals r.ID

            select new EmployeeInfo() {Name = e.Name, Role = r.RoleType, Birthday = e.Birthday };

            return View(query.Distinct().ToList());
          }
    }
}
</code>```

My context

```<code>//------------------------------------------------------------------------------
// <auto-generated> Built from database Movie </auto-generated>
//------------------------------------------------------------------------------

namespace WebApplication2.Entities
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using movieLayer;
    using WebApplication2.Models;

    public partial class MoviesEntities : DbContext
    {
        public MoviesEntities()
            : base("name=MoviesEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Employee> Employees { get; set; }
        public virtual DbSet<Location> Locations { get; set; }
        public virtual DbSet<Movie> Movies { get; set; }
        public virtual DbSet<MovieEmployee> MovieEmployees { get; set; }
        public virtual DbSet<Role> Roles { get; set; }
        public virtual DbSet<Show> Shows { get; set; }
        public virtual DbSet<sysdiagram> sysdiagrams { get; set; }

        public System.Data.Entity.DbSet<WebApplication2.Models.EmployeeInfo> EmployeeInfoes { get; set; }
    }
}
</code>```

Model of EmployeeInfo:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication2.Models

{
    public class EmployeeInfo
    {

        public EmployeeInfo() { }

        public string Name { get; set; }
        public string Role { get; set; }
        public DateTime Birthday { get; set; }
    }
}
</code>```

答:
What I did to solve this issue that I encountered when adding a scaffolded view by right clicking the controller action was to leave the "Data context class" field blank.

I'm not entirely sure as to why this works but I found this method from ASP.NET forums.

Title: Add View - Cannot retrieve Metadata

Body:
I am still new to MVC, but I am starting to get a feel for the general picture however I still mixup things like namespace, or using and I THINK that may be the case here where I am mis-referencing something.

Question: I am trying to add an EmployeeInfo View, with a List template, with Model class: EmployeeInfo, with data context class: MoviesEntities

The auto-generation will not execute. When I right-click in Controller's method EmployeeInfo. I select the option "Add View", fill in the information, then hit add and during the scaffolding load screen it gives me the error as follows.

There was an error running the selected code generator: 'Unable to
  retrieve metadata for 'WebApplication2.Models.EmployeeInfo'.'

My controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Entities;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class MoviesController : Controller
    {
        private MoviesEntities db = new MoviesEntities();

        // GET: /Movies/
        public ActionResult Index()
        {
            return View(db.Movies.ToList());
        }

        public ActionResult EmployeeInfo()
        {
            var query =
            from m in db.Movies
            join me in db.MovieEmployees
            on m.ID equals me.movieID
            join e in db.Employees
            on me.employeeID equals e.ID
            join r in db.Roles
            on me.roleID equals r.ID

            select new EmployeeInfo() {Name = e.Name, Role = r.RoleType, Birthday = e.Birthday };

            return View(query.Distinct().ToList());
          }
    }
}

My context

//------------------------------------------------------------------------------
// <auto-generated> Built from database Movie </auto-generated>
//------------------------------------------------------------------------------

namespace WebApplication2.Entities
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using movieLayer;
    using WebApplication2.Models;

    public partial class MoviesEntities : DbContext
    {
        public MoviesEntities()
            : base("name=MoviesEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Employee> Employees { get; set; }
        public virtual DbSet<Location> Locations { get; set; }
        public virtual DbSet<Movie> Movies { get; set; }
        public virtual DbSet<MovieEmployee> MovieEmployees { get; set; }
        public virtual DbSet<Role> Roles { get; set; }
        public virtual DbSet<Show> Shows { get; set; }
        public virtual DbSet<sysdiagram> sysdiagrams { get; set; }

        public System.Data.Entity.DbSet<WebApplication2.Models.EmployeeInfo> EmployeeInfoes { get; set; }
    }
}

Model of EmployeeInfo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication2.Models

{
    public class EmployeeInfo
    {

        public EmployeeInfo() { }

        public string Name { get; set; }
        public string Role { get; set; }
        public DateTime Birthday { get; set; }
    }
}


问:
Retrieving data from MS Access database using timestamps i.e. starting and ending date on a user form
I had a question about retrieving data from MS Access database using timestamps i.e. starting and ending date on a user form. Kindly let me know if and what's the process to do that. I'm using Microsoft Visual Studio 2015. Website user interface will be in Asp.net with VB. Although I have tried passing parameters I am not understanding why it is not reflecting on the Grid View

ASPX.VB Code

```<code>Partial Class _Default

Inherits System.Web.UI.Page

Public dad As OleDbDataAdapter

Protected Sub Page_Load(sender As Object, e As EventArgs)

End Sub

Protected Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged

End Sub

Protected Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged

End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

    Dim connectionString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;Data" + " Source=App_Data/VQT_GL Testing.mdb"
    Dim ds As New DataSet()
    Dim conn As New OleDbConnection(connectionString)
    conn.Open()

    Dim cmd As New OleDbCommand("SELECT AVG(POLQA_Score) AS MEAN FROM VQTPOLQA WHERE VQT_Timestamp BETWEEN ? AND ?", conn)
    cmd.Parameters.AddWithValue("@StartDate", (TextBox3.Text))
    cmd.Parameters.AddWithValue("@EndDate", (TextBox2.Text))

    GridView1.DataSource = ds

End Sub

End Class
</code>```

ASPX CODE

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>MOS FORM HOME</title>
    <script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"type="text/javascript"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"/>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript" ></script>
    <script src="Scripts/jquery.dynDateTime.min.js" type="text/javascript"></script>
    <script src="Scripts/calendar-en.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-timepicker-addon.js"></script>
    <link href="Styles/calendar-blue.css" rel="stylesheet" type="text/css" />
    <link href="Styles/jquery-ui-timepicker-addon.css" rel="stylesheet"  type="text/css"/>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextBox3.ClientID %>").dynDateTime({
            showsTime: true,
            ifFormat: "%m/%d/%Y %H:%M:%S",
            daFormat: "%l;%M %p, %e %m, %Y",
            align: "BR",
            electric: false,
            singleClick: false,
            displayArea: ".siblings('.dtcDisplayArea')",
            button: ".next()"
        });

         $("#<%=TextBox2.ClientID %>").dynDateTime({
            showsTime: true,
            ifFormat: "%m/%d/%Y %H:%M:%S",
            daFormat: "%l;%M %p, %e %m, %Y",
            align: "BR",
            electric: false,
            singleClick: false,
            displayArea: ".siblings('.dtcDisplayArea')",
            button: ".next()"
        });
    });
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div style="height: 74px">

                                                                              MOS FORM HOME PAGE</div>
        <p>
            START DATE
            <asp:TextBox ID="TextBox3" runat="server" TextMode="DateTime" Width="181px"  BorderColor="Black" BorderStyle="Solid"></asp:TextBox><img src="calender.png" />

        </p>
        <p>
            END DATE       <asp:TextBox ID="TextBox2" runat="server" TextMode="DateTime" Width="188px" BorderColor="Black" BorderStyle="Solid"></asp:TextBox><img src="calender.png" />
        </p>
        <p>
             </p>
        <p>
            <asp:Button ID="Button1" runat="server" Text="Submit" onclick="btnSave_Click"/>
        </p>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" DataSourceID="SqlDataSource2" GridLines="Horizontal" Height="146px" Width="53px">
            <Columns>
                <asp:BoundField DataField="MEAN" HeaderText="MEAN" ReadOnly="True" SortExpression="MEAN" />
            </Columns>
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#487575" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#275353" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:VQT_GL TestingConnectionString %>" ProviderName="<%$ ConnectionStrings:VQT_GL TestingConnectionString.ProviderName %>" SelectCommand="SELECT AVG(POLQA_Score) AS MEAN FROM VQTPOLQA WHERE VQT_Timestamp BETWEEN ? AND ?">
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox3" DefaultValue="" Name="?" PropertyName="Text" />
                <asp:ControlParameter ControlID="TextBox2" DefaultValue="" Name="?" PropertyName="Text" />
            </SelectParameters>
        </asp:SqlDataSource>

        <br />

        <asp:AccessDataSource runat="server" DataFile="~/App_Data/VQT_GL Testing.mdb" SelectCommand="SELECT AVG(POLQA_Score) AS MEANPOLQA FROM VQTPOLQA WHERE (VQT_Timestamp BETWEEN ? AND ?)">
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox3" DefaultValue="" Name="?" PropertyName="Text" />
                <asp:ControlParameter ControlID="TextBox2" Name="?" PropertyName="Text" />
            </SelectParameters>
        </asp:AccessDataSource>
    </form>
</body>
</html>
</code>```

答:
At first sight, your problem seems to be with your parameters to your OleDbCommand.  You are using cmd.Parameters.AddWithValue.  This is something I tend to avoid, as the datatype of the Parameter is inferred from the value passed.  In this case you are passing text.  This means that the parameter is treated as a string parameter not a DateTime.  This is almost certainly going to fail!
Instead you should set the type of the parameter yourself.  To do this use something like:

```<code>Dim param as OleDbParameter
param = cmd.CreateParameter
param.OleDbType = OleDbType.Date
param.Value = DateTime.Parse(TextBox1.Text)
param.ParameterName = "@myDate"
cmd.Parameters.Add(param)
</code>```

Note for Access OleDbType needs to be Date even though the field is DateTime.

It may be that I have a syntax error in the above - it is a very long time since I used VB, and I cannot remember when you need round brackets and when you don't, but it should be something like this (I could give it to you exactly in c# ).  I am sure you can correct my VB.

Secondly you are not actually executing your OleDbCommand!  Here there are different possiblilities.  You can use an OleDbDataAdapter or an OleDbDataReader.  Personally I prefer to use OleDbDataReader and I then build my own DataTable from the result to use as the DataSource, but you may find an Adapter easier.  Please google for examples of how to do this! It should be something like:

```<code>Dim adapter as New OleDbDataAdapter(cmd)
adapter.Fill(ds)
</code>```

Again my VB is not upto date!

Hope this helps

Body:
I had a question about retrieving data from MS Access database using timestamps i.e. starting and ending date on a user form. Kindly let me know if and what's the process to do that. I'm using Microsoft Visual Studio 2015. Website user interface will be in Asp.net with VB. Although I have tried passing parameters I am not understanding why it is not reflecting on the Grid View

ASPX.VB Code

Partial Class _Default

Inherits System.Web.UI.Page

Public dad As OleDbDataAdapter

Protected Sub Page_Load(sender As Object, e As EventArgs)

End Sub

Protected Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged

End Sub

Protected Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged

End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

    Dim connectionString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;Data" + " Source=App_Data/VQT_GL Testing.mdb"
    Dim ds As New DataSet()
    Dim conn As New OleDbConnection(connectionString)
    conn.Open()

    Dim cmd As New OleDbCommand("SELECT AVG(POLQA_Score) AS MEAN FROM VQTPOLQA WHERE VQT_Timestamp BETWEEN ? AND ?", conn)
    cmd.Parameters.AddWithValue("@StartDate", (TextBox3.Text))
    cmd.Parameters.AddWithValue("@EndDate", (TextBox2.Text))

    GridView1.DataSource = ds

End Sub

End Class

ASPX CODE

<!DOCTYPE html>

    <title>MOS FORM HOME</title>

    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"/>

    <link href="Styles/calendar-blue.css" rel="stylesheet" type="text/css" />
    <link href="Styles/jquery-ui-timepicker-addon.css" rel="stylesheet"  type="text/css"/>

    <form id="form1" runat="server">

                                                                              MOS FORM HOME PAGE

            START DATE
            <asp:TextBox ID="TextBox3" runat="server" TextMode="DateTime" Width="181px"  BorderColor="Black" BorderStyle="Solid"></asp:TextBox>

            END DATE       <asp:TextBox ID="TextBox2" runat="server" TextMode="DateTime" Width="188px" BorderColor="Black" BorderStyle="Solid"></asp:TextBox>

            <asp:Button ID="Button1" runat="server" Text="Submit" onclick="btnSave_Click"/>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" DataSourceID="SqlDataSource2" GridLines="Horizontal" Height="146px" Width="53px">
            <Columns>
                <asp:BoundField DataField="MEAN" HeaderText="MEAN" ReadOnly="True" SortExpression="MEAN" />
            </Columns>
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#487575" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#275353" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:VQT_GL TestingConnectionString %>" ProviderName="<%$ ConnectionStrings:VQT_GL TestingConnectionString.ProviderName %>" SelectCommand="SELECT AVG(POLQA_Score) AS MEAN FROM VQTPOLQA WHERE VQT_Timestamp BETWEEN ? AND ?">
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox3" DefaultValue="" Name="?" PropertyName="Text" />
                <asp:ControlParameter ControlID="TextBox2" DefaultValue="" Name="?" PropertyName="Text" />
            </SelectParameters>
        </asp:SqlDataSource>

        <asp:AccessDataSource runat="server" DataFile="~/App_Data/VQT_GL Testing.mdb" SelectCommand="SELECT AVG(POLQA_Score) AS MEANPOLQA FROM VQTPOLQA WHERE (VQT_Timestamp BETWEEN ? AND ?)">
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox3" DefaultValue="" Name="?" PropertyName="Text" />
                <asp:ControlParameter ControlID="TextBox2" Name="?" PropertyName="Text" />
            </SelectParameters>
        </asp:AccessDataSource>
    </form>

Body:
At first sight, your problem seems to be with your parameters to your OleDbCommand.  You are using cmd.Parameters.AddWithValue.  This is something I tend to avoid, as the datatype of the Parameter is inferred from the value passed.  In this case you are passing text.  This means that the parameter is treated as a string parameter not a DateTime.  This is almost certainly going to fail!
Instead you should set the type of the parameter yourself.  To do this use something like:

Dim param as OleDbParameter
param = cmd.CreateParameter
param.OleDbType = OleDbType.Date
param.Value = DateTime.Parse(TextBox1.Text)
param.ParameterName = "@myDate"
cmd.Parameters.Add(param)

Note for Access OleDbType needs to be Date even though the field is DateTime.

It may be that I have a syntax error in the above - it is a very long time since I used VB, and I cannot remember when you need round brackets and when you don't, but it should be something like this (I could give it to you exactly in c# ).  I am sure you can correct my VB.

Secondly you are not actually executing your OleDbCommand!  Here there are different possiblilities.  You can use an OleDbDataAdapter or an OleDbDataReader.  Personally I prefer to use OleDbDataReader and I then build my own DataTable from the result to use as the DataSource, but you may find an Adapter easier.  Please google for examples of how to do this! It should be something like:

Dim adapter as New OleDbDataAdapter(cmd)
adapter.Fill(ds)

Again my VB is not upto date!

Hope this helps


问:
Use response of XMLHttpRequest
I'm new in JS and I'm trying to create a function that check something before submit a form.
On  html I have:

```<code><form name="loginform" method="post" onsubmit="return foo()" action="adminlogin.php"> ... </form>
</code>```

The function foo() is:

```<code>foo(){
  if(..){
  return false;
  }
  else{
        var url = "credenziali.php";
        var params = "name="+username+"&password="+password;
        var http_r = new XMLHttpRequest();
        http_r.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //something
            }
        };
        http_r.open("GET", url+"?name="+username+"&pass="+password, true);
        http_r.send();
        // here I want to return false or true dependence of responseText
    }
</code>```

the comment in the function is where I want use the what the request returns.
How can I do?

答: Use JQuery AJAX instead...http://api.jquery.com/jquery.ajax/ it's much more concise.</p>

Title: Use response of XMLHttpRequest

Body:
I'm new in JS and I'm trying to create a function that check something before submit a form.
On  html I have:

<form name="loginform" method="post" onsubmit="return foo()" action="adminlogin.php"> ... </form>

The function foo() is:

foo(){
  if(..){
  return false;
  }
  else{
        var url = "credenziali.php";
        var params = "name="+username+"&password="+password;
        var http_r = new XMLHttpRequest();
        http_r.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //something
            }
        };
        http_r.open("GET", url+"?name="+username+"&pass="+password, true);
        http_r.send();
        // here I want to return false or true dependence of responseText
    }

the comment in the function is where I want use the what the request returns.
How can I do?


问:
undefined method `persisted?' with Reform and Virtus model

I'm currently developing an Rails app (rails v5.1.1 and ruby v2.3.4) and I'm getting an error when trying to use a reform form object at one of my routes (/bookings/new):

undefined method `persisted?' for #<Booking:0x007fbae9a98138>
```

<p>I'm using a virtus model (which works fine on other contexts):</p>

<pre class="lang-ruby prettyprint-override"><code>class Booking
  include Virtus.model

  attribute :id, Integer
  attribute :client_email, String
end
</code>```

This is my form object:

class BookingForm < Reform::Form
  property :client_email
end
```

<p>This is the <code>new</code> action on my controller:</p>

<pre class="lang-ruby prettyprint-override"><code>def new
  @form = BookingForm.new(Booking.new)
end
</code>```

This is my form partial:

<%= form_for @form do |form| %>
  <%= form.text_field :client_email %>

    <%= form.submit %>

<% end %>
```

I thought using a virtus model instead of an active record one should be no issue since reform sells itself as Form objects decoupled from your models. Did I get anything wrong?

答:
It seems like the comment from @fanta helped, but I the long-term answer is that you should avoid using Virtus, especially since you are building a new project. Virtus is no longer supported by it's own team, they moved on to dry-rb ( dry-types and dry-validations)

If you need to mock a model - you can use dry-struct, OpenStruct, etc

Also Reform now has full support for dry-validation and dry-types, and it is going to be the way of the future ( thou AM is going to be supported till version 4)
Best of luck :-)

Body:
I'm currently developing an Rails app (rails v5.1.1 and ruby v2.3.4) and I'm getting an error when trying to use a reform form object at one of my routes (/bookings/new):

undefined method `persisted?' for #<Booking:0x007fbae9a98138>

I'm using a virtus model (which works fine on other contexts):

class Booking
  include Virtus.model

  attribute :id, Integer
  attribute :client_email, String
end

This is my form object:

class BookingForm < Reform::Form
  property :client_email
end

This is the new action on my controller:

def new
  @form = BookingForm.new(Booking.new)
end

This is my form partial:

<%= form_for @form do |form| %>
  <%= form.text_field :client_email %>

    <%= form.submit %>

<% end %>

I thought using a virtus model instead of an active record one should be no issue since reform sells itself as Form objects decoupled from your models. Did I get anything wrong?


问:
C# ImageSearch DLL
So I have recently made a program which finds specific image on the screen and returns the location of it, I actually found this part of the code on stackoverflow, which is using ImageSearch.dll from AutoIT3.

It works pretty well, however, there's one thing missing and I have no idea how to do it. I mean tolerance. This is the original definition of what it does:

```<code>";                $tolerance - 0 for no tolerance (0-255). Needed when colors of
;                            image differ from desktop. e.g GIF"
</code>```

Basically allows to find the image even if there are a few differences.

So this is the code I've got:

```<code>    DllImport("ImageSearch.dll")]
    public static extern IntPtr ImageSearch(int x, int y, int right, int bottom, [MarshalAs(UnmanagedType.LPStr)]string imagePath);

        public static string[] UseImageSearch(string imgPath)
    {

        IntPtr result = ImageSearch(0, 0, Screen.PrimaryScreen.WorkingArea.Right, Screen.PrimaryScreen.WorkingArea.Bottom, imgPath);
        string res = Marshal.PtrToStringAnsi(result);

        if (res[0] == '0') return null;

        string[] data = res.Split('|');

        int x; int y;
        int.TryParse(data[1], out x);
        int.TryParse(data[2], out y);

        return data;
    }
</code>```

And I'd like to somehow make the tolerance work as it is in the original. Is that possible? Thanks for any help!

答:
I was actually wanting to do the same thing so I figured I would post how I did it. I added a second parameter, string tolerance, to UseImageSearch() and appended the tolerance string, prefixed with an * and postfixed with a space to the imgPath string, I passed the new string to the DLL and it returned a string[] with the desired results.

```<code>using System;
using System.Runtime.InteropServices;
using System.Windows;
</code>```

I referenced these guys

```<code>[DllImport(@"C:\ImageSearchDLL.dll")]
    public static extern IntPtr ImageSearch(int x, int y, int right, int bottom, [MarshalAs(UnmanagedType.LPStr)]string imagePath);

    public static string[] UseImageSearch(string imgPath, string tolerance)
    {
        imgPath = "*" + tolerance + " " + imgPath;

        IntPtr result = ImageSearch(0, 0, 1920, 1080, imgPath);
        string res = Marshal.PtrToStringAnsi(result);

        if (res[0] == '0') return null;

        string[] data = res.Split('|');

        int x; int y;
        int.TryParse(data[1], out x);
        int.TryParse(data[2], out y);

        return data;
    }
</code>```

Then I called UseImageSearch using the image path and the desired tolerance level 0-255

```<code> string image = (@"C:\Capture.PNG");

        string[] results = UseImageSearch(image, "30");
        if (results == null)
        {
            MessageBox.Show("null value bro, sad day");
        }
        else
        {
            MessageBox.Show(results[1] + ", " + results[2]);
        }
</code>```

It performed as desired.

Title: C# ImageSearch DLL

Body:
So I have recently made a program which finds specific image on the screen and returns the location of it, I actually found this part of the code on stackoverflow, which is using ImageSearch.dll from AutoIT3.

It works pretty well, however, there's one thing missing and I have no idea how to do it. I mean tolerance. This is the original definition of what it does:

";                $tolerance - 0 for no tolerance (0-255). Needed when colors of
;                            image differ from desktop. e.g GIF"

Basically allows to find the image even if there are a few differences.

So this is the code I've got:

    DllImport("ImageSearch.dll")]
    public static extern IntPtr ImageSearch(int x, int y, int right, int bottom, [MarshalAs(UnmanagedType.LPStr)]string imagePath);

        public static string[] UseImageSearch(string imgPath)
    {

        IntPtr result = ImageSearch(0, 0, Screen.PrimaryScreen.WorkingArea.Right, Screen.PrimaryScreen.WorkingArea.Bottom, imgPath);
        string res = Marshal.PtrToStringAnsi(result);

        if (res[0] == '0') return null;

        string[] data = res.Split('|');

        int x; int y;
        int.TryParse(data[1], out x);
        int.TryParse(data[2], out y);

        return data;
    }

And I'd like to somehow make the tolerance work as it is in the original. Is that possible? Thanks for any help!

Body:
I was actually wanting to do the same thing so I figured I would post how I did it. I added a second parameter, string tolerance, to UseImageSearch() and appended the tolerance string, prefixed with an * and postfixed with a space to the imgPath string, I passed the new string to the DLL and it returned a string[] with the desired results.

using System;
using System.Runtime.InteropServices;
using System.Windows;

I referenced these guys

[DllImport(@"C:\ImageSearchDLL.dll")]
    public static extern IntPtr ImageSearch(int x, int y, int right, int bottom, [MarshalAs(UnmanagedType.LPStr)]string imagePath);

    public static string[] UseImageSearch(string imgPath, string tolerance)
    {
        imgPath = "*" + tolerance + " " + imgPath;

        IntPtr result = ImageSearch(0, 0, 1920, 1080, imgPath);
        string res = Marshal.PtrToStringAnsi(result);

        if (res[0] == '0') return null;

        string[] data = res.Split('|');

        int x; int y;
        int.TryParse(data[1], out x);
        int.TryParse(data[2], out y);

        return data;
    }

Then I called UseImageSearch using the image path and the desired tolerance level 0-255

 string image = (@"C:\Capture.PNG");

        string[] results = UseImageSearch(image, "30");
        if (results == null)
        {
            MessageBox.Show("null value bro, sad day");
        }
        else
        {
            MessageBox.Show(results[1] + ", " + results[2]);
        }

It performed as desired.


问:
Angular 2 - moving embedded plugin to service
I am new to Angular 2, and am just learning how to include plugins. I am getting this error:

Uncaught Error: Can't resolve all parameters for SwitchClientComponent: ([object Object], [object Object], [object Object], [object Object], [object Object], [object Object], ?, ?)

when implementing crypto-js.

I'm sure it's because I haven't properly installed and referenced it.

I have an app.module.ts file (snipped for brevity):

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER  } from '@angular/core';
import { FormsModule } from '@angular/forms';
...
import { MomentModule } from 'angular2-moment';
import { CryptoJS } from "crypto-js";

@NgModule({
    declarations: [
        AppComponent,
        ...
        SwitchClientComponent
    ],
    imports: [
        BrowserModule,
        ...
        StoreModule.provideStore({ appState: appStateReducer }),
    ],providers: [
    { provide: AppConfig, useFactory: serviceConfigFactory },
    SiteService,
    AppContext,
    { provide: APP_INITIALIZER, useFactory: AppContextLoader, deps: [AppContext], multi: true },
    EmployeeService,
    EncryptionService
],
    ...

})
export class AppModule { }
</code>```

(I see an import line but no corresponding reference in the @NgModule...)

Here is where I'm trying to use it:

```<code>import { Injectable } from '@angular/core';
import { CryptoJS } from "crypto-js";

@Injectable()
export class EncryptionService {

    secretKey: string = "123";

    constructor() {
    }

    public setLocalStorage(storagePrefix : string, jsonObj) {
        localStorage.setItem(storagePrefix, this.encrypt(jsonObj));
    }

    encrypt(jsonObj) {
        return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
    }
}
</code>```

Here is the actual switch-client-component that is trying to utilize the service:

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SiteService } from '../../services/site.service';
import { CompanyRoutes } from '../../features/company/company.routes';
import { AppContext } from '../../services/app.context';
import { SiteConfig } from '../../models/site/site.config';
import { AuthService } from '../../services/auth/auth.service';
import { EncryptionService } from '../../services/encryption.service';

@Component({
  selector: 'app-switch-client',
  templateUrl: './switch-client.component.html',
  styleUrls: ['./switch-client.component.scss']

})
export class SwitchClientComponent implements OnInit {
    availableClients : any[] = [];
    filterString: string = '';
    frequentClients: any[] = [];
    maxFrequentClients: number = 6;
    storagePrefix = 'AbilitiConnect-FrequentClients';

    constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService, EncryptionService
    ) {}

    ngOnInit() {
        this.availableClients = this.siteService.getAvailableClientCodes();
        //redirect the user to main page if there is onlu one client.
        if (this.availableClients == null || this.availableClients.length <= 1) {
            this.router.navigate(['/']);
        }
        this.purgeFrequentClients();
        this.frequentClients = this.getFrequentClients();
    }

    switchClient(client) {
        this.updateFrequentClient(client);
        this.appContext.switchClient(client.ClientCode)
            .subscribe((siteConfig: SiteConfig) => {
                this.companyRoutes.resetCompanyRoutes(siteConfig.clientCode, "/");
                this.router.navigate(['/']);
            });
    };

    updateFrequentClient(client) {
        var tempClientArr = [];
        tempClientArr = this.getFrequentClients();
        tempClientArr = tempClientArr.filter(item => item.Name !== client.Name);
        tempClientArr.unshift(client);
        tempClientArr = tempClientArr.slice(0, this.maxFrequentClients);
        this.encryptionService.setLocalStorage(this.storagePrefix, tempClientArr);
    };

    getFrequentClients() {
        return this.encryptionService.getLocalStorage(this.storagePrefix);
    };
    purgeFrequentClients() {
        this.encryptionService.setLocalStorage(this.storagePrefix, []);
    };
}
</code>```

I don't know how to interpret that error.

答:
Seems you have a typo

```<code>constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService, EncryptionService
                               ^^^^^
                          you should change it to :
   ) {}
</code>```

Correct code should look like

```<code>constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService: EncryptionService
   ) {}
</code>```

Body:
I am new to Angular 2, and am just learning how to include plugins. I am getting this error:

Uncaught Error: Can't resolve all parameters for SwitchClientComponent: ([object Object], [object Object], [object Object], [object Object], [object Object], [object Object], ?, ?)

when implementing crypto-js.

I'm sure it's because I haven't properly installed and referenced it.

I have an app.module.ts file (snipped for brevity):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER  } from '@angular/core';
import { FormsModule } from '@angular/forms';
...
import { MomentModule } from 'angular2-moment';
import { CryptoJS } from "crypto-js";

@NgModule({
    declarations: [
        AppComponent,
        ...
        SwitchClientComponent
    ],
    imports: [
        BrowserModule,
        ...
        StoreModule.provideStore({ appState: appStateReducer }),
    ],providers: [
    { provide: AppConfig, useFactory: serviceConfigFactory },
    SiteService,
    AppContext,
    { provide: APP_INITIALIZER, useFactory: AppContextLoader, deps: [AppContext], multi: true },
    EmployeeService,
    EncryptionService
],
    ...

})
export class AppModule { }

(I see an import line but no corresponding reference in the @NgModule...)

Here is where I'm trying to use it:

import { Injectable } from '@angular/core';
import { CryptoJS } from "crypto-js";

@Injectable()
export class EncryptionService {

    secretKey: string = "123";

    constructor() {
    }

    public setLocalStorage(storagePrefix : string, jsonObj) {
        localStorage.setItem(storagePrefix, this.encrypt(jsonObj));
    }

    encrypt(jsonObj) {
        return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
    }
}

Here is the actual switch-client-component that is trying to utilize the service:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SiteService } from '../../services/site.service';
import { CompanyRoutes } from '../../features/company/company.routes';
import { AppContext } from '../../services/app.context';
import { SiteConfig } from '../../models/site/site.config';
import { AuthService } from '../../services/auth/auth.service';
import { EncryptionService } from '../../services/encryption.service';

@Component({
  selector: 'app-switch-client',
  templateUrl: './switch-client.component.html',
  styleUrls: ['./switch-client.component.scss']

})
export class SwitchClientComponent implements OnInit {
    availableClients : any[] = [];
    filterString: string = '';
    frequentClients: any[] = [];
    maxFrequentClients: number = 6;
    storagePrefix = 'AbilitiConnect-FrequentClients';

    constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService, EncryptionService
    ) {}

    ngOnInit() {
        this.availableClients = this.siteService.getAvailableClientCodes();
        //redirect the user to main page if there is onlu one client.
        if (this.availableClients == null || this.availableClients.length <= 1) {
            this.router.navigate(['/']);
        }
        this.purgeFrequentClients();
        this.frequentClients = this.getFrequentClients();
    }

    switchClient(client) {
        this.updateFrequentClient(client);
        this.appContext.switchClient(client.ClientCode)
            .subscribe((siteConfig: SiteConfig) => {
                this.companyRoutes.resetCompanyRoutes(siteConfig.clientCode, "/");
                this.router.navigate(['/']);
            });
    };

    updateFrequentClient(client) {
        var tempClientArr = [];
        tempClientArr = this.getFrequentClients();
        tempClientArr = tempClientArr.filter(item => item.Name !== client.Name);
        tempClientArr.unshift(client);
        tempClientArr = tempClientArr.slice(0, this.maxFrequentClients);
        this.encryptionService.setLocalStorage(this.storagePrefix, tempClientArr);
    };

    getFrequentClients() {
        return this.encryptionService.getLocalStorage(this.storagePrefix);
    };
    purgeFrequentClients() {
        this.encryptionService.setLocalStorage(this.storagePrefix, []);
    };
}

I don't know how to interpret that error.

Body:
Seems you have a typo

constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService, EncryptionService
                               ^^^^^
                          you should change it to :
   ) {}

Correct code should look like

constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService: EncryptionService
   ) {}


问:
missing required positional arguments while calling member function via thread pool
I wrote the following two methods, trying to benefit from multithreading:

```<code>class Data:

    def read_single_image(self, resample_size, index, image_directory_path):
        file_name = self.file_names[index]
        file_path = os.path.join(image_directory_path, file_name + '.*')
        files = glob.glob(file_path)
        if len(files) != 1:
            raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
        image = misc.imread(file_path, mode='RGB')
        zoom = image.shape
        # image = interpolation.zoom(image_directory_path)
        zoom = (resample_size[0] / zoom[0], resample_size[1] / zoom[1], 1)
        image = interpolation.zoom(image, zoom)
        return image

    def read_images(self, resample_size, indice=None, image_directory_path=train_jpeg_directory_path):

        if indice is None:
            indice = self.shuffled_indice

        # reading all images into list
        images = []
        # for i in indice:
        #     image = self.read_single_image(resample_size, i, image_directory_path)
        #     images.append(image)
        with ThreadPoolExecutor(cpu_count()) as pool:
            for image in pool.map(self.read_single_image, [(resample_size, i, image_directory_path) for i in indice]):
                images.append(image)

        return np.stack(images)
</code>```

Unfortunately, it doesn't work with error message:

```<code>TypeError: read_single_image() missing 2 required positional arguments: 'index' and 'image_directory_path'
</code>```

Why?

答:
Executor.map() (and consequently ThreadPoolExecutor.map()) takes an iterable and sends it over the enclosed pool one item per worker. This means that your Data.read_single_image() method gets called as: self.read_single_image((resample_size, i, image_directory_path)) i.e. gets a tuple of all the arguments as the first argument (after the implied self) so it complains that it didn't receive the last two positional arguments.

You can remedy that by simply changing your Data.read_single_image() signature to: Data.read_single_image(self, args) and then read from the args tuple resample_size as args[0], index as args[1] and image_directory_path as args[2].

If you want to keep the signature as it is, you can write a proxy expander as:

```<code>def _read_single_image(self, args):
    return self.read_single_image(*args)
</code>```

And call the _read_single_image() method from your ThreadPoolExecutor.map() instead (i.e. pool.map(self._read_single_image, [(resample_size, i, image_directory_path) for i in indice]))

Keep in mind that if you're going to perform some serious processing, you're much better off with the multiprocessing module, ThreadPoolExecutor is still somewhat limited by the dreaded GIL.

Body:
I wrote the following two methods, trying to benefit from multithreading:

class Data:

    def read_single_image(self, resample_size, index, image_directory_path):
        file_name = self.file_names[index]
        file_path = os.path.join(image_directory_path, file_name + '.*')
        files = glob.glob(file_path)
        if len(files) != 1:
            raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
        image = misc.imread(file_path, mode='RGB')
        zoom = image.shape
        # image = interpolation.zoom(image_directory_path)
        zoom = (resample_size[0] / zoom[0], resample_size[1] / zoom[1], 1)
        image = interpolation.zoom(image, zoom)
        return image

    def read_images(self, resample_size, indice=None, image_directory_path=train_jpeg_directory_path):

        if indice is None:
            indice = self.shuffled_indice

        # reading all images into list
        images = []
        # for i in indice:
        #     image = self.read_single_image(resample_size, i, image_directory_path)
        #     images.append(image)
        with ThreadPoolExecutor(cpu_count()) as pool:
            for image in pool.map(self.read_single_image, [(resample_size, i, image_directory_path) for i in indice]):
                images.append(image)

        return np.stack(images)

Unfortunately, it doesn't work with error message:

TypeError: read_single_image() missing 2 required positional arguments: 'index' and 'image_directory_path'

Why?

Body:
Executor.map() (and consequently ThreadPoolExecutor.map()) takes an iterable and sends it over the enclosed pool one item per worker. This means that your Data.read_single_image() method gets called as: self.read_single_image((resample_size, i, image_directory_path)) i.e. gets a tuple of all the arguments as the first argument (after the implied self) so it complains that it didn't receive the last two positional arguments.

You can remedy that by simply changing your Data.read_single_image() signature to: Data.read_single_image(self, args) and then read from the args tuple resample_size as args[0], index as args[1] and image_directory_path as args[2].

If you want to keep the signature as it is, you can write a proxy expander as:

def _read_single_image(self, args):
    return self.read_single_image(*args)

And call the _read_single_image() method from your ThreadPoolExecutor.map() instead (i.e. pool.map(self._read_single_image, [(resample_size, i, image_directory_path) for i in indice]))

Keep in mind that if you're going to perform some serious processing, you're much better off with the multiprocessing module, ThreadPoolExecutor is still somewhat limited by the dreaded GIL.


问:
How does access other thread stack variable work in C++?
For example, I have:

```<code>int main()
{
    int i = 0;
    std::thread t([&] {
        for (int c = 0; c < 100; ++c)
            ++i;
    });

    t.join();

    return 0;
}
</code>```

The thread t change the variable i value.
I think, that when OS changes current thread it must save an old thread stack and copy a new thread stack.

How does operation system provide a right access to the i?
Does it exists any explanation, how it works on an operating system level?

Does it more productive if I will use something like:

```<code>int main()
{
    int* i = new int;
    std::thread t([&] {
        for (int c = 0; c < 100; ++c)
            ++(*i);
    });

    t.join();

    return 0;
}
</code>```

答:
There are two separate things at play in your example code: capture of local variables to a lambda function and how threads and their stacks work.

Capture of local variables when a lambda function is created works the same way regardless of whether the lambda is in the same thread or a different thread. Basically references to the variables are passed to the lambda.
See How are C++11 lambdas represented and passed? for more details.

Threads, as commented by Margaret Bloom, share the address space of a process. They gave access to read and modify the same memory (including e.g. global variables). While each thread has a different stack area allocated to it, the stacks are all in the address space of the process so all threads can access the stack area of the other threads. So if a thread has a pointer or a reference to a variable in another threads stack, it can read and modify that.

Adding these 2 things together makes your example code work.

The first version of your code is probably slightly more efficient because there is one less level of indirection.

ContentLicense: CC BY-SA 4.0

Body:
For example, I have:

int main()
{
    int i = 0;
    std::thread t([&] {
        for (int c = 0; c < 100; ++c)
            ++i;
    });

    t.join();

    return 0;
}

The thread t change the variable i value.
I think, that when OS changes current thread it must save an old thread stack and copy a new thread stack.

How does operation system provide a right access to the i?
Does it exists any explanation, how it works on an operating system level?

Does it more productive if I will use something like:

int main()
{
    int* i = new int;
    std::thread t([&] {
        for (int c = 0; c < 100; ++c)
            ++(*i);
    });

    t.join();

    return 0;
}


问:
How does one Capture the Entire Kernel Panic on Boot
Using Buildroot, I'm attempting to make a custom kernel build. After building the image and booting it on a VirtualBox environment, the kernel always panics after the GRUB stage. General summary of what I see:

```<code>] CPU: 0 PID: 1 ...
] Hardware name: innotek GmbH ...
] <some registers>
] Call Trace:
]  [<c0a1c995>] dump_stack+...
]  [<........>] panic+...
]  [<........>] do_exit+...
]  ...
] Kernel Offset: 0x0 from 0xc0400000 ...
] ---[ end Kernel panic - not syncing: Attempted to kill init! ...
</code>```

Now, I'm assuming this is only the tail of the message that I want to see, but I have no means to view it (ex: cannot Shift-PageUp). When the panic occurs, the above text is never rendered for a second on the screen.

I first stumbled upon a KernelDebuggingTricks page which states:

Slowing down kernel messages on boot

... [Build] the kernel with the following option enabled:

CONFIG_BOOT_PRINTK_DELAY=y

And boot the machine with the following kernel boot parameter:

boot_delay=N

I have confirmed that my kernel (3.16) had built with the CONFIG_BOOT_PRINTK_DELAY option and have tried setting boot_delay to 10, 500 and 1000 milliseconds in my GRUB. Even with the 1000 millisecond delay set (and waiting for a good ~5 minutes), the entire kernal panic log message is spewed out in a blink of an eye.

Does anyone have any suggestions on how I can view the root of the kernel panic? The only thing I'm thinking now is manually adding sleeps into the kernel code (which is something I'd like to avoid).

答:
kdump and netdump are two more options if you don't have the convenience of a serial port, which is the case when running on metal for most current laptops. See this answer for more info: https://unix.stackexchange.com/a/60928/32558 The setup is more involved however.

Finally, you might also be interested in step debugging the kernel with JTAG or QEMU (not sure about Virtualbox support): Linux kernel live debugging, how it's done and what tools are used?

Body:
Using Buildroot, I'm attempting to make a custom kernel build. After building the image and booting it on a VirtualBox environment, the kernel always panics after the GRUB stage. General summary of what I see:

] CPU: 0 PID: 1 ...
] Hardware name: innotek GmbH ...
] <some registers>
] Call Trace:
]  [<c0a1c995>] dump_stack+...
]  [<........>] panic+...
]  [<........>] do_exit+...
]  ...
] Kernel Offset: 0x0 from 0xc0400000 ...
] ---[ end Kernel panic - not syncing: Attempted to kill init! ...

Now, I'm assuming this is only the tail of the message that I want to see, but I have no means to view it (ex: cannot Shift-PageUp). When the panic occurs, the above text is never rendered for a second on the screen.

I first stumbled upon a KernelDebuggingTricks page which states:

Slowing down kernel messages on boot

... [Build] the kernel with the following option enabled:

CONFIG_BOOT_PRINTK_DELAY=y

And boot the machine with the following kernel boot parameter:

boot_delay=N

I have confirmed that my kernel (3.16) had built with the CONFIG_BOOT_PRINTK_DELAY option and have tried setting boot_delay to 10, 500 and 1000 milliseconds in my GRUB. Even with the 1000 millisecond delay set (and waiting for a good ~5 minutes), the entire kernal panic log message is spewed out in a blink of an eye.

Does anyone have any suggestions on how I can view the root of the kernel panic? The only thing I'm thinking now is manually adding sleeps into the kernel code (which is something I'd like to avoid).


问:
Building GHC: configure fails on happy despite successful cabal install
I am attempting to build GHC from source following this page. When installing dependencies, I had to install happy and alex:

```<code>$ cabal install alex happy
Resolving dependencies...
Configuring alex-3.2.1...
Configuring happy-1.19.5...
Building happy-1.19.5...
Building alex-3.2.1...
Installed alex-3.2.1
Installed happy-1.19.5
</code>```

yet when running configure I get an error message:

```<code>$ ./configure
...
checking for happy... no
checking for version of happy...
configure: error: Happy version 1.19.4 or later is required to compile GHC.
</code>```

I am running on Debian stretch:

```<code>$ uname -a
Linux <host> 4.8.0-1-amd64 #1 SMP Debian 4.8.5-1 (2016-10-28) x86_64 GNU/Linux
</code>```

Can anyone suggest an obvious step I could try to resolve this?

答:
I suspect you simply don't have them on your PATH. Make sure to include something like

```<code>PATH="$HOME/.cabal/bin:$PATH"
</code>```

in your .bashrc (or startup files for whatever shell you use). Installing them through the package manager simply installed them in a location that was already on your PATH.

Even if you have things working now, you should consider modifying your .bashrc while it's fresh in your head, as other cabal-install'd executables will get put there in the future.

Body:
I am attempting to build GHC from source following this page. When installing dependencies, I had to install happy and alex:

$ cabal install alex happy
Resolving dependencies...
Configuring alex-3.2.1...
Configuring happy-1.19.5...
Building happy-1.19.5...
Building alex-3.2.1...
Installed alex-3.2.1
Installed happy-1.19.5

yet when running configure I get an error message:

$ ./configure
...
checking for happy... no
checking for version of happy...
configure: error: Happy version 1.19.4 or later is required to compile GHC.

I am running on Debian stretch:

$ uname -a
Linux <host> 4.8.0-1-amd64 #1 SMP Debian 4.8.5-1 (2016-10-28) x86_64 GNU/Linux

Can anyone suggest an obvious step I could try to resolve this?

Body:
I suspect you simply don't have them on your PATH. Make sure to include something like

PATH="$HOME/.cabal/bin:$PATH"

in your .bashrc (or startup files for whatever shell you use). Installing them through the package manager simply installed them in a location that was already on your PATH.

Even if you have things working now, you should consider modifying your .bashrc while it's fresh in your head, as other cabal-install'd executables will get put there in the future.


问:
Resizing Div vertically when view port is resized
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class='container'>
    <div class='content'>
      <div class='page-header'> System Dashboard </div>

      <div class='wrapper'>
        <div class='col-md-4 override'>
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
        </div>
      </div>

      <div class='footer'> Copyright here </div>
    </div>
  </div>
</body></code>```

答:
Try by adding vendor prefixes to calc function : -moz-calc and -webkit-calc.

CSS3 height: calc(100%) not working

Body:
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}

 System Dashboard

          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper

 Copyright here


问:
TypeError: 'module' object is not callable - using datetime
Sorry didn't find any other fix, so I created a new question.
I'm trying to run a code that prints to the screen the current hour, minute and second. The piece of code I'm using to do this is:

```<code>def time():
    import datetime
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)
</code>```

I get the following error when this piece of code tries to execute:

```<code>Traceback (most recent call last):
  File "/Users/Teolicht/Desktop/Python/testy.py", line 219, in <module>
    start()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 18, in start
    questions()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 34, in questions
    day()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 52, in day
    time()
TypeError: 'module' object is not callable
</code>```

start(), questions() and day() are some other functions the program went through before going through time(). If I try executing time() directly, it works! So, here's the entire code from the start till the end of the time() function:

```<code>from datetime import datetime
import time
import random
import sys

def start():
    import time
    name = input('Hi. What is your name? ')
    print ('Nice to meet you, ' + str(name) + '.')
    time.sleep(1)
    print ('How old are you?')
    age = input()
    time.sleep(1)
    print (age + '! Cool.')
    time.sleep(2)
    questions()

def questions():
    import time
    print ('Some things you can ask me:')
    time.sleep(1)
    print ('• What day is today? (qdh)')
    time.sleep(1)
    print ('• What time is it? (qhs)')
    time.sleep(1)
    print ('• I want to play a game! (qjj)')
    time.sleep(1)
    print ('• How many days till my birthday? (qda)')
    time.sleep(1)
    questionsAnswer = input()
    if questionsAnswer == 'qdh':
        day()
    elif questionsAnswer == 'qhs':
        time()
    elif questionsAnswer == 'qjj':
        game()
    else:
        birthday()

def day():
    import time
    time.sleep(1)
    nowDay = datetime.now()
    print ('Today is %s/%s/%s' % (nowDay.day,nowDay.month,nowDay.year))
    time.sleep(2)
    dayAnswer = input('Want to know what time it is? "Y" for yes and "N" for no: ').lower()
    if dayAnswer == 'n':
        questions()
    else:
        time()

def time():
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)
        questions()
       ...
</code>```

It might be something in start(), questions() or day() causing the error. Any ideas? Thanks a bunch!

答:
In your command

```<code>nowTime = datetime.now()
</code>```

datetime is the module which has no method now().

You probably wanted

```<code>nowTime = datetime.datetime.now()
</code>```

where the first datetime is the module, and the second one is the class in it - with the classmethod now() which creates an object with current local date and time.

Body:
Sorry didn't find any other fix, so I created a new question.
I'm trying to run a code that prints to the screen the current hour, minute and second. The piece of code I'm using to do this is:

def time():
    import datetime
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)

I get the following error when this piece of code tries to execute:

Traceback (most recent call last):
  File "/Users/Teolicht/Desktop/Python/testy.py", line 219, in <module>
    start()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 18, in start
    questions()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 34, in questions
    day()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 52, in day
    time()
TypeError: 'module' object is not callable

start(), questions() and day() are some other functions the program went through before going through time(). If I try executing time() directly, it works! So, here's the entire code from the start till the end of the time() function:

from datetime import datetime
import time
import random
import sys

def start():
    import time
    name = input('Hi. What is your name? ')
    print ('Nice to meet you, ' + str(name) + '.')
    time.sleep(1)
    print ('How old are you?')
    age = input()
    time.sleep(1)
    print (age + '! Cool.')
    time.sleep(2)
    questions()

def questions():
    import time
    print ('Some things you can ask me:')
    time.sleep(1)
    print ('• What day is today? (qdh)')
    time.sleep(1)
    print ('• What time is it? (qhs)')
    time.sleep(1)
    print ('• I want to play a game! (qjj)')
    time.sleep(1)
    print ('• How many days till my birthday? (qda)')
    time.sleep(1)
    questionsAnswer = input()
    if questionsAnswer == 'qdh':
        day()
    elif questionsAnswer == 'qhs':
        time()
    elif questionsAnswer == 'qjj':
        game()
    else:
        birthday()

def day():
    import time
    time.sleep(1)
    nowDay = datetime.now()
    print ('Today is %s/%s/%s' % (nowDay.day,nowDay.month,nowDay.year))
    time.sleep(2)
    dayAnswer = input('Want to know what time it is? "Y" for yes and "N" for no: ').lower()
    if dayAnswer == 'n':
        questions()
    else:
        time()

def time():
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)
        questions()
       ...

It might be something in start(), questions() or day() causing the error. Any ideas? Thanks a bunch!

Body:
In your command

nowTime = datetime.now()

datetime is the module which has no method now().

You probably wanted

nowTime = datetime.datetime.now()

where the first datetime is the module, and the second one is the class in it - with the classmethod now() which creates an object with current local date and time.


问:
Lodash/JS - Convert _.find statement to _.forEach
I'm having trouble converting the following Lodash statement to something that works in an application that I inherited at work and am trying to fix bugs in. At the moment, we are having issues with only one device on our system returning when two devices have the same name and the following code seems to be the culprit as it would only return the first "true" value in an array:

```<code>var group = _.find(groupList, {id: id});
</code>```

How would I successfully convert this to a statement that iterates over all objects in an array and then returns those objects? I've tried the following options to no avail:

```<code> var group = _.filter(groupList, {id: id});
</code>```

and

```<code> var group = _.every(groupList, {id: id});
</code>```

and

```<code> var group = _.forEach(groupList, {id: id})
 return {id};
</code>```

I know I am probably missing something in my syntax. Any help would be much appreciated. Running Lodash v3.7.0

Here's the rest of the code in the directive in case anyone is interested or sees something else I might be missing:

```<code>define(['./../_module'], function (directives) {
'use strict';
directives.directive('dmGroupedList', ['$compile', '$state', 'APP_CONSTANTS', function ($compile, $state, APP_CONSTANTS) {
    return {
        restrict: 'A',
        scope: {
            items: '=',
            groupBy: '=',
            actions: '=',
            nonameGroupLabel: '='
        },
        templateUrl: function (elem, attrs) {
            return attrs.templateUrl || 'views/shared-templates/grouped-list.html';
        },
        link: function (scope, element, attrs) {
            scope.$watchGroup(['items', 'groupBy', 'nonameGroupLabel'], function () {
                scope.groupList = [];
                scope.groupedItems = {};

                var actions = scope.actions[scope.groupBy];

                _.forEach(scope.items, function (item) {
                    scope.handlers.getGroups(scope.groupList, item, scope.items, scope.groupBy, actions);
                });

                _.forEach(scope.groupList, function (group) {
                    var items = scope.groupedItems[group.id];
                    items = _.sortBy(items, function (item) {
                        return item.description;
                    });

                    scope.groupedItems[group.id] = items;
                });

                var groupsToSort = _.where(scope.groupList, {unassigned: false});
                var unassignedGroups = _.sortBy(_.where(scope.groupList, {unassigned: true}), 'name');
                scope.groupList = _.sortBy(groupsToSort, function (group) {
                    return group.name;
                });
                //adds unassigned groups to a new array via the javascript "push" method
                if (angular.isDefined(unassignedGroups)) {
                    for (var i = 0; i < unassignedGroups.length; i++) {
                        scope.groupList.push(unassignedGroups[i]);
                    }
                }
            });

            scope.handlers = {
                getGroups: function (groupList, item, items, groupBy, actions) {
                    var group = item[groupBy];

                    if (_.isEmpty(group)) {
                        scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                    }
                    else {
                        if (angular.isArray(group) || angular.isObject(group)) {
                            _.forEach(group, function (groupName) {
                                if (groupName == APP_CONSTANTS.ZERO) {
                                    scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                                    return;
                                }

                                scope.handlers.addGroupToList(groupList, groupName, items, groupBy, item, actions, scope);
                            })
                        } else {
                            scope.handlers.addGroupToList(groupList, group, items, groupBy, item, actions, scope);
                        }
                    }
                },
                addGroupToList: function (groupList, groupId, items, groupBy, item, handlers, scope) {
                    var id = _.camelCase(groupId);

                   var group = _.find(groupList, {id: id});
                    //var group = _.forEach(groupList, {id: id})
                    //return {id};

                    if (!group) {
                        var name = '';
                        var unassigned = false;
                        var link = null;

                        if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE || groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                            if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE;
                            } else {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.UNASSIGNED;
                            }

                            unassigned = true;
                        } else {
                            link = handlers.getGroupLink(groupId);
                            name = handlers.getGroupName(groupId, items);
                        }

                        group = {id: id, name: name, unassigned: unassigned, link: link};

                        groupList.push(group);
                    }

                    scope.groupedItems[group.id] = scope.groupedItems[group.id] || [];

                    if (angular.isDefined(handlers.processingGroup)) {
                        handlers.processingGroup(group, groupList, groupId, items, groupBy, item, handlers, scope);
                    } else {
                        scope.groupedItems[group.id].push({
                            description: handlers.getItemDescription(item),
                            link: handlers.getItemLink(item)
                        })
                    }
                }
            };
        }
    };
}]);
</code>```

});

答:
You can _(groupList).groupBy('id').get(id):

var groupList = [
  { id: 1, name: 'site' },
  { id: 2, name: 'test' },
  { id: 2, name: 'prod' },
  { id: 3, name: 'dev' },
  { id: 4, name: 'back' },
  { id: 4, name: 'front' },
  { id: 5, name: 'sprint' }
];

console.log(_(groupList).groupBy('id').get(2));
console.log(_(groupList).groupBy('id').get(3));
console.log(_(groupList).groupBy('id').get(4));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
I'm having trouble converting the following Lodash statement to something that works in an application that I inherited at work and am trying to fix bugs in. At the moment, we are having issues with only one device on our system returning when two devices have the same name and the following code seems to be the culprit as it would only return the first "true" value in an array:

var group = _.find(groupList, {id: id});

How would I successfully convert this to a statement that iterates over all objects in an array and then returns those objects? I've tried the following options to no avail:

 var group = _.filter(groupList, {id: id});

and

 var group = _.every(groupList, {id: id});

and

 var group = _.forEach(groupList, {id: id})
 return {id};

I know I am probably missing something in my syntax. Any help would be much appreciated. Running Lodash v3.7.0

Here's the rest of the code in the directive in case anyone is interested or sees something else I might be missing:

define(['./../_module'], function (directives) {
'use strict';
directives.directive('dmGroupedList', ['$compile', '$state', 'APP_CONSTANTS', function ($compile, $state, APP_CONSTANTS) {
    return {
        restrict: 'A',
        scope: {
            items: '=',
            groupBy: '=',
            actions: '=',
            nonameGroupLabel: '='
        },
        templateUrl: function (elem, attrs) {
            return attrs.templateUrl || 'views/shared-templates/grouped-list.html';
        },
        link: function (scope, element, attrs) {
            scope.$watchGroup(['items', 'groupBy', 'nonameGroupLabel'], function () {
                scope.groupList = [];
                scope.groupedItems = {};

                var actions = scope.actions[scope.groupBy];

                _.forEach(scope.items, function (item) {
                    scope.handlers.getGroups(scope.groupList, item, scope.items, scope.groupBy, actions);
                });

                _.forEach(scope.groupList, function (group) {
                    var items = scope.groupedItems[group.id];
                    items = _.sortBy(items, function (item) {
                        return item.description;
                    });

                    scope.groupedItems[group.id] = items;
                });

                var groupsToSort = _.where(scope.groupList, {unassigned: false});
                var unassignedGroups = _.sortBy(_.where(scope.groupList, {unassigned: true}), 'name');
                scope.groupList = _.sortBy(groupsToSort, function (group) {
                    return group.name;
                });
                //adds unassigned groups to a new array via the javascript "push" method
                if (angular.isDefined(unassignedGroups)) {
                    for (var i = 0; i < unassignedGroups.length; i++) {
                        scope.groupList.push(unassignedGroups[i]);
                    }
                }
            });

            scope.handlers = {
                getGroups: function (groupList, item, items, groupBy, actions) {
                    var group = item[groupBy];

                    if (_.isEmpty(group)) {
                        scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                    }
                    else {
                        if (angular.isArray(group) || angular.isObject(group)) {
                            _.forEach(group, function (groupName) {
                                if (groupName == APP_CONSTANTS.ZERO) {
                                    scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                                    return;
                                }

                                scope.handlers.addGroupToList(groupList, groupName, items, groupBy, item, actions, scope);
                            })
                        } else {
                            scope.handlers.addGroupToList(groupList, group, items, groupBy, item, actions, scope);
                        }
                    }
                },
                addGroupToList: function (groupList, groupId, items, groupBy, item, handlers, scope) {
                    var id = _.camelCase(groupId);

                   var group = _.find(groupList, {id: id});
                    //var group = _.forEach(groupList, {id: id})
                    //return {id};

                    if (!group) {
                        var name = '';
                        var unassigned = false;
                        var link = null;

                        if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE || groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                            if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE;
                            } else {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.UNASSIGNED;
                            }

                            unassigned = true;
                        } else {
                            link = handlers.getGroupLink(groupId);
                            name = handlers.getGroupName(groupId, items);
                        }

                        group = {id: id, name: name, unassigned: unassigned, link: link};

                        groupList.push(group);
                    }

                    scope.groupedItems[group.id] = scope.groupedItems[group.id] || [];

                    if (angular.isDefined(handlers.processingGroup)) {
                        handlers.processingGroup(group, groupList, groupId, items, groupBy, item, handlers, scope);
                    } else {
                        scope.groupedItems[group.id].push({
                            description: handlers.getItemDescription(item),
                            link: handlers.getItemLink(item)
                        })
                    }
                }
            };
        }
    };
}]);

});

Body:
You can _(groupList).groupBy('id').get(id):

var groupList = [
  { id: 1, name: 'site' },
  { id: 2, name: 'test' },
  { id: 2, name: 'prod' },
  { id: 3, name: 'dev' },
  { id: 4, name: 'back' },
  { id: 4, name: 'front' },
  { id: 5, name: 'sprint' }
];

console.log(_(groupList).groupBy('id').get(2));
console.log(_(groupList).groupBy('id').get(3));
console.log(_(groupList).groupBy('id').get(4));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>