答:
Using the solution suggested by @wwnde, I've found one that scales better to my real data set:

```<code>import numpy as np
import pandas as pd

df1 = DataFrame({
    'id': ['a']*4,
    'date': ['02-02-2015']*4,
    'time_1': ['08:00:00', '09:00:00', '10:30:00', '12:45:00']
})

df2 = DataFrame({
    'id': ['a']*7,
    'date': ['02-02-2015',
        '02-02-2015',
        '03-02-2015', # small change here relatively to the df un my first post
        '02-02-2015',
        '02-02-2015',
        '02-02-2015',
        '02-02-2015'],
    'time_2': ['08:00:00', '08:09:00', '08:04:01','08:52:36', '09:34:25', '10:30:00', '11:23:38']
})

----------------------------------------------------

def preproDf(df1, df2, time_1, time_2, _id, date):
    '''
    Preprocess the dataframes for the following operations

    df1: pd.DataFrame, left dataframe
    df2: pd.DataFrame, right dataframe
    time_1:str, name of the left dataframe
    time_2:str, name of the right dataframe
    _id:str, name of the id variable. Should be the same for both dataframes
    date:str, name of the date variable. Should be the same for both dataframes

    return: None
    '''
    df2[time_2] = df2[time_2].apply(pd.to_datetime)
    df1[time_1] = df1[time_1].apply(pd.to_datetime)

    #sort to allow merge_asof
    df1=df1.sort_values([_id, date, time_1])
    df2=df2.sort_values([_id, date, time_2])

def processDF(df1, df2, time_1, time_2, _id, date):
    # initialisation
    groupKeys = list(df2.groupby([_id, date]).groups.keys())
    dfGroup=groupKeys[0]
    group = df2.groupby([_id, date]).get_group(dfGroup)
    rslt = pd.merge_asof(group, df1, left_on=time_2,  right_on=time_1, by=[_id, date], tolerance=pd.Timedelta('2H'),allow_exact_matches=True,direction='backward')#.dropna()

    # For loop to get the values in an array
    for group in groupKeys[1:]: # Iteration start at the second elmt
        group = df2.groupby([_id, date]).get_group(group)
        item = pd.merge_asof(group, df1, left_on=time_2,  right_on=time_1, by=[_id, date], tolerance=pd.Timedelta('2H'),allow_exact_matches=True,direction='backward')#.dropna()
        rslt = np.vstack((rslt, item))
    rslt = DataFrame(rslt, columns=item.columns)

    # Creating timeDifference variable
    rslt['timeDifference'] = rslt[time_2] - rslt[time_1]

    # Getting the actual result
    rslt = rslt.groupby([_id, date, time_1]).timeDifference.max()
    rslt = pd.DataFrame(rslt).reset_index()
    rslt.rename({time_1: 'openTime'}, axis='columns')

    return rslt
</code>```

The result:

```<code>preproDf(df1, df2, 'time_1', 'time_2', 'id', 'date')

processDF(df1, df2, 'time_1', 'time_2', 'id', 'date')
    id  date    time_1  screenOnDuration
0   a   02-02-2015  2020-05-29 08:00:00 00:52:36
1   a   02-02-2015  2020-05-29 09:00:00 00:34:25
2   a   02-02-2015  2020-05-29 10:30:00 00:53:38
</code>```

Title: Conditionally merging dataframes on time variable

Body:
I have to dataframe that I want to merge on the date, id and time variable in order to compute a duration.

from numpy import *
from pandas import *

df1 = DataFrame({
'id': ['a']*4,
'date': ['02-02-2015']*4,
'time_1': ['08:00:00', '09:00:00', '10:30:00', '12:45']})

df1
   id   date         time
0   a   02-02-2015  08:00:00
1   a   02-02-2015  09:00:00
2   a   02-02-2015  10:30:00
3   a   02-02-2015  12:45:00

-------------------------------------------------------------------------------------------------

df2 = DataFrame({
'id': ['a']*7,
'date': ['02-02-2015']*7,
'time_2': ['08:00:00', '08:09:00', '08:04:01','08:52:36', '09:34:25', '10:30:00', '11:23:38']})

df2
    id  date         time
0   a   02-02-2015  08:00:00
1   a   02-02-2015  08:09:00
2   a   02-02-2015  08:04:01
3   a   02-02-2015  08:52:36
4   a   02-02-2015  09:00:00
5   a   02-02-2015  10:30:00
6   a   02-02-2015  11:23:38

The rule that I want my merge to follow is that each row needs in df2 needs to go with the closest previous time in df1.

The intermediate result would be

intermediateResult = DataFrame({
'id': ['a']*8,
'date': ['02-02-2015']*8,
'time_1': ['08:00:00', '08:00:00', '08:00:00','08:00:00', '09:00:00', '10:30:00', '10:30:00', '12:45'],
'time_2': ['08:00:00', '08:09:00', '08:04:01','08:52:36', '09:34:25', '10:30:00', '11:23:38', nan] })

intermediateResult
    id  date        time_1      time_2
0   a   02-02-2015  08:00:00    08:00:00
1   a   02-02-2015  08:00:00    08:09:00
2   a   02-02-2015  08:00:00    08:04:01
3   a   02-02-2015  08:00:00    08:52:36   # end
4   a   02-02-2015  09:00:00    09:34:25   # end
5   a   02-02-2015  10:30:00    10:30:00
6   a   02-02-2015  10:30:00    11:23:38   # end
7   a   02-02-2015  12:45           NaN

Finally, I want to get the time difference between the latest time_2 of each period (inicated with the comment # end) and their corresponding time_1.

The final result would look like this

finalResult = DataFrame({
'id': ['a']*4,
'date': ['02-02-2015']*4,
'Duration': ['00:52:36', '00:34:25', '00:53:38', nan]})

finalResult
    id  date        Duration
0   a   02-02-2015  00:52:36
1   a   02-02-2015  00:34:25
2   a   02-02-2015  00:53:38
3   a   02-02-2015  NaN

Body:
Using the solution suggested by @wwnde, I've found one that scales better to my real data set:

import numpy as np
import pandas as pd

df1 = DataFrame({
    'id': ['a']*4,
    'date': ['02-02-2015']*4,
    'time_1': ['08:00:00', '09:00:00', '10:30:00', '12:45:00']
})

df2 = DataFrame({
    'id': ['a']*7,
    'date': ['02-02-2015',
        '02-02-2015',
        '03-02-2015', # small change here relatively to the df un my first post
        '02-02-2015',
        '02-02-2015',
        '02-02-2015',
        '02-02-2015'],
    'time_2': ['08:00:00', '08:09:00', '08:04:01','08:52:36', '09:34:25', '10:30:00', '11:23:38']
})

----------------------------------------------------

def preproDf(df1, df2, time_1, time_2, _id, date):
    '''
    Preprocess the dataframes for the following operations

    df1: pd.DataFrame, left dataframe
    df2: pd.DataFrame, right dataframe
    time_1:str, name of the left dataframe
    time_2:str, name of the right dataframe
    _id:str, name of the id variable. Should be the same for both dataframes
    date:str, name of the date variable. Should be the same for both dataframes

    return: None
    '''
    df2[time_2] = df2[time_2].apply(pd.to_datetime)
    df1[time_1] = df1[time_1].apply(pd.to_datetime)

    #sort to allow merge_asof
    df1=df1.sort_values([_id, date, time_1])
    df2=df2.sort_values([_id, date, time_2])

def processDF(df1, df2, time_1, time_2, _id, date):
    # initialisation
    groupKeys = list(df2.groupby([_id, date]).groups.keys())
    dfGroup=groupKeys[0]
    group = df2.groupby([_id, date]).get_group(dfGroup)
    rslt = pd.merge_asof(group, df1, left_on=time_2,  right_on=time_1, by=[_id, date], tolerance=pd.Timedelta('2H'),allow_exact_matches=True,direction='backward')#.dropna()

    # For loop to get the values in an array
    for group in groupKeys[1:]: # Iteration start at the second elmt
        group = df2.groupby([_id, date]).get_group(group)
        item = pd.merge_asof(group, df1, left_on=time_2,  right_on=time_1, by=[_id, date], tolerance=pd.Timedelta('2H'),allow_exact_matches=True,direction='backward')#.dropna()
        rslt = np.vstack((rslt, item))
    rslt = DataFrame(rslt, columns=item.columns)

    # Creating timeDifference variable
    rslt['timeDifference'] = rslt[time_2] - rslt[time_1]

    # Getting the actual result
    rslt = rslt.groupby([_id, date, time_1]).timeDifference.max()
    rslt = pd.DataFrame(rslt).reset_index()
    rslt.rename({time_1: 'openTime'}, axis='columns')

    return rslt

The result:

preproDf(df1, df2, 'time_1', 'time_2', 'id', 'date')

processDF(df1, df2, 'time_1', 'time_2', 'id', 'date')
    id  date    time_1  screenOnDuration
0   a   02-02-2015  2020-05-29 08:00:00 00:52:36
1   a   02-02-2015  2020-05-29 09:00:00 00:34:25
2   a   02-02-2015  2020-05-29 10:30:00 00:53:38


来源: stackexchange

问:
DetailView Django dont work error page not found
When I click on the article I get
How can I fix it?
 I tried url, path and other but I have this error
      urls.py</p>

```<code>from django.contrib import admin
    from django.urls import path,include

urlpatterns = [
    path('index', include('mainpage.urls')),
    path('blog', include('news.urls')),
    path('games', include('games.urls')),
    path('fortnite', include('fortnite.urls')),
    path('contacts', include('contact.urls')),
    path('admin', admin.site.urls),
]
news/urls.py
from django.urls import path,include,re_path
from django.conf.urls import url
from . import views
from django.views.generic import ListView, DetailView
from news.models import Articles
urlpatterns = [
    path('', ListView.as_view(queryset=Articles.objects.all().order_by('-date')[:20],template_name='news.html')),
    path('<int:pk>/', DetailView.as_view(model=Articles, template_name='news/post.html'))
                ]
</code>```

答:
First of all please add '/' at end of all your path strings , change it like this

```<code>    path('index/', include('mainpage.urls')),
    path('blog/', include('news.urls')),
    path('games/', include('games.urls')),
    path('fortnite/', include('fortnite.urls')),
    path('contacts/', include('contact.urls')),
    path('admin/', admin.site.urls),
]
</code>```

check if it works or not

ContentLicense: CC BY-SA 4.0

Body:
When I click on the article I get
How can I fix it?
 I tried url, path and other but I have this error
      urls.py

from django.contrib import admin
    from django.urls import path,include

urlpatterns = [
    path('index', include('mainpage.urls')),
    path('blog', include('news.urls')),
    path('games', include('games.urls')),
    path('fortnite', include('fortnite.urls')),
    path('contacts', include('contact.urls')),
    path('admin', admin.site.urls),
]
news/urls.py
from django.urls import path,include,re_path
from django.conf.urls import url
from . import views
from django.views.generic import ListView, DetailView
from news.models import Articles
urlpatterns = [
    path('', ListView.as_view(queryset=Articles.objects.all().order_by('-date')[:20],template_name='news.html')),
    path('<int:pk>/', DetailView.as_view(model=Articles, template_name='news/post.html'))
                ]

Body:
First of all please add '/' at end of all your path strings , change it like this

    path('index/', include('mainpage.urls')),
    path('blog/', include('news.urls')),
    path('games/', include('games.urls')),
    path('fortnite/', include('fortnite.urls')),
    path('contacts/', include('contact.urls')),
    path('admin/', admin.site.urls),
]

check if it works or not


问:
Silverlight Accessing ASPX Static Object
I have a website that started with ASP.NET and over time has had some Silverlight elements added to it throughout miscellaneous pages. One of these elements needs to change a static object on the ASP.NET Master Page containing it. Is this in any way possible? I had it in my mind that I might be able to create an event in Silverlight and catch it in the ASP.NET code, but I doubt that could work. Any help would be great.</p>

答:
This is fundamentally impossible.
Silverlight runs on the client, whereas ASP.Net runs on the server, and never the twain shall meet.

Instead, you can use AJAX (see the WebClient class)

ContentLicense: CC BY-SA 3.0


问:
How to avoid repeating generic type constraints with every usage in Typescript?
How do you avoid repeating types constantly when using generics in Typescript? If I have some constraint on a generic type then I must repeat that constraint anywhere I use the generic type. This is tedious and not very DRY.

```<code>//A constraint on this generic
type MyConstraint = { bar: number }
type GenericOne<T extends MyConstraint> = {
    foo: T
}
</code>```

To create an instance I annoyingly have to repeat the constraint because TS only does generic inference on functions

```<code>//This annoyance would I think be solved by generic values https://github.com/microsoft/TypeScript/issues/17574
const testok: GenericOne<MyConstraint> = { foo: { bar: 1 } }
</code>```

Now if I want to use my generic type in other places I also have to repeat the constraint!

```<code>const makeGenericOne2: <T extends MyConstraint>(arg: GenericOne<T>) => GenericOne<T> = (arg) => {
    return arg
}
</code>```

At least now I can create from object literals without repeating myself

```<code>const test5 = makeGenericOne2({ foo: { bar: 1 } })
// And I get nice error messsages
const test6 = makeGenericOne2({foo: {baz: 1}})
</code>```

The only way to avoid repeating the constraint seems to be a conditional type with inference

```<code>const makeGenericOne: <T>(arg: T extends GenericOne<infer U> ? T : never) => T = (arg) => {
    return arg
}
</code>```

I can still create instances from object literal without repeating myself

```<code>const test3 = makeGenericOne({ foo: { bar: 1 } })
</code>```

But now the error messages aren't so nice.

```<code>//"number not assignable to never" instead of { baz: 1 } is missing property "bar: number"
const test4 = makeGenericOne({ foo: { baz: 1 } })
</code>```

It seems like the following is needed -- infer T because we know it must extend Myconstraint

```<code>const propagateGeneric: <infer T>(arg: GenericOne<T>) => GenericOne<T>
</code>```

Unfortunately this isn't allowed in TS at the moment.

How do I "propogate" the constraint on a generic type to avoid repeating it everywhere that generic type is used?

Sandbox Link

答:
Tricky but it seems to work</p>

```<code>//A constraint on this generic
type MyConstraint = { bar: number }
type GenericOne<T extends MyConstraint = MyConstraint> = {
    foo: T
}
</code>```

Body:
How do you avoid repeating types constantly when using generics in Typescript? If I have some constraint on a generic type then I must repeat that constraint anywhere I use the generic type. This is tedious and not very DRY.

//A constraint on this generic
type MyConstraint = { bar: number }
type GenericOne<T extends MyConstraint> = {
    foo: T
}

To create an instance I annoyingly have to repeat the constraint because TS only does generic inference on functions

//This annoyance would I think be solved by generic values https://github.com/microsoft/TypeScript/issues/17574
const testok: GenericOne<MyConstraint> = { foo: { bar: 1 } }

Now if I want to use my generic type in other places I also have to repeat the constraint!

const makeGenericOne2: <T extends MyConstraint>(arg: GenericOne<T>) => GenericOne<T> = (arg) => {
    return arg
}

At least now I can create from object literals without repeating myself

const test5 = makeGenericOne2({ foo: { bar: 1 } })
// And I get nice error messsages
const test6 = makeGenericOne2({foo: {baz: 1}})

The only way to avoid repeating the constraint seems to be a conditional type with inference

const makeGenericOne: <T>(arg: T extends GenericOne<infer U> ? T : never) => T = (arg) => {
    return arg
}

I can still create instances from object literal without repeating myself

const test3 = makeGenericOne({ foo: { bar: 1 } })

But now the error messages aren't so nice.

//"number not assignable to never" instead of { baz: 1 } is missing property "bar: number"
const test4 = makeGenericOne({ foo: { baz: 1 } })

It seems like the following is needed -- infer T because we know it must extend Myconstraint

const propagateGeneric: <infer T>(arg: GenericOne<T>) => GenericOne<T>

Unfortunately this isn't allowed in TS at the moment.

How do I "propogate" the constraint on a generic type to avoid repeating it everywhere that generic type is used?

<a href="https://www.typescriptlang.org/play/index.html?ssl=38&ssc=71&pln=1&pc=1#code/PTCCAIGMHsDsGcAuAnAhgS1o8dyIBbrzgDmAprGcupALABQiAngA5ngCyTAwnEmpmwBecAG9wAI1TIAXOFgBXALYSq4AL4NmbcAHEKVGgHlKAHgAq4MgA9EFACbEuvBCgxYAfOBGiG4f%20AAZtDQcuYMmvQMIObQUMhkqHbgqOAANuh2aGngAJIpsLDQTJgkaUzg%20KgAbuyIcQlsSXj47DCuAliSZJCoCvDs5gDKOLDl4PbQZMTklNSQ4JiBVBSQ7LiBCrCQiOh80cDmhMSohcWna%20AA7tAKafZ5LZgA1t3g8NBptQ8SFbOGC2qqDSCmmlUQiBY8BkIBImXwCgkADoYEpgEoaMhoB9AohDqwyENINQWHiiPBQfBgABGADsAFZaQAWBjtJB4ab1Z5yfRzYxmZx8NyCLw%20IIhOTiKSycDUjQaBgHABy0Cui0Cjyup2w9XA-XYSj%20BnmeAJi1gOAIahYaVQa2I%20WBH0qNTqDTITR1rSgQs6iAAhKyheAlKhnmReQCTGQAExyCxWWwOJw8X3uRAeAAU0hIPON-LIFg8AEpvF5I-No0XvOBs8gSKWhF5fPQAuAEogFMgLTmIor6CBQNg0ol2UU1flehbiYlkoEsUocBIAFY9YeZKhO67w27YRqz0ohpgDNKBIOuDlIek10PhisFmOZ8TBUJiSTSORy9QaYsHcCgWAHnychsFgGh2CoLFkBDaZ4HgVByHgc92TsJAADYbzDCN80gaNH1EF9JSkAAvT91HUX8oiomJvTgcYtQqXUamgdAHn3JJDytH0OnTd4yDIJRiF1VQUm4%20xMj2WBgVNHQrnhc1lgSbYyGQ7Bb2wvlcMoeNzCzHMwkTOxAOIe8tMLJY1AAVS8AB%20cBLDkShamQRsvEsEQ6wbMsxD8AIOy7Ht6z7ajgEnU53l2NIchnJJ2EwJALjBedoEXaAVzXdIN2ybcCF3dsPQPWASCPE8z3oNkdU5ABmTC7xw6Mn3FV8pQ-WV5Qo-sQAAIQUUDVRaCDkCgmC4IQsFpAoABybBnTAtYkXAA4ACJFBUNQimwVA4PQEgpIkEc8DiJyqCW80kESB5oA1FrSLa78iBDclDxYLE2GQZhwCW6VHOUVRkCW1TL0QJlao0qNKEawi3xIz92so-sDgACX6yZHiWl7oBYaASFi06uIqv1RlE-4TW0N0UmqFi2IKjiisWbAyGcpgrlaBIWmaEmaBkuLiH1ewbIOXIZv4wTMvDAbxSi1VDweygyHseXwAAWiVhS1EsVRen1a52Gecd6ZDfoGaTQDOCYAn00BjGWAQ2LTPjCzoN0zy800qtdNcvR6rMXSgA" rel="nofollow noreferrer">Sandbox Link

Body:
Tricky but it seems to work

//A constraint on this generic
type MyConstraint = { bar: number }
type GenericOne<T extends MyConstraint = MyConstraint> = {
    foo: T
}


问:
Mockito InvalidUseOfMatchersException when mocking a post request
I'm totally new to mockito and I have tried a lot of solutions I found online but I still can't solve this problem. I'm not even sure what is causing it. I need to create a mock test for a very mature code which I am not allowed to change. The part of the code which I need to mock sends a post request to a server. I have recreated the code in a much simpler way but unfortunately, it is still rather long. Lets say I have ClassA which calls the api as shown bellow and returns an integer.

```<code>import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ClassA {

    public int moveActual(String path) throws IOException {
        Response wsResponse = null;
        String newHome = "0" ;
        ResteasyClient httpClient = new ResteasyClientBuilder().connectionPoolSize(1)
                .establishConnectionTimeout(10, TimeUnit.SECONDS).socketTimeout(10, TimeUnit.SECONDS).build();
        ResteasyWebTarget target = httpClient.target(path) ;

        Map<String, Object> request = new HashMap<>();
        request.put("operation", "dislocation");
        request.put("direction", "right");
        request.put("amount", "2");
        request.put("unit", "metric");
        String requestJson = new ObjectMapper().writeValueAsString(request);

        wsResponse = target.request().post(Entity.entity(requestJson, "application/json"));
        String responseString = wsResponse.readEntity(String.class);
        ObjectMapper responseMapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String, Object> response = (Map<String, Object>) responseMapper.readValue(responseString, Map.class);

        if (response != null) {
            newHome = (String) response.get("coordinate");
        }
        // In the real code there is much more code here.
        return Integer.parseInt(newHome) ;
    }
}
</code>```

I need to mock the server to test the moveActual method. So I decided to mock the post method. In order to do that, I came up with the test below:

```<code>import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.BDDMockito.given;

import java.util.HashMap;
import java.util.Map;

import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import externalTests.ClassA;

@RunWith(MockitoJUnitRunner.class)
public class DispositionMockTest {

    @Mock
    ResteasyWebTarget targetMock;

    @InjectMocks
    ClassA classA;

    @Test
    public void dispositionTest() throws Exception {
        // Given
        Map<String, Integer> outcomeMap = new HashMap<String, Integer>() ;
        outcomeMap.put("coordinate", 4) ;
        Response resp = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(outcomeMap).build() ;
        given(targetMock.request().post(ArgumentMatchers.isA(Entity.class))).willReturn(resp) ;

        // When
        int result = classA.moveActual("url") ;

        // Then
        assertEquals(4, result);
    }

}
</code>```

However, I get the error bellow no matter what I do.

```<code>java.lang.NullPointerException
    at externalTests.DispositionMockTest.dispositionTest(DispositionMockTest.java:42)
    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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:46)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:77)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:83)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:

-> at externalTests.DispositionMockTest.dispositionTest(DispositionMockTest.java:42)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

    at org.mockito.internal.runners.DefaultInternalRunner$1$2.testFinished(DefaultInternalRunner.java:68)
    at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56)
    at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190)
    at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72)
    at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187)
    at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:77)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:83)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
</code>```

I have tried @spy instead of @mock and other matchers like ArgumentMatchers.any(Entity.class) and ArgumentMatchers.any() but to no avail. I was looking into powermock but none of the methods and classes involved are private, nor static. I have no idea what else to try. I appreciate any help.

答:
Because you mocked ResteasyWebTarget and didn't define what should be the return of request() method, you got that exception.

You should first mock request and return it to the request() method and define the behavior to post() method from mockedRequest

```<code>when(targetMock.request()).thenReturn(mockedRequest);
when(mockedRequest.post(any(Entity.class))).thenReturn(resp) ;
</code>```

Body:
I'm totally new to mockito and I have tried a lot of solutions I found online but I still can't solve this problem. I'm not even sure what is causing it. I need to create a mock test for a very mature code which I am not allowed to change. The part of the code which I need to mock sends a post request to a server. I have recreated the code in a much simpler way but unfortunately, it is still rather long. Lets say I have ClassA which calls the api as shown bellow and returns an integer.

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ClassA {

    public int moveActual(String path) throws IOException {
        Response wsResponse = null;
        String newHome = "0" ;
        ResteasyClient httpClient = new ResteasyClientBuilder().connectionPoolSize(1)
                .establishConnectionTimeout(10, TimeUnit.SECONDS).socketTimeout(10, TimeUnit.SECONDS).build();
        ResteasyWebTarget target = httpClient.target(path) ;

        Map<String, Object> request = new HashMap<>();
        request.put("operation", "dislocation");
        request.put("direction", "right");
        request.put("amount", "2");
        request.put("unit", "metric");
        String requestJson = new ObjectMapper().writeValueAsString(request);

        wsResponse = target.request().post(Entity.entity(requestJson, "application/json"));
        String responseString = wsResponse.readEntity(String.class);
        ObjectMapper responseMapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String, Object> response = (Map<String, Object>) responseMapper.readValue(responseString, Map.class);

        if (response != null) {
            newHome = (String) response.get("coordinate");
        }
        // In the real code there is much more code here.
        return Integer.parseInt(newHome) ;
    }
}

I need to mock the server to test the moveActual method. So I decided to mock the post method. In order to do that, I came up with the test below:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.BDDMockito.given;

import java.util.HashMap;
import java.util.Map;

import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import externalTests.ClassA;

@RunWith(MockitoJUnitRunner.class)
public class DispositionMockTest {

    @Mock
    ResteasyWebTarget targetMock;

    @InjectMocks
    ClassA classA;

    @Test
    public void dispositionTest() throws Exception {
        // Given
        Map<String, Integer> outcomeMap = new HashMap<String, Integer>() ;
        outcomeMap.put("coordinate", 4) ;
        Response resp = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(outcomeMap).build() ;
        given(targetMock.request().post(ArgumentMatchers.isA(Entity.class))).willReturn(resp) ;

        // When
        int result = classA.moveActual("url") ;

        // Then
        assertEquals(4, result);
    }

}

However, I get the error bellow no matter what I do.

java.lang.NullPointerException
    at externalTests.DispositionMockTest.dispositionTest(DispositionMockTest.java:42)
    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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:46)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:77)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:83)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:

-> at externalTests.DispositionMockTest.dispositionTest(DispositionMockTest.java:42)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

    at org.mockito.internal.runners.DefaultInternalRunner$1$2.testFinished(DefaultInternalRunner.java:68)
    at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56)
    at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190)
    at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72)
    at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187)
    at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:77)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:83)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

I have tried @spy instead of @mock and other matchers like ArgumentMatchers.any(Entity.class) and ArgumentMatchers.any() but to no avail. I was looking into powermock but none of the methods and classes involved are private, nor static. I have no idea what else to try. I appreciate any help.

Body:
Because you mocked ResteasyWebTarget and didn't define what should be the return of request() method, you got that exception.

You should first mock request and return it to the request() method and define the behavior to post() method from mockedRequest

when(targetMock.request()).thenReturn(mockedRequest);
when(mockedRequest.post(any(Entity.class))).thenReturn(resp) ;


问:
Use jquery to find elements that contain a specific ID and highlight them
I'm a jquery/javascript noob so not really sure how to go about this. I want to modify a website that's already been served to me in my browser.

There are some boxes on the left hand side and then there are arrows going from these boxes to other boxes on the right hand side. What I am attempting to do is use a click event listener to click on a box on the left, have it highlighted, and also highlight the arrow that is associated with this box.

Here's what I have so far and it works to highlight the left hand side box. What I want to also do is highlight any arrows that contain this ID as there can be multiple arrows originating from a box.

```<code>javascript: document.designMode = "on"; document.designMode = "on";

$("div[example]").on('click', function(e) {
    var t = $(this).attr('id');
    e.preventDefault();
    $(this).css('background-color', 'red');
    console.log(t);

});
</code>```

I can print the correct element ID (e.g. ID_of_lefthandbox) out when I click on the box. So using this ID I would like to then find the arrow(s) on the webpage that contains this ID. Here is what the path looks like:

```<code><path to-id="12345" approved="true" id="43210" from-id="ID_of_lefthandbox" stroke-width="2" fill="" d="M5,193 53,261" stroke="DarkGreen" stroke-linecap="round" marker-end="url(#markGreenArrow)"></path>
</code>```

答:
Assuming that the attribute from-id contains the id of the lefthandbox you are looking for, the following works:

```<code> $("div[example]").on('click', function(e) {
    var t = $(this).attr('id');
    e.preventDefault();
    $(this).css('background-color', 'red');
    $("path[from-id='" + t + "']").css("background-color", "red");
    console.log(t);
 });
</code>```

Body:
I'm a jquery/javascript noob so not really sure how to go about this. I want to modify a website that's already been served to me in my browser.

There are some boxes on the left hand side and then there are arrows going from these boxes to other boxes on the right hand side. What I am attempting to do is use a click event listener to click on a box on the left, have it highlighted, and also highlight the arrow that is associated with this box.

Here's what I have so far and it works to highlight the left hand side box. What I want to also do is highlight any arrows that contain this ID as there can be multiple arrows originating from a box.

javascript: document.designMode = "on"; document.designMode = "on";

$("div[example]").on('click', function(e) {
    var t = $(this).attr('id');
    e.preventDefault();
    $(this).css('background-color', 'red');
    console.log(t);

});

I can print the correct element ID (e.g. ID_of_lefthandbox) out when I click on the box. So using this ID I would like to then find the arrow(s) on the webpage that contains this ID. Here is what the path looks like:

<path to-id="12345" approved="true" id="43210" from-id="ID_of_lefthandbox" stroke-width="2" fill="" d="M5,193 53,261" stroke="DarkGreen" stroke-linecap="round" marker-end="url(#markGreenArrow)"></path>

Body:
Assuming that the attribute from-id contains the id of the lefthandbox you are looking for, the following works:

 $("div[example]").on('click', function(e) {
    var t = $(this).attr('id');
    e.preventDefault();
    $(this).css('background-color', 'red');
    $("path[from-id='" + t + "']").css("background-color", "red");
    console.log(t);
 });


问:
is it possible to manually assign the value of the dummy variable?
I have a data set for automotive sales and i want to change the feature 'aspiration' which contains two unique values 'std' & 'turbo' to categorical values using pd.get_dummies. using the code below;

dummy_variable_2 = pd.get_dummies(df['aspiration'])

It is automatically assigning 0 to 'std' &  1 to 'turbo'.

I would like to change to 'std' to 1 & 'turbo' to 0.

答:
The return of pd.get_dummmies is a dataframe, which contains one column for each unique value in the dataframe. Whereby, in each column only the values of the corresponding unique value are set to one.

In your case, the dataframe contains two columns. One column is named turbo and one column std. If you want the column where the values of std are set to one, you have to do following:

```<code>df = pd.DataFrame({"aspiration":["std", "turbo", "std", "std", "std", "turbo"]})
dummies = pd.get_dummies(df)
std= dummies["aspiration_std"]
</code>```

In this example, the variable dummy looks like:

```<code>   std  turbo
0    1      0
1    0      1
2    1      0
3    1      0
4    1      0
5    0      1
</code>```

and std looks like:

```<code>0    1
1    0
2    1
3    1
4    1
5    0
</code>```

Body:
The return of pd.get_dummmies is a dataframe, which contains one column for each unique value in the dataframe. Whereby, in each column only the values of the corresponding unique value are set to one.

In your case, the dataframe contains two columns. One column is named turbo and one column std. If you want the column where the values of std are set to one, you have to do following:

df = pd.DataFrame({"aspiration":["std", "turbo", "std", "std", "std", "turbo"]})
dummies = pd.get_dummies(df)
std= dummies["aspiration_std"]

In this example, the variable dummy looks like:

   std  turbo
0    1      0
1    0      1
2    1      0
3    1      0
4    1      0
5    0      1

and std looks like:

0    1
1    0
2    1
3    1
4    1
5    0


问:
How may I access an attribute of a class from the __init__ of another?
I'm working on an OOP task, as we've just been introduced to it.
We are to create two classes: Animal and Desert
They have specified for us a variety of attributes and methods that these classes must have

Desert contains a Grid attribute that some Animal objects should be distributed on.
Animal objects are represented with an 'A' where present on the grid, but also store their position locally, with their attributes Across and Down.

Within __init__ of the Animal class, we are supposed to choose a random position on the Grid to place the animal. This means setting the  Across and Down attributes to a random value but also modifying the Grid to display an 'A' in this location.

I'm not sure how I would go about accessing Grid from the Animal objects though.  Here is the relevant code, the comments relate to the different bullet points of the task:

class Animal(Desert):

  # Constructor
  def __init__(self):

    # Generate a pair of random numbers between 0 and 39.
    rand_num1 = randint(0, 39)
    rand_num2 = randint(0, 39)

    # Place an animal at that random position.
    self.Across = rand_num1
    self.Down = rand_num2
    # HERE IS WHERE I WOULD LIKE TO MODIFY THE GRID ATTRIBUTE OF DESERT

    # Initialise the animal's score to 0.
    self.Score = 0
```

<pre class="lang-py prettyprint-override"><code>class Desert:

  # Constructor
  def __init__(self):

    # attributes:
    self.Grid = []
    self.StepCounter = 0
    self.AnimalList = []
    self.NumberofAnimals = 0

    # Initialises an empty grid
    self.Grid = [['ロ' * 40] * 40]

    # Creates 5 animal objects which are added to the AnimalList
    for _ in range(5):
      self.AnimalList.append(Animal())
</code>```

答:
You may want to reconsider the relationship between Animal and Desert.  If you look at the init of the Desert, it should give you some indication.  The Desert have a list of animals, which is a has-a relationship with Animal.  You can read it as, the Desert has a Animal rather than the Animal is a Desert.  From this modeling relationship you may do something like this to access the Desert's grid.

The Desert may have a function that add animal, and that function as you add a new animal you can pass the grid as a parameter to the Animal constructor.  Something like this,

```<code> #Animal __init__
 # Constructor
   def __init__(self, grid):
      ...

 # Desert __init__
 ....
 # Creates 5 animal objects which are added to the AnimalList
 for _ in range(5):
   self.AnimalList.append(Animal(self.Grid))
</code>```

Also remove the inheritance from Desert for Animal.

Body:
I'm working on an OOP task, as we've just been introduced to it.
We are to create two classes: Animal and Desert
They have specified for us a variety of attributes and methods that these classes must have

Desert contains a Grid attribute that some Animal objects should be distributed on.
Animal objects are represented with an 'A' where present on the grid, but also store their position locally, with their attributes Across and Down.

Within __init__ of the Animal class, we are supposed to choose a random position on the Grid to place the animal. This means setting the  Across and Down attributes to a random value but also modifying the Grid to display an 'A' in this location.

I'm not sure how I would go about accessing Grid from the Animal objects though.  Here is the relevant code, the comments relate to the different bullet points of the task:

class Animal(Desert):

  # Constructor
  def __init__(self):

    # Generate a pair of random numbers between 0 and 39.
    rand_num1 = randint(0, 39)
    rand_num2 = randint(0, 39)

    # Place an animal at that random position.
    self.Across = rand_num1
    self.Down = rand_num2
    # HERE IS WHERE I WOULD LIKE TO MODIFY THE GRID ATTRIBUTE OF DESERT

    # Initialise the animal's score to 0.
    self.Score = 0

class Desert:

  # Constructor
  def __init__(self):

    # attributes:
    self.Grid = []
    self.StepCounter = 0
    self.AnimalList = []
    self.NumberofAnimals = 0

    # Initialises an empty grid
    self.Grid = [['ロ' * 40] * 40]

    # Creates 5 animal objects which are added to the AnimalList
    for _ in range(5):
      self.AnimalList.append(Animal())

Body:
You may want to reconsider the relationship between Animal and Desert.  If you look at the init of the Desert, it should give you some indication.  The Desert have a list of animals, which is a has-a relationship with Animal.  You can read it as, the Desert has a Animal rather than the Animal is a Desert.  From this modeling relationship you may do something like this to access the Desert's grid.

The Desert may have a function that add animal, and that function as you add a new animal you can pass the grid as a parameter to the Animal constructor.  Something like this,

 #Animal __init__
 # Constructor
   def __init__(self, grid):
      ...

 # Desert __init__
 ....
 # Creates 5 animal objects which are added to the AnimalList
 for _ in range(5):
   self.AnimalList.append(Animal(self.Grid))

Also remove the inheritance from Desert for Animal.


问:
Spring RequestBody with Postman testing
I am testing my application and i found something weird.

My code:

```<code>  @RequestMapping(value = "/test/{subscriberId}", method = RequestMethod.PATCH, consumes = "application/json", produces = "application/json")
public void test(@PathVariable final String subscriberId,@RequestBody Boolean actDeact ) {
..
}
</code>```

and when i make a request via postman i take 400 bad request:

but when i pass only true in the body everything works fine:

I cant understand why is happening this.

I thought my first try was the valid one. The same is happening if i wait for a String
(i dont get error code 400 but is passing me all the body inside the string)

Can anyone explain it?

答: In principle, you should check the consistency between the use of HTTP methods. In Postman you are using POST, but PATCH in your RequestMapping method.

Title: Spring RequestBody with Postman testing

Body:
I am testing my application and i found something weird.

My code:

  @RequestMapping(value = "/test/{subscriberId}", method = RequestMethod.PATCH, consumes = "application/json", produces = "application/json")
public void test(@PathVariable final String subscriberId,@RequestBody Boolean actDeact ) {
..
}

and when i make a request via postman i take 400 bad request:

but when i pass only true in the body everything works fine:

I cant understand why is happening this.

I thought my first try was the valid one. The same is happening if i wait for a String
(i dont get error code 400 but is passing me all the body inside the string)

Can anyone explain it?


问:
"Failure during raster IO" possibly related to raster size?
I am with very large rasters in R.  I have a code that I have been able to run before, with the same large rasters, but when I try to run my code again for reproducibility, I am getting the same error "Failure during raster IO".

For instance, in this section of a code I am trying to break a large raster (~ 5 GB) into smaller tiles so that I can speed up processing time in R.

```<code>large_raster <- stack("D:/large_raster.tif")
tileno <- 2 # split the large raster into 2 tiles

cl <- makeCluster(3)
registerDoSNOW(cl)
foreach(i = 1:nlayers(large_raster))%dopar%{
  library(raster)
  library(SpaDES)
  removeTmpFiles(h=0)
  newraster <- splitRaster(large_raster[[i]],nx=tileno,ny=1)
  for(j in 1:length(newraster)){
    if(i<10){
      writeRaster(newraster[[j]], filename=paste("D:/large_raster_layer0", i, "_tile", j, ".tif",sep=""))
    }else{
      writeRaster(newraster[[j]],filename=paste("D:/large_raster_layer", i, "_tile", j, ".tif",sep = ""))
    }
  }
}
stopCluster(cl)

#stack tiles
dir <- ("D:/")
for(j in 1:tileno){
  tiles<-list.files(dir,pattern=paste("tile",j,sep=""))
  for(i in 1:length(tiles)){
    r<-raster(paste(dir,tiles[i],sep=""))
    if(i==1){s<-stack(r)
    }else{s<-stack(s,r)}
  }
  writeRaster(s, filename = paste("D:/large_raster_tile", j, ".tif", sep=""))
}
</code>```

But I get the error

```<code>Error in rgdal::getRasterData(object@file@con, offset = offs, region.dim = reg,  :
  Failure during raster IO
</code>```

If I skip the tiling step and just end up working with my 5 GB large_raster I end up getting the error again in this code, where I am creating a new raster called wfps_growSeas by overlaying 2 other rasters called dswe2wfps and swt:

```<code>cl <- makeCluster(3)
registerDoSNOW(cl)

wfps_growSeas <- foreach(j = 1:nlayers(dswe2wfps))%dopar%{
  library(raster)
  overlay(dswe2wfps[[j]],swt[[j]], fun=function (x,y){
    x[y[]<=5]<-0
    return (x)},filename=paste("D:/temp2delete/raster",j, "_", info, ".tif",sep=""),overwrite=TRUE)
}
stopCluster(cl)

wfps_growSeas <- stack(wfps_growSeas)

</code>```

And I get the error:

```<code>Error in { : task 1 failed - "Failure during raster IO
</code>```

Strangely, these errors has happened recently.  A few weeks ago, I was able to run this exact code with these exact same large rasters, and currently, I am able to run these coded using smaller rasters.  I am using R-3.6.2, but colleagues have suggested this error is usually related to sheer raster size and R's memory. This post suggests this error is due to corrupt rasters, but I don't think that's the problem. Any suggestions?

答: probably because you are out of disk space, mostly like in the temp folder. Clean the temp folder and/or set it to a different location. See ?rasterOptions

Body:
I am with very large rasters in R.  I have a code that I have been able to run before, with the same large rasters, but when I try to run my code again for reproducibility, I am getting the same error "Failure during raster IO".

For instance, in this section of a code I am trying to break a large raster (~ 5 GB) into smaller tiles so that I can speed up processing time in R.

large_raster <- stack("D:/large_raster.tif")
tileno <- 2 # split the large raster into 2 tiles

cl <- makeCluster(3)
registerDoSNOW(cl)
foreach(i = 1:nlayers(large_raster))%dopar%{
  library(raster)
  library(SpaDES)
  removeTmpFiles(h=0)
  newraster <- splitRaster(large_raster[[i]],nx=tileno,ny=1)
  for(j in 1:length(newraster)){
    if(i<10){
      writeRaster(newraster[[j]], filename=paste("D:/large_raster_layer0", i, "_tile", j, ".tif",sep=""))
    }else{
      writeRaster(newraster[[j]],filename=paste("D:/large_raster_layer", i, "_tile", j, ".tif",sep = ""))
    }
  }
}
stopCluster(cl)

#stack tiles
dir <- ("D:/")
for(j in 1:tileno){
  tiles<-list.files(dir,pattern=paste("tile",j,sep=""))
  for(i in 1:length(tiles)){
    r<-raster(paste(dir,tiles[i],sep=""))
    if(i==1){s<-stack(r)
    }else{s<-stack(s,r)}
  }
  writeRaster(s, filename = paste("D:/large_raster_tile", j, ".tif", sep=""))
}

But I get the error

Error in rgdal::getRasterData(object@file@con, offset = offs, region.dim = reg,  :
  Failure during raster IO

If I skip the tiling step and just end up working with my 5 GB large_raster I end up getting the error again in this code, where I am creating a new raster called wfps_growSeas by overlaying 2 other rasters called dswe2wfps and swt:

cl <- makeCluster(3)
registerDoSNOW(cl)

wfps_growSeas <- foreach(j = 1:nlayers(dswe2wfps))%dopar%{
  library(raster)
  overlay(dswe2wfps[[j]],swt[[j]], fun=function (x,y){
    x[y[]<=5]<-0
    return (x)},filename=paste("D:/temp2delete/raster",j, "_", info, ".tif",sep=""),overwrite=TRUE)
}
stopCluster(cl)

wfps_growSeas <- stack(wfps_growSeas)

And I get the error:

Error in { : task 1 failed - "Failure during raster IO

Strangely, these errors has happened recently.  A few weeks ago, I was able to run this exact code with these exact same large rasters, and currently, I am able to run these coded using smaller rasters.  I am using R-3.6.2, but colleagues have suggested this error is usually related to sheer raster size and R's memory. This post suggests this error is due to corrupt rasters, but I don't think that's the problem. Any suggestions?


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Should I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

As others have said, if you're not distributing the app to others there is no issue at all.

Normally, you would develop against a standard database API and let the user decide what database to connect to the app. In this case there is no issue. “Your code” wouldn't be linking to libmysqlclient, but it could potentially be combined with a database access module that does link to libmysqlclient.

If you want to distribute an installer that sets up your application and libmysqlclient together, that probably wouldn't count as “mere aggregation”, so it would require you to distribute your app under an open source licence. This needn't, however, necessarily be GPL — see the MySQL FOSS License Exception.

If you want to distribute an installer that sets up your application and the MySQL server itself, the Exception does not apply, so you are limited to GPL only.

Naturally IANAL, and there is certainly still some uncertainty about what counts as derivation especially with regard to dynamic linking. However the above is my understanding of MySQL AB's traditional position on licensing, and I've not heard of any change post-Sun-takeover.

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: bobince

LastEditorDisplayName: bobince


问:
How to Integrate Arc Lengths using python, numpy, and scipy?
On another thread, I saw someone manage to integrate the length of a arc using mathematica.They wrote:

```<code>In[1]:= ArcTan[3.05*Tan[5Pi/18]/2.23]
Out[1]= 1.02051
In[2]:= x=3.05 Cos[t];
In[3]:= y=2.23 Sin[t];
In[4]:= NIntegrate[Sqrt[D[x,t]^2+D[y,t]^2],{t,0,1.02051}]
Out[4]= 2.53143
</code>```

How exactly could this be transferred to python using the imports of numpy and scipy? In particular, I am stuck on line 4 in his code with the "NIntegrate" function. Thanks for the help!

Also, if I already have the arc length and the vertical axis length, how would I be able to reverse the program to spit out the original paremeters from the known values? Thanks!

答:
If you prefer a pure numerical approach, you could use the following barebones solution. This worked well for me given that I had two input numpy.ndarrays, x and y with no functional form available.

import numpy as np

def arclength(x, y, a, b):
    """
    Computes the arclength of the given curve
    defined by (x0, y0), (x1, y1) ... (xn, yn)
    over the provided bounds, `a` and `b`.

    Parameters
    ----------
    x: numpy.ndarray
        The array of x values

    y: numpy.ndarray
        The array of y values corresponding to each value of x

    a: int
        The lower limit to integrate from

    b: int
        The upper limit to integrate to

    Returns
    -------
    numpy.float64
        The arclength of the curve

    """
    bounds = (x >= a) & (y <= b)

    return np.trapz(
        np.sqrt(
            1 + np.gradient(y[bounds], x[bounds])
        ) ** 2),
        x[bounds]
    )
```

Note: I spaced the return variables out that way just to make it more readable and clear to understand the operations taking place.

As an aside, recall that the arc-length of a curve is given by:

Body:
On another thread, I saw someone manage to integrate the length of a arc using mathematica.They wrote:

In[1]:= ArcTan[3.05*Tan[5Pi/18]/2.23]
Out[1]= 1.02051
In[2]:= x=3.05 Cos[t];
In[3]:= y=2.23 Sin[t];
In[4]:= NIntegrate[Sqrt[D[x,t]^2+D[y,t]^2],{t,0,1.02051}]
Out[4]= 2.53143

How exactly could this be transferred to python using the imports of numpy and scipy? In particular, I am stuck on line 4 in his code with the "NIntegrate" function. Thanks for the help!

Also, if I already have the arc length and the vertical axis length, how would I be able to reverse the program to spit out the original paremeters from the known values? Thanks!

Body:
If you prefer a pure numerical approach, you could use the following barebones solution. This worked well for me given that I had two input numpy.ndarrays, x and y with no functional form available.

import numpy as np

def arclength(x, y, a, b):
    """
    Computes the arclength of the given curve
    defined by (x0, y0), (x1, y1) ... (xn, yn)
    over the provided bounds, `a` and `b`.

    Parameters
    ----------
    x: numpy.ndarray
        The array of x values

    y: numpy.ndarray
        The array of y values corresponding to each value of x

    a: int
        The lower limit to integrate from

    b: int
        The upper limit to integrate to

    Returns
    -------
    numpy.float64
        The arclength of the curve

    """
    bounds = (x >= a) & (y <= b)

    return np.trapz(
        np.sqrt(
            1 + np.gradient(y[bounds], x[bounds])
        ) ** 2),
        x[bounds]
    )

Note: I spaced the return variables out that way just to make it more readable and clear to understand the operations taking place.

As an aside, recall that the arc-length of a curve is given by:


问:
zipalign verification failed resources.arsc BAD-1

I try to upload my app to gplay but fail because my apk doesn't zipaligned. i try to zipalign but i got verification failed. really don't have idea, someone please tell me what to do.
thanks in advance.

答:
In case someone else has the same problem with gradle plugin '3.6.0' and later and because I spent several hours trying to track this down.

Gradle Plugin 3.6.0 is page aligning and packaging your native libraries uncompressed
https://developer.android.com/studio/releases/gradle-plugin?hl=el#3-6-0

The fix is to disable the uncompressed packaging of your native libraries by adding

```<code>android:extractNativeLibs="true"
</code>```

to your AndroidManifest.xml as an attribute on the application tag.

Body:
In case someone else has the same problem with gradle plugin '3.6.0' and later and because I spent several hours trying to track this down.

Gradle Plugin 3.6.0 is page aligning and packaging your native libraries uncompressed
https://developer.android.com/studio/releases/gradle-plugin?hl=el#3-6-0

The fix is to disable the uncompressed packaging of your native libraries by adding

android:extractNativeLibs="true"

to your AndroidManifest.xml as an attribute on the application tag.


问:
Creating Dynamic Class for Bitmap containing bitmapData from SWC
I have the following code

```<code>///Get BitmapData from library in SWC
var ClassReference:Class = getDefinitionByName(products[i].producticon+"Data") as Class;
// Create new BitmapData Instance From it
var bitMapS:BitmapData = new ClassReference();
// Create new Class that contains Bitmap Data
var IconBitmap:Class =  new AndroidAsset(bitMapS) as Class;
// Get String name from Class
var s:String = getQualifiedClassName(IconBitmap);
trace(s);
</code>```

I get null in the trace.   How do I make a dynamic class that I can refer to for this bitmap similar to how your reference a class from and embedded media?

答:
I'm not sure I understand you question exactly, but it sounds like you want a way to get a copy of this bitmap data in a manner similar to creating a new instance of a class.  If that's the case, you could do something like this :

```<code>//grab the name of the asset as a string
var bitmapDataAssetName:String = products[i].producticon+"Data";
//get the asset definition from the SWC
var CustomBitmapDataClass:Class = getDefinitionByName(bitmapDataAssetName) as Class;

//store it in an associative array or dictionary for use later
var myBitmaps:Array = [];
myBitmaps[bitmapDataAssetName] = CustomBitmapDataClass;

//then instantiate new bitmaps from the class definition that's stored in your array
var testBitmapData:BitmapData = new (myBitmaps[bitmapDataAssetName] as Class)() as BitmapData;
</code>```

So, in a practical use scenario, your array of symbol definitions would be a member variable on some BitmapManager class or something.  Then if you wanted to make it accessible from anywhere in your application, just make it a singleton, and presto - you can instantiate a new library asset from your SWC anywhere you need it with a call like this:

```<code>var localBitmapData:BitmapData = new (BitmapManager.instance.definitions[theNameOfTheBitmapIWant] as Class)() as BitmapData;
</code>```

Or, a better way to do that would to be to add a method to BitmapManager like

```<code>public function getBitmapAsset(assetName:String):BitmapData {
    var symbolDefinition:Class = myBitmaps[bitmapDataAssetName] as Class;
    return new symbolDefinition() as BitmapData;
}
</code>```

so you could just call it up like this :

```<code>var localBitmapData:BitmapData = BitmapManager.instance.getBitmapAsset("theNameOfTheBitmapIWant");
</code>```

Hope that helps (if that was even you question to begin with) :P

Body:
I have the following code

///Get BitmapData from library in SWC
var ClassReference:Class = getDefinitionByName(products[i].producticon+"Data") as Class;
// Create new BitmapData Instance From it
var bitMapS:BitmapData = new ClassReference();
// Create new Class that contains Bitmap Data
var IconBitmap:Class =  new AndroidAsset(bitMapS) as Class;
// Get String name from Class
var s:String = getQualifiedClassName(IconBitmap);
trace(s);

I get null in the trace.   How do I make a dynamic class that I can refer to for this bitmap similar to how your reference a class from and embedded media?

Body:
I'm not sure I understand you question exactly, but it sounds like you want a way to get a copy of this bitmap data in a manner similar to creating a new instance of a class.  If that's the case, you could do something like this :

//grab the name of the asset as a string
var bitmapDataAssetName:String = products[i].producticon+"Data";
//get the asset definition from the SWC
var CustomBitmapDataClass:Class = getDefinitionByName(bitmapDataAssetName) as Class;

//store it in an associative array or dictionary for use later
var myBitmaps:Array = [];
myBitmaps[bitmapDataAssetName] = CustomBitmapDataClass;

//then instantiate new bitmaps from the class definition that's stored in your array
var testBitmapData:BitmapData = new (myBitmaps[bitmapDataAssetName] as Class)() as BitmapData;

So, in a practical use scenario, your array of symbol definitions would be a member variable on some BitmapManager class or something.  Then if you wanted to make it accessible from anywhere in your application, just make it a singleton, and presto - you can instantiate a new library asset from your SWC anywhere you need it with a call like this:

var localBitmapData:BitmapData = new (BitmapManager.instance.definitions[theNameOfTheBitmapIWant] as Class)() as BitmapData;

Or, a better way to do that would to be to add a method to BitmapManager like

public function getBitmapAsset(assetName:String):BitmapData {
    var symbolDefinition:Class = myBitmaps[bitmapDataAssetName] as Class;
    return new symbolDefinition() as BitmapData;
}

so you could just call it up like this :

var localBitmapData:BitmapData = BitmapManager.instance.getBitmapAsset("theNameOfTheBitmapIWant");

Hope that helps (if that was even you question to begin with) :P


问:
Grid System in CSS
I would like to display 3 white blocks in a blue container. Each with a 10px margin between.

Currently I have this:

                    <t class="f30 helv grey">Create Group</t>

                    <t class="f30 helv-b grey">Group Name</t>

                    <input class="gen-input helv-b">

                    <t class="f30 helv-b grey">Array Type</t>

                    <select class="gen-input helv txtind-10">
                      <option>Option 1</option>
                      <option>Option 2</option>
                    </select>

                    <button class="b_next">Next</button>

```

<pre class="lang-css prettyprint-override"><code>.wbg-create{
    position: absolute;
    width: 84%;
    background-color: #f3fbff;
    border-radius: 50px;
    height: 98vh;
    margin-top: 0px;
    text-align: center;
}
.f30{
    font-size: 30px;
}
.helv{
    font-family: Helvetica Neue;
}
.helv-b{
    font-family: Helvetica Neue;
    font-weight: bold;
}
.grey{
    color: #545454;
}
.gen-input{
    background-color: #e3e8ed;
    height: 50px;
    width: 300px;
    border-radius: 30px;
    border-color: transparent;
    text-align: center;
    font-size: 20px;
}
.txtind-10{
    text-indent: 10px;
}
.full-create{
    margin: 10px;
}
.white-create{
    left: 50%;
    width: 33%;
    background-color: white;
    border-radius: 50px;
    height: 96vh;
}
.b_next{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #cad2e7;
    color: #28284c;
    border-color: transparent;
    bottom: 30px;
}

.b_next:hover{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #dde7ff;
    color: #4e4e95;
    border-color: transparent;
}
.b_next:active{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #ffffff;
    color: #30a3f5;
    border-color: transparent;
}

</code>```

I know this is really messy, and I should be using margin and padding instead of
 but I find it a very long process. My web-app is only run in full-screen and cannot be resized, so it shouldn't be too much of a problem.

How do I get these containers to appear side-by-side?
Currently, there are side-by-side, but they appear below the previous one.

Like this:

```<code>[]-should be here-
  []
    []
</code>```

How can I fix this?

答:
A dirty hack:

```<code>.white-create{display:inline-block;}
</code>```

Better:

Have a look at Common CSS Flexbox Layout Patterns with Example Code

More infos: MDN flexbox

Title: Grid System in CSS

Body:
I would like to display 3 white blocks in a blue container. Each with a 10px margin between.

Currently I have this:

                    <t class="f30 helv grey">Create Group</t>

                    <t class="f30 helv-b grey">Group Name</t>

                    <input class="gen-input helv-b">

                    <t class="f30 helv-b grey">Array Type</t>

                    <select class="gen-input helv txtind-10">
                      <option>Option 1</option>
                      <option>Option 2</option>
                    </select>

                    <button class="b_next">Next</button>

.wbg-create{
    position: absolute;
    width: 84%;
    background-color: #f3fbff;
    border-radius: 50px;
    height: 98vh;
    margin-top: 0px;
    text-align: center;
}
.f30{
    font-size: 30px;
}
.helv{
    font-family: Helvetica Neue;
}
.helv-b{
    font-family: Helvetica Neue;
    font-weight: bold;
}
.grey{
    color: #545454;
}
.gen-input{
    background-color: #e3e8ed;
    height: 50px;
    width: 300px;
    border-radius: 30px;
    border-color: transparent;
    text-align: center;
    font-size: 20px;
}
.txtind-10{
    text-indent: 10px;
}
.full-create{
    margin: 10px;
}
.white-create{
    left: 50%;
    width: 33%;
    background-color: white;
    border-radius: 50px;
    height: 96vh;
}
.b_next{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #cad2e7;
    color: #28284c;
    border-color: transparent;
    bottom: 30px;
}

.b_next:hover{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #dde7ff;
    color: #4e4e95;
    border-color: transparent;
}
.b_next:active{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #ffffff;
    color: #30a3f5;
    border-color: transparent;
}

I know this is really messy, and I should be using margin and padding instead of
 but I find it a very long process. My web-app is only run in full-screen and cannot be resized, so it shouldn't be too much of a problem.

How do I get these containers to appear side-by-side?
Currently, there are side-by-side, but they appear below the previous one.

Like this:

[]-should be here-
  []
    []

How can I fix this?

Body:
A dirty hack:

.white-create{display:inline-block;}

Better:

Have a look at Common CSS Flexbox Layout Patterns with Example Code

More infos: MDN flexbox


问:
i tried to run the following query but it shows syntax error
i tried to run the following query but it shows syntax error</p>

```<code>CREATE TABLE books
(
    book_id INT NOT NULL AUTO_INCREMENT,
    title VARCHAR(100),
    author_fname VARCHAR(100),
    author_lname VARCHAR(100),
    released_year INT,
    stock_quantity INT,
    pages INT,
    PRIMARY KEY(book_id)
);
</code>```

答:
What languange are you using?  That looks correct for mySQL if using SQL it's:</p>

```<code>    CREATE TABLE books
(
    book_id int IDENTITY(1,1) PRIMARY KEY,
    title VARCHAR(100),
    author_fname VARCHAR(100),
    author_lname VARCHAR(100),
    released_year INT,
    stock_quantity INT,
    pages INT
);
</code>```

Body:
i tried to run the following query but it shows syntax error

CREATE TABLE books
(
    book_id INT NOT NULL AUTO_INCREMENT,
    title VARCHAR(100),
    author_fname VARCHAR(100),
    author_lname VARCHAR(100),
    released_year INT,
    stock_quantity INT,
    pages INT,
    PRIMARY KEY(book_id)
);

Body:
What languange are you using?  That looks correct for mySQL if using SQL it's:

    CREATE TABLE books
(
    book_id int IDENTITY(1,1) PRIMARY KEY,
    title VARCHAR(100),
    author_fname VARCHAR(100),
    author_lname VARCHAR(100),
    released_year INT,
    stock_quantity INT,
    pages INT
);


问:
Strange definition and call of a function with curly bracket in Scala (function as parameter of a function)
I'm totally new with Scala, I have to maintain an old code, so I have to understand what it does.

Now I am stuck on this piece of code, it is about defining and calling a method.

This is the definition of the method:

```<code>private def myMethod[I, O](price: Long, id: Int)(i: I)(f: (I, String) => O): O = {
      ..some code..
}
</code>```

this is the method call

```<code>myMethod(price, id)(b) {
      ..some code.. //single line of code, just calling an other function
}
</code>```

I understood the part of having type parameter also of having multiple parameter (currying).

But what I didn't understand, is :

first of all this part: (f: (I, String) => O) , this is completely strange for me

second, why in the method call, it contains code after the { symbol, is it overriding the original method? even it's the case, it make no sense to override it when making the call

also, myMethod is supposed to return a value of type O , but in my code it's never affected to any variable. (EDIT: this point is clear now, I just misunderstood the code, nvm mind about it)

Please can any one clarify this points (especially the first and second one which are making me so confused)

EDIT

```<code>private var x : classX

myMethod(price, id)(b) {
      x.listX //calling method without parameters
}
</code>```

```<code>def listX (param1: ListFaFBI, param2: String): ListX ={
  //returning an Object of type ListX, not a function
}
</code>```

as you can see that myMethod is calling listX. if I understood well, myMethod is returning the method listX itself which has two parameters ListFaFBI (or I) and String and returning ListX (or O) as defined in (f: (I, String) => O)

答:
first of all this part: (f: (I, String) => O) , this is completely strange for me

It is a function, taking a tuple of two elements of type I and String, and returns an O

why in the method call, it contains code after the { symbol, is it overriding the original method?

Your method is using multiple parameter list, and the syntax of the last parameter group is a block definition that allows to define the function value ((I, String) => O)

For example, if we had a method which takes a function in the same parameter list:

```<code>def foo(s: String, f: String => String)
</code>```

Our implementation would look like this:

```<code>foo("hello", {
    s => s + "world"
  }
)
</code>```

However, if we used a separate parameter group:

```<code>def foo(s: String)(f: String => String)
</code>```

Our implementation look like this:

```<code>foo("hello") {
   s => s + "world"
}
</code>```

Which is more eye pleasing and reads nicer.

myMethod is supposed to return a value of type O , but in my code it's never affected to any variable

If you add the implemention of the method we can better help show you where it is returning a value of type O

Body:
I'm totally new with Scala, I have to maintain an old code, so I have to understand what it does.

Now I am stuck on this piece of code, it is about defining and calling a method.

This is the definition of the method:

private def myMethod[I, O](price: Long, id: Int)(i: I)(f: (I, String) => O): O = {
      ..some code..
}

this is the method call

myMethod(price, id)(b) {
      ..some code.. //single line of code, just calling an other function
}

I understood the part of having type parameter also of having multiple parameter (currying).

But what I didn't understand, is :

first of all this part: (f: (I, String) => O) , this is completely strange for me

second, why in the method call, it contains code after the { symbol, is it overriding the original method? even it's the case, it make no sense to override it when making the call

also, myMethod is supposed to return a value of type O , but in my code it's never affected to any variable. (EDIT: this point is clear now, I just misunderstood the code, nvm mind about it)

Please can any one clarify this points (especially the first and second one which are making me so confused)

EDIT

private var x : classX

myMethod(price, id)(b) {
      x.listX //calling method without parameters
}

def listX (param1: ListFaFBI, param2: String): ListX ={
  //returning an Object of type ListX, not a function
}

as you can see that myMethod is calling listX. if I understood well, myMethod is returning the method listX itself which has two parameters ListFaFBI (or I) and String and returning ListX (or O) as defined in (f: (I, String) => O)

Body:
first of all this part: (f: (I, String) => O) , this is completely strange for me

It is a function, taking a tuple of two elements of type I and String, and returns an O

why in the method call, it contains code after the { symbol, is it overriding the original method?

Your method is using multiple parameter list, and the syntax of the last parameter group is a block definition that allows to define the function value ((I, String) => O)

For example, if we had a method which takes a function in the same parameter list:

def foo(s: String, f: String => String)

Our implementation would look like this:

foo("hello", {
    s => s + "world"
  }
)

However, if we used a separate parameter group:

def foo(s: String)(f: String => String)

Our implementation look like this:

foo("hello") {
   s => s + "world"
}

Which is more eye pleasing and reads nicer.

myMethod is supposed to return a value of type O , but in my code it's never affected to any variable

If you add the implemention of the method we can better help show you where it is returning a value of type O


问:
Is it possible to run a greater than query in AWS DynamoDB?
Let's say I have my DynamoDB table like this, with Order ID as the primary key. :

The Order ID increments by one, everytime I add/put a new item.

Now, I have one number, let's say 1000, and my user wants to get all the items which have Order ID > 1000.
So the items returned would be 1001, 1002, 1003, and so on till the last one.

My requirement is as simple as it seems - but is this thing possible to do with Query method of AWS DynamoDB?

Any help is appreciated :)
Thanks!

答:
There's currently no way to filter on partition key, but I can suggest a way that you can achieve what you want.

You're heading in the right direction with Query which has a "greater than" operator. However, it only operates on the sort key attribute.

With Query, you essentially choose a single partition key, and provide a filter expression that is applied to the sort key of items within that partition.

Since your partition key is currently "Order ID?", you'll need to add a Global Secondary Index to query the way you want.

Without knowing more about your access patterns, I'd suggest you add a Global Secondary Index using "From" as the partition key, which I assume is the user ID. You can then use "Order ID" as the sort key.

my user wants to get all the items which have Order ID > 1000.

With the GSI in place, you can achieve this by doing a query for items where "User ID" is userId and "Order ID" > orderId.

You can find more on query here, details on adding a GSI here, and more info on choosing a partition key here.


问:
JSON in React Native FlatList
I want parse Woocomerce API response in React Native.

Can any one tell how to parse id, name, categories array and images array in React Native FlatList from JSON response mention below.

```<code>{
   "id":794,
   "name":"Premium Quality",
   "catalog_visibility":"visible",
   "price":"21.99",
   "regular_price":"21.99",
   "sale_price":"",
   "categories":[
      {
         "id":9,
         "name":"Clothing",
         "slug":"clothing"
      },
      {
         "id":14,
         "name":"T-shirts",
         "slug":"t-shirts"
      }
   ],
   "tags":[

   ],
   "images":[
      {
         "id":792,
         "date_created":"2017-03-23T14:01:13",
         "date_created_gmt":"2017-03-23T20:01:13",
         "date_modified":"2017-03-23T14:01:13",
         "date_modified_gmt":"2017-03-23T20:01:13",
         "src":"https://example.com/wp-content/uploads/2017/03/T_2_front-4.jpg",
         "name":"",
         "alt":""
      },
      {
         "id":793,
         "date_created":"2017-03-23T14:01:14",
         "date_created_gmt":"2017-03-23T20:01:14",
         "date_modified":"2017-03-23T14:01:14",
         "date_modified_gmt":"2017-03-23T20:01:14",
         "src":"https://example.com/wp-content/uploads/2017/03/T_2_back-2.jpg",
         "name":"",
         "alt":""
      }
   ]
}
</code>```

答:
You can store the JSON inside a var (eg. myJSON), and do JSON.parse in FlatList prop.

This is the simplest way. After achieve that, you can improve performance using useEffect and useState to avoid unnecessary re-render.

import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text } from 'react-native';

// JSON.stringify only used here to simulate a true JSON
const myJson = JSON.stringify([
  {
    "id": 794,
    "name": "Premium Quality",
    "catalog_visibility": "visible",
    "price": "21.99",
    "regular_price": "21.99",
    "sale_price": "",
    "categories": [
      {
        "id": 9,
        "name": "Clothing",
        "slug": "clothing"
      },
      {
        "id": 14,
        "name": "T-shirts",
        "slug": "t-shirts"
      }
    ],
    "tags": [],
    "images": [
      {
        "id": 792,
        "date_created": "2017-03-23T14:01:13",
        "date_created_gmt": "2017-03-23T20:01:13",
        "date_modified": "2017-03-23T14:01:13",
        "date_modified_gmt": "2017-03-23T20:01:13",
        "src": "https://example.com/wp-content/uploads/2017/03/T_2_front-4.jpg",
        "name": "",
        "alt": ""
      },
      {
        "id": 793,
        "date_created": "2017-03-23T14:01:14",
        "date_created_gmt": "2017-03-23T20:01:14",
        "date_modified": "2017-03-23T14:01:14",
        "date_modified_gmt": "2017-03-23T20:01:14",
        "src": "https://example.com/wp-content/uploads/2017/03/T_2_back-2.jpg",
        "name": "",
        "alt": ""
      }
    ]
  }
]);

function Item({ item }) {
  return (
    <View style={styles.item}>
      <Text style={styles.title}>{item.name} - {item.price}</Text>

      <View style={{ flex: 1 }}>
        <Text>Categories: </Text>

        {item.categories.map((category) => {
          return (
            <Text>{category.name}</Text>
          )
        })}
      </View>

      <View style={{ flex: 1 }}>
        <Text>Images: </Text>

        {item.images.map((image) => {
          return (
            <Text>Image src: {image.src}</Text>
          )
        })}
      </View>
    </View>
  );
}

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={JSON.parse(myJson)}
        renderItem={Item}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

```

Title: JSON in React Native FlatList

Body:
I want parse Woocomerce API response in React Native.

Can any one tell how to parse id, name, categories array and images array in React Native FlatList from JSON response mention below.

{
   "id":794,
   "name":"Premium Quality",
   "catalog_visibility":"visible",
   "price":"21.99",
   "regular_price":"21.99",
   "sale_price":"",
   "categories":[
      {
         "id":9,
         "name":"Clothing",
         "slug":"clothing"
      },
      {
         "id":14,
         "name":"T-shirts",
         "slug":"t-shirts"
      }
   ],
   "tags":[

   ],
   "images":[
      {
         "id":792,
         "date_created":"2017-03-23T14:01:13",
         "date_created_gmt":"2017-03-23T20:01:13",
         "date_modified":"2017-03-23T14:01:13",
         "date_modified_gmt":"2017-03-23T20:01:13",
         "src":"https://example.com/wp-content/uploads/2017/03/T_2_front-4.jpg",
         "name":"",
         "alt":""
      },
      {
         "id":793,
         "date_created":"2017-03-23T14:01:14",
         "date_created_gmt":"2017-03-23T20:01:14",
         "date_modified":"2017-03-23T14:01:14",
         "date_modified_gmt":"2017-03-23T20:01:14",
         "src":"https://example.com/wp-content/uploads/2017/03/T_2_back-2.jpg",
         "name":"",
         "alt":""
      }
   ]
}