问:
How to solve "undefined is not an object (evaluating 'Object.keys(_routers.CommonActions)')" in react-native navigation?

Description

I am trying to create a react-native app with expo using @react-navigation. The navigation worked but after I recently did some dependency-updates (with care to not update required dependencies), my navigation broke. When I am running the expo client in my phone, I just get

```<code>undefined is not an object (evaluating 'Object.keys(_routers.CommonActions)')
* [native code]:null in keys
- node_modules/@react-navigation/core/src/BaseNavigationContainer.tsx:240:35 in React.useImperativeHandle$argument_1
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:11228:23 in imperativeHandleEffect
* [native code]:null in imperativeHandleEffect
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:16921:31 in commitHookEffectList
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:16989:27 in commitLifeCycles
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:20002:23 in commitLayoutEffects
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:307:15 in invokeGuardedCallbackImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:531:36 in invokeGuardedCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19768:10 in commitRootImpl
* [native code]:null in commitRootImpl
- node_modules/react-native/node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19590:4 in commitRoot
* [native code]:null in commitRoot
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18709:28 in runRootCallback
* [native code]:null in runRootCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5642:32 in runWithPriority$argument_1
- node_modules/react-native/node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5638:22 in flushSyncCallbackQueueImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5627:28 in flushSyncCallbackQueue
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18556:30 in scheduleUpdateOnFiber
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:21822:15 in scheduleRootUpdate
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:23042:20 in ReactNativeRenderer.render
- node_modules/react-native/Libraries/ReactNative/renderApplication.js:52:52 in renderApplication
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:116:10 in runnables.appKey.run
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:197:26 in runApplication
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
</code>```

I tried to follow https://reactnavigation.org/docs/en/hello-react-navigation.html and don't know what to do.

Code

My App.tsx looks like that:

```<code>import 'react-native-gesture-handler';
import React from 'react';
// navigation
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
// screens
import { LoginScreen } from './src/components/screens/login-screen';
import { DashboardScreen } from './src/components/screens/dashboard-screen';
import { SplashScreen } from './src/components/screens/spash-screen';
// graphql
import { ApolloProvider } from '@apollo/react-hooks';
import { ApolloClient, HttpLink, InMemoryCache } from 'apollo-boost';

// create stack navigator
const Stack = createStackNavigator();

// graphql stack
const cache = new InMemoryCache();
const client = new ApolloClient({cache, link: new HttpLink({ uri: 'http://192.168.0.52:3000' }), });

/** main app */
export default function App() {
    return(
        <ApolloProvider client={ client }>
            <NavigationContainer>
                <Stack.Navigator>
                    <Stack.Screen name={'splashscreen'} component={SplashScreen} options={{ headerShown: false }} />
                    <Stack.Screen name={'dashboard'} component={DashboardScreen} options={{ headerShown: false }} />
                    <Stack.Screen name={'login'} component={LoginScreen} options={{ headerShown: false }} />
                </Stack.Navigator>
            </NavigationContainer>
        </ApolloProvider>
    );
}

</code>```

and my components navigate like that:

```<code><View style={styles.container}>
    <Button title={ 'Login' } onPress={ () => {
        this.props.navigation.dispatch(StackActions.push('login'))
    } } />
</View>
</code>```

My Repository with the full code: https://github.com/vampyre-io/vampyre-app

and finally my package.json-dependencies:

```<code>  "dependencies": {
    "@apollo/react-hooks": "^3.1.3",
    "@react-native-community/masked-view": "0.1.5",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/routers": "^5.0.1",
    "@react-navigation/stack": "^5.0.5",
    "apollo-boost": "^0.4.7",
    "apollo-client": "^2.6.8",
    "expo": "~36.0.2",
    "graphql": "^14.6.0",
    "graphql-tag": "^2.10.3",
    "react": "~16.9.0",
    "react-dom": "~16.12.0",
    "react-native": "^0.61.5",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-safe-area-context": "^0.6.0",
    "react-native-screens": "2.0.0-alpha.12"
  },
</code>```

答:
Can you remove */routers from your dependencies?

And then run npm install/yarn and expo start -c

Body:
Description

I am trying to create a react-native app with expo using @react-navigation. The navigation worked but after I recently did some dependency-updates (with care to not update required dependencies), my navigation broke. When I am running the expo client in my phone, I just get

undefined is not an object (evaluating 'Object.keys(_routers.CommonActions)')
* [native code]:null in keys
- node_modules/@react-navigation/core/src/BaseNavigationContainer.tsx:240:35 in React.useImperativeHandle$argument_1
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:11228:23 in imperativeHandleEffect
* [native code]:null in imperativeHandleEffect
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:16921:31 in commitHookEffectList
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:16989:27 in commitLifeCycles
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:20002:23 in commitLayoutEffects
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:307:15 in invokeGuardedCallbackImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:531:36 in invokeGuardedCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19768:10 in commitRootImpl
* [native code]:null in commitRootImpl
- node_modules/react-native/node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19590:4 in commitRoot
* [native code]:null in commitRoot
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18709:28 in runRootCallback
* [native code]:null in runRootCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5642:32 in runWithPriority$argument_1
- node_modules/react-native/node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5638:22 in flushSyncCallbackQueueImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5627:28 in flushSyncCallbackQueue
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18556:30 in scheduleUpdateOnFiber
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:21822:15 in scheduleRootUpdate
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:23042:20 in ReactNativeRenderer.render
- node_modules/react-native/Libraries/ReactNative/renderApplication.js:52:52 in renderApplication
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:116:10 in runnables.appKey.run
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:197:26 in runApplication
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

I tried to follow https://reactnavigation.org/docs/en/hello-react-navigation.html and don't know what to do.

Code

My App.tsx looks like that:

import 'react-native-gesture-handler';
import React from 'react';
// navigation
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
// screens
import { LoginScreen } from './src/components/screens/login-screen';
import { DashboardScreen } from './src/components/screens/dashboard-screen';
import { SplashScreen } from './src/components/screens/spash-screen';
// graphql
import { ApolloProvider } from '@apollo/react-hooks';
import { ApolloClient, HttpLink, InMemoryCache } from 'apollo-boost';

// create stack navigator
const Stack = createStackNavigator();

// graphql stack
const cache = new InMemoryCache();
const client = new ApolloClient({cache, link: new HttpLink({ uri: 'http://192.168.0.52:3000' }), });

/** main app */
export default function App() {
    return(
        <ApolloProvider client={ client }>
            <NavigationContainer>
                <Stack.Navigator>
                    <Stack.Screen name={'splashscreen'} component={SplashScreen} options={{ headerShown: false }} />
                    <Stack.Screen name={'dashboard'} component={DashboardScreen} options={{ headerShown: false }} />
                    <Stack.Screen name={'login'} component={LoginScreen} options={{ headerShown: false }} />
                </Stack.Navigator>
            </NavigationContainer>
        </ApolloProvider>
    );
}

and my components navigate like that:

<View style={styles.container}>
    <Button title={ 'Login' } onPress={ () => {
        this.props.navigation.dispatch(StackActions.push('login'))
    } } />
</View>

My Repository with the full code: https://github.com/vampyre-io/vampyre-app

and finally my package.json-dependencies:

  "dependencies": {
    "@apollo/react-hooks": "^3.1.3",
    "@react-native-community/masked-view": "0.1.5",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/routers": "^5.0.1",
    "@react-navigation/stack": "^5.0.5",
    "apollo-boost": "^0.4.7",
    "apollo-client": "^2.6.8",
    "expo": "~36.0.2",
    "graphql": "^14.6.0",
    "graphql-tag": "^2.10.3",
    "react": "~16.9.0",
    "react-dom": "~16.12.0",
    "react-native": "^0.61.5",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-safe-area-context": "^0.6.0",
    "react-native-screens": "2.0.0-alpha.12"
  },


来源: stackexchange

问:
405 on POST request, unsupported method is GET
I'm having a bit of a fight with the following problem, I have a ASP.NET Web API, when making one of the POST requests on the development machine, I get the expected output from it, but after deploying it on IIS, I get the response

```<code>"message": "The requested resource does not support http method 'GET'."
</code>```

The input I give via Postman looks as follows

I've read the following post, but I didn't get much out of it after poking around in IIS for a while.https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

Start of the method looks as follows

```<code>    [HttpPost]
    [Route("something/CandidatePersonal")]
    public IHttpActionResult PostCandidatePersonal(CanPersonal apiPostInput)
</code>```

and it returns an OK statement considering everything goes well.

答: Regarding your scenario, you need to add [AcceptVerbs("GET", "POST")] on your API method.

ContentLicense: CC BY-SA 4.0

Body:
I'm having a bit of a fight with the following problem, I have a ASP.NET Web API, when making one of the POST requests on the development machine, I get the expected output from it, but after deploying it on IIS, I get the response

"message": "The requested resource does not support http method 'GET'."

The input I give via Postman looks as follows

I've read the following post, but I didn't get much out of it after poking around in IIS for a while.https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

Start of the method looks as follows

    [HttpPost]
    [Route("something/CandidatePersonal")]
    public IHttpActionResult PostCandidatePersonal(CanPersonal apiPostInput)

and it returns an OK statement considering everything goes well.


问:
ResourceAccessException when trying to execute a post service
I am getting this exception
org.springframework.web.client.ResourceAccessException
I/O error on POST request for \"http://host.docker.internal:8073/user-management/users/login\": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect",
My code looks like this

```<code>@Resource(name="restTemp")
    private RestTemplate restTemplate;

String url = "user-management/users/login";
        //String fullUrl = "https://localhost:8073/user-management/users/login";
        InstanceInfo instance = eurekaClient.getNextServerFromEureka("user-management", false);
        LoginRequest user =  restTemplate.postForObject(instance.getHomePageUrl()+url, loginRequest, LoginRequest.class);
</code>```

Also I dont understand why instance.getHomePageUrl() generates a internal docker url . what could be the reason behind this docker desktop is running.
I need help in resolving this exception.According to what I could find this exception occurs when we are trying to access a third party url

答: Just try increasing the context timeout for request sent by RestTemplate</p>

Body:
I am getting this exception
org.springframework.web.client.ResourceAccessException
I/O error on POST request for \"http://host.docker.internal:8073/user-management/users/login\": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect",
My code looks like this

@Resource(name="restTemp")
    private RestTemplate restTemplate;

String url = "user-management/users/login";
        //String fullUrl = "https://localhost:8073/user-management/users/login";
        InstanceInfo instance = eurekaClient.getNextServerFromEureka("user-management", false);
        LoginRequest user =  restTemplate.postForObject(instance.getHomePageUrl()+url, loginRequest, LoginRequest.class);

Also I dont understand why instance.getHomePageUrl() generates a internal docker url . what could be the reason behind this docker desktop is running.
I need help in resolving this exception.According to what I could find this exception occurs when we are trying to access a third party url


问:
How to filter nodes or edges with special character in Networkx graph
I have the following NetworkX graph, G. I would like to filter only nodes having special characters for example (A/B and B/C) or edges (A/B, B/C) excluding others.

I have tried with this but it is printing all information.

```<code>G.nodes()
A,A/B, C, B/C, D
</code>```

and

```<code>G.edges()
(A,A/B),(A,C), (A/B, B/C), (C,B/C), (B/C,D)
</code>```

But I would like to get only A/B and B/C as mentioned above by excluding others.

Is there any way to do this in networkx python? Any solution is appreciated!

答:
You can filter out the nodes, using the following code and simply use nx.subgraph function to get the subgraph.</p>

```<code>import networkx as nx

G = nx.DiGraph()

G.add_edge('A', 'C')
G.add_edge('A', 'A/B')
G.add_edge('A', 'C')
G.add_edge('A/B', 'B/C')
G.add_edge('C', 'B/C')
G.add_edge('B/C', 'D')

# This will pick up nodes containing any
# special character in them
from string import punctuation
special_chars = set(punctuation)

all_nodes = G.nodes()

special_nodes = []
for node in all_nodes:
    for ch in special_chars:
        if ch in node:
            special_nodes.append(node)
            break

H = nx.subgraph(G, special_nodes)

H.nodes()
# NodeView(('A/B', 'B/C'))

H.edges()
# OutEdgeView([('A/B', 'B/C')])
</code>```

Body:
I have the following NetworkX graph, G. I would like to filter only nodes having special characters for example (A/B and B/C) or edges (A/B, B/C) excluding others.

I have tried with this but it is printing all information.

G.nodes()
A,A/B, C, B/C, D

and

G.edges()
(A,A/B),(A,C), (A/B, B/C), (C,B/C), (B/C,D)

But I would like to get only A/B and B/C as mentioned above by excluding others.

Is there any way to do this in networkx python? Any solution is appreciated!

Body:
You can filter out the nodes, using the following code and simply use nx.subgraph function to get the subgraph.

import networkx as nx

G = nx.DiGraph()

G.add_edge('A', 'C')
G.add_edge('A', 'A/B')
G.add_edge('A', 'C')
G.add_edge('A/B', 'B/C')
G.add_edge('C', 'B/C')
G.add_edge('B/C', 'D')

# This will pick up nodes containing any
# special character in them
from string import punctuation
special_chars = set(punctuation)

all_nodes = G.nodes()

special_nodes = []
for node in all_nodes:
    for ch in special_chars:
        if ch in node:
            special_nodes.append(node)
            break

H = nx.subgraph(G, special_nodes)

H.nodes()
# NodeView(('A/B', 'B/C'))

H.edges()
# OutEdgeView([('A/B', 'B/C')])


问:
Switching to an iframe on android native and web app using appium via ROBOT framework
Hi I have been searching a lot on the internet to find how i am supposed to switch from web or native context view to an iframe. I am trying to automate a user logging into an app and the third piece of identification is generating a OTP. This happens to be inside an iframe and i have tried quite a few things to interact with it. Firstly I cannot find any good documentation on how to achieve this through keywords (Appium) using robot, and i do not have a lot of programming experience to write it in python then call it but i have tried.

First thing i tried was using the keyword 'switch to context' and 'get contexts' which i am already using to switch between native and webview already:

```<code>List Contexts
${contexts}=                              Get Contexts
${native}=                                Get From List           ${contexts}           0
${webview}=                               Get From List           ${contexts}           1  #-1
${chromeviewiframe}                       get from list           ${contexts}           -1  #1
Set Test Variable                         ${native}
Set Test Variable                         ${webview}
set test variable                         ${chromeviewiframe}

#Test Case code
sleep 60
list contexts
switch to context  ${chromeviewiframe}
wait until element is visible  xpath=//*[@id="btnSMS"]  30
click element  xpath=//*[@id="btnSMS"]
</code>```

However it never finds the iframe or button and therefore times out - I am not sure if 'get contexts' can be used to find iframes.

I have also tried to put the little bit of code appium supplied on their page into a python file in which i intended to call and hoped that would switch frames but didnt succeed at this attempt

```<code>#no idea what library's i am supposed to import and if the return makes sense?
class _frames():
def frame (self):
self.driver.switch_to.frame(3)
return   self.driver.switch_to.frame(3)
</code>```

My iframe xpath is (x'd out some characters) #iframe   //*[@id="xxx2iframe"]

I have been having errors such as:

The phone is still activate and connection isnt lost but i think it just cant find the iframe context - I cant properly test the python file as the code isn't compelete and im not sure what i need to do to fix it to test that 'solution' out. I also wondered if i had another file calling selenium and call the switch frame keyword would it work for appium automation as they use the same drivers? I assume not?

Help to figure this out would be much appreciated, there isn't much point in me writing automation test cases if i cannot get it to automatically log in and get past this point.

Kind Regards, Jem

答: Please set your default browser as Chrome and then restart the device. The webviews will be automatically detected by Appium after that.</p>

Body:
Hi I have been searching a lot on the internet to find how i am supposed to switch from web or native context view to an iframe. I am trying to automate a user logging into an app and the third piece of identification is generating a OTP. This happens to be inside an iframe and i have tried quite a few things to interact with it. Firstly I cannot find any good documentation on how to achieve this through keywords (Appium) using robot, and i do not have a lot of programming experience to write it in python then call it but i have tried.

First thing i tried was using the keyword 'switch to context' and 'get contexts' which i am already using to switch between native and webview already:

List Contexts
${contexts}=                              Get Contexts
${native}=                                Get From List           ${contexts}           0
${webview}=                               Get From List           ${contexts}           1  #-1
${chromeviewiframe}                       get from list           ${contexts}           -1  #1
Set Test Variable                         ${native}
Set Test Variable                         ${webview}
set test variable                         ${chromeviewiframe}

#Test Case code
sleep 60
list contexts
switch to context  ${chromeviewiframe}
wait until element is visible  xpath=//*[@id="btnSMS"]  30
click element  xpath=//*[@id="btnSMS"]

However it never finds the iframe or button and therefore times out - I am not sure if 'get contexts' can be used to find iframes.

I have also tried to put the little bit of code appium supplied on their page into a python file in which i intended to call and hoped that would switch frames but didnt succeed at this attempt

#no idea what library's i am supposed to import and if the return makes sense?
class _frames():
def frame (self):
self.driver.switch_to.frame(3)
return   self.driver.switch_to.frame(3)

My iframe xpath is (x'd out some characters) #iframe   //*[@id="xxx2iframe"]

I have been having errors such as:

The phone is still activate and connection isnt lost but i think it just cant find the iframe context - I cant properly test the python file as the code isn't compelete and im not sure what i need to do to fix it to test that 'solution' out. I also wondered if i had another file calling selenium and call the switch frame keyword would it work for appium automation as they use the same drivers? I assume not?

Help to figure this out would be much appreciated, there isn't much point in me writing automation test cases if i cannot get it to automatically log in and get past this point.

Kind Regards, Jem


问:
Vert.x data access benefits over CompletableFuture.supplyAsync with JDBC
What are the benefits of using a vert.x data access library for connecting to a database (for example Reactive PostgreSQL client) over CompletableFuture.supplyAsync with JDBC in terms of thread management.

Let's assume that we have a web application.
In both cases the request thread would not be blocked while waiting for the database, so then why would someone use the vert.x driver over the official jdbc?

For example in JDBC:

```<code>String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("ssl","true");

CompletableFuture.supplyAsync(() -> {
    Connection conn = DriverManager.getConnection(url, props);

    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
    while (rs.next())
    {
        System.out.print("Column 1 returned ");
        System.out.println(rs.getString(1));
    }
    rs.close();
    st.close();
});
</code>```

In vert.x

```<code>PgConnectOptions connectOptions = new PgConnectOptions()
  .setPort(5432)
  .setHost("the-host")
  .setDatabase("the-db")
  .setUser("user")
  .setPassword("secret");

// Pool options
PoolOptions poolOptions = new PoolOptions()
  .setMaxSize(5);

// Create the client pool
PgPool client = PgPool.pool(connectOptions, poolOptions);

// A simple query
client.query("SELECT * FROM users WHERE id='julien'", ar -> {
  if (ar.succeeded()) {
    RowSet<Row> result = ar.result();
    System.out.println("Got " + result.size() + " rows ");
  } else {
    System.out.println("Failure: " + ar.cause().getMessage());
  }

  // Now close the pool
  client.close();
});
</code>```

答:
Indeed, in both cases, the caller thread will not be blocked.

But in the first case, the task is handed over to a thread from a pool (in your example, the JDK's internal pool) while in the second case, the Reactive Pg Client operates asynchronously and invokes the provided callback when the results are ready.

Threads comes with a cost (memory, context switches). So if your applications need to handle a lot of requests with lower resources, the Reactive Pg Client can be a better option.

Body:
What are the benefits of using a vert.x data access library for connecting to a database (for example Reactive PostgreSQL client) over CompletableFuture.supplyAsync with JDBC in terms of thread management.

Let's assume that we have a web application.
In both cases the request thread would not be blocked while waiting for the database, so then why would someone use the vert.x driver over the official jdbc?

For example in JDBC:

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("ssl","true");

CompletableFuture.supplyAsync(() -> {
    Connection conn = DriverManager.getConnection(url, props);

    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
    while (rs.next())
    {
        System.out.print("Column 1 returned ");
        System.out.println(rs.getString(1));
    }
    rs.close();
    st.close();
});

In vert.x

PgConnectOptions connectOptions = new PgConnectOptions()
  .setPort(5432)
  .setHost("the-host")
  .setDatabase("the-db")
  .setUser("user")
  .setPassword("secret");

// Pool options
PoolOptions poolOptions = new PoolOptions()
  .setMaxSize(5);

// Create the client pool
PgPool client = PgPool.pool(connectOptions, poolOptions);

// A simple query
client.query("SELECT * FROM users WHERE id='julien'", ar -> {
  if (ar.succeeded()) {
    RowSet<Row> result = ar.result();
    System.out.println("Got " + result.size() + " rows ");
  } else {
    System.out.println("Failure: " + ar.cause().getMessage());
  }

  // Now close the pool
  client.close();
});


问:
jsvc.exec error: Still running according to PID file
Running my Java service using jsvc on Linux (Ubuntu) 10.04.4 LTS and when I stop service and requests and then hung, checked log to find jsvc exec error below.

14/03/2014 12:49:48 19831 jsvc.exec error: Still running according to PID file /home/user/tmp/example.pid, PID is 19728
14/03/2014 12:49:48 19830 jsvc.exec error: Service exit with a return value of 122

Any idea ?

Thanks,

答:
Try to run below command. Here 19728 is the process id.

```<code>pkill -9 19728
</code>```

Now start your process. It will work.

This will solve your problem.

Thank you.

ContentLicense: CC BY-SA 3.0

Body:
Try to run below command. Here 19728 is the process id.

pkill -9 19728

Now start your process. It will work.

This will solve your problem.

Thank you.


问:
Convert String to boolean only if input is "true" or "false"
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

```<code>String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");
</code>```

答:
A little bit more modern (requires --enable-preview option to compile/run):

var result = switch (input) {
    case "true"  -> true;
    case "false" -> false;
    default      -> throw new InvalidInputException ("true or false is allowed");
};
```

<p>for case insensitive convertion:</p>

<pre class="lang-java prettyprint-override"><code>var result = switch (input.toLowerCase()) {
    case "true"  -> true;
    case "false" -> false;
    default      -> throw new InvalidInputException ("true or false is allowed");
};
</code>```

Note: eventually missing check for null

Body:
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");

Body:
A little bit more modern (requires --enable-preview option to compile/run):

var result = switch (input) {
    case "true"  -> true;
    case "false" -> false;
    default      -> throw new InvalidInputException ("true or false is allowed");
};

for case insensitive convertion:

var result = switch (input.toLowerCase()) {
    case "true"  -> true;
    case "false" -> false;
    default      -> throw new InvalidInputException ("true or false is allowed");
};

Note: eventually missing check for null


问:
Calling Delete Service not working in Angular
ListStore.ts file

```<code>export class ListstoreComponent implements OnInit {
  rawlist;
  name = '';
  id = '';
  storeid = "";
  store: Store;

  constructor(private api: APIService, private router: Router, private route: ActivatedRoute, private cookieService: CookieService) { }

  ngOnInit() {
    this.storelist();

  }

  //store list
  async storelist() {
    this.rawlist = await this.api.ListStores();
    this.storelist = this.rawlist.items;
  }
  //delete list
  async deleteStore(id) {
  if (window.confirm('Are you sure, you want to delete?')){
    await this.api.DeleteStore(id).catch(data => {
      this.rawlist();
    })
  }
}
</code>```

HTML File

```<code> <button type="button" class="btn btn-primary btn-gap" (click)="deleteStore(Store.id)">Close Ticket</button>
</code>```

I'm deleting the list and updating database. But I am not quite sure if catch() would work or not. I've tried subscribe but didn't work

答:
Your event handler should handle the async nature of the call rather than leaking it up to the HTML.

```<code>deleteStore(id): void {
  if (!window.confirm('Are you sure, you want to delete?')){
    return;
  }

  this.api.DeleteStore(id).then(message => {
    // handle response
  });
}
</code>```

Edit:

You could handle it in the HTML, but you would have to return a promise from your event handler, and you would end up with more code in you HTML than there should be.

If you're really keen to use the async await syntax, the following would be equivalent:

```<code>async deleteStore(id): void {
  if (!window.confirm('Are you sure, you want to delete?')){
    return;
  }

  const message = await this.api.DeleteStore(id);
  // handle response
}
</code>```

Body:
ListStore.ts file

export class ListstoreComponent implements OnInit {
  rawlist;
  name = '';
  id = '';
  storeid = "";
  store: Store;

  constructor(private api: APIService, private router: Router, private route: ActivatedRoute, private cookieService: CookieService) { }

  ngOnInit() {
    this.storelist();

  }

  //store list
  async storelist() {
    this.rawlist = await this.api.ListStores();
    this.storelist = this.rawlist.items;
  }
  //delete list
  async deleteStore(id) {
  if (window.confirm('Are you sure, you want to delete?')){
    await this.api.DeleteStore(id).catch(data => {
      this.rawlist();
    })
  }
}

HTML File

 <button type="button" class="btn btn-primary btn-gap" (click)="deleteStore(Store.id)">Close Ticket</button>

I'm deleting the list and updating database. But I am not quite sure if catch() would work or not. I've tried subscribe but didn't work

Body:
Your event handler should handle the async nature of the call rather than leaking it up to the HTML.

deleteStore(id): void {
  if (!window.confirm('Are you sure, you want to delete?')){
    return;
  }

  this.api.DeleteStore(id).then(message => {
    // handle response
  });
}

Edit:

You could handle it in the HTML, but you would have to return a promise from your event handler, and you would end up with more code in you HTML than there should be.

If you're really keen to use the async await syntax, the following would be equivalent:

async deleteStore(id): void {
  if (!window.confirm('Are you sure, you want to delete?')){
    return;
  }

  const message = await this.api.DeleteStore(id);
  // handle response
}


问:
Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4
Thanks to a Dropwizard Maven archetype I generated a sample Dropwizard Maven project. The pom.xml notably uses maven-source-plugin:

```<code><plugin>
    <artifactId>maven-source-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
           <id>attach-sources</id>
           <goals>
              <goal>jar</goal>
           </goals>
        </execution>
    </executions>
</plugin>
</code>```

When I run "clean install" I have the following error :

Plugin org.apache.maven.plugins:maven-source-plugin:2.4 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4: Could not transfer artifact org.apache.maven.plugins:maven-source-plugin:pom:2.4 from/to central (http://repo.maven.apache.org/maven2): Connection refused: connect -> [Help 1]

The "maven-source-plugin" dependency is stored in the Nexus repository of my company. So I tried the adding of the plugin dependency between dependencies and /dependencies :

```<code><dependencies>
    ...
    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.4</version>
    </dependency>
</dependencies>
</code>```

but it did not correct the problem. I also tried to add the dependency at the call of the plugin :

```<code> <plugin>
    <artifactId>maven-source-plugin</artifactId>
    <version>2.4</version>
    <executions>
       <execution>
           <id>attach-sources</id>
           <goals>
              <goal>jar</goal>
           </goals>
       </execution>
      </executions>
      <dependencies>
          <dependency>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-source-plugin</artifactId>
              <version>2.4</version>
          </dependency>
     </dependencies>
 </plugin>
</code>```

but it did not work either

答: I am using JDK 7 for maven project and I used -Dhttps.protocols=TLSv1.2 as argument in JRE. It has allowed to download all maven repository which were failing earlier.</p>

Body:
Thanks to a Dropwizard Maven archetype I generated a sample Dropwizard Maven project. The pom.xml notably uses maven-source-plugin:

<plugin>
    <artifactId>maven-source-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
           <id>attach-sources</id>
           <goals>
              <goal>jar</goal>
           </goals>
        </execution>
    </executions>
</plugin>

When I run "clean install" I have the following error :

Plugin org.apache.maven.plugins:maven-source-plugin:2.4 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4: Could not transfer artifact org.apache.maven.plugins:maven-source-plugin:pom:2.4 from/to central (http://repo.maven.apache.org/maven2): Connection refused: connect -> [Help 1]

The "maven-source-plugin" dependency is stored in the Nexus repository of my company. So I tried the adding of the plugin dependency between dependencies and /dependencies :

<dependencies>
    ...
    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.4</version>
    </dependency>
</dependencies>

but it did not correct the problem. I also tried to add the dependency at the call of the plugin :

 <plugin>
    <artifactId>maven-source-plugin</artifactId>
    <version>2.4</version>
    <executions>
       <execution>
           <id>attach-sources</id>
           <goals>
              <goal>jar</goal>
           </goals>
       </execution>
      </executions>
      <dependencies>
          <dependency>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-source-plugin</artifactId>
              <version>2.4</version>
          </dependency>
     </dependencies>
 </plugin>

but it did not work either


问:
$_FILES["imagefile"]["name"] return name but $_FILES["imagefile"]["tmp_name"] return null value?
In my case i was include enctype on myform like

```<code><form id="product_add" name="product_add" accept-charset="utf-8" action="product_add_inter.php" method="post" enctype="multipart/form-data">
</code>```

then my input type file is

```<code><input name="imagefile" class="form-control" type="file"   />
</code>```

Problem is in server side i need to upload my image to distination folder.I was tried to get file from form using

```<code>$_FILES["imagefile"]["name"]
</code>```

its worked and returned name of my image. But when i get the file using temp_name it return null values.

```<code>$_FILES["imagefile"]["tmp_name"]
</code>```

how can i solve this.

答:
You can use this code to see the upload error:

```<code>print_r($_FILES['imagefile]['error']);
</code>```

The error code 6 means that there is no tmp directory. Go to your php.ini and post whats behind that variable:

```<code>upload_tmp_dir =
</code>```

Body:
In my case i was include enctype on myform like

<form id="product_add" name="product_add" accept-charset="utf-8" action="product_add_inter.php" method="post" enctype="multipart/form-data">

then my input type file is

<input name="imagefile" class="form-control" type="file"   />

Problem is in server side i need to upload my image to distination folder.I was tried to get file from form using

$_FILES["imagefile"]["name"]

its worked and returned name of my image. But when i get the file using temp_name it return null values.

$_FILES["imagefile"]["tmp_name"]

how can i solve this.

Body:
You can use this code to see the upload error:

print_r($_FILES['imagefile]['error']);

The error code 6 means that there is no tmp directory. Go to your php.ini and post whats behind that variable:

upload_tmp_dir =


问:
Postgresql Schema and Data Compare
Is it possible to compare postgresql database in Redgate SQL Compare tool.

or Any other recommend tool for postgresql database compare tool.

答: No, Redgate just has comparison tools for SQL Server and Oracle. You could try PostgresCompare, which is an analogous tool to SQL Compare.</p>

Title: Postgresql Schema and Data Compare


问:
How to put the content of a file in a global variable in JMeter?
I want to save the content of a file in a variable one time and use it in JSR223 pre-processor script.
How can I do this?</p>

答:
Add User Defined Variables to your Test Plan and define the variable name of your choice, i.e. myFile. As the value use __FileToString() function and provide the path of the file which you want to load:

Once done you can refer the file content from any of the JSR223 Test Elements using vars shorthand for JMeterVariables class instance as:

```<code>String myFile = vars.get('myFile')
</code>```

Body:
Add User Defined Variables to your Test Plan and define the variable name of your choice, i.e. myFile. As the value use __FileToString() function and provide the path of the file which you want to load:

Once done you can refer the file content from any of the JSR223 Test Elements using vars shorthand for JMeterVariables class instance as:

String myFile = vars.get('myFile')


问:
How to execute a loop with sequential summation?
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});```
</div>
</div>
</p>

<p>At the moment, I get this result:</p>

```5
9
18
24
28
```

<p>But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:</p>

```0
5
9
18
24
```

答:
Well, you can do that in a lot of different ways. Moving console.log one line up can be one. However, if you don't want to move your console.log, please refer to the below code where I used two sum variables:

```<code>var arr = [5, 4, 9, 6, 4];

var sum = 0;
var sum2 = 0;

arr.forEach(function(item) {
  sum += sum2;
  sum2 = parseInt(item);
  console.log(sum)
});
</code>```

Body:
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});

At the moment, I get this result:

5
9
18
24
28

But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:

0
5
9
18
24

Body:
Well, you can do that in a lot of different ways. Moving console.log one line up can be one. However, if you don't want to move your console.log, please refer to the below code where I used two sum variables:

var arr = [5, 4, 9, 6, 4];

var sum = 0;
var sum2 = 0;

arr.forEach(function(item) {
  sum += sum2;
  sum2 = parseInt(item);
  console.log(sum)
});


问:
How to define format for both Y and List[X] in Play JSON when X extends from Y and Y is trait?
I can't convert list in specific case: when type is extends from trait.

When I can convert:

  import play.api.libs.functional.syntax._
  import play.api.libs.json._
  sealed trait Item
  case class Id(id: Long) extends Item
  case class MyList(list: List[Id])
  object MyFormat {
    implicit lazy val idFormat = Json.format[Id]
    implicit lazy val myListFormat = Json.format[MyList]
  }
```

<p>When I can not convert:</p>

<pre class="lang-scala prettyprint-override"><code>  sealed trait Item
  case class Id(id: Long) extends Item
  case class MyList(list: List[Id])
  object MyFormat {
    implicit lazy val itemFormat = new Format[Item] {
      override def writes(o: Item): JsValue = o match {
        case i: Id => idFormat.writes(i)
      }
      override def reads(json: JsValue): JsResult[Item] = {
        idFormat.reads(json)
      }
    }
    implicit lazy val idFormat = Json.format[Id]
    implicit lazy val myListFormat = Json.format[MyList]
  }
</code>```

Error:
Error:(33, 49) No instance of play.api.libs.json.Format is available for scala.collection.immutable.List[Main2.Id] in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
    implicit lazy val myListFormat = Json.format[MyList]

Why I can't format in 2nd case?

If I add formatter for list:

implicit lazy val idsFormat = Json.format[List[Id]]
```

<p>then I got <code>Error:(33, 46) No instance of Reads is available for scala.collection.immutable.Nil in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
    implicit lazy val idsFormat = Json.format[List[Id]]</code></p>

<p>PS:
The only one solution than I found:</p>

<ol>
<li>Define custom format for <code>List[Id]</code></li>
<li>When read or write, use format for <code>Id</code></li>
<li>When read, use</li>
</ol>

```def flatten[T](xs: Seq[JsResult[T]]): JsResult[List[T]] = {
  val (ss: Seq[JsSuccess[T]], fs: Seq[JsError]) = xs.partition(_.isSuccess)
  if (fs.isEmpty) JsSuccess(ss.map(_.get).toList) else fs.head
}
```

答:
If play JSON features automatic/semiautomatic codec instances derivation, then it will use implicit to enable such a mechanism. It means that codecs for complex things should be introduced after their components.

In your case, it seems like play JSON tries to derive codec for List as for case class ,i. e. as for List(a1, List(a2, ..., List(an, Nil))) and when it hits Nil, it doesn't know how to derive codec for that.

I believe you want your list encoded not like a chain of folded objects but as JSON array.

Then you should search play sources for default List[T] codec and try to use it by specializing it for Id.

General tool for debugging missing implicits is compiler option "-Xlog-implicits". It will log all failed implicit searches to console, and it is possible to figure out what's missing by these messages.

It is also strongly advised to know how implicit works before working with libraries that use this feautre extensively.

And last, but not least:

Have you ever tried using circe? It features automatic and semi-automatic JSON derivation for families of sealed traits and standard scala classes. It even has integration with play framework. Circe derivation removes the most headache of writing codec code, but requires strong knowledge of implicit precedence to work properly. The way it works described here and here.

You can also try to create your own derivation for play-json if there's no adequate standard one with morphling.

Body:
I can't convert list in specific case: when type is extends from trait.

When I can convert:

  import play.api.libs.functional.syntax._
  import play.api.libs.json._
  sealed trait Item
  case class Id(id: Long) extends Item
  case class MyList(list: List[Id])
  object MyFormat {
    implicit lazy val idFormat = Json.format[Id]
    implicit lazy val myListFormat = Json.format[MyList]
  }

When I can not convert:

  sealed trait Item
  case class Id(id: Long) extends Item
  case class MyList(list: List[Id])
  object MyFormat {
    implicit lazy val itemFormat = new Format[Item] {
      override def writes(o: Item): JsValue = o match {
        case i: Id => idFormat.writes(i)
      }
      override def reads(json: JsValue): JsResult[Item] = {
        idFormat.reads(json)
      }
    }
    implicit lazy val idFormat = Json.format[Id]
    implicit lazy val myListFormat = Json.format[MyList]
  }

Error:
Error:(33, 49) No instance of play.api.libs.json.Format is available for scala.collection.immutable.List[Main2.Id] in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
    implicit lazy val myListFormat = Json.format[MyList]

Why I can't format in 2nd case?

If I add formatter for list:

implicit lazy val idsFormat = Json.format[List[Id]]

then I got Error:(33, 46) No instance of Reads is available for scala.collection.immutable.Nil in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
    implicit lazy val idsFormat = Json.format[List[Id]]

PS:
The only one solution than I found:

Define custom format for List[Id]

When read or write, use format for Id

When read, use

def flatten[T](xs: Seq[JsResult[T]]): JsResult[List[T]] = {
  val (ss: Seq[JsSuccess[T]], fs: Seq[JsError]) = xs.partition(_.isSuccess)
  if (fs.isEmpty) JsSuccess(ss.map(_.get).toList) else fs.head
}


问:
Having trouble finding an object that i need to click on
I'm trying to find and click an element on a sidebar on the protonmail webpage but I'm having a hard time locating it.

```<code>openProtonTab = driver.execute_script("window.open('https://mail.protonmail.com/login','proton window')")
openProtonTab

pageSwitch = driver.switch_to.window(driver.window_handles[1])
pageSwitch

protonEmail = driver.find_element_by_id('username')
protonEmail.send_keys('botusername')

protonPass = driver.find_element_by_id('password')
protonPass.send_keys(botpassword)

loginButton = driver.find_element_by_xpath('//*[@id="login_btn"]')
loginButton.click()

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='ptSidebar'] and @id='pm_sidebar']/button']")))

compose = driver.find_element_by_xpath('//*[@id="pm_sidebar"]/button')
# didnt work either compose = driver.find_element_by_class_name('compose pm_button sidebar-btn-compose')
compose.click()
</code>```

How can I find the compose element and click on it ?

答: After taking a quick look, it seems xpath is not in correct format so, instead of //*[@id="pm_sidebar"]/button use //*[@id='pm_sidebar']/button it seems to be working for me.

Body:
I'm trying to find and click an element on a sidebar on the protonmail webpage but I'm having a hard time locating it.

openProtonTab = driver.execute_script("window.open('https://mail.protonmail.com/login','proton window')")
openProtonTab

pageSwitch = driver.switch_to.window(driver.window_handles[1])
pageSwitch

protonEmail = driver.find_element_by_id('username')
protonEmail.send_keys('botusername')

protonPass = driver.find_element_by_id('password')
protonPass.send_keys(botpassword)

loginButton = driver.find_element_by_xpath('//*[@id="login_btn"]')
loginButton.click()

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='ptSidebar'] and @id='pm_sidebar']/button']")))

compose = driver.find_element_by_xpath('//*[@id="pm_sidebar"]/button')
# didnt work either compose = driver.find_element_by_class_name('compose pm_button sidebar-btn-compose')
compose.click()

How can I find the compose element and click on it ?


问:
Deploying a kubernetes pods after a job is completed - helm
Goal - Start deployment of pod when a particular jobs in completed using helm.

Currently I am using helm to deploy the configmap/pods/jobs. When I do "helm install" everything get deployed at the same time.
Can I add delay/trigger saying when a particular jobs is completed then only deploy other pods.

I tried using "init container" but it difficult to get status of job in "init container"

答: This is somewhat out of the wheelhouse of Helm. You can use Hooks to get some relatively simplistic forms of this, but many people find them frustrating as complexity grows. The more complete form of this pattern requires writing an operator instead.</p>


问:
R ggplot2: How to make a histogram and color according to diferent columns?
I am trying to generate a histogram with some data, but I can't find a way to make ggplot2 work to achieve what I want.

For context, my data looks like this: (column names)

```<code>

|  Name  |  Total Enrichment % (A+B+C+D)  |  %A  |  %B  |  %C  |  %D  |
</code>```

I want to generate a histogram showing the distribution of the total Enrichment column and then filling the column with 4 colors showing the different percentages of A, B, C, and D.

I've tried to convert the data into long format, but still, I cannot seem to get exactly what I want.

Any advice would be very helpful! Thank you very much!

Here is an example (it's not the original data, just a small part of it):

```<code>    dat <- read.table(text = "Name Total A B C D
1 0.1396104 0.029220779 0.009740260 0.029220779 0.07142857
2 0.1250000 0.010869565 0.021739130 0.016304348 0.07608696
3 0.1337580 0.006369427 0.000000000 0.025477707 0.10191083
4 0.1239669 0.016528926 0.024793388 0.033057851 0.04958678
5 0.1242938 0.011299435 0.016949153 0.039548023 0.05649718
6 0.1311475 0.000000000 0.000000000 0.021857923 0.10928962
7 0.1376147 0.004587156 0.004587156 0.004587156 0.12385321
8 0.1574074 0.046296296 0.018518519 0.032407407 0.06018519
9 0.1269036 0.010152284 0.010152284 0.020304569 0.08629442", sep = "",    header=T)
</code>```

My goal is to create a histogram with the Total enrichment data, but with each column filled with the other contribution variables (A, B, C and D)

Thanks!

Edit

Thanks to StupidWolf amazing help and comments I could come a little bit closer to what I want.

Here is what I've fot so far (It's not perfect, but so far so good)

What I would like to do is to have the y axis in logarithmic scale, since I have a lot of data in the lower range, and I'm also interesed in the data with a higher enrichment.
Also, does anyone know why the bars are not filled? Why are there these white spaces?

Again, thank you very much for your help and patience!

答:
I am making an educated guess on what you want to do, first let's get some data:

```<code>set.seed(321)
library(ggplot2)
library(dplyr)
dat = data.frame(Name=1:500,matrix(runif(500*4),ncol=4))
colnames(dat)[-1] = LETTERS[1:4]
dat$Total = rowSums(dat[,-1])
</code>```

If you want to calculate the contribution of A,B,C and D to each binned value of Total, then we need to do a histogram of Total, it looks like this, and we store the breaks to classify each row:

```<code>his_all = hist(dat$Total,br=40)
dat$bin = cut(dat$Total,br=his_all$breaks,labels=his_all$mids)
</code>```

In the above, I used the middle of the histogram to represent the position to plot the bar again. Hence there's a step to convert the factor label to numeric. Then we need to calculate the contribution of A to D to each total, then pivot longer and plot :

```<code>dat %>%
mutate_at(c("A","B","C","D"),~.x/Total) %>%
pivot_longer(A:D) %>%
mutate(bin=as.numeric(as.character(bin))) %>%
ggplot(aes(x=bin,y=value,fill=name)) +
geom_col() +
xlab("enrichment")
</code>```

Another way to visualize your data:

```<code>dat$interval = cut_interval(dat$Total,5)

dat %>% mutate_at(c("A","B","C","D"),~.x/Total) %>%
group_by(interval) %>% select(c(interval,A:D)) %>%
summarize_all(mean) %>% pivot_longer(-interval) %>%
ggplot(aes(x=interval,y=value,fill=name)) + geom_col()
</code>```

This shows you for every range of Total, what proportion of A/B/C/D contributes to it..

Body:
I am trying to generate a histogram with some data, but I can't find a way to make ggplot2 work to achieve what I want.

For context, my data looks like this: (column names)

|  Name  |  Total Enrichment % (A+B+C+D)  |  %A  |  %B  |  %C  |  %D  |

I want to generate a histogram showing the distribution of the total Enrichment column and then filling the column with 4 colors showing the different percentages of A, B, C, and D.

I've tried to convert the data into long format, but still, I cannot seem to get exactly what I want.

Any advice would be very helpful! Thank you very much!

Here is an example (it's not the original data, just a small part of it):

    dat <- read.table(text = "Name Total A B C D
1 0.1396104 0.029220779 0.009740260 0.029220779 0.07142857
2 0.1250000 0.010869565 0.021739130 0.016304348 0.07608696
3 0.1337580 0.006369427 0.000000000 0.025477707 0.10191083
4 0.1239669 0.016528926 0.024793388 0.033057851 0.04958678
5 0.1242938 0.011299435 0.016949153 0.039548023 0.05649718
6 0.1311475 0.000000000 0.000000000 0.021857923 0.10928962
7 0.1376147 0.004587156 0.004587156 0.004587156 0.12385321
8 0.1574074 0.046296296 0.018518519 0.032407407 0.06018519
9 0.1269036 0.010152284 0.010152284 0.020304569 0.08629442", sep = "",    header=T)

My goal is to create a histogram with the Total enrichment data, but with each column filled with the other contribution variables (A, B, C and D)

Thanks!

Edit

Thanks to StupidWolf amazing help and comments I could come a little bit closer to what I want.

Here is what I've fot so far (It's not perfect, but so far so good)

What I would like to do is to have the y axis in logarithmic scale, since I have a lot of data in the lower range, and I'm also interesed in the data with a higher enrichment.
Also, does anyone know why the bars are not filled? Why are there these white spaces?

Again, thank you very much for your help and patience!

Body:
I am making an educated guess on what you want to do, first let's get some data:

set.seed(321)
library(ggplot2)
library(dplyr)
dat = data.frame(Name=1:500,matrix(runif(500*4),ncol=4))
colnames(dat)[-1] = LETTERS[1:4]
dat$Total = rowSums(dat[,-1])

If you want to calculate the contribution of A,B,C and D to each binned value of Total, then we need to do a histogram of Total, it looks like this, and we store the breaks to classify each row:

his_all = hist(dat$Total,br=40)
dat$bin = cut(dat$Total,br=his_all$breaks,labels=his_all$mids)

In the above, I used the middle of the histogram to represent the position to plot the bar again. Hence there's a step to convert the factor label to numeric. Then we need to calculate the contribution of A to D to each total, then pivot longer and plot :

dat %>%
mutate_at(c("A","B","C","D"),~.x/Total) %>%
pivot_longer(A:D) %>%
mutate(bin=as.numeric(as.character(bin))) %>%
ggplot(aes(x=bin,y=value,fill=name)) +
geom_col() +
xlab("enrichment")

Another way to visualize your data:

dat$interval = cut_interval(dat$Total,5)

dat %>% mutate_at(c("A","B","C","D"),~.x/Total) %>%
group_by(interval) %>% select(c(interval,A:D)) %>%
summarize_all(mean) %>% pivot_longer(-interval) %>%
ggplot(aes(x=interval,y=value,fill=name)) + geom_col()

This shows you for every range of Total, what proportion of A/B/C/D contributes to it..


问:
No fixtures found when testing an app on Django
I have finally decided to create unit test for all my code. That is I'm trying to create fixtures based on my models to test my function against them.

I have create a json fixture using dumpdata command and placed it under fixtures directory on my app. The following is the code on my test:

```<code>import unittest
from mysite.myapp.models import Post

class RatingTestCase(unittest.TestCase):
  fixtures = [
      'posts.json',
  ]

def test_me(self):
  p = Post.objects.all()
  self.assertTrue(p)
</code>```

I run my test using the following command on my Arch Linux machine:

```<code>python2.7 manage.py test myapp
</code>```

It creates a sqlite database and installs all the tables and indeces, however at the end it says no fixtures found and it says my test failed since it didn't find any data.

I'm running the latest revision of development version of Django and noticed that based on the documentation I am supposed to import unittest using:

from django.utils import unittest

However, when I do this, it complains that unittest cannot be imported. That's why I import
unittest directly from my python path which worked.

I've tried to mock django model objects before, but I think it's better to test Django apps using fixtures than using mock libraries. Any idea how to load the fixtures?

Thanks in advance.

EDIT: If I change my fixture name to initial_data.json, it will load it every time I run my test. However, I still need to have multiple fixture names for running different tests.

EDIT: I got it working by importing TestCase from the following:

```<code>from django.test import TestCase
</code>```

答:
Have you checked if the path where the fixture is present is available in:</p>

```<code>settings.FIXTURE_DIRS = ('/path/to/proj_folder/fixtures/',)
</code>```

Body:
I have finally decided to create unit test for all my code. That is I'm trying to create fixtures based on my models to test my function against them.

I have create a json fixture using dumpdata command and placed it under fixtures directory on my app. The following is the code on my test:

import unittest
from mysite.myapp.models import Post

class RatingTestCase(unittest.TestCase):
  fixtures = [
      'posts.json',
  ]

def test_me(self):
  p = Post.objects.all()
  self.assertTrue(p)

I run my test using the following command on my Arch Linux machine:

python2.7 manage.py test myapp

It creates a sqlite database and installs all the tables and indeces, however at the end it says no fixtures found and it says my test failed since it didn't find any data.

I'm running the latest revision of development version of Django and noticed that based on the documentation I am supposed to import unittest using:

from django.utils import unittest

However, when I do this, it complains that unittest cannot be imported. That's why I import
unittest directly from my python path which worked.

I've tried to mock django model objects before, but I think it's better to test Django apps using fixtures than using mock libraries. Any idea how to load the fixtures?

Thanks in advance.

EDIT: If I change my fixture name to initial_data.json, it will load it every time I run my test. However, I still need to have multiple fixture names for running different tests.

EDIT: I got it working by importing TestCase from the following:

from django.test import TestCase

Body:
Have you checked if the path where the fixture is present is available in:

settings.FIXTURE_DIRS = ('/path/to/proj_folder/fixtures/',)


问:
datepicker does not display months but days
Hello I have a problem with the datepicker. I see the days and not only the months I mean instead of having this :

I get this :

Here is my code :

```<code> <input type="text" id="datepicker" />
</code>```

and here is the js :

```<code>$("#datepicker").datepicker( {
    format: "mm-yyyy",
    viewMode: "months",
    minViewMode: "months"
});
</code>```

Could you help me please ?

Thank you very much !

答:
Try this.

$(document).ready(function(){

    $("#datepicker-month").datepicker( {
        format: "mm-yyyy",
        viewMode: "months",
        minViewMode: "months"
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

<input type="text" id="datepicker-month" /></code>```

Body:
Hello I have a problem with the datepicker. I see the days and not only the months I mean instead of having this :

I get this :

Here is my code :

 <input type="text" id="datepicker" />

and here is the js :

$("#datepicker").datepicker( {
    format: "mm-yyyy",
    viewMode: "months",
    minViewMode: "months"
});

Could you help me please ?

Thank you very much !

Body:
Try this.

$(document).ready(function(){

    $("#datepicker-month").datepicker( {
        format: "mm-yyyy",
        viewMode: "months",
        minViewMode: "months"
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

<input type="text" id="datepicker-month" />


问:
i am getting this type of error while running the program of recycle view in android
```<code>  E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.example.spammessagedetector, PID: 2137
     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.spammessagedetector/com.example.spammessagedetector.Inbox}:
 java.lang.NullPointerException: Attempt to invoke virtual method 'void
 androidx.swiperefreshlayout.widget.SwipeRefreshLayout.setOnRefreshListener(androidx.swiperefreshlayout.widget.SwipeRefreshLayout$OnRefreshListener)'
 on a null object reference
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
         at android.app.ActivityThread.-wrap12(ActivityThread.java)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6077)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
 androidx.swiperefreshlayout.widget.SwipeRefreshLayout.setOnRefreshListener(androidx.swiperefreshlayout.widget.SwipeRefreshLayout$OnRefreshListener)'
 on a null object reference
         at com.example.spammessagedetector.Inbox.onCreate(Inbox.java:76)
         at android.app.Activity.performCreate(Activity.java:6662)
         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
   at android.app.ActivityThread.-wrap12(ActivityThread.java)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6077)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
</code>```

here is the code for    Inbox.java

```<code>package com.example.spammessagedetector;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Bundle;

import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

import com.example.spammessagedetector.R;
import com.example.spammessagedetector.adapter.MessagesAdapter;
import com.example.spammessagedetector.helper.DividerItemDecoration;
import com.example.spammessagedetector.model.Message;
import com.example.spammessagedetector.network.ApiClient;
import com.example.spammessagedetector.network.ApiInterface;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Inbox extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, MessagesAdapter.MessageAdapterListener{

    private List<Message> messages = new ArrayList<>();
    private RecyclerView recyclerView;
    private MessagesAdapter mAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ActionModeCallback actionModeCallback;
    private ActionMode actionMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inbox);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        if (fab != null)
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(this);

        mAdapter = new MessagesAdapter(this, messages, this);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(mAdapter);

        actionModeCallback = new ActionModeCallback();

        // show loader and fetch messages
        swipeRefreshLayout.post(
                new Runnable() {
                    @Override
                    public void run() {
                        getInbox();
                    }
                }
        );
    }

    /**
     * Fetches mail messages by making HTTP request
     * url: https://api.androidhive.info/json/inbox.json
     */
    private void getInbox() {
        swipeRefreshLayout.setRefreshing(true);

        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<List<Message>> call = apiService.getInbox();
        call.enqueue(new Callback<List<Message>>() {
            @Override
            public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
                // clear the inbox
                messages.clear();

                // add all the messages
                // messages.addAll(response.body());

                // TODO - avoid looping
                // the loop was performed to add colors to each message
                for (Message message : response.body()) {
                    // generate a random color
                    message.setColor(getRandomMaterialColor("400"));
                    messages.add(message);
                }

                mAdapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<List<Message>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * chooses a random color from array.xml
     */
    private int getRandomMaterialColor(String typeColor) {
        int returnColor = Color.GRAY;
        int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());

        if (arrayId != 0) {
            TypedArray colors = getResources().obtainTypedArray(arrayId);
            int index = (int) (Math.random() * colors.length());
            returnColor = colors.getColor(index, Color.GRAY);
            colors.recycle();
        }
        return returnColor;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_search) {
            Toast.makeText(getApplicationContext(), "Search...", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRefresh() {
        // swipe refresh is performed, fetch the messages again
        getInbox();
    }

    @Override
    public void onIconClicked(int position) {
        if (actionMode == null) {
            actionMode = startSupportActionMode(actionModeCallback);
        }

        toggleSelection(position);
    }

    @Override
    public void onIconImportantClicked(int position) {
        // Star icon is clicked,
        // mark the message as important
        Message message = messages.get(position);
        message.setImportant(!message.isImportant());
        messages.set(position, message);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onMessageRowClicked(int position) {
        // verify whether action mode is enabled or not
        // if enabled, change the row state to activated
        if (mAdapter.getSelectedItemCount() > 0) {
            enableActionMode(position);
        } else {
            // read the message which removes bold from the row
            Message message = messages.get(position);
            message.setRead(true);
            messages.set(position, message);
            mAdapter.notifyDataSetChanged();

            Toast.makeText(getApplicationContext(), "Read: " + message.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRowLongClicked(int position) {
        // long press is performed, enable action mode
        enableActionMode(position);
    }

    private void enableActionMode(int position) {
        if (actionMode == null) {
            actionMode = startSupportActionMode(actionModeCallback);
        }
        toggleSelection(position);
    }

    private void toggleSelection(int position) {
        mAdapter.toggleSelection(position);
        int count = mAdapter.getSelectedItemCount();

        if (count == 0) {
            actionMode.finish();
        } else {
            actionMode.setTitle(String.valueOf(count));
            actionMode.invalidate();
        }
    }

    private class ActionModeCallback implements ActionMode.Callback {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.getMenuInflater().inflate(R.menu.menu_action_mode, menu);

            // disable swipe refresh if action mode is enabled
            swipeRefreshLayout.setEnabled(false);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_delete:
                    // delete all the selected messages
                    deleteMessages();
                    mode.finish();
                    return true;

                default:
                    return false;
            }
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mAdapter.clearSelections();
            swipeRefreshLayout.setEnabled(true);
            actionMode = null;
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    mAdapter.resetAnimationIndex();
                    // mAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    // deleting the messages from recycler view
    private void deleteMessages() {
        mAdapter.resetAnimationIndex();
        List<Integer> selectedItemPositions =
                mAdapter.getSelectedItems();
        for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
            mAdapter.removeData(selectedItemPositions.get(i));
        }
        mAdapter.notifyDataSetChanged();
    }
}
</code>```

activity_inbox.xml

```<code>

     <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:mContext=".Inbox">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>
        </com.google.android.material.appbar.AppBarLayout>

        <include layout="@layout/content_main"/>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:onClick="floatbuttonclick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:backgroundTint="@color/colorPrimary"
            app:srcCompat="@drawable/ic_edit_white_24dp"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.spammessagedetector">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">
        <!-- <activity android:name=".Inbox"></activity> -->
        <activity android:name=".MainActivity" />
        <activity android:name=".Profile" />
        <activity android:name=".Splash" />
        <activity android:name=".Inbox">

            <!-- android:theme="@style/splash" -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
error at this line.Your referenced  id not found on current layout.

```<code> swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
</code>```

why call same method multiple time in your activity.may be here miss lead your swipe_refresh_layout id.

```<code>    setContentView(R.layout.activity_inbox);
    setContentView(R.layout.activity_main);
</code>```

Body:
  E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.example.spammessagedetector, PID: 2137
     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.spammessagedetector/com.example.spammessagedetector.Inbox}:
 java.lang.NullPointerException: Attempt to invoke virtual method 'void
 androidx.swiperefreshlayout.widget.SwipeRefreshLayout.setOnRefreshListener(androidx.swiperefreshlayout.widget.SwipeRefreshLayout$OnRefreshListener)'
 on a null object reference
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
         at android.app.ActivityThread.-wrap12(ActivityThread.java)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6077)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
 androidx.swiperefreshlayout.widget.SwipeRefreshLayout.setOnRefreshListener(androidx.swiperefreshlayout.widget.SwipeRefreshLayout$OnRefreshListener)'
 on a null object reference
         at com.example.spammessagedetector.Inbox.onCreate(Inbox.java:76)
         at android.app.Activity.performCreate(Activity.java:6662)
         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
   at android.app.ActivityThread.-wrap12(ActivityThread.java)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6077)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

here is the code for    Inbox.java

package com.example.spammessagedetector;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Bundle;

import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

import com.example.spammessagedetector.R;
import com.example.spammessagedetector.adapter.MessagesAdapter;
import com.example.spammessagedetector.helper.DividerItemDecoration;
import com.example.spammessagedetector.model.Message;
import com.example.spammessagedetector.network.ApiClient;
import com.example.spammessagedetector.network.ApiInterface;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Inbox extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, MessagesAdapter.MessageAdapterListener{

    private List<Message> messages = new ArrayList<>();
    private RecyclerView recyclerView;
    private MessagesAdapter mAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ActionModeCallback actionModeCallback;
    private ActionMode actionMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inbox);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        if (fab != null)
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(this);

        mAdapter = new MessagesAdapter(this, messages, this);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(mAdapter);

        actionModeCallback = new ActionModeCallback();

        // show loader and fetch messages
        swipeRefreshLayout.post(
                new Runnable() {
                    @Override
                    public void run() {
                        getInbox();
                    }
                }
        );
    }

    /**
     * Fetches mail messages by making HTTP request
     * url: https://api.androidhive.info/json/inbox.json
     */
    private void getInbox() {
        swipeRefreshLayout.setRefreshing(true);

        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<List<Message>> call = apiService.getInbox();
        call.enqueue(new Callback<List<Message>>() {
            @Override
            public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
                // clear the inbox
                messages.clear();

                // add all the messages
                // messages.addAll(response.body());

                // TODO - avoid looping
                // the loop was performed to add colors to each message
                for (Message message : response.body()) {
                    // generate a random color
                    message.setColor(getRandomMaterialColor("400"));
                    messages.add(message);
                }

                mAdapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<List<Message>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * chooses a random color from array.xml
     */
    private int getRandomMaterialColor(String typeColor) {
        int returnColor = Color.GRAY;
        int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());

        if (arrayId != 0) {
            TypedArray colors = getResources().obtainTypedArray(arrayId);
            int index = (int) (Math.random() * colors.length());
            returnColor = colors.getColor(index, Color.GRAY);
            colors.recycle();
        }
        return returnColor;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_search) {
            Toast.makeText(getApplicationContext(), "Search...", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRefresh() {
        // swipe refresh is performed, fetch the messages again
        getInbox();
    }

    @Override
    public void onIconClicked(int position) {
        if (actionMode == null) {
            actionMode = startSupportActionMode(actionModeCallback);
        }

        toggleSelection(position);
    }

    @Override
    public void onIconImportantClicked(int position) {
        // Star icon is clicked,
        // mark the message as important
        Message message = messages.get(position);
        message.setImportant(!message.isImportant());
        messages.set(position, message);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onMessageRowClicked(int position) {
        // verify whether action mode is enabled or not
        // if enabled, change the row state to activated
        if (mAdapter.getSelectedItemCount() > 0) {
            enableActionMode(position);
        } else {
            // read the message which removes bold from the row
            Message message = messages.get(position);
            message.setRead(true);
            messages.set(position, message);
            mAdapter.notifyDataSetChanged();

            Toast.makeText(getApplicationContext(), "Read: " + message.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRowLongClicked(int position) {
        // long press is performed, enable action mode
        enableActionMode(position);
    }

    private void enableActionMode(int position) {
        if (actionMode == null) {
            actionMode = startSupportActionMode(actionModeCallback);
        }
        toggleSelection(position);
    }

    private void toggleSelection(int position) {
        mAdapter.toggleSelection(position);
        int count = mAdapter.getSelectedItemCount();

        if (count == 0) {
            actionMode.finish();
        } else {
            actionMode.setTitle(String.valueOf(count));
            actionMode.invalidate();
        }
    }

    private class ActionModeCallback implements ActionMode.Callback {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.getMenuInflater().inflate(R.menu.menu_action_mode, menu);

            // disable swipe refresh if action mode is enabled
            swipeRefreshLayout.setEnabled(false);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_delete:
                    // delete all the selected messages
                    deleteMessages();
                    mode.finish();
                    return true;

                default:
                    return false;
            }
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mAdapter.clearSelections();
            swipeRefreshLayout.setEnabled(true);
            actionMode = null;
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    mAdapter.resetAnimationIndex();
                    // mAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    // deleting the messages from recycler view
    private void deleteMessages() {
        mAdapter.resetAnimationIndex();
        List<Integer> selectedItemPositions =
                mAdapter.getSelectedItems();
        for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
            mAdapter.removeData(selectedItemPositions.get(i));
        }
        mAdapter.notifyDataSetChanged();
    }
}

activity_inbox.xml

     <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:mContext=".Inbox">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>
        </com.google.android.material.appbar.AppBarLayout>

        <include layout="@layout/content_main"/>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:onClick="floatbuttonclick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:backgroundTint="@color/colorPrimary"
            app:srcCompat="@drawable/ic_edit_white_24dp"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.spammessagedetector">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">

        <activity android:name=".MainActivity" />
        <activity android:name=".Profile" />
        <activity android:name=".Splash" />
        <activity android:name=".Inbox">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Body:
error at this line.Your referenced  id not found on current layout.

 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

why call same method multiple time in your activity.may be here miss lead your swipe_refresh_layout id.

    setContentView(R.layout.activity_inbox);
    setContentView(R.layout.activity_main);


问:
How to count the number of quarters between two dates

Question 1:

How would you count the number of quarters between the starting date (base_date variable) and the y column in the pandas dataframe?

```<code>from dateutil.relativedelta import relativedelta
import pandas as pd
import numpy as np

base_date=pd.to_datetime('07/01/2019')
fake_data=pd.DataFrame([(x,pd.to_datetime('04/01/2020')+relativedelta(months=y)) for x in list(range(0,100)) for y in list(range(0,100))],columns=['x','y'])
fake_data['z']=fake_data['x']*np.random.uniform(low=1,high=1000)
</code>```

UPDATE: one option seems to work for question1:

```<code>fake_data['month_diff']=(fake_data['y'].dt.year-base_date.year)*12+fake_data['y'].dt.month-base_date.month
fake_data['quarter']=(fake_data['month_diff']/3).astype(int)
</code>```

Question 2:

If the x and y variables are now set to a pandas dataframe multi-level index.  How would you perform the same task as in question 1?

```<code>fake_data.set_index(['x','y'],drop=True,inplace=True)
</code>```

答:
Question 1:

A year contains 4 quarters. A simple way to count the difference of quarters between to dates is to convert them to year * 4 + quarter and use the difference:

```<code>fake_data.y.dt.year * 4 + fake_data.y.dt.quarter - (base_date.year * 4 + base_date.quarter)
</code>```

Question 2:

The previous method still applies, but on index.levels[1]:

```<code>fake_data.index.levels[1].year * 4 + fake_data.index.levels[1].quarter - (base_date.year * 4 + base_date.quarter)
</code>```

Simply in first question you get a plain Series, while here it is an Index...

Body:
Question 1:

How would you count the number of quarters between the starting date (base_date variable) and the y column in the pandas dataframe?

from dateutil.relativedelta import relativedelta
import pandas as pd
import numpy as np

base_date=pd.to_datetime('07/01/2019')
fake_data=pd.DataFrame([(x,pd.to_datetime('04/01/2020')+relativedelta(months=y)) for x in list(range(0,100)) for y in list(range(0,100))],columns=['x','y'])
fake_data['z']=fake_data['x']*np.random.uniform(low=1,high=1000)

UPDATE: one option seems to work for question1:

fake_data['month_diff']=(fake_data['y'].dt.year-base_date.year)*12+fake_data['y'].dt.month-base_date.month
fake_data['quarter']=(fake_data['month_diff']/3).astype(int)

Question 2:

If the x and y variables are now set to a pandas dataframe multi-level index.  How would you perform the same task as in question 1?

fake_data.set_index(['x','y'],drop=True,inplace=True)

Body:
Question 1:

A year contains 4 quarters. A simple way to count the difference of quarters between to dates is to convert them to year * 4 + quarter and use the difference:

fake_data.y.dt.year * 4 + fake_data.y.dt.quarter - (base_date.year * 4 + base_date.quarter)

Question 2:

The previous method still applies, but on index.levels[1]:

fake_data.index.levels[1].year * 4 + fake_data.index.levels[1].quarter - (base_date.year * 4 + base_date.quarter)

Simply in first question you get a plain Series, while here it is an Index...


问:
How to support WebAuthN in MacOS WKWebView?
Safari 13 supports WebAuthN, but WKWebView doesn't. Here is the test page: https://demo.yubico.com/webauthn-technical/registration. It appears navigator.credentials is not implemented in WKWebView. Is there a way to add WebAuthN support?

答:
The correct API to use is this scenario ASWebAuthenticationSession:

https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession

On iOS 13.3 that will work with USB, Lightning or NFC security keys based on our testing.

On iOS 11 or below you should use SFAuthenticationSession but obviously there's no WebAuthn support.