text:
Q: Random Test Crash TDD Kotlin The following test below causes a random crash.   I am at a loss most of the time it works fine.
> @Test fun `perform login without a previously saved user`() =
> runBlocking {
>     testSavedUser1LiveData = MutableLiveData()
>
>     coEvery { userDao.getCurrentUserLiveData() } returns testSavedUser1LiveData
>     coEvery { userDao.upsert(any()) } returns Unit
>
>     coEvery { userAPIDataSource.fetchLoginUser(loginCredentials) } returns Unit
>     coEvery { userAPIDataSource.getLoginUserResults } returns testUser1ResponseLiveDataOfJsonElement
>
>     loginRepository = LoginRepositoryImpl(userDao, companyDao, userAPIDataSource)
>     loginViewModel = LoginViewModel(dispatchers, validator, loginRepository)
>
>     loginViewModel.loginLiveData().observeForever(loginLiveDataObserver)
>     loginViewModel.login(loginCredentials)
>
>     coVerifyOrder {
>         loginLiveDataObserver.onChanged(enableLoading)
>         loginLiveDataObserver.onChanged(loginResults)
>         loginLiveDataObserver.onChanged(disableLoading)
>     } }

The code that accompanies this is
    fun login(credentials: LoginCredentials) {
        _loginLiveData.value = LoginResult.Loading(true)
    if(validator.validate(credentials)) {
        triggerLogin(credentials)
    } else {
        _loginLiveData.value = LoginResult.Failure("Incorrect Credentials")
        _loginLiveData.value = LoginResult.Loading(false)
    }
}

private fun triggerLogin(credentials: LoginCredentials) {
    launch(dispatchers.background) {
        loginRepository.performLogin(credentials)

        withContext(dispatchers.ui) {
            _loginLiveData.value = loginRepository.getLoginUserResults
            _loginLiveData.value = LoginResult.Loading(false)
        }
    }
}

the crash is:

java.lang.AssertionError: Verification failed: less calls happened
  then demanded by order verification sequence.
Matchers:  Observer(#94).onChanged(eq(Loading(value=true))))
  Observer(#94).onChanged(eq(Success(user=Current User Response: 1:
  testUserName1  )))) Observer(#94).onChanged(eq(Loading(value=false))))
Calls: 1) Observer(#94).onChanged(Loading(value=true)) 2)
  Observer(#94).onChanged(Success(user=Current User Response: 1:
  testUserName1  ))
Stack traces: 1)
  io.mockk.impl.InternalPlatform.captureStackTrace
  (InternalPlatform.kt:114)
                                                                                io.mockk.impl.stub.MockKStub.handleInvocation
  (MockKStub.kt:256)
                                                 io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation
  (JvmMockFactoryHelper.kt:25)
                                                                          io.mockk.proxy.jvm.advice.Interceptor.call
  (Interceptor.kt:20)
                                                                           io.mockk.proxy.jvm.advice.BaseAdvice.handle
  (BaseAdvice.kt:42)
                                                         io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyInterceptor.interceptNoSuper
  (JvmMockKProxyInterceptor.java:45)
                                                                         androidx.lifecycle.Observer$Subclass18.onChanged
  (-:-1)
                                                                                androidx.lifecycle.LiveData.considerNotify
  (LiveData.java:131)
                                                                                androidx.lifecycle.LiveData.dispatchingValue
  (LiveData.java:149)
                                                                                androidx.lifecycle.LiveData.setValue
  (LiveData.java:307)
                                                                             androidx.lifecycle.MutableLiveData.setValue
  (MutableLiveData.java:50)
                                                                   com.test.testapp.ui.login.LoginViewModel.login
  (LoginViewModel.kt:84)
  com.test.testapp.featureTests.login.LoginFeatureShould$perform
  login without a previously saved user$1.invokeSuspend
  (LoginFeatureShould.kt:102)
                                                            kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith
  (ContinuationImpl.kt:32)
                                                                              kotlinx.coroutines.DispatchedTask.run
  (Dispatched.kt:233)
                                                                           kotlinx.coroutines.EventLoopImplBase.processNextEvent
  (EventLoop.kt:116)
                                                                           kotlinx.coroutines.BlockingCoroutine.joinBlocking
  (Builders.kt:76)
                                                                      kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking
  (Builders.kt:53)
                                                                                kotlinx.coroutines.BuildersKt.runBlocking
  (-:1)
                                                                      kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default
  (Builders.kt:35)
                                                                                kotlinx.coroutines.BuildersKt.runBlocking$default
  (-:1)
                                                     com.test.testapp.featureTests.login.LoginFeatureShould.perform
  login without a previously saved user (LoginFeatureShould.kt:89)
                                                                     sun.reflect.NativeMethodAccessorImpl.invoke0

(NativeMethodAccessorImpl.java:-2)N
                                                                           sun.reflect.NativeMethodAccessorImpl.invoke
  (NativeMethodAccessorImpl.java:62)
                                                                       sun.reflect.DelegatingMethodAccessorImpl.invoke
  (DelegatingMethodAccessorImpl.java:43)
                                                                                java.lang.reflect.Method.invoke
  (Method.java:498)
                                                                org.junit.platform.commons.util.ReflectionUtils.invokeMethod
  (ReflectionUtils.java:628)
                                                           org.junit.jupiter.engine.execution.ExecutableInvoker.invoke
  (ExecutableInvoker.java:117)
                                                   org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7
  (TestMethodTestDescriptor.java:184)
                                              org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute
  (ThrowableCollector.java:73)
                                                   org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod
  (TestMethodTestDescriptor.java:180)
                                                   org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute
  (TestMethodTestDescriptor.java:127)
                                                   org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute
  (TestMethodTestDescriptor.java:68)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5
  (NodeTestTask.java:135)
                                              org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute
  (ThrowableCollector.java:73)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7
  (NodeTestTask.java:125)
                                                            org.junit.platform.engine.support.hierarchical.Node.around
  (Node.java:135)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8
  (NodeTestTask.java:123)
                                              org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute
  (ThrowableCollector.java:73)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively
  (NodeTestTask.java:122)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.execute
  (NodeTestTask.java:80)
                                                                                java.util.ArrayList.forEach
  (ArrayList.java:1251)
                       org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll
  (SameThreadHierarchicalTestExecutorService.java:38)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5
  (NodeTestTask.java:139)
                                              org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute
  (ThrowableCollector.java:73)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7
  (NodeTestTask.java:125)
                                                            org.junit.platform.engine.support.hierarchical.Node.around
  (Node.java:135)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8
  (NodeTestTask.java:123)
                                              org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute
  (ThrowableCollector.java:73)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively
  (NodeTestTask.java:122)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.execute
  (NodeTestTask.java:80)
                                                                                java.util.ArrayList.forEach
  (ArrayList.java:1251)
                       org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll
  (SameThreadHierarchicalTestExecutorService.java:38)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5
  (NodeTestTask.java:139)
                                              org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute
  (ThrowableCollector.java:73)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7
  (NodeTestTask.java:125)
                                                            org.junit.platform.engine.support.hierarchical.Node.around
  (Node.java:135)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8
  (NodeTestTask.java:123)
                                              org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute
  (ThrowableCollector.java:73)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively
  (NodeTestTask.java:122)
                                                    org.junit.platform.engine.support.hierarchical.NodeTestTask.execute
  (NodeTestTask.java:80)
                       org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit
  (SameThreadHierarchicalTestExecutorService.java:32)
                                        org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute
  (HierarchicalTestExecutor.java:57)
                                          org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute
  (HierarchicalTestEngine.java:51)
                                                               org.junit.platform.launcher.core.DefaultLauncher.execute
  (DefaultLauncher.java:229)
                                                               org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6
  (DefaultLauncher.java:197)
                                                               org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams
  (DefaultLauncher.java:211)
                                                               org.junit.platform.launcher.core.DefaultLauncher.execute
  (DefaultLauncher.java:191)
                                                               org.junit.platform.launcher.core.DefaultLauncher.execute
  (DefaultLauncher.java:128)
                                                                       com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs
  (JUnit5IdeaTestRunner.java:74)
                                                        com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs
  (IdeaTestRunner.java:47)
                                                                   com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart
  (JUnitStarter.java:242)
                                                                   com.intellij.rt.execution.junit.JUnitStarter.main
  (JUnitStarter.java:70)
2)
  io.mockk.impl.InternalPlatform.captureStackTrace
  (InternalPlatform.kt:114)
                                       io.mockk.impl.stub.MockKStub.handleInvocation
  (MockKStub.kt:256)
  io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation
  (JvmMockFactoryHelper.kt:25)
                              io.mockk.proxy.jvm.advice.Interceptor.call                      (Interceptor.kt:20)
                               io.mockk.proxy.jvm.advice.BaseAdvice.handle
  (BaseAdvice.kt:42)
             io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyInterceptor.interceptNoSuper
  (JvmMockKProxyInterceptor.java:45)
                             androidx.lifecycle.Observer$Subclass18.onChanged
  (-:-1)
                                        androidx.lifecycle.LiveData.considerNotify
  (LiveData.java:131)
                                        androidx.lifecycle.LiveData.dispatchingValue
  (LiveData.java:149)
                                        androidx.lifecycle.LiveData.setValue
  (LiveData.java:307)
                                 androidx.lifecycle.MutableLiveData.setValue
  (MutableLiveData.java:50)
      com.test.testapp.ui.login.LoginViewModel$triggerLogin$1$1.invokeSuspend
  (LoginViewModel.kt:99)
      com.test.testapp.ui.login.LoginViewModel$triggerLogin$1$1.invoke
  (LoginViewModel.kt:-1)
                       kotlinx.coroutines.intrinsics.UndispatchedKt.startUndispatchedOrReturn
  (Undispatched.kt:91)
                   kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext
  (Builders.common.kt:146)
                                      kotlinx.coroutines.BuildersKt.withContext               (-:1)
  com.test.testapp.ui.login.LoginViewModel$triggerLogin$1.invokeSuspend

(LoginViewModel.kt:98)
                kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith
  (ContinuationImpl.kt:32)
                                  kotlinx.coroutines.DispatchedTask.run                       (Dispatched.kt:233)
                   kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely
  (CoroutineScheduler.kt:594)
                   kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely
  (CoroutineScheduler.kt:60)
            kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run                       (CoroutineScheduler.kt:742)
at
  io.mockk.impl.recording.states.VerifyingState.failIfNotPassed(VerifyingState.kt:66)
    at
  io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:42)
    at
  io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:48)
    at
  io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
    at
  io.mockk.impl.eval.VerifyBlockEvaluator.verify(VerifyBlockEvaluator.kt:27)
    at io.mockk.MockKDsl.internalCoVerify(API.kt:143)   at
  io.mockk.MockKDsl.internalCoVerify$default(API.kt:134)    at
  io.mockk.MockKDsl.internalCoVerifyOrder(API.kt:212)   at
  io.mockk.MockKKt.coVerifyOrder(MockK.kt:264)  at
  io.mockk.MockKKt.coVerifyOrder$default(MockK.kt:261)  at
  com.test.testapp.featureTests.login.LoginFeatureShould$perform
  login without a previously saved
  user$1.invokeSuspend(LoginFeatureShould.kt:104)   at
  kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:233)     at
  kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:76)
    at
  kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:53)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)    at
  kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:35)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    at com.test.testapp.featureTests.login.LoginFeatureShould.perform
  login without a previously saved user(LoginFeatureShould.kt:89)   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:628)
    at
  org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:117)
    at
  org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
    at
  org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at
  org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
    at
  org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:127)
    at
  org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at
  org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at
  org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at
  org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1251)     at
  org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at
  org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at
  org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at
  org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1251)     at
  org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at
  org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at
  org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at
  org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at
  org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at
  org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at
  org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at
  org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at
  org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at
  org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at
  org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at
  org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at
  org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at
  com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:74)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

A: Check timeout feature in docs or on medium about advanced features(again link is on https://mockk.io)


text:
Q: Spring Boot 2.0 Static content not using context path I have a Spring Boot 2.0 application that I'm trying to deploy as a WAR file. This means that it will have a custom context path. To test as a Java application I added
server.servlet.context-path=/MyApplication

to the application.properties. In my index.html (located in src/main/resources/static) I try to include Javascript using something like this:
<script src="dist/main.js"</script>

Regardless of whether I am using the context path, this always tries to load the file from http://localhost:8080/dist/main.js completely ignoring the context path I have specified. The same is true if I try to deploy my application as a WAR. The file is really at http://localhost:8080/MyApplication/dist/main.js.
What do I need to change in my configuration to make Spring Boot use the context path when serving static content?

A: I just figured it out. In my index.html I had set a base href:
<base href="/">

I converted index.html to a JSP and set the base href using a JSP tag:
<base href='<c:url value="/" />'>

A: Modify the <base href="/"> in index.html to the following,
<base href="./">
This will try to load all the scripts from the context path that is specified and it fixed the issue for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to transfer paramenters to Partial View in ASP.NET MVC? On the Details view I want to display a grid from other table. How to implement it better? I'm trying to do it in a such a way (error: Cannot implicitly convert type 'void' to 'object'):
<%= Html.RenderPartial("~/Views/Appartament/Index.ascx", new { id  = Model.blockhouse_id })%>

Here is the code from details view:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<testMVC.Models.Blockhouse>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Details

            blockhouse_id:
            <%= Html.Encode(Model.blockhouse_id) %>

            name:
            <%= Html.Encode(Model.name) %>

            Appartaments:
            <%= Html.RenderPartial("~/Views/Appartament/Index.ascx", new { id  = Model.blockhouse_id })%>

</asp:Content>

And the code of the Index.ascx controller:
public ActionResult Index(int blockhouse_id)
        {
            var _appartament = apt.GetBlockAppartaments(blockhouse_id).ToList();
            return View("Index", _appartament);
        }

A: RenderPartial doesn't have a return value.
Instead of
<%= %>

Use
<% %>

*

*ASP.NET MVC RenderPartial Compiler Error
As for Razor, instead of
@

Use
@{ }


text:
Q: Not getting results with datastore.GetAll in golang I have two functions: one which writes entities to datastore and the other is suppose to retrieve them. When I use datastore.GetAll() function in my retrieval it returns no results. I do have a test that verifies that the writing seems to be working correctly. Any ideas as to why retrieval isn't working?
Here is the application code:
package tracker

import (
   "fmt"

   "appengine"
   "appengine/datastore"
)

type User struct {
    Email string
}

func createUser(ctx appengine.Context, email string) (*datastore.Key, error) {
    u := &User{
        Email: email,
        }
    incompleteKey := datastore.NewIncompleteKey(ctx, "User", nil)
    key, err := datastore.Put(ctx, incompleteKey, u)
    if err != nil {
        return key, err
    }

    return key, nil
}

func getUser(ctx appengine.Context, email string) (u *User, e error) {
    users := []User{}
    q := datastore.NewQuery("User").Filter("Email", email)
    keys, err := q.GetAll(ctx, &users)
    if err != nil {
        return nil, err
    }
    fmt.Printf("KEYS: %v", keys)
    return &users[0], nil
}

Here is the test code:
package tracker

import (
    "fmt"
    "testing"

    "appengine/datastore"
    "appengine/aetest"
)

// This test is passing.
func TestCreateUser(t *testing.T) {
    ctx, err := aetest.NewContext(nil)
    if err != nil {
        t.Fatal(err)
    }
    defer ctx.Close()

    email := "testing@testing.go"
    newKey, err := createUser(ctx, email)
    if err != nil {
        t.Errorf("Failed to create a new user: %v", err)
    }

    u := User{}
    datastore.Get(ctx, newKey, &u)

    if u.Email != email {
        t.Errorf("Expected email to be %s, found %v.", email, u.Email)
    }
}

func TestGetUser(t *testing.T) {
    ctx, err := aetest.NewContext(nil)
    if err != nil {
        t.Fatal(err)
    }
    defer ctx.Close()

    email := "testing@testing.go"
    newKey, err := createUser(ctx, email)
    fmt.Printf("key, %v; ", newKey)
    u, err := getUser(ctx, newKey)
    fmt.Printf("user, %v; error: %s", u, err)

    if u.Email != email {
        t.Error("Expected email to be %s, found %v.", email, u.Email)
    }
}

A: datastore.GetAll() doesn't return result to you because with that query eventual consistency applies. The SDK simulates the eventual consistency and doesn't return you the newly saved entities immediately.
But in your TestCreateUser() method when you use datastore.Get(), that will return you the entity even if it was newly ("just now") saved, because it's a lookup by a key, and they are strongly consistent.
What happens behind the scenes is that when you call datastore.Put(), the entity data (values of properties) is saved and its key is indexed, then datastore.Put() returns, and indices of other properties and composite indices are updated asynchronously "in the background". So if you try to execute a query that uses an index to find/list entities (you were querying by the Email property), that query will not see (will not include) new entities until they are properly indexed. When you do a datastore.Get(), that loads the entity by its key and not by other (non-key property or composite) indices, so getting an entity by key will see the new entity "immediately" (after datastore.Put() has returned).
If you want to test this in local environment, you may provide StronglyConsistentDatastore option when creating the instance that will be used to create a new context, like this:
inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
if err != nil {
    t.Fatalf("Failed to create instance: %v", err)
}
defer inst.Close()

req, err := inst.NewRequest("GET", "/", nil)
if err != nil {
    t.Fatalf("Failed to create req: %v", err)
}
ctx := appengine.NewContext(req)

Also note that if you use a sleep (e.g. time.Sleep(time.Millisecond * 500)), datastore.GetAll() will also return the new entity, but the above option is the proper way to test this.
There are numerous similar questions (+answers), read them for more details:
Google App Engine Datastore - Testing Queries fails
How to filter a GAE query?
Google app engine datastore query with cursor won't iterate all items


text:
Q: Stream symmetric encrypted data with java that can be decryptet by GPG I am trying to stream output a large file that can be decrypted with the following command:
gpg --decrypt --cipher-algo AES256 --passphrase="password"
I do not know the size of the data before I start streaming.
I am able to encrypt using Java Cipher, but it appears then that it can only be decrypted using OpenSSL.
I have looked into Bouncy Castle and BouncyGPG but find it hard to find good examples using symmetric encryption and a passphrase only. I am able to encrypt using GPG and a passphrase in both ends, so I feel that it should be possible when encrypting with Java too.
The closest example I've found is https://github.com/bcgit/bc-java/blob/master/pg/src/main/java/org/bouncycastle/openpgp/examples/PBEFileProcessor.java
I have tried to adjust this example so that I can pass through a stream in a similar way to Java Cipher, but I've been unable to get it working, and I don't even know if I am on the right path.
UPDATE:
I got it to work now. Below is the code used:
    public OutputStream cOut;

    public OutputStream armoredOutputStream;

    public OutputStream encryptedOutputStream;

    public PGPEncrypter() {
        Security.addProvider(new BouncyCastleProvider());
    }

    public OutputStream encrypt(
        OutputStream encryptedOutputStream, String passPhrase
    ) throws IOException,
        PGPException {

        encryptedOutputStream = new ArmoredOutputStream(encryptedOutputStream);

        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256)
                .setWithIntegrityPacket(true)
                .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase.toCharArray()).setProvider("BC"));

        OutputStream cOut = encGen.open(encryptedOutputStream, new byte[4096]);

        PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
        return lData.open(cOut, PGPLiteralData.BINARY, "", new Date(), new byte[4096]);
    }

Testing it with:
PGPEncrypter pgpEncrypter = new PGPEncrypter();
FileOutputStream fileOutputStream = new FileOutputStream("encrypted.txt");
OutputStream outputStream = pgpEncrypter.encrypt(fileOutputStream, "password");
outputStream.write("content".getBytes(StandardCharsets.UTF_8));
outputStream.close()
pgpEncrypter.cOut.close()
pgpEncrypter.armoredOutputStream.close()
pgpEncrypter.encryptedOutputStream.close()

And then I am able to decrypt using PGP and the command at the start of the post.
The next step will be to have the class extend OutputStream and automatically close the underlying streams in the correct order when close() is called.

A: You were right on the edge of it. If you look at the whole directory https://github.com/bcgit/bc-java/tree/master/pg/src/main/java/org/bouncycastle/openpgp/examples you see there are:

*

*KeyBasedFileProcessor -- for the encrypt side, does:

*

*read the (whole) input file and create compressed-literal-data packet in memory

*create PGPEncryptedDataGenerator and give it a public-key encryption 'method' (for a selected key)

*open a stream on the generator and write the compressed-literal-data packet to it (which results in it being encrypted and written to the output file)

*KeyBasedLargeFileProcessor -- ditto:

*

*don't read the whole input

*create the same generator as for non-Large

*open a stream on the generator

*use PGPCompressedDataGenerator to open a compressed-data stream on 3

*(in PGPUtil.writeFileToLiteralData) use PGPLiteralDataGenerator to open a literal-data stream on 4, and then copy from the input file to that stream, which results in it being put into PGP's literal-data format, compressed and encrypted and written to the output file)

*PBEFileProcessor -- for encrypt is exactly the same as KeyBased except that it uses a method for PBE (with the given passphrase) instead of one for public-key encryption
Now, what do you think would happen if you make the same changes to PBEFileProcessor as the KeyBasedLargeFileProcessor made to KeyBasedFileProcessor? Might you have a PBELargeFileProcessor that does password-based encryption of large files -- or with the obvious changes, anything you can access and read as an InputStream?
Except that (all) the examples use CAST5; you want to change that to AES_256 (or whatever else).


text:
Q: What are some really cool problems that involve "least squares and Eigenvalue problems"? I am required to find a research topic in this domain, so I'm really interested in finding out what kind of problems are covered in this domain, and how others are using these techniques to solve them. Preferably, I'd be more interested in if/how one can use them in Machine Learning or Pattern Recognition.
I know this is a very open-ended questions, so I will not get a concrete answer. At this point, I only require a board answer to help me get started to get acquainted more with this area.


text:
Q: Query @ElementCollection JPA I have an Entity Transaction as following :
@Entity
class Transaction extends AbstractEntity<Long>{
        private static final long serialVersionUID = 7222139865127600245L;
        //other attributes

    @ElementCollection(fetch = FetchType.EAGER, targetClass = java.lang.String.class)
    @CollectionTable(name = "transaction_properties", joinColumns = @JoinColumn(name = "p_id"))
    @MapKeyColumn(name = "propertyKey")
    @Column(name = "propertyValue")
    private Map<String, String> properties;

    //getters and setters
}

So, my Database Table for transaction_properties is
mysql> desc transaction_properties;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| p_id          | bigint(20)   | NO   | PRI |         |       |
| propertyValue | varchar(255) | YES  |     | NULL    |       |
| propertyKey   | varchar(255) | NO   | PRI |         |       |
+---------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Now, I want to search entity Transaction with key and value.
    Path<Map<String, String>> propertiesPath = root.get("properties");
    Path<String> propertyKeyPath = propertiesPath.<String> get("propertyKey"); //where m getting error
    Path<String> propertyValuePath = propertyKeyPath.<String> get("propertyValue");
    p = cb.and(p, cb.and(cb.like(propertyKeyPath, "%" + searchTrxnKey + "%"), cb.like(propertyValuePath, "%" + searchTrxnValue + "%")));

But am getting error for Path<String> propertyKeyPath = propertiesPath.<String> get("propertyKey"); as following :
[...] threw an unexpected exception: org.springframework.dao.InvalidDataAccessApiUsageException: Illegal attempt to dereference path source [null]; nested exception is java.lang.IllegalArgumentException: Illegal attempt to dereference path source [null]

One of the reference I went through was : Spring Data JPA Tutorial Part Four: JPA Criteria Queries but no luck for me.

A: The solution is .join("properties") than .get("properties").
Path<Map<String, String>> propertiesPath = root.join("properties");
predicate = (predicate != null) ? criteriaBuilder.and(predicate, criteriaBuilder.and(propertiesPath.in(searchTrxnKey), propertiesPath.in(searchTrxnValue)))
                                : criteriaBuilder.and(propertiesPath.in(searchTrxnKey), propertiesPath.in(searchTrxnValue));

More at JPA Criteria API - How to add JOIN clause (as general sentence as possible)


text:
Q: How to read disk drive space for each different path in a PowerShell script? I have my first small project and I just started a PowerShell (total beginner).
We have three different shared C:\ drives and I need to output each disk storage info (e.g. total and free space) by using Powershell script.
Here is the script I made, but these three results are all the same even though they have different free spaces and total.
Can anyone please advise me on what is wrong with my ps script?
Plus, in the result, I don't want to display any other drives (e.g D and E) but only the C drive. How to do so?
[Script]
Set-Location -Path \\vm1\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, @{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, @{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}

Set-Location -Path \\vm2\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, @{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, @{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}

Set-Location -Path \\vm3\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, @{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, @{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}

[Result]
DeviceId   Size FreeSpace
--------   ---- ---------
C:       473.95    114.22
D:            0         0
E:            0         0

DeviceId   Size FreeSpace
--------   ---- ---------
C:       473.95    114.22
D:            0         0
E:            0         0

DeviceId   Size FreeSpace
--------   ---- ---------
C:       473.95    114.22
D:            0         0
E:            0         0

A: Setting location to an UNC Path does not mean you're actually querying the win32_logicaldisk of that remote host, you need to use the -ComputerName Parameter to query the remote hosts information. Also worth noting, you should start using Get-CimInstance instead of Get-WmiObject (no longer available in newer versions of PowerShell).
As for displaying only the C drive, for this you can use -Filter. I've also added PSComputerName to your Format-Table returned properties so you can know which host the output belongs to.
$vms = 'vm1', 'vm2', 'vm3'
Get-CimInstance -Class win32_logicaldisk -Filter "DeviceID='C:'" -ComputerName $vms |
    Format-Table @(
        'PSComputerName'
        'DeviceId'
        @{ N='Size'; E={ [math]::Round($_.Size/1GB, 2) }}
        @{ N='FreeSpace'; E={ [math]::Round($_.FreeSpace/1GB, 2) }}
    )

A: Set-Location -Path \vm1\c$ does not work this way. it sets the default location on the filesystem for the current powershell session but does not influence get-wmiobject. to query remote computer you must use the parameter -computername.
you should use the cim cmdlets as they replace the wmi-object cmdlet. the parameter -computername supports an array as input so you only need to call get-wmiobject/get-ciminstance one time and if you only want to know about the C:\ drive, you can query for it:
$computers = @('vmName1','vmName2','nmName3')
Get-CimInstance -ComputerName $computers -Query "select freeSpace from win32_loogicaldoisk where deviceId='C:'" | select-object pscomputername,deviceid,freeSpace


text:
Q: Lettuce/Selenium removing newly created DOM elements Scenario
Given I navigate to the table menu
When I click the "Add" button
And I fill "First name" with "Bob"
And I fill "Last name" with "Dylan"
And I click the "Create" button
Then I should see a new entry with a name of "Bob Dylan"

Step Definitions
@step(u'I click the "(.*)" button')
def i_click_the_named_button(step, field):
    button = world.browser.find_element_by_xpath('(//a[contains(text(),"{0}") and not(contains(@style, "display:none"))] | //input[@value="{0}" and not(contains(@style, "display:none"))] | //li[contains(text(), "{0}") and not(contains(@style, "display:none"))])[1]'.format(field))
    button.click()

@step(u'I fill "(.*)" with "(.*)"')
def i_fill_in_field_with_value(step, field, value):
    try:
        label = world.browser.find_element_by_xpath('//label[contains(text(),"%s")]' % field)
        id = label.get_attribute('for')

        input = world.browser.find_element_by_id(id)
        input.clear()
        input.send_keys(value)
    except:
        input = world.browser.find_element_by_xpath('//input[@placeholder="%s"]' % field)
        input.clear()
        input.send_keys(value)

Error

NoSuchElementException: Message: u' no such element (Session info:
  chrome=31.0.1650.63) (Driver info:
  chromedriver=2.8.240825,platform=Linux 3.8.0-34-generic x86_64) '

Description
When clicking the 'Create' button a div element is inserted into the DOM (via JavaScript) displaying the 'First name' and 'Last name' fields.  When running with a window visible I can see the div element appear briefly before vanishing and causing the 'I fill...' steps to fail.
From what I've read its an issue with maintaining focus on the newly created div element?
Solutions Attempted

*

*ActionChains(world.browser).move_to_element(button).click().perform()

*world.browser.switchTo() and friends

*world.browser.find_element(...).send_keys("\n")

*sleep_until, implicitly_wait, etc...

Environment

*

*PyVirtualDisplay 0.1.2

*Selenium 2.38.4

*Lettuce 0.2.19

*Python 2.7.4

*Lubuntu Linux 13.10

Research
Keeping the focus after opening a new window in the Selenium IDE
Using Python bindings, Selenium WebDriver click() is not working sometimes.
How to switch to the new browser window, which opens after click on the button?
Selenium WebDriver ActionChains
WebDriver.py implementation
Selenium API

A: I know not why this fixes the problem, but it has indeed resolved the situation.
@step(u'I click the "(.*)" button')
def i_click_the_named_button(step, field):
    button = world.browser.find_element_by_xpath('(//a[contains(text(),"{0}") and not(contains(@style, "display:none"))] | //input[@value="{0}" and not(contains(@style, "display:none"))] | //li[contains(text(), "{0}") and not(contains(@style, "display:none"))])[1]'.format(field))
    button.click()
    time.sleep(1)


text:
Q: Capture date & time when cell is edited (google spreadsheet) I'm looking for a way to capture time & date (or maybe date only) when a cell is updated/edited.
I found some tutorials while searching through the web, but I guess its a little outdated that it doesn't run 100%. here is the code I found
function capdatetime(event)
{
var timezone = "GMT+8";
var timestamp_format = "MM-dd-yyyy"; //Timestamp format
var updateColName = "Date Sent";
var sheet = SpreadsheetApp.getActiveSpreadsheet(); //Name of the sheet where you want to run the script
var actRng = SpreadsheetApp.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName);
var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
if (dateCol > -1 && index > 1 && editColumn == updateCol) { //only timestamp of 'Last Updated' header exists, but not in the header row itself!
var cell = sheet.getRange(index, dateCol + 1);
var date = Utilities.formatDate(new date(), timezone, timestamp_format);
cell.setValue(date);
}
}

I modified this to address some errors I encountered but there's one particular error that I can't understand that much.
here is the error:

can someone explain and help me with this? thanks, I'll also continue searching for some ideas.

A: How about this?
function capdatetime(event)
{
  var timezone = "GMT+8";
  var timestamp_format = "MM-dd-yyyy"; //Timestamp format
  var updateColName = "Name";
  var timeStampColName = "LastUpdated";
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sample'); //Name of the sheet where you want to run the script
  var actRng = sheet.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { //only timestamp of 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}


text:
Q: How could i pass cookies in Axios I am in a next-js app and my auth token is stored in cookies.
For some raisons i use Swr and Api route to fetch my secured api backend.
i am trying to find a way to put my auth token in all api request.
During login cookie is set
  res.setHeader(
        'Set-Cookie',
        cookie.serialize('token', data.access_token, {
          httpOnly: true,
          secure: process.env.NODE_ENV !== 'development',
          maxAge: data.expires_in, // 1 week
          sameSite: 'strict',
          path: '/',
        }),
      );

This is an example of a page using swr fetch
//page/test.ts - example of my test route

  const { data, error } = useFetchContent(id);

  if (error) {
    showError('error');
    replace('/');
  }

  return <DisplayContent content={data} />

This is a swrFetchHook
// fetchContentHook

function useFetchContent(id: string): ContentDetail {
  return useSWR<any>(`/api/content/${id}`, fetcherApiRoute);
}

const fetcherApiRoute = (url: string): Promise<any> => {
  return axios(url)
  .then((r) => r.data)
  .catch((err) => {
    console.info('error is ', err)
    throw err
  });
};

export default useFetchContent;

inside api route

export default async (req, res): Promise<ContentDetail> => {
  const { id } = req.query;
  if (req.method === 'GET') {

    const fetchRealApi = await apiAxios(url);

  if(fetchRealApi) {
   // here depending on result of fetchRealApi i add some other fetch ...
   return res.status(200).json({ ...fetchRealApi, complement: comp1 });
  }

  return res.status(500)

  }

  return res.status(500).json({ message: 'Unsupported method only GET is allowed' });
};

and finally api axios configuration

const apiAxios = axios.create({
  baseURL: '/myBase',
});

apiAxios.interceptors.request.use(
  async (req) => {

    // HERE i am trying to get token from cookies
    // and also HERE if token is expired i am trying to refresh token
    config.headers.Authorization = token;
    req.headers['Content-type'] = 'application/x-www-form-urlencoded';
    return req;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default apiAxios;

I am stuck here because i cant find token during apiAxios.interceptors.request.use...
Did you know what i am doing wrong, and am i on a correct way to handle this behavior ?

A: To allow sending server cookie to every subsequent request, you need to set withCredentials to true. here is the code.
const apiAxios = axios.create({
  baseURL: '/myBase',
  withCredentials: true,
});

A: Nilesh's answer is right if your API is able to authorize requests based on cookies. Also it needs the API to be in the same domain as your frontend app. If you need to send tokens to the API (the one which is in the cookie), then you will need a small backend component often called BFF or Token Handler. It can extract the token from the cookie and put in an Authorization header.
At Curity we've created a sample implementation of such a Token Handler, of which you can inspire: https://github.com/curityio/kong-bff-plugin/ You can also have a look at an overview article of the Token Handler pattern.


text:
Q: How to handle Events for "HttpClient" in Windows Phone 8.1 The below code is working in WP8 but when coming to WP8.1 the Events are not fired, What is the solution for handle the Events.
HttpClient wb = new HttpClient();
wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadList_DownloadProgressChanged);
if (itm.LinkUrl.StartsWith("http://www.youtube.com/watch?v="))
{
    wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcYoutubeReadCompleted_OpenReadCompleted);
}
else
{
    wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcDownloadList_OpenReadCompleted);
}

A: HttpClient do not support Progress Reporting
The best way to go is using Windows.Web.Http.HttpClient instead of System.Net.Http.HttpClient. The first one supports progress.
I don't find an event DownloadProgressChanged in HttpClient in msdn
Try using webclient for DownloadProgress.
Difference between httpclient vs webclient
If you still need a httpclient to Progress Reporting you need to implement yourself .Progress Bar with HttpClient

A: I think you should use WebClient instead of HttpClient
WebClient client = new WebClient ();
    Uri uri = new Uri(address);

    // Specify that the DownloadFileCallback method gets called
    // when the download completes.
    client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);
    // Specify a progress notification handler.
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);

Event handler
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
    (string)e.UserState,
    e.BytesReceived,
    e.TotalBytesToReceive,
    e.ProgressPercentage);
}


text:
Q: stop loss triggers with the position I often have a problem with my stop loss. It starts immediately after placing a position. I have tried various ways to fix it but unfortunately it failed. Does anyone know where the problem is? Thank you!
longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1,
defval=1) * 0.01
shortLossPerc = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1,
defval=1) * 0.01

longStopPrice  = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)

strategy.entry('Long', strategy.long, when=long, comment='Long',alert_message =
message_long_entry)
strategy.exit( "SL","Long", stop=longStopPrice, comment = "SL Long",alert_message =
message_long_exit)
strategy.entry('Short', strategy.short, when=short, comment='Short',alert_message =
message_short_entry)
strategy.exit( "SL","Short", stop=shortStopPrice, comment = "SL Short",alert_message =
message_short_exit)

enter image description here

A: I think the id of the exit order should be unique:
strategy.exit("SLL","Long", stop=longStopPrice, comment = "SL Long",alert_message=message_long_exit)
strategy.exit("SLS","Short", stop=shortStopPrice, comment = "SL Short",alert_message=message_short_exit)


text:
Q: No intellisense for std::shared_ptr in template class header file in VS2017 I'm new to std::shared_ptr and trying to use it in linked list implementation. The code is:
#pragma once
#include <memory>

template <typename T>
class Node
{
public:
    Node();
    Node(const T& anItem);
    Node(const Node& anNode);

    T getItem() const;
    std::shared_ptr<Node<T>> getNext() const;
    std::shared_ptr<Node<T>> getPrev() const;
    void setItem(const T& anItem);
    void setNext(std::shared_ptr<Node<T>> nextNodePtr);
    void setPrev(std::shared_ptr<Node<T>> prevNodePtr);
private:
    T item;
    std::shared_ptr<Node<T>> next;
    std::shared_ptr<Node<T>> prev;
};

template <typename T>
Node<T>::Node(): next(nullptr), prev(nullptr) {}

template <typename T>
Node<T>::Node(const T& anItem) : next(nullptr), prev(nullptr), item(anItem) {}

template <typename T>
Node<T>::Node(const Node& anNode) : next(anNode.getNext()), prev(anNode.getPrev()), item(anNode.getItem()) {}

template <typename T>
T Node<T>::getItem() const
{
    return item;
}

template <typename T>
std::shared_ptr<Node<T>> Node<T>::getNext() const
{
    return next;
}

template <typename T>
std::shared_ptr<Node<T>> Node<T>::getPrev() const
{
    return prev;
}

template <typename T>
void Node<T>::setItem(const T& anItem)
{
    item = anItem;
}

template <typename T>
void Node<T>::setNext(std::shared_ptr<Node<T>> nextNodePtr)
{
    next = nextNodePtr;
}

template <typename T>
void Node<T>::setPrev(std::shared_ptr<Node<T>> prevNodePtr)
{
    prev = prevNodePtr;
}

This is in a header file. In any of these member functions, dereferencing the shared pointer doesn't show up the members and methods.
For example, suppose that in setPrev() I typed the following:
prev->
Now if it's a raw pointer (I tested with raw pointer), intellisense will show the members and methods available. But for std::shared_ptr intellisense doesn't work, and the only thing I saw is the methods of std::shared_ptr itself (operator* for example). I'm wondering what I did wrong?
Additionally, if I type (*prev). VS2017 simply tells me:

IntelliSense: 'No members available'

BTW it works in main.cpp, just not working in the header file, which is painful as I have to check the header files frequently, so I'm wondering I did something wrong with the smart pointer.


text:
Q: Overheating on Dell Studio XPS 1645 So I was wondering if anyone else has come upon this problem, and/or has come up with a solution. When I use my Ubuntu partition, my computer becomes extremely hot, and the fan runs very noisily for a very long time. If I reboot into windows while this is happening, my computer actually begins to cool down while doing the exact same tasks. Thinking this might just be a bug with Ubuntu, I installed fedora on another partition, and the same problem occurs. Is this a problem with the kernel? Cpufreq tells me that my CPU is running at 933 MHz out of a possible 1.6 GHz from my Intel Core i7 CPU Q70. For anyone who wants more information, I have 8 GB of memory, and an ATI Mobility Raedon HD 5730 Graphics Card. I'm open to any ideas anyone might have. Thanks in advance!

A: There is an overheating problem with some Intel processors running Linux kernel < 3.2 (power regressions). This issue, I read, has been fixed in 12.04 (Linux
kernel 3.2) So upgrade to 12.04 when it is released in 16
days. Hope this helps

A: Although your computer has some mighty powerful specs for the time of writing, I'd recommend giving Lubuntu a spin (Ubuntu with LXDE). I know LXDE is ideal for old computers, but I've tried running Ubuntu and Lubuntu on an old HP laptop, on Ubuntu with Unity (even in Unity 2D) it would overheat and shut off, whereas with LXDE it would run for much much longer before overheating to the point of shutting off. LXDE may not be as packed with features as Gnome or KDE, but I'd still use Linux with LXDE over windows on any hardware. If that does make a difference, you may then want to give Xubuntu a spin, see if you prefer Xfce or LXDE (LXDE is lighter than Xfce, but you may find that Xfce is light enough and has a few more features). Also you could try formatting your Linux partition with different filesystems.

A: I had a similar problem...and a BIOS Update fixed my problem..Hope this piece of information helps.


text:
Q: Getting system specifications using softlayer api is same as probing the machine and fetching? Softlayer has exposed REST APIs to get the system specifications like memory, disk etc. When we run the APIs, will it probe the machine and fetch the values or it will be based on the order template. I meant running df -h on the machine and fetching the same using softlayer API will be same? I want to write a validation script to check whether machine is provisioned as per the specifications provided or not. So I am looking for which option to use Softlayer API or run the commands on the machine and get the info.
Thanks

A: The API will probe the machine and fetch the values, I can suggest to use the following REST requests to get information about the servers:
Virtual Servers:
https://$user:$apiKey@api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/18078091/getObject?objectMask=mask[blockDevices, billingItem, datacenter, localDiskFlag, controlPanel, firewallServiceComponent, networkComponents, operatingSystem, softwareComponents, evaultNetworkStorage, hourlyBillingFlag, monitoringAgents, networkMonitors, networkStorage, antivirusSpywareSoftwareComponent, bandwidthAllocation, networkVlans]

Method: Get

Replace: $user, $apiKey and 18078091 with your own values
Hardware Servers:
https://$user:$apiKey@api.softlayer.com/rest/v3/SoftLayer_Hardware_Server/154931/getObject?objectMask=mask[hardDrives, activeComponents, billingItem, datacenter, controlPanel, components, firewallServiceComponent, networkComponents, operatingSystem, softwareComponents, evaultNetworkStorage, hourlyBillingFlag, monitoringAgents, networkMonitors, networkStorage, antivirusSpywareSoftwareComponent, bandwidthAllocation, networkVlans, driveControllers, memory, motherboard, networkCards, powerComponents, processors, remoteManagementComponent, uplinkNetworkComponents]

Method: Get

Replace: $user, $apiKey and 154931 with your own values
References:

*

*SoftLayer_Virtual_Guest::getObject

*SoftLayer_Hardware_Server::getObject
I hope it helps


text:
Q: Destroy an object and replace with a prefab at original objects location?
The green balls search out for white ones and "infect" them. The white balls are destroyed but they come back at the point of origin. I've tried to make a variable of the position of the white balls but I keep running into "Can't convert Transform to Vector3" errors.
public Rigidbody prefabInfection;
public Transform infectLocation;

void OnCollisionEnter(Collision colInfo)
{
    if (colInfo.collider.tag == "Infection")
    {
        Destroy(gameObject);
        Instantiate(prefabInfection);
    }
}

That's the code that's currently being used on collision.
I'm new to Unity also. Should I not destroy the white balls and instead somehow turn them into green balls? Is that possible?
Instantiation seemed like the only way. All I want to do is replace the white "human" balls to green "infection" ones.

A: The error you're seeing is probably because you're using the Transform object instead of its .position. Assuming your code is a component on the white ball gameObject, try this:
public Rigidbody prefabInfection;

void OnCollisionEnter(Collision colInfo)
{
    if (colInfo.collider.tag == "Infection")
    {
        Destroy(gameObject);
        Instantiate(prefabInfection, transform.position, transform.rotation);
    }
}

By passing your transform.position to the Instantiate function, the new object will be created in the same position as the one you're destroying. Hopefully this is the behaviour you intended!

A: Because you're destroying the current object, your script will never instantiate the new object because it's been destroyed before it got the chance to.
Instantiate(prefabInfection, gameObject.transform.position);
Destroy(gameObject);

If you do it in this order, and pass in the position of the object, it should work how you intend it to.
EDIT: I've just learned that Destroy will actually wait until the current Update() frame has finished to destroy objects. I'm going to leave my answer up because I still think that's it is a better practice to call Destroy() last.


text:
Q: Select specific text in the editorState I'm creating a rich text editor using draftjs. Here is the minimal codesandbox so you have an idea of what the issue is.
So I have an helper function getCurrentTextSelection that return me the text that I'm selecting:
const getCurrentTextSelection = (editorState: EditorState): string => {
  const selectionState = editorState.getSelection();
  const anchorKey = selectionState.getAnchorKey();
  const currentContent = editorState.getCurrentContent();
  const currentContentBlock = currentContent.getBlockForKey(anchorKey);
  const start = selectionState.getStartOffset();
  const end = selectionState.getEndOffset();
  const selectedText = currentContentBlock.getText().slice(start, end);

  return selectedText;
};

When I click outside the TextEditor, the focus is lost so the text isn't selected (but stay the selected one for the editorState).
Is there a programmatic way to reselect this text using the editorState? So that when you click the Select text again button, the text in the TextEditor is selected.

A: I believe what you're looking to do is restore focus to the editor. If all you do is click outside the editor, the selection state doesn't change (which is why your selected text remains the same). If you then restore focus the same selection becomes visible again, without any changes to editorState.
Draft.js has some documentation about how to do this: https://draftjs.org/docs/advanced-topics-managing-focus/
The Editor component itself has a focus() method which, as you might expect, restores focus to the editor. You can gain access to the component instance with a ref:
const editorRef = React.useRef<Editor>(null)

const selectAgain = () => {
  editorRef.current.focus()
};

Then connect the ref to the component and add the click handler to the button:

  <Editor
    editorState={editorState}
    onChange={onEditorStateChange}
    placeholder={placeholder}
    ref={editorRef} // added ref
  />

Selected text:

{getCurrentTextSelection(editorState)}

  // added click handler
  <button onClick={selectAgain}>Select text again</button>

Complete example: https://codesandbox.io/s/flamboyant-hill-l31bn

A: Maybe you can store the selectedText into EditorState
Using
EditorState.push( editorState, contentState, changeType)

More Info


text:
Q: How to change icon files with code constant on xCode? I'm building an app that has a Free version and Paid version.
The difference between the apps are only a define line of some constant in the code (it creates the code needed to add on each app).
I want the icons to change too according to this definition. Does someone knows how can I do that? can I choose for example between different info.plist files using code generated?
Please help.

A: You want to setup a duplicate Target of your main target for your lite version. In this secondary target, it should be identical except for a PREPROCESSOR MACRO that you add like LITE_VERSION. It should also point to a different info.plist
Then, in the code at compile time, you can use #ifdef LITE_VERSION to compile Lite code vs Reg Code when you compile for that target.


text:
Q: Filesystem/directory layout for unit and functional tests with PHPUnit I have a need to add integration tests to my test suite. Although the name is PHPUnit, I find that there's plenty of support for running non-unit tests here. My layout is something like this:
<root>
    lib/
        Foo/
            Component.php
    tests/
        lib/
            Foo/
                ComponentTest.php
        resources/
            fixtures/

There are (as I see it), three ways to add higher-than-unit level tests here:
Adding a parallel structure
<root>
    tests/
        unit/
            lib/
                Foo/
                    ComponentTest.php
        integration/
            lib/
                Foo/
                    ComponentTest.php
        resources/
            fixtures/

This should work, except now there isn't a 1:1 class : test class relationship which might (and probably will) confuse Netbeans.
Adding <root>/tests/lib/Foo/ComponentIntegrationTest.php
Has the same problem as above, with less directories.
Adding the tests to the existing test class, with notation like @group integration
This keeps the 1:1 relationship, but adds significant complexity to the test suite. Also, as the SUT will need to be invoked in changing environment, I can't just reuse the _setup() from unit tests.
Ideas?

A: Unit tests are used to test a single unit (class) in isolation. Integration tests are designed to test multiple units together. As such you probably won't have a 1:1 correlation between classes and the integration tests to which they belong.
I would create a separate directory structure--perhaps even a separate project--to house the integration tests. NetBeans won't be able to open "the test" that a class belongs to because it will belong to multiple tests, but it will continue to open its matching unit test.
We have a separate project for our integration tests (called sanity tests before I arrived) using Selenium, and it works well enough so far.
Update
The directory layout for our integration tests is pretty simple: one directory per site. We have a single codebase for the site and use views to allow single sites to override the layout (more than just skinning). We haven't spent as much time on these tests as I'd like. We use Selenium to run the tests after pushing the sites to a staging server. I haven't had a chance to hook them up to our continuous integration server (Jenkins) yet, but that would be ideal.
I'd recommend organizing them by functional area or module on your site. Mostly, it depends on how you think about the project you're testing. An example might look like this:
src/
    Model/
        Cart.php
    ...
tests/
    unit/
        phpunit.xml
        bootstrap.php
        Model/
            CartTest.php
        ...
    integration/
        account/
            login/
            register/
            subscriptions/
        products/
            listing/
            details/
            search/
        cart/
            shop/
            checkout/


text:
Q: Fit data to a model of two-variable differential equations I am trying to fit some data to the solution of a differential equation. I am using ParametricNDSolve to create a model which should fit the data using FindFit.
Now, the code I propose is very similar to the examples I have seen to solve similar problems. However, the equation of this case is a little more complicated that the examples of Mathematica manuals (because is a function of two variables, and the initials conditions involves two numeric integrals).
The code keeps running for hours, and it does not appear to solve the problems at all:
data = {{21/100, 0.260882276365091`}, {6/25, 0.330910580727009`}, {27/
100, 0.271601829283246`}, {3/10, 0.294039749043066`}, {33/100,
0.373363616981994`}, {9/25, 0.467495450916`}, {39/100,
0.50972503848512`}, {21/50, 0.639300915026114`}, {9/20,
0.679672806174314`}, {12/25, 0.693446859556429`}, {51/100,
0.697043731283207`}, {27/50, 0.736147748563448`}, {57/100,
0.706580484286456`}, {3/5, 0.719128578284264`}, {63/100,
0.762276173639189`}, {33/50, 0.788753648395851`}, {69/100,
0.802107836002146`}, {18/25, 0.803992011056852`}, {3/4,
0.796349018322968`}, {39/50, 0.795845629380594`}, {81/100,
0.808805024532776`}, {21/25, 0.812210415525446`}, {87/100,
0.811677706096654`}, {9/10, 0.796614634731033`}, {93/100,
0.802573366818874`}, {24/25, 0.801851431134633`}, {99/100,
0.799762250401537`}, {51/50, 0.803234757269179`}, {21/20,
0.812346679044962`}, {27/25, 0.804974524275207`}, {111/100,
0.813054479870107`}, {57/50, 0.802494974488922`}, {117/100,
0.811124462792484`}, {6/5, 0.810259975308694`}, {123/100,
0.810910967136978`}, {63/50, 0.815891670404585`}, {33/25,
0.803843274767398`}, {69/50, 0.814778081357444`}, {36/25,
0.809686831953762`}, {3/2, 0.829532613157218`}, {9/5,
0.815351190536115`}, {21/10, 0.828143435644695`}, {12/5,
0.791269047273677`}, {27/10, 0.821321230878138`}, {3,
0.81153212440728`}, {33/10, 0.821798500231733`}, {18/5,
0.819594302125574`}, {39/10, 0.828629593518031`}};

model = ParametricNDSolveValue[{
D[v[x, t], t] == d1*D[v[x, t], x, x],
v[-5, t] == 0,
v[10, t] == flux,
v[x, 0] == flux*NIntegrate[Cos[y]^n1, {y, ArcTan[-b1*(x + a1)], Pi/2}]/NIntegrate[Cos[y]^n1, {y, -Pi/2, Pi/2}]},
v, {x, -5, 10}, {t, 0, 2}, {d1, flux, n1, b1, a1}]

fit = FindFit[data,
(c*model[d1, flux, n1, b1, a1][x, 2])/((c - 1)*model[d1, flux, n1, b1, a1][x, 2] + 1),
{{d1, 0.001}, {flux, 0.57}, {c, 3.2}, {n1, 2}, {b1,1}, {a1, -0.4}}, x]

I guess that this code is computationally inefficient, but I need help to understand why.
Thank you all very much
Ps: english is obviously not my first lenguage, so I apologize for the grammar mistakes.


text:
Q: What causes "Unsatisfied dependency expressed through method 'setTargetDatastore' parameter 0"? I'm a complete novice regarding Spring applications, and I'm trying to integrate a project using Kotlin + Spring + GORM (Which requires usage of Groovy). When I try to run it I get:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'messageController': Unsatisfied dependency expressed through method 'setTargetDatastore' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException

I have just 5 files in the project, including the build.gradle.
Message.groovy
import grails.gorm.annotation.Entity
import groovy.transform.ToString
import org.grails.datastore.gorm.GormEntity

@ToString
@Entity
class Message implements GormEntity<Message> {
    String user;
    String date;
    String message;
}

Message.service
import domain.Message
import groovy.transform.CompileStatic
import org.springframework.stereotype.Service

@CompileStatic
@grails.gorm.services.Service(Message)
@Service
interface MessageService {
    List<Message> findAll()
}

MessageController.groovy
@RestController
@Transactional
class MessageController {

    @Autowired
    MessageService messageService

    @RequestMapping("/")
    List<String> index() {
        return messageService.findAll().collect { "[" + it.user + "@" + it.date + ": " + it.message + "]" }
    }

    @RequestMapping(value = "/save/", method = RequestMethod.POST)
    String save(@RequestBody Message message) {
        message.save()
        return "Saved"
    }
}

App.kt
@SpringBootApplication
class SimManagerApplication

fun main(args: Array<String>) {

    SpringApplication.run(SimManagerApplication::class.java, *args)
}

build.gradle dependencies
dependencies {
    compile('org.springframework.boot:spring-boot-starter-quartz')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('com.fasterxml.jackson.module:jackson-module-kotlin')
    compile('com.vaadin:vaadin-spring-boot-starter')
    compile('org.flywaydb:flyway-core')
    compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    compile("org.jetbrains.kotlin:kotlin-reflect")

    compile("com.h2database:h2")

    compile("eu.vaadinonkotlin:vok-rest:0.6.2")
    compile('org.codehaus.groovy:groovy-all:2.5.4')
    compile("org.flywaydb:flyway-core:5.2.0")

    compile "org.grails:gorm-hibernate5-spring-boot:6.1.6.RELEASE"
    compile "org.hibernate:hibernate-core:5.1.0.Final"
    compile "org.hibernate:hibernate-ehcache:5.1.0.Final"

    runtime "org.apache.tomcat:tomcat-jdbc:8.5.0"
    runtime "org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.5.0"
    runtime "org.slf4j:slf4j-api:1.7.10"

}

and as simple as that, the project fails to start. What, exactly, causes the UnsatisfiedDependencyException? Is there a simple straightforward way to solve it?.
Thank you very much in advance.


text:
Q: Modeling with an equation The fish population in a lake rises and falls according to the formula
$$F=1000(30+17t-t^2)$$
Here $F$ is the number of fish at the time $t$, where $t$ is measured in years since January 1, 2002, when the fish population was first estimated.
On what date will the fish population again be the same as it was on January 1, 2002?
By what date will all the fish in the lake have died?

*

*I don't know exactly how to go about solving this problem. I suspect that it requires for me to solve for one variable in terms of another. I think that it wants me to solve for $t$ in terms of $F$

So this is what I got:
$$F=30000+17000t-1000t^2$$
$$F-30000=17000t-1000t^2$$
Am I going in the right direction?

A: First, use the equation you were given to determine what the population $F$ was in $2002$, when $t=0$. Then the first question asks you to determine when the population will again be that much. Suppose the answer you get for the 2002 population is $F_0$. Then you want to solve
$$F_0 = 1000(30+17t-t^2)$$
or
$$1000t^2 - 17000t + (F_0-30000) = 0.$$
This is a quadratic equation; I suspect you know how to solve it.
For the second question, you want to solve $0 = 1000(30+17t-t^2)$ to find when the population is zero. Divide both sides by $1000$ to simplify, again giving a quadratic that you can solve for $t$.

A: Yes you are.
So,
notice that initially:
$$F(0) = 30000$$
So, we must find a time where the population equals $30,000$
So,
$$F=30000+17000t-1000t^2 = 30000$$
Simple algebra from here:
$$17000t - 1000t^2 = 0$$
$$1000t(17 - t) = 0$$
So $t = 17$
Comment if you have any questions.

A: First you should find out how many fish there were in the lake on January 1, 2002 (i.e., t=0). This will give you a value for F, say F=a. Then the question becomes, for what other values of t does F=a?


text:
Q: bash language output In my english linux system, I have
$ diff a b
Only in b: bmm.awda
Common subdirectories: a/c and b/c
Only in b: gsegwehh
Only in a: Link to t
Only in b: new file (4th copy)
Only in a: r
Only in a: t
Only in b: zxzxczx

what would be the output in a system with a different language? Are bash commands output translated to every language?? Like in Italian I would have
$ diff a b
Solo in b: bmm.awda
Subdirectories comuni: a/c e b/c
Solo in b: gsegwehh
Solo in a: Link to t
Solo in b: new file (4th copy)
Solo in a: r
Solo in a: t
Solo in b: zxzxczx

or something similar?

A: Yes, bash quite often translates output depending on your locale settings. But this also depends on how the tools / scripts are written. There is a section about "Locale Specific Translation" in the BASH manual.


text:
Q: Where to define gradle task so that it doesn't run with every build I have defined a gradle task that increments version code.
The thing is that it is in the app.gradle and it runs with every build.
My goal is to make it run on demand from our CI server.

A: Just make your task depends on a special task. In your case:
task incVersionCode(dependsOn: ["assembleRelease"]) << {
    // your task code
}

you can also use this android gradle plugin for auto increasing version code:
https://github.com/moallemi/gradle-advanced-build-version/


text:
Q: Приведение типов и списки Приветствую. Имеется List<CellSpec>, где CellSpec - интерфейс. Далее, имеется класс DefCellSpec, реализующий вышеупомянутый интерфейс.
Вопрос: почему, когда я передаю в метод: boolean checkCellSpec (List<CellSpec> specList) список List<DefCellSpec> - компилятор ругается на несоответствие типов?
Притом если передавать один объект - то все ок.
Если создать новый лист по принципу:
List<CellSpec> specList = new ArrayList<>();
defCellSpecs.forEach(defCellSpec -> specList.add(defCellSpec));

и уже его передавать в вышеупомянутый метод, то также все ок, но выглядит как костыль.


text:
Q: How to show the Date integer value in mongodb After logging into MongoDB server with shell, I try the following commands
rs1:PRIMARY> x = Date()
Thu Dec 12 2013 11:25:58 GMT+0800 (CST)
rs1:PRIMARY> x -1
NaN
rs1:PRIMARY> print(x)
Thu Dec 12 2013 11:25:58 GMT+0800 (CST)
rs1:PRIMARY> x - 1000
NaN

In MongoDB doc, http://docs.mongodb.org/manual/reference/bson-types/
the Date type is a 64bit integer which represents the mill-seconds since epoch. I want to show its value, but always get one string.

A: Its a Javascript Date object.  getTime() returns the millisecond value as an integer
dmReplSet:PRIMARY> var now = new Date();
dmReplSet:PRIMARY> now.getTime()
1386820859427
dmReplSet:PRIMARY>

A: Use the new operator.
$ mongo
MongoDB shell version: 2.4.5
connecting to: test
> var x = new Date()
> x - 1
1386820087199
> print(x)
Thu Dec 12 2013 01:48:07 GMT-0200 (BRST)
> x - 1000
1386820086200


text:
Q: Kinect + Visual Studio 2013 LNK errors, how to properly link the library? I downloaded kinect sdk both 1.8, and 2.0. I then created a new project, and edited its properties via C/C++ and included x86 headers folders

I also edited its Linker and added its corresponding x86 libraries folder.

Yet I still get linking errors, and it's not clear to me what it may be.
error LNK2019: unresolved external symbol __imp__NuiInitialize@4 referenced in function _wmain
error LNK1120: 1 unresolved externals
Any idea? Not sure what else I can do in the linker settings.

A: Problem resolved,
In addition to

*

*C/C++ include

*Linker library

You also need to edit

*Linker Input
In here you add Kinect10.lib (or Kinect20.lib, depending on what version you're using)


text:
Q: Android - How to stop starting service interval while service on running? I have a service class called myService and I using interval to running the service
here's the code :
public class myService extends Service {
    public Runnable mRunnable = null;
    IBinder mBinder = new LocalBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class LocalBinder extends Binder {
        public myService getServerInstance() {
            return myService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final Handler mHandler = new Handler();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("Service jalan", "beneran dah");
                DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                List<Contact> contacts = db.getAllContacts();
                for (Contact cn : contacts)
                {
                    int idsql = cn.getID();
                    if(String.valueOf(cn.getFlag()).equals("0")){
                        Log.d("Id", String.valueOf(cn.getID()) + " Flag :" + cn.getFlag());
                        sending a  = new sending(); //communicate to server
                        a.execute();
                    }
                    else
                    {
                        Log.d("Data kosong", "atau tidak ada flag = 0");
                    }
                }
                mHandler.postDelayed(mRunnable, 30 * 1000);
            }
        };
        mHandler.postDelayed(mRunnable, 30 * 1000);
        return super.onStartCommand(intent, flags, startId);
    }
}

the issue :
when my service still running on if statement but the interval already loop for 30 sec, my service will be start again,
how can I avoid that?

A: You can use a flag to check whether service is in progress before restarting it as in
 boolean isInProgress = false;
 mRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("Service jalan", "beneran dah");
                if(!isInProgress){
                isInProgress = true;
                DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                List<Contact> contacts = db.getAllContacts();
                for (Contact cn : contacts)
                {
                    int idsql = cn.getID();
                    if(String.valueOf(cn.getFlag()).equals("0")){
                        Log.d("Id", String.valueOf(cn.getID()) + " Flag :" + cn.getFlag());
                        sending a  = new sending(); //communicate to server
                        a.execute();
                    }
                    else
                    {
                        Log.d("Data kosong", "atau tidak ada flag = 0");
                    }
                  }
                 isInProgress = false;
               }
                mHandler.postDelayed(mRunnable, 30 * 1000);
            }


text:
Q: `git revert` behaves strangely When we run 'git revert HEAD~9', here is the error:
$ git revert HEAD~9
error: could not revert 45ebde6... AC: added stat summary function
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

The problem is that after we solve the conflicts and commit, then git revert HEAD~9 brings up the exact same conflict again. We get into this strange loop and never going anywhere with git revert' and commit` (just increase of junk commit!). How to fix this problem?

A: Based on your comments above, what you would like to do is throw away the most recent 9 commits. In this case, git revert is not the command you need to use. Instead, git reset is correct:
git reset --hard HEAD~9

This will reset your current branch pointer to 9 commits back from HEAD. The --hard option also changes the files in your working copy to match the state they were at HEAD~9.


text:
Q: I am trying to querymongodb collection to get one particular id field - I am trying to get _id from last updated("timeSliceStart") row which has matching "EmployeeName"
DBCursor cursor = collection.find(EmployeeName).sort(new BasicDBObject("timeSliceStart", -1)).limit(1);
 while(cursor.hasNext()) {
            String result = cursor.next().get("id"); }

Data in Mongo DB::
{
    "_id" : {
        "employeeId" : "1234567890",
        "@objectName" : "FeedMetadata"
    },
    "school" : false,
    "college" : null,
    "errorCount" : 0,
    "errors" : [],
    "EmployeeName" : "Peter"
}
The result that is getting printed is :
{ "employeeId" : "1234567890" , "@objectName" : "FeedMetadata"}
I want just the employeeId from _id, I tried _id.employeeId ;, but it returned null.
Is there a way to display only the employeeId?
My Java program -
  BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("EmployeeName", empName);
    DBCursor cursor = collection.find(whereQuery).sort(new BasicDBObject("lastUpdate", -1)).limit(1);
    while(cursor.hasNext()) {
        String result = cursor.next().get("_id").toString();
        System.out.println(result);
    }

A: You can change the while loop like this:
while(cursor.hasNext()) {
    String result = ((HashMap)((BasicDBObject)(cursor.next().get("_id")))).get("employeeId");
    System.out.println(result);
}


text:
Q: Use TF 2.1 install in user directory I have an existing tensorflow 1.13.1 installation in /opt/conda, which I do not have permission to uninstall. When I do a pip install tensorflow==2.1 --user --upgrade, it goes to the user folder /home/myuser/.local/bin/tf_upgrade_v2. When I run
import tensorflow as tf
tf.__version

it still gives 1.13.1. Is there any way for me to invoke the tensorflow 2.1 installed in /home/myuser/.local/bin/tf_upgrade_v2?


text:
Q: What does it mean when the default activity of an app is android.app.Activity? This is a AndroidManifests.xml for a non default Android project generated by Projuce (juce.com)
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0.0"
          package="com.yourcompany.NewProject">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:anyDensity="true"
                    android:xlargeScreens="true"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  <uses-permission android:name="android.permission.BLUETOOTH"/>
  <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
  <uses-permission android:name="android.permission.INTERNET"/>
  <application android:label="@string/app_name" android:name="com.rmsl.juce.JuceApp" android:hardwareAccelerated="false">
    <activity android:name="android.app.Activity" android:label="@string/app_name" android:configChanges="keyboardHidden|orientation|screenSize"
              android:screenOrientation="unspecified" android:launchMode="singleTask" android:hardwareAccelerated="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
  </application>
</manifest>

You can see that the default activity is <activity android:name="android.app.Activity". How can this be the default activity? What is launched then?
This is the entire project: https://github.com/lzunsec/juce_example_android/tree/faf9e3362b7e7e56ae8918f31196e35a3e6dadca/NewProject
It has no java files, almost no C++ files, so I do not understand how it could work.


text:
Q: JWT Verify Causing ERR_HTTP_HEADERS_SENT We are developing a ReST API using Restify (Node.js). As part of the authentication mechanism, we developed a middleware whose purpose is to screen incoming tokens and verify them. However, looking at the logs, multiple errors related to ERR_HTTP_HEADERS_SENT are popping up.
Here is the code for the middleware:
var client = jwksClient({
    strictSsl: false,
    jwksUri: process.env.JWKS_URI
})

// Route middleware to verify a token
server.use(
    async (req, res, next) => {

        let path = req.route.path.replace(/\?.*$/,'')

        let url = req.url

        let whitelist = [
            // list of endpoints that are left unprotected
        ]

        if(whitelist.indexOf(path) > -1 || whitelist.indexOf(url) > -1){
            return next()
        }
        else {
            const r = req
            let token = req.headers['x-access-token'] || req.headers['authorization']

            // Decode token
            token = token.slice(7,token.length).trimLeft()

            token = token.trim()

            if (token == undefined || token.length <= 0) {
               res.send(401)
               return
            }

            try{
                // Verify the token
                jwt.verify(
                    token,
                    getKey,
                    {
                        algorithm: process.env.JWT_ALGORITHM
                    },
                    (err, decoded) => {
                        if (err) {
                            res.end(401)
                            return
                        }
                        else{
                            next()
                        }
                })
            }
            catch(e){
                res.send(401)
                return
            }

            let email = jwtDecode(token)['email']

            // Code here to query database and check whether email is registered

            // If no result has been returned
            if (email != null && email != undefined && email.length > 0) {
                return next()
            }
            else {
                res.send(401)
                return
            }
        }
})

We're using jsonwebtoken as the library to do the verification.

A: What happen is that your using the callback, and the rest of the function keep going on, so untill the callback happens your already sending the headers

            try{
                // Verify the token
                jwt.verify(
                    token,
                    getKey,
                    {
                        algorithm: process.env.JWT_ALGORITHM
                    })
                 return next()
            }
            catch(e){
                res.send(401)
                return
            }


text:
Q: Getting framebuffer width and height in C without Xorg or file read on /sys item about fb width/height Is theres a way to access framebuffer width and height in a primitive linux system that lacks /sys and does not has any ability to run xorg?
Need this to know width and height for framebuffer to draw images on this limited system properly on the screen.
Every resource I found on internet mentioned using xorg or reading from a obscure file under /sys to get it which isn't what I want.


text:
Q: How to use Quartz .net in Windows form? i try to write a project to use Quart.net (http://quartznet.sourceforge.net/)
to make job scheduling system (Quartz.NET is a full-featured, open source job scheduling system that can be used from smallest apps to large scale enterprise systems.)
But i can not use listbox1.items add in execute method. How can use windows form controls is Quartz?
using System.Threading;
using Quartz;
using Quartz.Impl;

namespace QuartzTest1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       private void btnStart_Click(object sender, EventArgs e)
        {
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            //Yeni bir zamanlayıcı oluşturulup çalıştırılıyor
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            //Oluşturduğumuz görev(MyJob) hazırlanıyor

            JobDetail jobDetail = new JobDetail("myJob", null, typeof(MyJob));

            //Başlatıldıktan 20 sn sonra çalışacak bir SimpleTrigger oluşturuluyor.
            //İlk çalışmadan sonra 10 sn arayla 5 kez daha tetiklenecek
            Trigger trigger = new SimpleTrigger("myFirstTrigger",
                                                   null,
                                                   DateTime.UtcNow.AddSeconds(20),
                                                   null,
                                                   5,
                                                   TimeSpan.FromSeconds(10));

            //Görev tetikleyici ile zamanlanıyor
            sched.ScheduleJob(jobDetail, trigger);
            //Uygulama bekletiliyor
            ManualResetEvent resetEvent = new ManualResetEvent(false);
            resetEvent.WaitOne();
        }
    }

    public class MyJob :Form1, IJob
    {

        public void Execute(JobExecutionContext context)
        {
            listBox1.Invoke(new Action(delegate()
            {
                listBox1.Items.Add(String.Format("Görev çalıştırıldı : {0}", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")));
            }));

        }
    }
}

How to use below codes:

 public void Execute(JobExecutionContext context)
        {
            listBox1.Invoke(new Action(delegate()
            {
//.....
//...
//..
//.

ERROR:InvalidOperationException: Invoke or BeginInvoke can not be called on Window handler until the creation of the audit.

A: OK!
I have wasted too much time with this issue making Quartz.net working on windows form.
BUT, I have a Generic solution which I hope will help others.

*

*Create the IJOB class as you normally do

*Create a static pointer to the form

*In the main form have a public function called something like:
public void Execute()
public delegate void ExecuteCallback();

*On Execute, check to see if "Invoke is Required"

*Construct the delegate, and call Invoke.
Then hopefully all the threading issues see to be removed, you can call any controls, you can reschedule a Quartz job ,etc.
public class RunMyTask: IJob
{

    public static SalesBuddy.Form1 CurrentForm = null;

    public RunMyTask()
    {
    }

    public void Execute(IJobExecutionContext context)
    {
        if (CurrentForm.InvokeRequired)
        {
            SalesBuddy.Form1.ExecuteCallback x = new SalesBuddy.Form1.ExecuteCallback(CurrentForm.Execute);
            CurrentForm.Invoke(x);

        }
        else
        {
            CurrentForm.Execute();
        }
    }

A: Quartz.net instantiate job objects based on the passed in type. In your code:
JobDetail jobDetail = new JobDetail("myJob", null, typeof(MyJob));

when you then try to call:
listBox1.Invoke(new Action(delegate()
            {
                listBox1.Items.Add(String.Format("Görev çalıştırıldı : {0}", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")));
            }));

You are executing this on a freshly created instance of a form in another thread (quartz.net executes jobs in a predefined amount of workerthreads) that is not displayed, that's why you are getting the error.
To prevent this you should not call the UI code in your Job, do not derive the job from Form1. Enable communication between UI and job via some sort of observer pattern e.g. EventAggregator.


text:
Q: Lexicology, Semasiology Is metonymy considered to be linguistic or extralinguistic factor of semantic change? For example crown for a monarchy

A: Wikipedia lists "metonymy" under its types of semantic change:

A number of classification schemes have been suggested for semantic change. The most widely accepted scheme in the English-speaking academic world is from Bloomfield (1933):

*

*Narrowing: Change from superordinate level to subordinate level. For example, skyline formerly referred to any horizon, but now it has narrowed to a horizon decorated by skyscrapers.

*Widening: Change from subordinate level to superordinate level. There are many examples of specific brand names being used for the general product, such as with Kleenex. Such uses are known as generonyms.

*[...]

*Metonymy: Change based on contiguity between concepts, e.g., horn "animal horn" → "musical instrument".

So yes, metonymy can be considered a factor of semantic change.


text:
Q: BigQuery - extract the most used tables I'm using the Google BigQuery and looking on the default audit dataset.
I know that this dataset contains various data about the queries the users are running.
I wondered if I can write a query that will show me the MOST USED tables over my project (lets say for the last 30 days)?
Output example:
table_1_name: 5000 queries
table_2_name: 4000 queries
table_3_name: 2000 queries

and so on...

A: Adding the answer from Tamir Klein, here's the query you can use:
SELECT
job_id,
creation_time,
referenced_tables.dataset_id,
referenced_tables.table_id
FROM `your-project-name`.`your-region`.INFORMATION_SCHEMA.JOBS_BY_PROJECT,
UNNEST(referenced_tables) AS referenced_tables
WHERE job_type = 'QUERY'
AND DATE(creation_time) >= DATE_SUB(DATE(CURRENT_TIMESTAMP()), INTERVAL 30 DAY)

That will give you list of jobs and the reference tables used in all your query jobs in the past 30 days.
Then you can aggregate them by dataset_id and table_id:
SELECT
dataset_id,
table_id,
COUNT(DISTINCT job_id) AS total_jobs
FROM referenced_table_list
GROUP BY 1,2
ORDER BY 3 DESC

and add conditions as you wish, e.g. WHERE dataset_id = 'audit'.
Hope it helps!

A: You can use BigQuery Jobs.list to get all the Jobs you executed.
Inside the response, there is an array, referencedTables, which tells you which tables where used in the Job
"referencedTables": [
           {
              "projectId": string,
              "datasetId": string,
              "tableId": string
            }
]

You can now collect this information into a destination table or other storage to get the metadata you are looking for


text:
Q: Kafka console producer does not fail if broker address is incorrect I run the following command (where <incorrect port> is a number):
bin/kafka-console-producer.sh --broker-list localhost:<incorrect port> --topic some-topic

And the process doesnt fail, it continues as if nothing is wrong
Is there a way upon startup of kafka-console-producer.sh  to check the destination broker port has a broker listening to that port upon startup?
I'm using kafka 0.10.2.0 on osx 10.12.3

A: That's by design... The producer just assumes, that the broker will get available at the specified port eventually. However, the producer should time out at some point (IIRC the default is 5 minutes). You can reduce the timeout config to get the error earlier via request.timeout.ms or metadata.fetch.timeout.ms.


text:
Q: Restart Pod from OpenShift Java REST Client i'm trying to programmatically restart a Pod. First I've found some ways of doing this through the oc command line:

*

*Delete the pod and a new Pod will be created: oc delete pod postgresql-2-wz989

*Launch a new Deployment: oc rollout latest dc/postgresql
I think the second way is better because the deployment config name is static and doesn't change like the pod's name.
My question is how to do this using the Java Rest Client? It's not very clear to me how to use this client API.
Thanks in advance.

A: Taking into account the hint from Graham Dumpleton regarding the use of --loglevel=9 I got to a solution using the java client:
IClient client = new ClientBuilder("https://10.0.75.2:8443")
                    .withUserName("developer")
                    .withPassword("developer")
                    .build();
IProject project = client.getResourceFactory().stub(ResourceKind.PROJECT, "prj4testing");
IDeploymentConfig deploymentConfig = client.getResourceFactory().stub(ResourceKind.DEPLOYMENT_CONFIG, "postgresql", project.getName());
IDeploymentTriggerable capability = deploymentConfig.getCapability(IDeploymentTriggerable.class);
capability.setForce(true);
capability.setLatest(true);
capability.trigger();

I got to this solution through researching the source code from the client. I don't know if there are better ways to achieve this. Any comments are welcome.


text:
Q: Changing HTML using javascript dynamically as the page first loads I am making a dynamic page that contains several divs that change when the user selects to go to the next passage on my page. However, I cannot get my website to load the first set of information.
The HTML contains these blank divs, and then my function loads in a JSON file and changes the divs by their ID's. When I first load my page, these divs appear without text. Could it be that my javascript is not running when the page is first loaded?  Here is an example of my HTML:

<button id="max-passage" class="max"></button>

And here is my function:
//This section of code handles the calling of the first passage.
//Loading in the JSON file and changing the contents of the page.
function loadFirstPassage()
{
    var timeout = 250;
    //load the new JSON file and change the elements
    $.getJSON("passages/2.1.1.json", function( data ) {
        document.getElementById("passage-title").innerHTML = data["passageNumber"];
        document.getElementById("passage").innerHTML = "
".concat(data["reading"]).concat('
');\

        //fading the elements back in
        $("#passage-title").fadeIn(timeout);
        $("#passage").fadeIn(timeout);
   });
}

I tried calling this function in the body and that did not work, so currently it is getting called in the head.

A: Try
$(document).ready(function() {
    loadFirstPassage();
});

instead of $(document).load.

A: you could try load it right after the DOM finished
(function() {
   console.log('DOM Loaded')
})();

jQuery would use
$( document ).ready(function() {
    console.log('DOM Loaded');
});