问:
Testing void methods that do not change anything in Test scenario
I know that every method that doesn't do anything shouldn't be tested (or not even exist). The thing is, that my method does something normally, but for the test-scenario I have to mock that thing that it does. But I would still like to assert the parameters that it would send to the external thing.

Sounds more complicated than it is - Check my snippet for better understanding:

```<code>class A {
    @Inject
    private Mailer mailer; // Custom mailer class

    public void doSomething() {
        Date date = new Date(); // dynamic parameter I do not care about in the test
        String parameter = "test"; // The parameter I want to test later

        mailer.sendMail(parameter, date);
    }
}

class ATest {
    @Mock
    @Produces
    private Mailer mailer;

    @Inject
    private A classToTest;

    @Test
    public void testDoSomething() throws Exception {

        classToTest.doSomething();

        assertThat(??).isEqualTo("test"); //How can I get the value of parameter?
    }
}
</code>```

As you can see I need to mock my emailer, so that I dont send a email everytime a test runs.

It would make no sense to promote parameter to a global variable.

Is there any way to test the value of parameter without changing the code of A? And if not what would be the best solution without messing up my class just for testing?

答:
You need to use Mockito.verify:

```<code>verify(mailer, times(1)).sendMail("test");
</code>```

Verify checks what happened with your mocks: how many times a method was called, and what arguments were given to that method.

Update:
If you want to exclude certain parameters, you can use org.mockito.Matchers.any - easier to have it as a static import. (NB: if you do ignore some parameters, then the ones you want to INCLUDE now have to be wrapped in org.mockito.Matchers.eq).

```<code>verify(mailer, times(1)).sendMail(eq("test"), any(Date.class));
</code>```

Body:
I know that every method that doesn't do anything shouldn't be tested (or not even exist). The thing is, that my method does something normally, but for the test-scenario I have to mock that thing that it does. But I would still like to assert the parameters that it would send to the external thing.

Sounds more complicated than it is - Check my snippet for better understanding:

class A {
    @Inject
    private Mailer mailer; // Custom mailer class

    public void doSomething() {
        Date date = new Date(); // dynamic parameter I do not care about in the test
        String parameter = "test"; // The parameter I want to test later

        mailer.sendMail(parameter, date);
    }
}

class ATest {
    @Mock
    @Produces
    private Mailer mailer;

    @Inject
    private A classToTest;

    @Test
    public void testDoSomething() throws Exception {

        classToTest.doSomething();

        assertThat(??).isEqualTo("test"); //How can I get the value of parameter?
    }
}

As you can see I need to mock my emailer, so that I dont send a email everytime a test runs.

It would make no sense to promote parameter to a global variable.

Is there any way to test the value of parameter without changing the code of A? And if not what would be the best solution without messing up my class just for testing?

Body:
You need to use Mockito.verify:

verify(mailer, times(1)).sendMail("test");

Verify checks what happened with your mocks: how many times a method was called, and what arguments were given to that method.

Update:
If you want to exclude certain parameters, you can use org.mockito.Matchers.any - easier to have it as a static import. (NB: if you do ignore some parameters, then the ones you want to INCLUDE now have to be wrapped in org.mockito.Matchers.eq).

verify(mailer, times(1)).sendMail(eq("test"), any(Date.class));


来源: stackexchange

问:
ASP.NET MVC 5 Data is NULL Due To Network Related Instance
I am getting the value from text field but can not find the reason of not getting saved in the variable.

```<code>var user = new ApplicationUser() { UserName = model.Email ,Email = model.Email};
</code>```

user is null despite Email contains the value. I have found it through debugging.

```<code>{
Line 81:       var user = new ApplicationUser() { UserName = model.Email ,Email = model.Email};

Line 82:       var result = await UserManager.CreateAsync(user, model.Password);
Line 83:       if (result.Succeeded)
Line 84:       {
</code>```

Line 82 is the error.
Below is the code.

```<code>var user = new ApplicationUser() { UserName = model.Email ,Email = model.Email};

var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    var db = new ApplicationDbContext();
    var checkingAccount = new CheckingAccount
    {
        FirstName = model.FirstName,
        LastName = model.LastName,
        AccountNumber = "111014005",
        Balance = 0,
        ApplicationUserId = user.Id

    };
    db.CheckingAccounts.Add(checkingAccount);
    db.SaveChanges();
</code>```

Stack Trace:

[Win32Exception (0x80004005): The system cannot find the file
  specified]

[SqlException (0x80131904): A network-related or instance-specific
  error occurred while establishing a connection to SQL Server. The
  server was not found or was not accessible. Verify that the instance
  name is correct and that SQL Server is configured to allow remote
  connections. (provider: SQL Network Interfaces, error: 52 - Unable to
  locate a Local Database Runtime installation. Verify that SQL Server
  Express is properly installed and that the Local Database Runtime
  feature is enabled.)]

System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
  allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +414

  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +78

  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
  owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
  connection) +196

  System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource1 retry, DbConnectionOptions userOptions) +146

  System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource1 retry, DbConnectionOptions userOptions) +16

  System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1
  retry) +94

  System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
  retry) +110    System.Data.SqlClient.SqlConnection.Open() +96

  System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.b__36(DbConnection
  t, DbConnectionInterceptionContext c) +10

  System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget
  target, Action2 operation, TInterceptionContext interceptionContext,
  Action3 executing, Action3 executed) +72

  System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection
  connection, DbInterceptionContext interceptionContext) +360

  System.Data.Entity.SqlServer.<>c__DisplayClass33.b__32()
  +426    System.Data.Entity.SqlServer.<>c__DisplayClass1.b__0() +10

  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1
  operation) +189

  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action
  operation) +78

  System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection
  sqlConnection, Action1 act) +175

  System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection
  sqlConnection, Action1 act) +557

  System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1
  commandTimeout, DbConnection sqlConnection, String
  createDatabaseScript) +86

  System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection
  connection, Nullable1 commandTimeout, StoreItemCollection
  storeItemCollection) +164

  System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection
  connection, Nullable1 commandTimeout, StoreItemCollection
  storeItemCollection) +76

  System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() +134

  System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection
  connection) +119

  System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
  mustSucceedToKeepDatabase) +142

  System.Data.Entity.Migrations.DbMigrator.Update(String
  targetMigration) +78

  System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext
  internalContext, Func3 createMigrator, ObjectContext objectContext)
  +89    System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext
  objectContext, DatabaseExistenceState existenceState) +116

  System.Data.Entity.Database.Create(DatabaseExistenceState
  existenceState) +218

  System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext
  context) +149

  System.Data.Entity.Internal.<>c__DisplayClassf1.<CreateInitializationAction>b__e()
  +76    System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action
  action) +60

  System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
  +357    System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext
  c) +7

  System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
  +110    System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1
  action) +198

  System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
  +73    System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
  entityType) +28

  System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53

  System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
  +15    System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
  +38    System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1
  source, Expression1 predicate, CancellationToken cancellationToken)
  +138    System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1
  source, Expression1 predicate) +133

  Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext()
  +486    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.CultureAwaiter1.GetResult()
  +59    Microsoft.AspNet.Identity.<ValidateUserName>d__4.MoveNext() +592    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.<ValidateAsync>d__0.MoveNext()
  +283    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext()
  +582    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.<CreateAsync>d__d.MoveNext()
  +531    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
  +24    AutomatedTellerMachine.Controllers.d__9.MoveNext() in e:\Passion\Work\AutomatedTellerMachine\AutomatedTellerMachine\Controllers\AccountController.cs:82
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52

  System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult
  asyncResult) +84

  System.Web.Mvc.Async.<>c__DisplayClass37.b__36(IAsyncResult
  asyncResult) +17

  System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49

  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
  asyncResult) +32

  System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d()
  +50    System.Web.Mvc.Async.<>c__DisplayClass46.b__3f()
  +225    System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49

  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult
  asyncResult) +34

  System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c()
  +26    System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult
  asyncResult) +100

  System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49

  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult
  asyncResult) +27

  System.Web.Mvc.Controller.b__1d(IAsyncResult
  asyncResult, ExecuteCoreState innerState) +13

  System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult) +36

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54

  System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
  System.Web.Mvc.Controller.b__15(IAsyncResult
  asyncResult, Controller controller) +12

  System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult) +28

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54

  System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29

  System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.MvcHandler.b__5(IAsyncResult
  asyncResult, ProcessRequestState innerState) +21

  System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult) +36

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54

  System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
  +31    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
  result) +9

  System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +9514812    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

答:
```<code>System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +357
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting the value from text field but can not find the reason of not getting saved in the variable.

var user = new ApplicationUser() { UserName = model.Email ,Email = model.Email};

user is null despite Email contains the value. I have found it through debugging.

{
Line 81:       var user = new ApplicationUser() { UserName = model.Email ,Email = model.Email};

Line 82:       var result = await UserManager.CreateAsync(user, model.Password);
Line 83:       if (result.Succeeded)
Line 84:       {

Line 82 is the error.
Below is the code.

var user = new ApplicationUser() { UserName = model.Email ,Email = model.Email};

var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    var db = new ApplicationDbContext();
    var checkingAccount = new CheckingAccount
    {
        FirstName = model.FirstName,
        LastName = model.LastName,
        AccountNumber = "111014005",
        Balance = 0,
        ApplicationUserId = user.Id

    };
    db.CheckingAccounts.Add(checkingAccount);
    db.SaveChanges();

Stack Trace:

[Win32Exception (0x80004005): The system cannot find the file
  specified]

[SqlException (0x80131904): A network-related or instance-specific
  error occurred while establishing a connection to SQL Server. The
  server was not found or was not accessible. Verify that the instance
  name is correct and that SQL Server is configured to allow remote
  connections. (provider: SQL Network Interfaces, error: 52 - Unable to
  locate a Local Database Runtime installation. Verify that SQL Server
  Express is properly installed and that the Local Database Runtime
  feature is enabled.)]

System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
  allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +414

  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +78

  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
  owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
  connection) +196

  System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource1 retry, DbConnectionOptions userOptions) +146

  System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource1 retry, DbConnectionOptions userOptions) +16

  System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1
  retry) +94

  System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
  retry) +110    System.Data.SqlClient.SqlConnection.Open() +96

  System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.b__36(DbConnection
  t, DbConnectionInterceptionContext c) +10

  System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget
  target, Action2 operation, TInterceptionContext interceptionContext,
  Action3 executing, Action3 executed) +72

  System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection
  connection, DbInterceptionContext interceptionContext) +360

  System.Data.Entity.SqlServer.<>c__DisplayClass33.b__32()
  +426    System.Data.Entity.SqlServer.<>c__DisplayClass1.b__0() +10

  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1
  operation) +189

  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action
  operation) +78

  System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection
  sqlConnection, Action1 act) +175

  System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection
  sqlConnection, Action1 act) +557

  System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1
  commandTimeout, DbConnection sqlConnection, String
  createDatabaseScript) +86

  System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection
  connection, Nullable1 commandTimeout, StoreItemCollection
  storeItemCollection) +164

  System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection
  connection, Nullable1 commandTimeout, StoreItemCollection
  storeItemCollection) +76

  System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() +134

  System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection
  connection) +119

  System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
  mustSucceedToKeepDatabase) +142

  System.Data.Entity.Migrations.DbMigrator.Update(String
  targetMigration) +78

  System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext
  internalContext, Func3 createMigrator, ObjectContext objectContext)
  +89    System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext
  objectContext, DatabaseExistenceState existenceState) +116

  System.Data.Entity.Database.Create(DatabaseExistenceState
  existenceState) +218

  System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext
  context) +149

  System.Data.Entity.Internal.<>c__DisplayClassf1.<CreateInitializationAction>b__e()
  +76    System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action
  action) +60

  System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
  +357    System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext
  c) +7

  System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
  +110    System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1
  action) +198

  System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
  +73    System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
  entityType) +28

  System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53

  System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
  +15    System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
  +38    System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1
  source, Expression1 predicate, CancellationToken cancellationToken)
  +138    System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1
  source, Expression1 predicate) +133

  Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext()
  +486    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.CultureAwaiter1.GetResult()
  +59    Microsoft.AspNet.Identity.<ValidateUserName>d__4.MoveNext() +592    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.<ValidateAsync>d__0.MoveNext()
  +283    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext()
  +582    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    Microsoft.AspNet.Identity.<CreateAsync>d__d.MoveNext()
  +531    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52    System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
  +24    AutomatedTellerMachine.Controllers.d__9.MoveNext() in e:\Passion\Work\AutomatedTellerMachine\AutomatedTellerMachine\Controllers\AccountController.cs:82
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +93

  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +52

  System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult
  asyncResult) +84

  System.Web.Mvc.Async.<>c__DisplayClass37.b__36(IAsyncResult
  asyncResult) +17

  System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49

  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
  asyncResult) +32

  System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d()
  +50    System.Web.Mvc.Async.<>c__DisplayClass46.b__3f()
  +225    System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49

  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult
  asyncResult) +34

  System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c()
  +26    System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult
  asyncResult) +100

  System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49

  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult
  asyncResult) +27

  System.Web.Mvc.Controller.b__1d(IAsyncResult
  asyncResult, ExecuteCoreState innerState) +13

  System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult) +36

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54

  System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
  System.Web.Mvc.Controller.b__15(IAsyncResult
  asyncResult, Controller controller) +12

  System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult) +28

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54

  System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29

  System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
  asyncResult) +10

  System.Web.Mvc.MvcHandler.b__5(IAsyncResult
  asyncResult, ProcessRequestState innerState) +21

  System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult) +36

  System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54

  System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
  +31    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
  result) +9

  System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +9514812    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)


问:
Searching XML through Java Codes
I have around 30 xml files with proper formatting  and huge amount of data. I want to search these xml files for specific data retrival. Can you suggest any site or blog which i can use as aguideline to solve my problem.

I need to search inside of each tag for the keyword provided by the user. And also sometime the specific tag name which will return the content inside the tag according to the user request.

example : a.xml, b.xml, c.xml

```<code>inside a.xml

<abc>
some content
</abc>
</code>```

User may search for abc the tag or some keyword inside the content. In both cases it should return the content or if more than one match then it should return the link for both by clicking which the user can see them one by one.

答:
I'd recommend using XPath, which is a SQL-like language for searching in XML documents

http://www.ibm.com/developerworks/library/x-javaxpathapi.html

ContentLicense: CC BY-SA 3.0

Title: Searching XML through Java Codes

Body:
I have around 30 xml files with proper formatting  and huge amount of data. I want to search these xml files for specific data retrival. Can you suggest any site or blog which i can use as aguideline to solve my problem.

I need to search inside of each tag for the keyword provided by the user. And also sometime the specific tag name which will return the content inside the tag according to the user request.

example : a.xml, b.xml, c.xml

inside a.xml

<abc>
some content
</abc>

User may search for abc the tag or some keyword inside the content. In both cases it should return the content or if more than one match then it should return the link for both by clicking which the user can see them one by one.


问:
How to repetitively update a portion of GUI after show.dialog()?
I have a list of statuses that will need to be checked every 5 seconds, then update a panel in my gui. With my current code, I have a Timeout set to an hour and a while loop that will run the Show-Statuses function which updates the GUI.

My issue is that when this While loop is entered, the Form.ShowDialog() will never bet triggered.

How do I make it so I can show the form and the continuously update a portion of it?

```<code>Function Determine-JabadStatus {

    $JabadLOStatus = (Get-Aduser adepolo -Properties LockedOut).LockedOut

    If ($JabadLOStatus -eq $False) {
        $JabadStatusF = "Unlocked"
    } else {
        $JabadStatusF = "Locked"
    }

    $JabadStatusF
}

Function Show-Statuses {

    #Load statuses
    $JabadStatus = Determine-JabadStatus

    #Add each status seperated by + "`r`n`r`n" + quotes
    $ImportantInformationStatuses.Text = $JabadStatus
}

$Timeout = New-TimeSpan -Hours 1
$sw = [diagnostics.stopwatch]::StartNew()

While ($sw.Elapsed -lt $Timeout) {
    Show-Statuses
    Start-Sleep -Seconds 5
}

$form.ShowDialog()
</code>```

答:
Try putting this into your While

```<code> $form.Dispatcher.Invoke( [Action]{},[Windows.Threading.DispatcherPriority]::ContextIdle )
</code>```

i.e.

```<code>While ($sw.Elapsed -lt $Timeout) {
    Show-Statuses
    $form.Dispatcher.Invoke( [Action]{},[Windows.Threading.DispatcherPriority]::ContextIdle )
    Start-Sleep -Seconds 5
}
</code>```

I use that line of text when updating progress bars within a GUI, and when dumping output into a RichTextbox. It should work for you too.

Body:
I have a list of statuses that will need to be checked every 5 seconds, then update a panel in my gui. With my current code, I have a Timeout set to an hour and a while loop that will run the Show-Statuses function which updates the GUI.

My issue is that when this While loop is entered, the Form.ShowDialog() will never bet triggered.

How do I make it so I can show the form and the continuously update a portion of it?

Function Determine-JabadStatus {

    $JabadLOStatus = (Get-Aduser adepolo -Properties LockedOut).LockedOut

    If ($JabadLOStatus -eq $False) {
        $JabadStatusF = "Unlocked"
    } else {
        $JabadStatusF = "Locked"
    }

    $JabadStatusF
}

Function Show-Statuses {

    #Load statuses
    $JabadStatus = Determine-JabadStatus

    #Add each status seperated by + "`r`n`r`n" + quotes
    $ImportantInformationStatuses.Text = $JabadStatus
}

$Timeout = New-TimeSpan -Hours 1
$sw = [diagnostics.stopwatch]::StartNew()

While ($sw.Elapsed -lt $Timeout) {
    Show-Statuses
    Start-Sleep -Seconds 5
}

$form.ShowDialog()

Body:
Try putting this into your While

 $form.Dispatcher.Invoke( [Action]{},[Windows.Threading.DispatcherPriority]::ContextIdle )

i.e.

While ($sw.Elapsed -lt $Timeout) {
    Show-Statuses
    $form.Dispatcher.Invoke( [Action]{},[Windows.Threading.DispatcherPriority]::ContextIdle )
    Start-Sleep -Seconds 5
}

I use that line of text when updating progress bars within a GUI, and when dumping output into a RichTextbox. It should work for you too.


问:
how to change index directory of my laravel website
I want to create a website using Laravel Framework in my localhost laragon server

I uploaded the website files in a Web Hosting. and when I enter the url http://www.mywebsite.com. then I just get the files like

But when I enter the url http://www.mywebsite.com/public then it is working perfectly.

Can anyone suggest me that what's I'm doing wrong.

答:
i moved all files from public folder (project_folder/public/ )

into project folder

in index.php i changed this lines:

require DIR.'/../vendor/autoload.php';

$app = require_once DIR.'/../bootstrap/app.php';

INTO:

require DIR.'/./vendor/autoload.php';

$app = require_once DIR.'/./bootstrap/app.php';

and works fine ...
Thank you to everyone :)


问:
Mockito: how to test method that changes private field value?
I have a method void create(File file); which creates data structure (map) in a class, which will instantiate and put data into the private field:

```<code>private Map<String> myMap
</code>```

of the class.

Now I want to unit test the method create, how could I do it ?
Thanks!

答:
```<code>class MyClass {
    private final Map<K, V> map;

    MyClass() {
        // production ctr
        this(new HashMap<>();
    }

    MyClass(Map<K, V> map) {
        // visible for testing
        this.map = map;
    }

    void create...
</code>```

This way your test can inject the map and assert that create causes the expected side effects

Body:
I have a method void create(File file); which creates data structure (map) in a class, which will instantiate and put data into the private field:

private Map<String> myMap

of the class.

Now I want to unit test the method create, how could I do it ?
Thanks!

Body:
class MyClass {
    private final Map<K, V> map;

    MyClass() {
        // production ctr
        this(new HashMap<>();
    }

    MyClass(Map<K, V> map) {
        // visible for testing
        this.map = map;
    }

    void create...

This way your test can inject the map and assert that create causes the expected side effects


问:
Set environment variables from file of key/value pairs
TL;DR: How do I export a set of key/value pairs from a text file into the shell environment?

For the record, below is the original version of the question, with examples.

I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:

```<code>MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"
</code>```

This file is stored in ./conf/prac1

My script minientrega.sh then parses the file using this code:

```<code>cat ./conf/$1 | while read line; do
    export $line
done
</code>```

But when I execute minientrega.sh prac1 in the command line it doesn't set the environment variables

I also tried using source ./conf/$1 but the same problem still applies

Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.

答:
The shortest way I found:

Your .env file:

```<code>VARIABLE_NAME="A_VALUE"
</code>```

Then just

```<code>. ./.env && echo ${VARIABLE_NAME}
</code>```

Bonus: Because it's a short one-liner, it's very useful in package.json file

```<code>  "scripts": {
    "echo:variable": ". ./.env && echo ${VARIABLE_NAME}"
  }
</code>```

Note: This way does not export the variables to the child process, check other answers if this is your need.

Body:
TL;DR: How do I export a set of key/value pairs from a text file into the shell environment?

For the record, below is the original version of the question, with examples.

I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:

MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"

This file is stored in ./conf/prac1

My script minientrega.sh then parses the file using this code:

cat ./conf/$1 | while read line; do
    export $line
done

But when I execute minientrega.sh prac1 in the command line it doesn't set the environment variables

I also tried using source ./conf/$1 but the same problem still applies

Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.

Body:
The shortest way I found:

Your .env file:

VARIABLE_NAME="A_VALUE"

Then just

. ./.env && echo ${VARIABLE_NAME}

Bonus: Because it's a short one-liner, it's very useful in package.json file

  "scripts": {
    "echo:variable": ". ./.env && echo ${VARIABLE_NAME}"
  }

Note: This way does not export the variables to the child process, check other answers if this is your need.


问:
C# Server program is unable to detect broken link
The following are the basic skeletons of my .net server and Java client programs:

C# server skeleton

```<code>class ServerProgram
{
    static string origClientID = string.Empty;
    static string reqClientID = string.Empty;
    static string stKey = string.Empty;
    static string stValue = string.Empty;
    static Dictionary<string, KeyValue> KeyValueDictionary;
    static Dictionary<string, ClientClass> ClientDictionary;

    static void Main(string[] args)
    {
        Console.Title = "Server";
        Console.WriteLine("Server program started on address [" + Constants.SERVER_IP +":"+Constants.PORT_NO+"]");

        KeyValueDictionary = new Dictionary<string, KeyValue>();
        ClientDictionary = new Dictionary<string, ClientClass>();

        string ipAddress = Constants.SERVER_IP;
        int portNo = Constants.PORT_NO;

        IPAddress ip = IPAddress.Parse(ipAddress);
        TcpListener listener = new TcpListener(ip, portNo);

        // poll for clients in a 2nd thread
        Thread thread = new Thread(delegate()
        {
            ServerProgram.PollIncomingClientConns(listener);
        });

        thread.Start();
    }

    #region catching client connections
    static void PollIncomingClientConns(TcpListener listener)
    {
        listener.Start();

        try
        {
            bool keepRunning = true;

            while (keepRunning)
            {
                ClientClass client = new ClientClass(listener);

                ClientDictionary.Add(client.ID, client);

                Thread thread = new Thread(delegate()
                {
                    ServerProgram.ReadFromClient(client);
                });
                thread.Start();
            }
        }
        catch (Exception ex)
        {
            var inner = ex.InnerException as SocketException;
            if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
                Console.WriteLine("Disconnected");
            else
                Console.WriteLine(ex.Message);

            listener.Stop();
        }
    }
    #endregion

    static void ReadFromClient(ClientClass client)
    {
       try
        {
            while (client.Tcp.Connected)
            {
                string str = client.Read();
                Console.WriteLine("[" + client.ID + "] says: " + str);

                switch(str)
                {
                    case Commands.AddKeyValue:
                        //...
                        break;

                    case Commands.ListKeys:
                        //...
                        break;

                    case Commands.UpdateValue:
                        //...
                        break;

                    case Commands.Yes:
                        //...
                        break;
                }
            }
        }
        catch
        {
            client.Disconnect();
        }
    }
}
</code>```

Java Client skeleton

```<code>public class FirstJavaClientProgramTest
{
    final static String LOCAL_HOST = "127.0.0.1";
    final static int PORT_NO = 4321;

    public static void main(String args[]) throws UnknownHostException, IOException
    {
        try
        {
            Consolas.WriteLine("Hit enter twice to connect to localhost...\n");

            Consolas.WriteLine("Enter server IP : ");
            String ip = Consolas.ReadLine();

            Consolas.WriteLine("Enter server port : ");
            String portStr = Consolas.ReadLine();

            int port = -99;
            if(ip.equals("\n") || ip.equals(""))
            {
                ip = LOCAL_HOST;
            }

            if(!ip.equals("\n") || !ip.equals(""))
            {
                port = PORT_NO;
            }
            else
            {
                port = Integer.parseInt(portStr);
            }

            // establish the connection
            Socket socket = new Socket(ip, port);

            //send the client ID
            String ID = AlphaNumRandom.randomString(5);
            Consolas.WriteLine(ID);

            BinaryWriter writer = new BinaryWriter(socket);
            writer.Write(ID);

            ReaderRunnableClass readRunnable = new ReaderRunnableClass(socket);
            Thread readThread = new Thread(readRunnable);
            readThread.start();

            WriterRunnableClass writeRunnable = new WriterRunnableClass(socket);
            Thread writeThread = new Thread(writeRunnable);
            writeThread.start();
        }
        catch(Exception ex)
        {
            Consolas.WriteLine("Failed to connect to the server!");
            //Consoles.WriteLine(ex.getMessage());
        }
    }//:~ main
}//:~ class
</code>```

There is a problem with the server program.

The server program can detect a disconnected client if a client is explicitly closed by the user.

But, the server program cannot explicitly detect

if the client is crashed, and/or

if the network link is failed during the communication

How can I detect that?

答: I think that you´ll have to create a method, iterate over the ClientDictionary, to check if the client conections are still alive. Take a look here: Instantly detect client disconnection from server socket</p>

Body:
The following are the basic skeletons of my .net server and Java client programs:

C# server skeleton

class ServerProgram
{
    static string origClientID = string.Empty;
    static string reqClientID = string.Empty;
    static string stKey = string.Empty;
    static string stValue = string.Empty;
    static Dictionary<string, KeyValue> KeyValueDictionary;
    static Dictionary<string, ClientClass> ClientDictionary;

    static void Main(string[] args)
    {
        Console.Title = "Server";
        Console.WriteLine("Server program started on address [" + Constants.SERVER_IP +":"+Constants.PORT_NO+"]");

        KeyValueDictionary = new Dictionary<string, KeyValue>();
        ClientDictionary = new Dictionary<string, ClientClass>();

        string ipAddress = Constants.SERVER_IP;
        int portNo = Constants.PORT_NO;

        IPAddress ip = IPAddress.Parse(ipAddress);
        TcpListener listener = new TcpListener(ip, portNo);

        // poll for clients in a 2nd thread
        Thread thread = new Thread(delegate()
        {
            ServerProgram.PollIncomingClientConns(listener);
        });

        thread.Start();
    }

    #region catching client connections
    static void PollIncomingClientConns(TcpListener listener)
    {
        listener.Start();

        try
        {
            bool keepRunning = true;

            while (keepRunning)
            {
                ClientClass client = new ClientClass(listener);

                ClientDictionary.Add(client.ID, client);

                Thread thread = new Thread(delegate()
                {
                    ServerProgram.ReadFromClient(client);
                });
                thread.Start();
            }
        }
        catch (Exception ex)
        {
            var inner = ex.InnerException as SocketException;
            if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
                Console.WriteLine("Disconnected");
            else
                Console.WriteLine(ex.Message);

            listener.Stop();
        }
    }
    #endregion

    static void ReadFromClient(ClientClass client)
    {
       try
        {
            while (client.Tcp.Connected)
            {
                string str = client.Read();
                Console.WriteLine("[" + client.ID + "] says: " + str);

                switch(str)
                {
                    case Commands.AddKeyValue:
                        //...
                        break;

                    case Commands.ListKeys:
                        //...
                        break;

                    case Commands.UpdateValue:
                        //...
                        break;

                    case Commands.Yes:
                        //...
                        break;
                }
            }
        }
        catch
        {
            client.Disconnect();
        }
    }
}

Java Client skeleton

public class FirstJavaClientProgramTest
{
    final static String LOCAL_HOST = "127.0.0.1";
    final static int PORT_NO = 4321;

    public static void main(String args[]) throws UnknownHostException, IOException
    {
        try
        {
            Consolas.WriteLine("Hit enter twice to connect to localhost...\n");

            Consolas.WriteLine("Enter server IP : ");
            String ip = Consolas.ReadLine();

            Consolas.WriteLine("Enter server port : ");
            String portStr = Consolas.ReadLine();

            int port = -99;
            if(ip.equals("\n") || ip.equals(""))
            {
                ip = LOCAL_HOST;
            }

            if(!ip.equals("\n") || !ip.equals(""))
            {
                port = PORT_NO;
            }
            else
            {
                port = Integer.parseInt(portStr);
            }

            // establish the connection
            Socket socket = new Socket(ip, port);

            //send the client ID
            String ID = AlphaNumRandom.randomString(5);
            Consolas.WriteLine(ID);

            BinaryWriter writer = new BinaryWriter(socket);
            writer.Write(ID);

            ReaderRunnableClass readRunnable = new ReaderRunnableClass(socket);
            Thread readThread = new Thread(readRunnable);
            readThread.start();

            WriterRunnableClass writeRunnable = new WriterRunnableClass(socket);
            Thread writeThread = new Thread(writeRunnable);
            writeThread.start();
        }
        catch(Exception ex)
        {
            Consolas.WriteLine("Failed to connect to the server!");
            //Consoles.WriteLine(ex.getMessage());
        }
    }//:~ main
}//:~ class

There is a problem with the server program.

The server program can detect a disconnected client if a client is explicitly closed by the user.

But, the server program cannot explicitly detect

if the client is crashed, and/or

if the network link is failed during the communication

How can I detect that?


问:
Does Kafka guarantee zero message loss?
I'm reading contradictory views on this. I have a critical application and every message is important. So does kafka guarantees zero message loss at same level of other traditional messaging systems like IBM MQ?</p>

答:
Every topic, is a particular stream of data (similar to a table in a database). Topics, are split into partitions (as many as you like) where each message within a partition gets an incremental id, known as offset as shown below.

Partition 0:

```<code>+---+---+---+-----+
| 0 | 1 | 2 | ... |
+---+---+---+-----+
</code>```

Partition 1:

```<code>+---+---+---+---+----+
| 0 | 1 | 2 | 3 | .. |
+---+---+---+---+----+
</code>```

Now a Kafka cluster is composed of multiple brokers. Each broker is identified with an ID and can contain certain topic partitions.

Example of 2 topics (each having 3 and 2 partitions respectively):

Broker 1:

```<code>+-------------------+
|      Topic 1      |
|    Partition 0    |
|                   |
|                   |
|     Topic 2       |
|   Partition 1     |
+-------------------+
</code>```

Broker 2:

```<code>+-------------------+
|      Topic 1      |
|    Partition 2    |
|                   |
|                   |
|     Topic 2       |
|   Partition 0     |
+-------------------+
</code>```

Broker 3:

```<code>+-------------------+
|      Topic 1      |
|    Partition 1    |
|                   |
|                   |
|                   |
|                   |
+-------------------+
</code>```

Note that data is distributed (and Broker 3 doesn't hold any data of topic 2).

Topics, should have a replication-factor > 1 (usually 2 or 3) so that when a broker is down, another one can serve the data of a topic. For instance, assume that we have a topic with 2 partitions with a replication-factor set to 3 as shown below:

Broker 1:

```<code>+-------------------+
|      Topic 1      |
|    Partition 0    |
|                   |
|                   |
|                   |
|                   |
+-------------------+
</code>```

Broker 2:

```<code>+-------------------+
|      Topic 1      |
|    Partition 0    |
|                   |
|                   |
|     Topic 1       |
|   Partition 0     |
+-------------------+
</code>```

Broker 3:

```<code>+-------------------+
|      Topic 1      |
|    Partition 1    |
|                   |
|                   |
|                   |
|                   |
+-------------------+
</code>```

Now assume that Broker 2 has failed. Broker 1 and 3 can still serve the data for topic 1. So a replication-factor of 3 is always a good idea since it allows for one broker to be taken down for maintenance purposes and also for another one to be taken down unexpectedly. Therefore, Apache-Kafka offers strong durability and fault tolerance guarantees.

Note about Leaders:
At any time, only one broker can be a leader of a partition and only that leader can receive and serve data for that partition. The remaining brokers will just synchronize the data (in-sync replicas). Also note that when the replication-factor is set to 1, the leader cannot be moved elsewhere when a broker fails. In general, when all replicas of a partition fail or go offline, the leader will automatically be set to -1.

Title: Does Kafka guarantee zero message loss?

Body:
Every topic, is a particular stream of data (similar to a table in a database). Topics, are split into partitions (as many as you like) where each message within a partition gets an incremental id, known as offset as shown below.

Partition 0:

+---+---+---+-----+
| 0 | 1 | 2 | ... |
+---+---+---+-----+

Partition 1:

+---+---+---+---+----+
| 0 | 1 | 2 | 3 | .. |
+---+---+---+---+----+

Now a Kafka cluster is composed of multiple brokers. Each broker is identified with an ID and can contain certain topic partitions.

Example of 2 topics (each having 3 and 2 partitions respectively):

Broker 1:

+-------------------+
|      Topic 1      |
|    Partition 0    |
|                   |
|                   |
|     Topic 2       |
|   Partition 1     |
+-------------------+

Broker 2:

+-------------------+
|      Topic 1      |
|    Partition 2    |
|                   |
|                   |
|     Topic 2       |
|   Partition 0     |
+-------------------+

Broker 3:

+-------------------+
|      Topic 1      |
|    Partition 1    |
|                   |
|                   |
|                   |
|                   |
+-------------------+

Note that data is distributed (and Broker 3 doesn't hold any data of topic 2).

Topics, should have a replication-factor > 1 (usually 2 or 3) so that when a broker is down, another one can serve the data of a topic. For instance, assume that we have a topic with 2 partitions with a replication-factor set to 3 as shown below:

Broker 1:

+-------------------+
|      Topic 1      |
|    Partition 0    |
|                   |
|                   |
|                   |
|                   |
+-------------------+

Broker 2:

+-------------------+
|      Topic 1      |
|    Partition 0    |
|                   |
|                   |
|     Topic 1       |
|   Partition 0     |
+-------------------+

Broker 3:

+-------------------+
|      Topic 1      |
|    Partition 1    |
|                   |
|                   |
|                   |
|                   |
+-------------------+

Now assume that Broker 2 has failed. Broker 1 and 3 can still serve the data for topic 1. So a replication-factor of 3 is always a good idea since it allows for one broker to be taken down for maintenance purposes and also for another one to be taken down unexpectedly. Therefore, Apache-Kafka offers strong durability and fault tolerance guarantees.

Note about Leaders:
At any time, only one broker can be a leader of a partition and only that leader can receive and serve data for that partition. The remaining brokers will just synchronize the data (in-sync replicas). Also note that when the replication-factor is set to 1, the leader cannot be moved elsewhere when a broker fails. In general, when all replicas of a partition fail or go offline, the leader will automatically be set to -1.


问:
Retrain image detection with MobileNet
Several ways of retraining MobileNet for use with Tensorflow.js have failed for me. Is there any way to use a retrained model with Tensorflow.js?

Both using the modern, hub-based tutorial, as well as using retrain.py seem to fail.

Convert output of retrain.py to tensorflow.js

Error converting keras model to tfjs: duplicate weight name Variable

as well as some other open questions

Retrain an Image Classifier in tensorflow js

Loading of mobilenet v2 works, but pretrained mobilenet v2 fails

Can't convert TensorFlow saved model to tfjs_layers_model webmodel

The top two other questions show the code that failed in both instances, both are unsolved.

The aim is to load the mobilenet, retrain using custom data, and use it in Tensorflow.js. Following both tutorials seem to fail. Could this be done inside node.js? Is there another way? Where did I make mistakes (or is the software unable to use retrained models)? How can this work?

EDITs: latest github issue and one more question

答:
To use the latest TFjs:

```<code>python retrain.py --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2 \
    --image_dir /tmp/flower_photos --saved_model_dir /tmp/saved_retrained_model
tensorflowjs_converter --input_format=tf_saved_model \
    --output_format=tfjs_graph_model \
    --saved_model_tags=serve \
    /tmp/saved_retrained_model/ /tmp/converted_model/
</code>```

creates a model.json file. Command described in https://github.com/tensorflow/tfjs-converter#step-1-converting-a-savedmodel-keras-h5-tfkeras-savedmodel-or-tensorflow-hub-module-to-a-web-friendly-format.

Yet, loading the model with tf.loadLayersModel("file:///tmp/web_model/model.json") failed with

'className' and 'config' must set.

Title: Retrain image detection with MobileNet

Body:
To use the latest TFjs:

python retrain.py --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2 \
    --image_dir /tmp/flower_photos --saved_model_dir /tmp/saved_retrained_model
tensorflowjs_converter --input_format=tf_saved_model \
    --output_format=tfjs_graph_model \
    --saved_model_tags=serve \
    /tmp/saved_retrained_model/ /tmp/converted_model/

creates a model.json file. Command described in https://github.com/tensorflow/tfjs-converter#step-1-converting-a-savedmodel-keras-h5-tfkeras-savedmodel-or-tensorflow-hub-module-to-a-web-friendly-format.

Yet, loading the model with tf.loadLayersModel("file:///tmp/web_model/model.json") failed with

'className' and 'config' must set.


问:
Nested integration for incomplete convolution of gauss densities
Let g(x) = 1/(2*pi) exp ( - x^2 / 2) be the density of the normal distribution with mean 0 and standard deviation 1. In some calculation on paper appeared integrals of the form

where c>0 is a positive number.

Since I could not evaluate this by hand, I had the idea to approximate and plot it. I tried this in R, because R provides the dnorm function and a function to do integrals.

You see that I need to integrate numerically n times, where n shall be chosed by the call of a plot function. My code has an for-loop to create those "incomplete" convolutions iterativly.

For example even with n=3 and c=1 this gives me an error. n=2 (thus it's one integration) works.

```<code>N = 3

ngauss <- function(x) dnorm(x , mean = 0, sd = 1)

convoluts <- list()
convoluts[[1]] <- ngauss

for (i in 2:N) {

 h <- function(y) {
   g <- function(z) {ngauss(y-z)*convoluts[[i-1]](z)}
   return(integrate(g, lower = -1, upper = 1)$value)
 }
 h <- Vectorize(h)

 convoluts[[i]] <- h

}

convoluts[[3]](0)
</code>```

What I get is:

Error: evaluation nested too deeply: infinite recursion /
  options(expressions=)?

I understand that this is a hard computation, but for "small" n something similar should possible.

Maybe someone can help me to fix my code or provide a recommendation how I can implement this in a better way. Another language that is more appropriate for this would be also okay.

答:
The issue appears to be in how integrate deals with variables in different environments. In particular, it doesn't really deal with i correctly in each iteration. Instead using

```<code>  h <- evalq(function(y) {
    g <- function(z) {ngauss(y - z) * convoluts[[i - 1]](z)}
    integrate(g, lower = -1, upper = 1)$value
  }, list(i = i))
</code>```

does the job and, say, setting N <- 6 quickly gives

```<code>convoluts[[N]](0)
# [1] 0.03423872
</code>```

As your integration is simply the pdf of a sum of N independent standard normals (which then follows N(0, N)), we may also verify this approach by setting lower = -Inf and upper = Inf. Then with N <- 4 we have

```<code>dnorm(0, sd = sqrt(N))
# [1] 0.1994711
convoluts[[N]](0)
# [1] 0.1994711
</code>```

So, for practical purposes, when c = Inf, you are way better off using dnorm rather than manual computations.

Body:
Let g(x) = 1/(2*pi) exp ( - x^2 / 2) be the density of the normal distribution with mean 0 and standard deviation 1. In some calculation on paper appeared integrals of the form

where c>0 is a positive number.

Since I could not evaluate this by hand, I had the idea to approximate and plot it. I tried this in R, because R provides the dnorm function and a function to do integrals.

You see that I need to integrate numerically n times, where n shall be chosed by the call of a plot function. My code has an for-loop to create those "incomplete" convolutions iterativly.

For example even with n=3 and c=1 this gives me an error. n=2 (thus it's one integration) works.

N = 3

ngauss <- function(x) dnorm(x , mean = 0, sd = 1)

convoluts <- list()
convoluts[[1]] <- ngauss

for (i in 2:N) {

 h <- function(y) {
   g <- function(z) {ngauss(y-z)*convoluts[[i-1]](z)}
   return(integrate(g, lower = -1, upper = 1)$value)
 }
 h <- Vectorize(h)

 convoluts[[i]] <- h

}

convoluts[[3]](0)

What I get is:

Error: evaluation nested too deeply: infinite recursion /
  options(expressions=)?

I understand that this is a hard computation, but for "small" n something similar should possible.

Maybe someone can help me to fix my code or provide a recommendation how I can implement this in a better way. Another language that is more appropriate for this would be also okay.

Body:
The issue appears to be in how integrate deals with variables in different environments. In particular, it doesn't really deal with i correctly in each iteration. Instead using

  h <- evalq(function(y) {
    g <- function(z) {ngauss(y - z) * convoluts[[i - 1]](z)}
    integrate(g, lower = -1, upper = 1)$value
  }, list(i = i))

does the job and, say, setting N <- 6 quickly gives

convoluts[[N]](0)
# [1] 0.03423872

As your integration is simply the pdf of a sum of N independent standard normals (which then follows N(0, N)), we may also verify this approach by setting lower = -Inf and upper = Inf. Then with N <- 4 we have

dnorm(0, sd = sqrt(N))
# [1] 0.1994711
convoluts[[N]](0)
# [1] 0.1994711

So, for practical purposes, when c = Inf, you are way better off using dnorm rather than manual computations.


问:
How to fix this code? It writes to file the first argument, why not the second?
I am working on this code to automate "copy-paste" by reading from an access table and write to excel sheet.
Different values from access table, needs to be written in a particular cells on excel sheet.
My problem is that the code works by reading and writing the first value, but not the second++ values.

The first value is correctly written on E15 in Excel, but the second value which is supposed to be written on cell E16 is not written, Why?

```<code>Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"

Application.ScreenUpdating = False

Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")

cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(14, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(15, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

End Sub
</code>```

I dont get any error messages, the code runs, but the output is not complete.

答:
Try this: </p>

```<code>range(cells(15,4), cells(15,3+rs.Fields.Count)).CopyFromRecordset rs
</code>```

Body:
I am working on this code to automate "copy-paste" by reading from an access table and write to excel sheet.
Different values from access table, needs to be written in a particular cells on excel sheet.
My problem is that the code works by reading and writing the first value, but not the second++ values.

The first value is correctly written on E15 in Excel, but the second value which is supposed to be written on cell E16 is not written, Why?

Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"

Application.ScreenUpdating = False

Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")

cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(14, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(15, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

End Sub

I dont get any error messages, the code runs, but the output is not complete.

Body:
Try this:

range(cells(15,4), cells(15,3+rs.Fields.Count)).CopyFromRecordset rs


问:
Regarding to save previous record in asp.net
Hi
I have one label for question, radiobuttonlist for their answers, next button to move next question & previous button. I am displaying one question per page after clicking next button next question appears, but when i click previous button previous question appears.
But i want previous question with earlier selected answer when i click to previous button.
Asp.net c# Thank you.</p>

答:
You can use asp.net wizard too...

Wizard Class

Wizard Web Server Control Overview

Walkthrough: Advanced Use of the ASP.NET Wizard Control


问:
How to create collapsible cards in bootstrap in django template?
I have a table of these collapsible cards with dynamic content in them. The code I have taken from bootstrap looks like this:

```<code><p>
  <a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</a>
  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button>
</p>
<div class="row">
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample1">
      <div class="card card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
      </div>
    </div>
  </div>
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample2">
      <div class="card card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
      </div>
    </div>
  </div>
</div>
</code>```

Problem

But as you can see, each collapse is controlled by this attribute multiCollapseExample1. In my django template, when I use this, on clicking any of the close button, only the first card collases because it has a static value of 1. How can I give it a dynamic value so every card opens and closes correctly? Reason I am asking is because my code is pretty complicated and is return about 10+ parameters from the views.py function, and I am iterating a dictionary of dictionaries to print all the values in the format I want. For that reason, I have about 4-5 nested for loops, and also an if statement which checks if the if looper counter is same as the parent's loop counter. I am not able to undertand how I can simple solve this problem.

This is my actual full code:

```<code><table class="table mb-0 table-striped loadingplan">
            <thead>
            <tr>
                <th>ID</th>
                <th>Vehicles</th>
                <th>Gross Weight</th>
                <th>Route</th>
                <th>Route Distance</th>
                <th>Route TAT</th>
                <th>ETD</th>
                <th>ETA</th>
                <th></th>
                <th>Action</th>
            </tr>
            </thead>
            <tbody>
            {% for d,t,r,y,w,f in open_route_info %}
                {% for k,v in open_trucks.items %}
                    {% if forloop.counter == forloop.parentloop.counter %}
                        <td class="align-middle">YNT1151<br>
                            <small class="align-right">{{ f }}% Filled</small>
                        </td>
                        <td>
                            {% for x in v %}
                                {% for y,z in x.items %}
                                    {{ y.display_name }}
                                {% endfor %}
                            {% endfor %}
                        </td>

                        {% for truck,value in v.items %}
                            <td class="align-middle">{{ truck }} {{ value }}<br>o
                                <a href="#">
                                    <small>Download Loading Plan {{ value.pk }}</small>
                                </a>
                            </td>
                        {% endfor %}

                        <td class="align-middle">{{ w }}KG</td>
                        <td class="align-middle">{{ k }}</td>
                        <td class="align-middle">{{ d }} KM</td>
                        <td class="align-middle">{{ t }}</td>
                        <td class="align-middle">{{ y }}</td>
                        <td class="align-middle">{{ scheduled_date }}</td>
                        <td class="align-middle">
                            <button class="btn" type="button" data-toggle="collapse"
                                    data-target="#multiCollapseExample2" aria-expanded="false"
                                    aria-controls="multiCollapseExample2"><img
                                    src="{% static 'img/cardopen.svg' %}" alt="card open"></button>
                        </td>
                        <td class="align-middle"><a href="#" class="btn btn-primary">Raise RFQ</a>
                        </td>
                        <tr class="collapse multi-collapse" id="multiCollapseExample2">
                            <td colspan="5">

                                <table class="table table-bordered">
                                    <thead>
                                    <tr>
                                        <th>SKU ID</th>
                                        <th>SKU Name</th>
                                        <th>Quantity</th>
                                    </tr>
                                    </thead>
                                    <tbody>

                                    {% for x in v %}
                                        {% for y,z in x.items %}
                                            {% for w in z %}
                                                <tr>

                                                    <td>{{ w.name }}</td>
                                                    <td>{{ w.pid }}</td>
                                                    <td>{{ w.quantity }}</td>

                                                </tr>
                                            {% endfor %}

                                        {% endfor %}
                                    {% endfor %}

                                    </tbody>
                                </table>

                            </td>
                            <td colspan="5" class="align-middle">
                                <div class="card card-body iframecard">

                                    <iframe src="{{ r }}"></iframe>

                                </div>
                            </td>
                        </tr>

                    {% endif %}
                {% endfor %}
            {% endfor %}

            </tbody>
        </table>
</code>```

What I want

All I want to do is, replace multiCollapseExample2 with a dynamic variable which is the same length as the number of items. I tried using a simple loop on a list which has the length as the number of items, but it did not work probably because of the if statement {% if forloop.counter == forloop.parentloop.counter %}.

答:
Looks like you can use the 2 for-loops and their variables to create an unique id for your cards.
Something like

```<code>data-target="#multiCollapse{{d}}{{t}}{{k}}{{v}}"
</code>```

Where d,t is from outer for-loop and k,v is from the inner loop.

Body:
I have a table of these collapsible cards with dynamic content in them. The code I have taken from bootstrap looks like this:

  Toggle first element
  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button>

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Problem

But as you can see, each collapse is controlled by this attribute multiCollapseExample1. In my django template, when I use this, on clicking any of the close button, only the first card collases because it has a static value of 1. How can I give it a dynamic value so every card opens and closes correctly? Reason I am asking is because my code is pretty complicated and is return about 10+ parameters from the views.py function, and I am iterating a dictionary of dictionaries to print all the values in the format I want. For that reason, I have about 4-5 nested for loops, and also an if statement which checks if the if looper counter is same as the parent's loop counter. I am not able to undertand how I can simple solve this problem.

This is my actual full code:

                ID
                Vehicles
                Gross Weight
                Route
                Route Distance
                Route TAT
                ETD
                ETA

                Action

            {% for d,t,r,y,w,f in open_route_info %}
                {% for k,v in open_trucks.items %}
                    {% if forloop.counter == forloop.parentloop.counter %}
                        YNT1151

                            {{ f }}% Filled

                            {% for x in v %}
                                {% for y,z in x.items %}
                                    {{ y.display_name }}
                                {% endfor %}
                            {% endfor %}

                        {% for truck,value in v.items %}
                            {{ truck }} {{ value }}
o

                                    Download Loading Plan {{ value.pk }}

                        {% endfor %}

                        {{ w }}KG
                        {{ k }}
                        {{ d }} KM
                        {{ t }}
                        {{ y }}
                        {{ scheduled_date }}

                            <button class="btn" type="button" data-toggle="collapse"
                                    data-target="#multiCollapseExample2" aria-expanded="false"
                                    aria-controls="multiCollapseExample2"></button>

                        Raise RFQ

                                        SKU ID
                                        SKU Name
                                        Quantity

                                    {% for x in v %}
                                        {% for y,z in x.items %}
                                            {% for w in z %}

                                                    {{ w.name }}
                                                    {{ w.pid }}
                                                    {{ w.quantity }}

                                            {% endfor %}

                                        {% endfor %}
                                    {% endfor %}

                    {% endif %}
                {% endfor %}
            {% endfor %}

What I want

All I want to do is, replace multiCollapseExample2 with a dynamic variable which is the same length as the number of items. I tried using a simple loop on a list which has the length as the number of items, but it did not work probably because of the if statement {% if forloop.counter == forloop.parentloop.counter %}.

Body:
Looks like you can use the 2 for-loops and their variables to create an unique id for your cards.
Something like

data-target="#multiCollapse{{d}}{{t}}{{k}}{{v}}"

Where d,t is from outer for-loop and k,v is from the inner loop.


问:
Starting Automator Script with LaunchAgent
I built a job by Automator to clear the downloads folder and empty the trash. When i start the created app by double click, it starts correctly. But it has to be transferred to other computer in our company and i dont want to give the user the job to launch the app.
So i created this LaunchAgent script to start the app.

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.herpag.aufraeumen.plist</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Users/hansthiele/Applications/Aufraeumen.app</string>
        </array>
        <key>StartCalendarInterval</key>
        <dict>
            <key>Minute</key>
            <integer>45</integer>
            <key>Hour</key>
            <integer>13</integer>
        </dict>
    </dict>
    </plist>
</code>```

My problem is now, that the console tells me that the job is started, but nothing happens. The downloads are not cleared and the trash is still full. Also the error.log is empty.

答:
There are 2 issues:

The Label argument must be specified without the .plist extension.

The path must represent the executable rather than the application container. In case of an Automator app the executable is named Application Stub (unlike Applet in an AppleScript app). It's assumed that hansthiele is the real short username of the current user.

Try

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.herpag.aufraeumen</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/hansthiele/Applications/Aufraeumen.app/Contents/MacOS/Application Stub</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Minute</key>
        <integer>45</integer>
        <key>Hour</key>
        <integer>13</integer>
    </dict>
</dict>
</plist>
</code>```

Body:
I built a job by Automator to clear the downloads folder and empty the trash. When i start the created app by double click, it starts correctly. But it has to be transferred to other computer in our company and i dont want to give the user the job to launch the app.
So i created this LaunchAgent script to start the app.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.herpag.aufraeumen.plist</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Users/hansthiele/Applications/Aufraeumen.app</string>
        </array>
        <key>StartCalendarInterval</key>
        <dict>
            <key>Minute</key>
            <integer>45</integer>
            <key>Hour</key>
            <integer>13</integer>
        </dict>
    </dict>
    </plist>

My problem is now, that the console tells me that the job is started, but nothing happens. The downloads are not cleared and the trash is still full. Also the error.log is empty.

Body:
There are 2 issues:

The Label argument must be specified without the .plist extension.

The path must represent the executable rather than the application container. In case of an Automator app the executable is named Application Stub (unlike Applet in an AppleScript app). It's assumed that hansthiele is the real short username of the current user.

Try

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.herpag.aufraeumen</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/hansthiele/Applications/Aufraeumen.app/Contents/MacOS/Application Stub</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Minute</key>
        <integer>45</integer>
        <key>Hour</key>
        <integer>13</integer>
    </dict>
</dict>
</plist>


答:
One way is to parameterize the method doSomething with a mutable object, that you can set upon method execution and assert in the test method. Otherwise, you may also check for exception thrown for any negative scenario, something like

```<code>@Test(expected = EmailSendException.class)
public void testDoSomething(){
    ....
}
</code>```

Title: Testing void methods that do not change anything in Test scenario

Body:
I know that every method that doesn't do anything shouldn't be tested (or not even exist). The thing is, that my method does something normally, but for the test-scenario I have to mock that thing that it does. But I would still like to assert the parameters that it would send to the external thing.

Sounds more complicated than it is - Check my snippet for better understanding:

class A {
    @Inject
    private Mailer mailer; // Custom mailer class

    public void doSomething() {
        Date date = new Date(); // dynamic parameter I do not care about in the test
        String parameter = "test"; // The parameter I want to test later

        mailer.sendMail(parameter, date);
    }
}

class ATest {
    @Mock
    @Produces
    private Mailer mailer;

    @Inject
    private A classToTest;

    @Test
    public void testDoSomething() throws Exception {

        classToTest.doSomething();

        assertThat(??).isEqualTo("test"); //How can I get the value of parameter?
    }
}

As you can see I need to mock my emailer, so that I dont send a email everytime a test runs.

It would make no sense to promote parameter to a global variable.

Is there any way to test the value of parameter without changing the code of A? And if not what would be the best solution without messing up my class just for testing?

Body:
One way is to parameterize the method doSomething with a mutable object, that you can set upon method execution and assert in the test method. Otherwise, you may also check for exception thrown for any negative scenario, something like

@Test(expected = EmailSendException.class)
public void testDoSomething(){
    ....
}


问:
How to calculate tax in salary
I am working on a payroll project in which I want to calculate overtime, allowance and tax to salary. I want to add overtime and allowance to salary and subtract tax from salary.

The following script works with overtime and allowance but I'm facing problems with calculating tax.

When I enter a tax percentage it should calculate the tax amount from the salary to the tax field and calculate the total. When I enter the tax directly it should calculate the percentage to the taxPercentage field and calculate the total.

$(document).on('change keyup blur', '.add', function(e) {
  add();
});

function add() {
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (allowance > 0 || over > 0) {
    total = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
    $('#total').val(total);
  } else {
    $('#total').val(prevTotal);
  }
}

$(document).on('change keyup blur', '.tax', function(e) {
  subtracttax();
});

function subtracttax() {
  salary = $('#salary').val();
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (taxPercentage > 0) {
    total = parseFloat(salary) * parseFloat(taxPercentage) / 100;
    $('#tax').val(total);
    $('#total').val(prevTotal - total);
  } else {
    $('#total').val(prevTotal);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
  <label> salary </label>
  <input type="text" id="salary" value="9000" />
</div>
<br>
<div>
  <label> over Time </label>
  <input type="text" class="add" id="over" />
</div>
<br>
<div>
  <label> allowance </label>
  <input type="text" class="add" id="allowance" />
</div>
<br>
<div>
  <label> Tax Percentage</label>
  <input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
  <label> Total Tax</label>
  <input type="text" class="tax" id="tax" />
</div>
<br>
<div>
  <label> Total salary</label>
  <input type="text" id="total" />
</div></code>```

答:
Try like this.

as per your comment I only added salary + over time.

calculateTax();
$(document).on('change keyup blur', '.tax', function(e) {
  calculateTax();
});

$(document).on('change keyup blur', '.taxVal', function(e) {
  calculateTaxPer();
});

function calculateTax() {
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  $('#total').val(total);

  if (taxPercentage > 0) {
    totalTax = (parseFloat(salary) + parseFloat(over)) * parseFloat(taxPercentage) / 100;
    $('#tax').val(totalTax);
    $('#total').val(total - totalTax);
    return false;
  }

}

function calculateTaxPer(){
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  $('#total').val(total);

  if(tax > 0){
    taxPer = (parseFloat(tax)/(parseFloat(salary) + parseFloat(over)))*100;
    $('#taxPercentage').val(taxPer);
    $('#total').val(total - tax);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
  <label> salary </label>
  <input type="text" id="salary" value="9000" />
</div>
<br>
<div>
  <label> over Time </label>
  <input type="text" class="tax" id="over" />
</div>
<br>
<div>
  <label> allowance </label>
  <input type="text" class="tax" id="allowance" />
</div>
<br>
<div>
  <label> Tax Percentage</label>
  <input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
  <label> Total Tax</label>
  <input type="text" class="taxVal" id="tax" />
</div>
<br>
<div>
  <label> Total salary</label>
  <input type="text" id="total" />
</div></code>```

Title: How to calculate tax in salary

Body:
I am working on a payroll project in which I want to calculate overtime, allowance and tax to salary. I want to add overtime and allowance to salary and subtract tax from salary.

The following script works with overtime and allowance but I'm facing problems with calculating tax.

When I enter a tax percentage it should calculate the tax amount from the salary to the tax field and calculate the total. When I enter the tax directly it should calculate the percentage to the taxPercentage field and calculate the total.

$(document).on('change keyup blur', '.add', function(e) {
  add();
});

function add() {
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (allowance > 0 || over > 0) {
    total = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
    $('#total').val(total);
  } else {
    $('#total').val(prevTotal);
  }
}

$(document).on('change keyup blur', '.tax', function(e) {
  subtracttax();
});

function subtracttax() {
  salary = $('#salary').val();
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (taxPercentage > 0) {
    total = parseFloat(salary) * parseFloat(taxPercentage) / 100;
    $('#tax').val(total);
    $('#total').val(prevTotal - total);
  } else {
    $('#total').val(prevTotal);
  }
}

   salary
  <input type="text" id="salary" value="9000" />

   over Time
  <input type="text" class="add" id="over" />

   allowance
  <input type="text" class="add" id="allowance" />

   Tax Percentage
  <input type="text" class="tax" id="taxPercentage" />

   Total Tax
  <input type="text" class="tax" id="tax" />

   Total salary
  <input type="text" id="total" />

Body:
Try like this.

as per your comment I only added salary + over time.

calculateTax();
$(document).on('change keyup blur', '.tax', function(e) {
  calculateTax();
});

$(document).on('change keyup blur', '.taxVal', function(e) {
  calculateTaxPer();
});

function calculateTax() {
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  $('#total').val(total);

  if (taxPercentage > 0) {
    totalTax = (parseFloat(salary) + parseFloat(over)) * parseFloat(taxPercentage) / 100;
    $('#tax').val(totalTax);
    $('#total').val(total - totalTax);
    return false;
  }

}

function calculateTaxPer(){
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  $('#total').val(total);

  if(tax > 0){
    taxPer = (parseFloat(tax)/(parseFloat(salary) + parseFloat(over)))*100;
    $('#taxPercentage').val(taxPer);
    $('#total').val(total - tax);
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
  <label> salary </label>
  <input type="text" id="salary" value="9000" />
</div>
<br>
<div>
  <label> over Time </label>
  <input type="text" class="tax" id="over" />
</div>
<br>
<div>
  <label> allowance </label>
  <input type="text" class="tax" id="allowance" />
</div>
<br>
<div>
  <label> Tax Percentage</label>
  <input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
  <label> Total Tax</label>
  <input type="text" class="taxVal" id="tax" />
</div>
<br>
<div>
  <label> Total salary</label>
  <input type="text" id="total" />
</div>


问:
Mysql problem: no mysql.sock
Yesterday I was working using MySQL installed on my computer.

I downloaded xampp, so I have I changed on my.cnf file the path to the socket:

```<code> /opt/lampp/var/mysql/mysql.sock
</code>```

That file was just there. Today I wanted to keep working on it, and I found that file is not there anymore, so I am getting the following error while I am starting mysql server:

```<code>ERROR 2002 (HY000):
Can't connect to local MySQL server through socket
'/opt/lampp/var/mysql/mysql.sock' (2)
</code>```

Here are some tests I made:

```<code>mujeresponja@ubuntu:~$ ps -fea | grep mysqld
1000     15707 15615  0 16:28 pts/1    00:00:00 grep --color=auto mysqld
mujeresponja@ubuntu:~$ ps -fea | grep mysql
1000     15709 15615  0 16:29 pts/1    00:00:00 grep --color=auto mysql
</code>```

As a possible solution I uninstalled xampp and reinstall it, and also a new MySQL server, just in case. Anyway, that file is not there anymore.

EDIT
Where the mysql.sock should be, instead there are two files mysql_upgrade_info (Which contains just 5.5.8) and another binary file called ubuntu.err:

```<code>mujeresponja@ubuntu:/opt/lampp/var/mysql$ sudo cat ubuntu.err
110403 17:28:52 mysqld_safe Starting mysqld daemon with databases from /opt/lampp/var/mysql
110403 17:28:52 [Note] Plugin 'FEDERATED' is disabled.
/opt/lampp/sbin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
110403 17:28:52 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
InnoDB: The InnoDB memory heap is disabled
InnoDB: Mutexes and rw_locks use InnoDB's own implementation
InnoDB: Compressed tables use zlib 1.2.3
110403 17:28:52  InnoDB: Initializing buffer pool, size = 16.0M
110403 17:28:52  InnoDB: Completed initialization of buffer pool
110403 17:28:52  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name /opt/lampp/var/mysql/ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.
110403 17:28:52 mysqld_safe mysqld from pid file /opt/lampp/var/mysql/ubuntu.pid ended
110403 17:29:22 mysqld_safe Starting mysqld daemon with databases from /opt/lampp/var/mysql
110403 17:29:22 [Note] Plugin 'FEDERATED' is disabled.
/opt/lampp/sbin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
110403 17:29:22 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
InnoDB: The InnoDB memory heap is disabled
InnoDB: Mutexes and rw_locks use InnoDB's own implementation
InnoDB: Compressed tables use zlib 1.2.3
110403 17:29:22  InnoDB: Initializing buffer pool, size = 16.0M
110403 17:29:22  InnoDB: Completed initialization of buffer pool
110403 17:29:22  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name /opt/lampp/var/mysql/ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.
110403 17:29:22 mysqld_safe mysqld from pid file /opt/lampp/var/mysql/ubuntu.pid ended
</code>```

(Sorry, I don't know how to show terminal messages in an appropiuate way)
 Can anybody help me on this? Thanks in advance!

答:
I didn't find a certain reason for my problem.
I just unisntalled  and reinstalled, and then everything went Ok.

That is not a real solution, but it worked. Good luck

ContentLicense: CC BY-SA 2.5

Title: Mysql problem: no mysql.sock

Body:
Yesterday I was working using MySQL installed on my computer.

I downloaded xampp, so I have I changed on my.cnf file the path to the socket:

 /opt/lampp/var/mysql/mysql.sock

That file was just there. Today I wanted to keep working on it, and I found that file is not there anymore, so I am getting the following error while I am starting mysql server:

ERROR 2002 (HY000):
Can't connect to local MySQL server through socket
'/opt/lampp/var/mysql/mysql.sock' (2)

Here are some tests I made:

mujeresponja@ubuntu:~$ ps -fea | grep mysqld
1000     15707 15615  0 16:28 pts/1    00:00:00 grep --color=auto mysqld
mujeresponja@ubuntu:~$ ps -fea | grep mysql
1000     15709 15615  0 16:29 pts/1    00:00:00 grep --color=auto mysql

As a possible solution I uninstalled xampp and reinstall it, and also a new MySQL server, just in case. Anyway, that file is not there anymore.

EDIT
Where the mysql.sock should be, instead there are two files mysql_upgrade_info (Which contains just 5.5.8) and another binary file called ubuntu.err:

mujeresponja@ubuntu:/opt/lampp/var/mysql$ sudo cat ubuntu.err
110403 17:28:52 mysqld_safe Starting mysqld daemon with databases from /opt/lampp/var/mysql
110403 17:28:52 [Note] Plugin 'FEDERATED' is disabled.
/opt/lampp/sbin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
110403 17:28:52 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
InnoDB: The InnoDB memory heap is disabled
InnoDB: Mutexes and rw_locks use InnoDB's own implementation
InnoDB: Compressed tables use zlib 1.2.3
110403 17:28:52  InnoDB: Initializing buffer pool, size = 16.0M
110403 17:28:52  InnoDB: Completed initialization of buffer pool
110403 17:28:52  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name /opt/lampp/var/mysql/ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.
110403 17:28:52 mysqld_safe mysqld from pid file /opt/lampp/var/mysql/ubuntu.pid ended
110403 17:29:22 mysqld_safe Starting mysqld daemon with databases from /opt/lampp/var/mysql
110403 17:29:22 [Note] Plugin 'FEDERATED' is disabled.
/opt/lampp/sbin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
110403 17:29:22 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
InnoDB: The InnoDB memory heap is disabled
InnoDB: Mutexes and rw_locks use InnoDB's own implementation
InnoDB: Compressed tables use zlib 1.2.3
110403 17:29:22  InnoDB: Initializing buffer pool, size = 16.0M
110403 17:29:22  InnoDB: Completed initialization of buffer pool
110403 17:29:22  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name /opt/lampp/var/mysql/ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.
110403 17:29:22 mysqld_safe mysqld from pid file /opt/lampp/var/mysql/ubuntu.pid ended

(Sorry, I don't know how to show terminal messages in an appropiuate way)
 Can anybody help me on this? Thanks in advance!