问:
GraphQL Error: Expected undefined to be a GraphQL type
I have been running into this GraphQL error for the past day or so and I have a hard time pinpointing where the problem lies. I hope the following makes sense...

In my project I have the following GraphQL types; Questionnaire & Question were a Questionnaire has many Questions and a Question belongs to a single Questionnaire.

I have the following queries: getQuestionnaires (gets all Questionnaires), getQuestionnaire (gets a single Questionnaire by its Id), getQuestions (gets all Questions, either all questions in the system or the questions for a Questionnaire by specifying the questionnaireId).

This is the Questionnaire Type (I have left out a bunch of attributes for brevity):

```<code>import {
  GraphQLID,
  GraphQLObjectType,
  GraphQLNonNull,
} from 'graphql'
import QuestionType from './Question'
import QuestionResolver from '../resolver/question'

const QuestionnaireType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Questionnaire',
  fields() {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLID),
      },

      // other literal attributes go here

      questions: QuestionResolver.query.getQuestions,
    }
  },
})

export default QuestionnaireType
</code>```

As you can see, the questions attribute for the Questionnaire Type simply calls the resolver for getQuestions.

This is the resolver for getQuestions:

```<code>import {
  GraphQLList,
  GraphQLID
} from 'graphql'

import QuestionType from '../../type/Question'

export default {
  type: GraphQLList(QuestionType),
  description: 'Returns a list of questions',
  args: {
    questionnaireId: {
      type: GraphQLID,
      description: 'Questions that belong to this questionnaire',
    },
  },
  async resolve(source: any, { questionnaireId = undefined }: any, ctx: any): Promise<any> {
    // Based on the `questionnaireId` get the questions. If `undefined` get "all" questions.
  },
}
</code>```

As you can see, the getQuestions returns a GraphQLList(QuestionType). Which brings us to the  Question Type:

```<code>import {
  GraphQLID,
  GraphQLObjectType,
  GraphQLNonNull,
} from 'graphql'
import QuestionnaireType from './Questionnaire'
import QuestionnaireResolver from '../resolver/questionnaire'

const QuestionType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Question',
  fields() {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLID),
      },

      questionnaire: QuestionnaireResolver.query.getQuestionnaire,
    }
  },
})

export default QuestionType
</code>```

Okay. So far so good. This code compiles and runs.

However, there is a problem with this code. The getQuestions resolver takes in the Questionnaire Id as a parameter (questionnaireId). If the Questionnaire Id is not passed (undefined) it simply returns all Questions in the system. This means that in the Questionnaire Type, on the questions attribute, we don't want call the getQuestions resolver directly, but we want to wrap it in a resolver that extracts the source.id (the source is the Questionnaire in this context) and pass it as an argument to the getQuestions resolver. If we don't do this, then querying for questions on a Questionnaire will always return all Questions in the system, which is what we don't want.

So, we wrap the resolver in a resolver that extracts the Questionnaire Id before calling the getQuestions resolver. Our Questionnaire Type now looks like this:

```<code>import {
  GraphQLID,
  GraphQLObjectType,
  GraphQLNonNull,
} from 'graphql'
import QuestionType from './Question'
import QuestionResolver from '../resolver/question'

const QuestionnaireType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Questionnaire',
  fields() {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLID),
      },

      // other literal attributes go here

      questions: {
        type: GraphQLList(QuestionType),
        async resolve(source: any, args: any, ctx: any): Promise<any> {
          return QuestionResolver.query.getQuestions.resolve(
            source,
            {
              questionnaireId: source.questionnaireId,
            },
            ctx
          )
        },
      },
    }
  },
})

export default QuestionnaireType
</code>```

We have now wrapped the getQuestions resolver to extract the source.id (i.e. the Questionnaire Id) so we can always pass it on to the getQuestions resolver (since that is what we always want in this context).

However, when I do the above. I get this error:

```<code>[Node] /Project/api/node_modules/graphql/type/definition.js:91
[Node]     throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL type."));
[Node]     ^
[Node]
[Node] Error: Expected undefined to be a GraphQL type.
[Node]     at assertType (/Project/api/node_modules/graphql/type/definition.js:91:11)
[Node]     at new GraphQLList (/Project/api/node_modules/graphql/type/definition.js:307:19)
[Node]     at Object.GraphQLList (/Project/api/node_modules/graphql/type/definition.js:309:12)
[Node]     at Object.<anonymous> (/Project/api/build/graphql/resolver/question/getQuestions.js:11:21)
[Node]     at Module._compile (internal/modules/cjs/loader.js:936:30)
[Node]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
[Node]     at Module.load (internal/modules/cjs/loader.js:790:32)
[Node]     at Function.Module._load (internal/modules/cjs/loader.js:703:12)
[Node]     at Module.require (internal/modules/cjs/loader.js:830:19)
[Node]     at require (internal/modules/cjs/helpers.js:68:18)
</code>```

I'm stumped....

On line 11 of getQuestions is:

```<code>08: export default {
09:   type: GraphQLList(QuestionType),
10:   description: 'Returns a list of questions',
11:   args: {
12:     questionnaireId: {
13:       type: GraphQLID,
14:       description: 'Questions that belong to this questionnaire',
15:     },
</code>```

I think I have literally tried everything that comes to mind to find the problem. My project is biggish and I use this technique in several other places without problems but for some reason, in this particular scenario it fails to compile..

The only workaround I have at the moment is to use something like this in the getQuestions resolver:

```<code>import {
  GraphQLList,
  GraphQLID
} from 'graphql'

import QuestionType from '../../type/Question'

export default {
  type: GraphQLList(QuestionType),
  description: 'Returns a list of questions',
  args: {
    questionnaireId: {
      type: GraphQLID,
      description: 'Questions that belong to this questionnaire',
    },
  },
  async resolve(source: any, { questionnaireId = undefined }: any, ctx: any): Promise<any> {

    // The workaround
    const id = questionnaireId || source.id
  },
}
</code>```

However, it's not the responsibility of the getQuestions resolver to look at the source to extract arguments and also, the source could technically be another object than a Questionnaire adding more complexity to the getQuestions resolver.

Any help and insight appreciated.

答:
You need to look at the compiled code to trace the error. Based on the stack trace, though, it looks like QuestionType is evaluating to undefined. This can happen when you have circular dependencies (i.e. module A which imports module B which imports module A etc.).

You should generally avoid calling other resolvers inside a resolver to begin with. If you have a lot of duplication, the shared logic can be extracted to a common function that can be called from both resolvers. There's a tendency for this to happen when our resolvers contain business logic -- it's a good practice to try to keep your resolvers as lean as possible, isolating business logic inside separate models or services whose methods can then be called from your resolvers.

It's hard to know how to fix your circular dependency without seeing all the relevant code. The guaranteed way to resolve any circular dependencies is to swap out your import statements for dynamic requires inside the fields function. However, you may not find that solution particularly elegant. A good first step may be to consolidate some of your modules -- for example, creating a single Question module that includes the Question type and all related Query and Mutation fields.

Body:
I have been running into this GraphQL error for the past day or so and I have a hard time pinpointing where the problem lies. I hope the following makes sense...

In my project I have the following GraphQL types; Questionnaire & Question were a Questionnaire has many Questions and a Question belongs to a single Questionnaire.

I have the following queries: getQuestionnaires (gets all Questionnaires), getQuestionnaire (gets a single Questionnaire by its Id), getQuestions (gets all Questions, either all questions in the system or the questions for a Questionnaire by specifying the questionnaireId).

This is the Questionnaire Type (I have left out a bunch of attributes for brevity):

import {
  GraphQLID,
  GraphQLObjectType,
  GraphQLNonNull,
} from 'graphql'
import QuestionType from './Question'
import QuestionResolver from '../resolver/question'

const QuestionnaireType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Questionnaire',
  fields() {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLID),
      },

      // other literal attributes go here

      questions: QuestionResolver.query.getQuestions,
    }
  },
})

export default QuestionnaireType

As you can see, the questions attribute for the Questionnaire Type simply calls the resolver for getQuestions.

This is the resolver for getQuestions:

import {
  GraphQLList,
  GraphQLID
} from 'graphql'

import QuestionType from '../../type/Question'

export default {
  type: GraphQLList(QuestionType),
  description: 'Returns a list of questions',
  args: {
    questionnaireId: {
      type: GraphQLID,
      description: 'Questions that belong to this questionnaire',
    },
  },
  async resolve(source: any, { questionnaireId = undefined }: any, ctx: any): Promise<any> {
    // Based on the `questionnaireId` get the questions. If `undefined` get "all" questions.
  },
}

As you can see, the getQuestions returns a GraphQLList(QuestionType). Which brings us to the  Question Type:

import {
  GraphQLID,
  GraphQLObjectType,
  GraphQLNonNull,
} from 'graphql'
import QuestionnaireType from './Questionnaire'
import QuestionnaireResolver from '../resolver/questionnaire'

const QuestionType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Question',
  fields() {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLID),
      },

      questionnaire: QuestionnaireResolver.query.getQuestionnaire,
    }
  },
})

export default QuestionType

Okay. So far so good. This code compiles and runs.

However, there is a problem with this code. The getQuestions resolver takes in the Questionnaire Id as a parameter (questionnaireId). If the Questionnaire Id is not passed (undefined) it simply returns all Questions in the system. This means that in the Questionnaire Type, on the questions attribute, we don't want call the getQuestions resolver directly, but we want to wrap it in a resolver that extracts the source.id (the source is the Questionnaire in this context) and pass it as an argument to the getQuestions resolver. If we don't do this, then querying for questions on a Questionnaire will always return all Questions in the system, which is what we don't want.

So, we wrap the resolver in a resolver that extracts the Questionnaire Id before calling the getQuestions resolver. Our Questionnaire Type now looks like this:

import {
  GraphQLID,
  GraphQLObjectType,
  GraphQLNonNull,
} from 'graphql'
import QuestionType from './Question'
import QuestionResolver from '../resolver/question'

const QuestionnaireType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Questionnaire',
  fields() {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLID),
      },

      // other literal attributes go here

      questions: {
        type: GraphQLList(QuestionType),
        async resolve(source: any, args: any, ctx: any): Promise<any> {
          return QuestionResolver.query.getQuestions.resolve(
            source,
            {
              questionnaireId: source.questionnaireId,
            },
            ctx
          )
        },
      },
    }
  },
})

export default QuestionnaireType

We have now wrapped the getQuestions resolver to extract the source.id (i.e. the Questionnaire Id) so we can always pass it on to the getQuestions resolver (since that is what we always want in this context).

However, when I do the above. I get this error:

[Node] /Project/api/node_modules/graphql/type/definition.js:91
[Node]     throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL type."));
[Node]     ^
[Node]
[Node] Error: Expected undefined to be a GraphQL type.
[Node]     at assertType (/Project/api/node_modules/graphql/type/definition.js:91:11)
[Node]     at new GraphQLList (/Project/api/node_modules/graphql/type/definition.js:307:19)
[Node]     at Object.GraphQLList (/Project/api/node_modules/graphql/type/definition.js:309:12)
[Node]     at Object.<anonymous> (/Project/api/build/graphql/resolver/question/getQuestions.js:11:21)
[Node]     at Module._compile (internal/modules/cjs/loader.js:936:30)
[Node]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
[Node]     at Module.load (internal/modules/cjs/loader.js:790:32)
[Node]     at Function.Module._load (internal/modules/cjs/loader.js:703:12)
[Node]     at Module.require (internal/modules/cjs/loader.js:830:19)
[Node]     at require (internal/modules/cjs/helpers.js:68:18)

I'm stumped....

On line 11 of getQuestions is:

08: export default {
09:   type: GraphQLList(QuestionType),
10:   description: 'Returns a list of questions',
11:   args: {
12:     questionnaireId: {
13:       type: GraphQLID,
14:       description: 'Questions that belong to this questionnaire',
15:     },

I think I have literally tried everything that comes to mind to find the problem. My project is biggish and I use this technique in several other places without problems but for some reason, in this particular scenario it fails to compile..

The only workaround I have at the moment is to use something like this in the getQuestions resolver:

import {
  GraphQLList,
  GraphQLID
} from 'graphql'

import QuestionType from '../../type/Question'

export default {
  type: GraphQLList(QuestionType),
  description: 'Returns a list of questions',
  args: {
    questionnaireId: {
      type: GraphQLID,
      description: 'Questions that belong to this questionnaire',
    },
  },
  async resolve(source: any, { questionnaireId = undefined }: any, ctx: any): Promise<any> {

    // The workaround
    const id = questionnaireId || source.id
  },
}

However, it's not the responsibility of the getQuestions resolver to look at the source to extract arguments and also, the source could technically be another object than a Questionnaire adding more complexity to the getQuestions resolver.

Any help and insight appreciated.


来源: stackexchange

问:
Translation of this Python Line
I am relatively new to Python and having problem translating the following one line:

```<code>diffList = [key for key in set(dict1n.keys() + dict2.keys()) if dict1.get(key) != dict2t.get(key)]
</code>```

Can someone please rewrite it for me - break it down into multiple lines in a "normal" nice format?

I think - and I am not sure - what the line is trying to do is to compare two dictionaries and output the differences to a list.

Thanks.

UPDATE: I had typos in the line - there should only be dict1 and dict2:

```<code>diffList = [key for key in set(dict1.keys() + dict2.keys()) if dict1.get(key) != dict2.get(key
</code>```

答:
The code you posted is a "List Comprehension"

It translates to:

```<code>diffList = []
for key in  set(dict1n.keys() + dict2.keys()):
  if dict1.get(key) != dict2t.get(key):
    diffList.append(key)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Translation of this Python Line

Body:
I am relatively new to Python and having problem translating the following one line:

diffList = [key for key in set(dict1n.keys() + dict2.keys()) if dict1.get(key) != dict2t.get(key)]

Can someone please rewrite it for me - break it down into multiple lines in a "normal" nice format?

I think - and I am not sure - what the line is trying to do is to compare two dictionaries and output the differences to a list.

Thanks.

UPDATE: I had typos in the line - there should only be dict1 and dict2:

diffList = [key for key in set(dict1.keys() + dict2.keys()) if dict1.get(key) != dict2.get(key

Body:
The code you posted is a "List Comprehension"

It translates to:

diffList = []
for key in  set(dict1n.keys() + dict2.keys()):
  if dict1.get(key) != dict2t.get(key):
    diffList.append(key)


问:
AdaCore : importing packages e.g.'Display'
can someone advise on how to import the 'Display' packages to GPS community edition?
[YouTube: AdaCore Lesson#2]https://youtube.com/watch?v=3jtOFle5K_c</p>

答: They are part of the Game_Support library found here.</p>

ContentLicense: CC BY-SA 4.0


问:
Dask array mean throws "setting an array element with a sequence" exception where pandas array mean works
I have a pandas data frame that consist of a single column of numpy arrays. I can use the numpy.mean function to calculate the mean of the arrays.

```<code>import numpy
import pandas
f = pandas.DataFrame({"a":[numpy.array([1.0, 2.0]), numpy.array([3.0, 4.0])]})
numpy.mean(f["a"]) # returns array([2., 3.])
</code>```

I want to do the same thing in Dask.

```<code>import dask.dataframe
import dask.array
g = dask.dataframe.from_pandas(f, npartitions=1)
dask.array.mean(g["a"], dtype="float64")
</code>```

(You have to specify the dtype, otherwise you get a TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' exception.)

The call to dask.array.mean returns the following, which looks correct.

```<code>dask.array<mean_agg-aggregate, shape=(), dtype=float64, chunksize=(), chunktype=numpy.ndarray>
</code>```

However, when I run dask.array.mean(g["a"], dtype="float64").compute() to get the final value I get a ValueError: setting an array element with a sequence. exception. The full stack is as follows.

```<code>Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/base.py", line 165, in compute
    (result,) = compute(self, traverse=False, **kwargs)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/base.py", line 436, in compute
    results = schedule(dsk, keys, **kwargs)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/threaded.py", line 81, in get
    **kwargs
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/local.py", line 486, in get_async
    raise_exception(exc, tb)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/local.py", line 316, in reraise
    raise exc
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/local.py", line 222, in execute_task
    result = _execute_task(task, data)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 118, in _execute_task
    args2 = [_execute_task(a, cache) for a in args]
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 118, in <listcomp>
    args2 = [_execute_task(a, cache) for a in args]
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 119, in _execute_task
    return func(*args2)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/optimization.py", line 982, in __call__
    return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 149, in get
    result = _execute_task(task, cache)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 119, in _execute_task
    return func(*args2)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/utils.py", line 29, in apply
    return func(*args, **kwargs)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/array/reductions.py", line 539, in mean_chunk
    total = sum(x, dtype=dtype, **kwargs)
  File "<__array_function__ internals>", line 6, in sum
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 2229, in sum
    initial=initial, where=where)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 90, in _wrapreduction
    return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
ValueError: setting an array element with a sequence.
</code>```

Is it possible to perform the equivalent Dask operation?

答:
It would be good if Dask Dataframe handled this case, but it doesn't today.  It's not actually that surprising given the situation.

Your dataframe is a bit odd, in that elements of that dataframe are themselves Numpy arrays.

```<code>>>> f
            a
0  [1.0, 2.0]
1  [3.0, 4.0]
</code>```

As a result, Pandas thinks that this is an object dtype dataframe

```<code>>>> f.dtypes
a    object
dtype: object
</code>```

Because Dask Dataframe is lazy it doesn't actually keep track of all of the data at any given point, it only knows the dtypes, which in this case are pretty non-informative.  Dask Dataframe doesn't really know what do to with a mean computation on these complex elements.  It doesn't know if your elements are numpy arrays or strings, or custom Python objects, etc..

So it errs and you need to provide a data type explicitly.

The full solution to this problem is probably for Pandas to develop a much more complex dtype heirarchy, but that's probably unlikely near term.

Ideally Dask Dataframe would give a better error message here encouraging you to specify a dtype manually.  If you wanted to raise an issue, that would be welcome.

Body:
I have a pandas data frame that consist of a single column of numpy arrays. I can use the numpy.mean function to calculate the mean of the arrays.

import numpy
import pandas
f = pandas.DataFrame({"a":[numpy.array([1.0, 2.0]), numpy.array([3.0, 4.0])]})
numpy.mean(f["a"]) # returns array([2., 3.])

I want to do the same thing in Dask.

import dask.dataframe
import dask.array
g = dask.dataframe.from_pandas(f, npartitions=1)
dask.array.mean(g["a"], dtype="float64")

(You have to specify the dtype, otherwise you get a TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' exception.)

The call to dask.array.mean returns the following, which looks correct.

dask.array<mean_agg-aggregate, shape=(), dtype=float64, chunksize=(), chunktype=numpy.ndarray>

However, when I run dask.array.mean(g["a"], dtype="float64").compute() to get the final value I get a ValueError: setting an array element with a sequence. exception. The full stack is as follows.

Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/base.py", line 165, in compute
    (result,) = compute(self, traverse=False, **kwargs)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/base.py", line 436, in compute
    results = schedule(dsk, keys, **kwargs)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/threaded.py", line 81, in get
    **kwargs
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/local.py", line 486, in get_async
    raise_exception(exc, tb)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/local.py", line 316, in reraise
    raise exc
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/local.py", line 222, in execute_task
    result = _execute_task(task, data)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 118, in _execute_task
    args2 = [_execute_task(a, cache) for a in args]
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 118, in <listcomp>
    args2 = [_execute_task(a, cache) for a in args]
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 119, in _execute_task
    return func(*args2)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/optimization.py", line 982, in __call__
    return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 149, in get
    result = _execute_task(task, cache)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/core.py", line 119, in _execute_task
    return func(*args2)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/utils.py", line 29, in apply
    return func(*args, **kwargs)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/dask/array/reductions.py", line 539, in mean_chunk
    total = sum(x, dtype=dtype, **kwargs)
  File "<__array_function__ internals>", line 6, in sum
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 2229, in sum
    initial=initial, where=where)
  File "/Users/wmcneill/src.private/radius_limit/venv/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 90, in _wrapreduction
    return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
ValueError: setting an array element with a sequence.

Is it possible to perform the equivalent Dask operation?

Body:
It would be good if Dask Dataframe handled this case, but it doesn't today.  It's not actually that surprising given the situation.

Your dataframe is a bit odd, in that elements of that dataframe are themselves Numpy arrays.

>>> f
            a
0  [1.0, 2.0]
1  [3.0, 4.0]

As a result, Pandas thinks that this is an object dtype dataframe

>>> f.dtypes
a    object
dtype: object

Because Dask Dataframe is lazy it doesn't actually keep track of all of the data at any given point, it only knows the dtypes, which in this case are pretty non-informative.  Dask Dataframe doesn't really know what do to with a mean computation on these complex elements.  It doesn't know if your elements are numpy arrays or strings, or custom Python objects, etc..

So it errs and you need to provide a data type explicitly.

The full solution to this problem is probably for Pandas to develop a much more complex dtype heirarchy, but that's probably unlikely near term.

Ideally Dask Dataframe would give a better error message here encouraging you to specify a dtype manually.  If you wanted to raise an issue, that would be welcome.


问:
Conditional picking of values
I am working with a piece of code, which is supposed to read the columns in each row of the data and based on the value of that cell, create a file name to pick. I was required to use the if elif else statements but the code sometimes picks the right value, sometimes not. So,

This is the data sample:

S.No     File refrence   Time         Detection_Location
1     5008_P1_272   2019-04-24 16:15:53      CV22
2     5007_P2_467   2019-04-25 19:00:22      CV23```
</div>
</div>
</p>

<p>The code I am using for this operation is:</p>

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

# Converting columns to datetime format
df['Time'] = pd.to_datetime(df['Time'], errors = 'coerce').dt.date

#Stripping the  datetime
df['Time'] = pd.to_datetime(df['Time'])
df['Time'] = df['Time'].dt.strftime('%Y-%m-%d')

df[['Stripped Year', 'Stripped Month','Strip date']] = df['Time'].str.split(pat = "-", n=2, expand = True)

# Creating the file name string

for i in df.index:
    First = 'PHD'

    #for s in df['Stripped Year']:
    s = df.iloc[i]['Stripped Year']
    second1 = s[2:]
    print(second1)

    s1 = df.iloc[i]['Stripped Month']
    second2 = s1
    print(second2)
    if second2 == '02':
        second3 = '28'
    if second2 == '01' or '03' or '05' or '07' or '08' or '10' or '12':
        second3 = '31'
    if second2 == '04' or '06' or '09' or '11':
                second3 = '30'
    print(second3)

    s2 = df.iloc[i]['Detection_Location']
    if s2 == 'CV22':
        second4 = 'L1'
    elif s2 == 'CV23':
        second4 = 'L2'
    elif s2 == 'CV3':
        second4 = 'LC'
    print(second4)

    PHD_File_Name = First + ' ' +second1+second2+'01' + ' ' +second1+second2+second3 + ' ' + second4 + '_transformed' + '.xlsx'
    print(PHD_File_Name)

</code>```

My code seems to work well in picking the month value( second3 value from second2 value) sometimes and sometimes it does not pick the right month. I used if elif else and if else else statement but the performance of the code is not consistent. Please help what am I doing wrong.

The desired output for the first row of the data should be:

second1 = 2019
second2 = 04
second3 = 30

```

Thanks

答:
Your conditional statements are wrong. You cannot use

second2 == '01' or '03' or '05' or '07' or '08' or '10' or '12'

Each comparison need to be separate, like second2 == '01' or second2 == '03'

Title: Conditional picking of values

Body:
I am working with a piece of code, which is supposed to read the columns in each row of the data and based on the value of that cell, create a file name to pick. I was required to use the if elif else statements but the code sometimes picks the right value, sometimes not. So,

This is the data sample:

S.No     File refrence   Time         Detection_Location
1     5008_P1_272   2019-04-24 16:15:53      CV22
2     5007_P2_467   2019-04-25 19:00:22      CV23

The code I am using for this operation is:

# Converting columns to datetime format
df['Time'] = pd.to_datetime(df['Time'], errors = 'coerce').dt.date

#Stripping the  datetime
df['Time'] = pd.to_datetime(df['Time'])
df['Time'] = df['Time'].dt.strftime('%Y-%m-%d')

df[['Stripped Year', 'Stripped Month','Strip date']] = df['Time'].str.split(pat = "-", n=2, expand = True)

# Creating the file name string

for i in df.index:
    First = 'PHD'

    #for s in df['Stripped Year']:
    s = df.iloc[i]['Stripped Year']
    second1 = s[2:]
    print(second1)

    s1 = df.iloc[i]['Stripped Month']
    second2 = s1
    print(second2)
    if second2 == '02':
        second3 = '28'
    if second2 == '01' or '03' or '05' or '07' or '08' or '10' or '12':
        second3 = '31'
    if second2 == '04' or '06' or '09' or '11':
                second3 = '30'
    print(second3)

    s2 = df.iloc[i]['Detection_Location']
    if s2 == 'CV22':
        second4 = 'L1'
    elif s2 == 'CV23':
        second4 = 'L2'
    elif s2 == 'CV3':
        second4 = 'LC'
    print(second4)

    PHD_File_Name = First + ' ' +second1+second2+'01' + ' ' +second1+second2+second3 + ' ' + second4 + '_transformed' + '.xlsx'
    print(PHD_File_Name)

My code seems to work well in picking the month value( second3 value from second2 value) sometimes and sometimes it does not pick the right month. I used if elif else and if else else statement but the performance of the code is not consistent. Please help what am I doing wrong.

The desired output for the first row of the data should be:

second1 = 2019
second2 = 04
second3 = 30

Thanks


问:
Exception "type 'String' is not a subtype of type 'int' of 'index'"
I am trying to access values from a DocumentSnapshot which to the best of my knowledge returns a map. I then store the keys in the map to a list, from which I build a ListView. Then I try to access the values by using the keys in the map iteratively. Although I get my expected result and the UI is also rendered as required, the console logs an exception as follows.
I/flutter ( 2093): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2093): The following assertion was thrown building:
I/flutter ( 2093): type 'String' is not a subtype of type 'int' of 'index'
I/flutter ( 2093):
I/flutter ( 2093): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 2093): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 2093): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 2093):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 2093):
I/flutter ( 2093): When the exception was thrown, this was the stack:
I/flutter ( 2093): #0      _CartState.cartTile.<anonymous closure> (package:zombie/screens/home/nav/tabs/cart.dart:78:71)
I/flutter ( 2093): #1      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:446:15)
I/flutter ( 2093): #2      SliverMultiBoxAdaptorElement._build.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1260:67)
I/flutter ( 2093): #3      _HashMap.putIfAbsent (dart:collection-patch/collection_patch.dart:139:29)
I/flutter ( 2093): #4      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1260:26)
I/flutter ( 2093): #5      SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1273:55)
I/flutter ( 2093): #6      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2412:19)
I/flutter ( 2093): #7      SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1266:11)
I/flutter ( 2093): #8      RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:354:23)
I/flutter ( 2093): #9      RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1823:58)
I/flutter ( 2093): #10     PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:875:15)
I/flutter ( 2093): #11     RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1823:13)
I/flutter ( 2093): #12     RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:343:5)
I/flutter ( 2093): #13     RenderSliverMultiBoxAdaptor.addInitialChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:427:5)
I/flutter ( 2093): #14     RenderSliverList.performLayout (package:flutter/src/rendering/sliver_list.dart:78:12)
I/flutter ( 2093): #15     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #16     RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:134:11)
I/flutter ( 2093): #17     RenderSliverPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:373:11)
I/flutter ( 2093): #18     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #19     RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:410:13)
I/flutter ( 2093): #20     RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1367:12)
I/flutter ( 2093): #21     RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1285:20)
I/flutter ( 2093): #22     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #23     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #24     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #25     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #26     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #27     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #28     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #29     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #30     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #31     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #32     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #33     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #34     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #35     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #36     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #37     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #38     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #39     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #40     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #41     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #42     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #43     RenderConstrainedBox.performLayout (package:flutter/src/rendering/proxy_box.dart:259:13)
I/flutter ( 2093): #44     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #45     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:744:15)
I/flutter ( 2093): #46     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #47     RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:206:11)
I/flutter ( 2093): #48     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #49     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:163:11)
I/flutter ( 2093): #50     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:477:7)
I/flutter ( 2093): #51     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:232:7)
I/flutter ( 2093): #52     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:391:14)
I/flutter ( 2093): #53     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1584:7)
I/flutter ( 2093): #54     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:844:18)
I/flutter ( 2093): #55     RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:344:19)
I/flutter ( 2093): #56     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:774:13)
I/flutter ( 2093): #57     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:283:5)
I/flutter ( 2093): #58     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1102:15)
I/flutter ( 2093): #59     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1041:9)
I/flutter ( 2093): #60     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:957:5)
I/flutter ( 2093): #64     _invoke (dart:ui/hooks.dart:259:10)
I/flutter ( 2093): #65     _drawFrame (dart:ui/hooks.dart:217:3)
I/flutter ( 2093): (elided 3 frames from package dart:async)
I/flutter ( 2093): ════

The following is a part of my code which causes the exception

```<code>Widget cartTile(DocumentSnapshot doc) {
var snap = doc.data;
if(snap == null){
  return SizedBox();
}
List<String> _keys = snap.keys.toList();
print(_keys);
return ListView.builder(
  itemCount: _keys.length,
  physics: BouncingScrollPhysics(),
  itemBuilder: (BuildContext context, int index) {
    return Padding(
      padding: EdgeInsets.fromLTRB(20.0, 3.0, 20.0, 3.0),
      child: Material(
          elevation: 10.0,
          borderRadius: BorderRadius.circular(10.0),
          color: Colors.white,
          child: InkWell(
            borderRadius: BorderRadius.circular(10.0),
            onTap: () async {

            },
            child: Padding(
              padding: const EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
              child: ListTile(
                leading: CircleAvatar(
                  radius: 25,
                  backgroundColor: Colors.white,
                  backgroundImage: NetworkImage(snap[_keys[index]]['imgPath']),
                ),
</code>```

Obviously the last line  backgroundImage: NetworkImage(snap[_keys[index]]['imgPath']), is the cause of exception. I've tried to solve it for hours but am not able to. Would appreciate any help. Thanks.

答: Maybe the problem is around "['imgPath']", have you tried to print only snap[_keys[index]] and sees if the output are a map? According the exception, seens to be a list to me...

Body:
I am trying to access values from a DocumentSnapshot which to the best of my knowledge returns a map. I then store the keys in the map to a list, from which I build a ListView. Then I try to access the values by using the keys in the map iteratively. Although I get my expected result and the UI is also rendered as required, the console logs an exception as follows.
I/flutter ( 2093): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2093): The following assertion was thrown building:
I/flutter ( 2093): type 'String' is not a subtype of type 'int' of 'index'
I/flutter ( 2093):
I/flutter ( 2093): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 2093): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 2093): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 2093):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 2093):
I/flutter ( 2093): When the exception was thrown, this was the stack:
I/flutter ( 2093): #0      _CartState.cartTile.<anonymous closure> (package:zombie/screens/home/nav/tabs/cart.dart:78:71)
I/flutter ( 2093): #1      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:446:15)
I/flutter ( 2093): #2      SliverMultiBoxAdaptorElement._build.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1260:67)
I/flutter ( 2093): #3      _HashMap.putIfAbsent (dart:collection-patch/collection_patch.dart:139:29)
I/flutter ( 2093): #4      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1260:26)
I/flutter ( 2093): #5      SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1273:55)
I/flutter ( 2093): #6      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2412:19)
I/flutter ( 2093): #7      SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1266:11)
I/flutter ( 2093): #8      RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:354:23)
I/flutter ( 2093): #9      RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1823:58)
I/flutter ( 2093): #10     PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:875:15)
I/flutter ( 2093): #11     RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1823:13)
I/flutter ( 2093): #12     RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:343:5)
I/flutter ( 2093): #13     RenderSliverMultiBoxAdaptor.addInitialChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:427:5)
I/flutter ( 2093): #14     RenderSliverList.performLayout (package:flutter/src/rendering/sliver_list.dart:78:12)
I/flutter ( 2093): #15     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #16     RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:134:11)
I/flutter ( 2093): #17     RenderSliverPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:373:11)
I/flutter ( 2093): #18     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #19     RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:410:13)
I/flutter ( 2093): #20     RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1367:12)
I/flutter ( 2093): #21     RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1285:20)
I/flutter ( 2093): #22     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #23     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #24     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #25     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #26     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #27     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #28     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #29     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #30     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #31     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #32     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #33     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #34     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #35     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #36     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #37     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #38     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #39     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #40     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #41     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter ( 2093): #42     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #43     RenderConstrainedBox.performLayout (package:flutter/src/rendering/proxy_box.dart:259:13)
I/flutter ( 2093): #44     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #45     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:744:15)
I/flutter ( 2093): #46     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #47     RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:206:11)
I/flutter ( 2093): #48     RenderObject.layout (package:flutter/src/rendering/object.dart:1724:7)
I/flutter ( 2093): #49     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:163:11)
I/flutter ( 2093): #50     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:477:7)
I/flutter ( 2093): #51     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:232:7)
I/flutter ( 2093): #52     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:391:14)
I/flutter ( 2093): #53     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1584:7)
I/flutter ( 2093): #54     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:844:18)
I/flutter ( 2093): #55     RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:344:19)
I/flutter ( 2093): #56     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:774:13)
I/flutter ( 2093): #57     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:283:5)
I/flutter ( 2093): #58     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1102:15)
I/flutter ( 2093): #59     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1041:9)
I/flutter ( 2093): #60     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:957:5)
I/flutter ( 2093): #64     _invoke (dart:ui/hooks.dart:259:10)
I/flutter ( 2093): #65     _drawFrame (dart:ui/hooks.dart:217:3)
I/flutter ( 2093): (elided 3 frames from package dart:async)
I/flutter ( 2093): ════

The following is a part of my code which causes the exception

Widget cartTile(DocumentSnapshot doc) {
var snap = doc.data;
if(snap == null){
  return SizedBox();
}
List<String> _keys = snap.keys.toList();
print(_keys);
return ListView.builder(
  itemCount: _keys.length,
  physics: BouncingScrollPhysics(),
  itemBuilder: (BuildContext context, int index) {
    return Padding(
      padding: EdgeInsets.fromLTRB(20.0, 3.0, 20.0, 3.0),
      child: Material(
          elevation: 10.0,
          borderRadius: BorderRadius.circular(10.0),
          color: Colors.white,
          child: InkWell(
            borderRadius: BorderRadius.circular(10.0),
            onTap: () async {

            },
            child: Padding(
              padding: const EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
              child: ListTile(
                leading: CircleAvatar(
                  radius: 25,
                  backgroundColor: Colors.white,
                  backgroundImage: NetworkImage(snap[_keys[index]]['imgPath']),
                ),

Obviously the last line  backgroundImage: NetworkImage(snap[_keys[index]]['imgPath']), is the cause of exception. I've tried to solve it for hours but am not able to. Would appreciate any help. Thanks.


问:
Cypress custom commands not recognized
I want to create a custom login command.  I've added the command to my commands.js file, and also have the import command added to index.js.

When I create a new test file under my integration folder, I try to reference my new command with cy.loginWith(), but it is not recognizing it as a command.

If I add import ../../../support/commands to the top of my new login spec file, the cy.loginWith() custom command is recognized and invoked correctly.

However I know this is not a good thing to do.

This is my custom command in my commands.js file:

```<code>Cypress.Commands.add('loginWith' , (email, password) => {
    cy.get('[name="username"]').type(email)
    cy.get('[name="password"]').type(password)
    cy.get('[name="Login"]').click()
})
</code>```

This is my index.js file:

```<code>import "./commands.js"
</code>```

This is my list.js spec file that sits under /cypress/integration/clients/client list/lists:

```<code>/// <reference types="Cypress" />

import "../../../support/commands"

// login to the app
it('A User logs in and sees a welcome message', () => {
    cy.visit('.../login.cfm')
    cy.loginWith('username', 'password')
    expect(cy.contains('Welcome back!'))

   }
)
</code>```

Is there something I may have misconfigured that is not recognizing the index.js file?

答:
My issue was that intellisense worked fine and everything ran perfectly after doing:

import '../support/commands';

My fix was very simple... just add supportFile to your cypress.json:

```<code>{
  "supportFile": "cypress/support/index.ts",
  "baseUrl": "http://localhost:3000"
}
</code>```
```<code>// index.ts
import './commands'
</code>```

Title: Cypress custom commands not recognized

Body:
I want to create a custom login command.  I've added the command to my commands.js file, and also have the import command added to index.js.

When I create a new test file under my integration folder, I try to reference my new command with cy.loginWith(), but it is not recognizing it as a command.

If I add import ../../../support/commands to the top of my new login spec file, the cy.loginWith() custom command is recognized and invoked correctly.

However I know this is not a good thing to do.

This is my custom command in my commands.js file:

Cypress.Commands.add('loginWith' , (email, password) => {
    cy.get('[name="username"]').type(email)
    cy.get('[name="password"]').type(password)
    cy.get('[name="Login"]').click()
})

This is my index.js file:

import "./commands.js"

This is my list.js spec file that sits under /cypress/integration/clients/client list/lists:

/// <reference types="Cypress" />

import "../../../support/commands"

// login to the app
it('A User logs in and sees a welcome message', () => {
    cy.visit('.../login.cfm')
    cy.loginWith('username', 'password')
    expect(cy.contains('Welcome back!'))

   }
)

Is there something I may have misconfigured that is not recognizing the index.js file?

Body:
My issue was that intellisense worked fine and everything ran perfectly after doing:

import '../support/commands';

My fix was very simple... just add supportFile to your cypress.json:

{
  "supportFile": "cypress/support/index.ts",
  "baseUrl": "http://localhost:3000"
}

// index.ts
import './commands'


问:
How to angular route for sub modules?
I have a dashboard module in my angular application. And my app.module.ts is like following.

```<code>@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DashboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And app-routing.module.ts is

```<code>const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

And dashboard.route.ts is

```<code>const dashboardRoutes: Routes = [
    { path: 'dashboard', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(dashboardRoutes)],
    exports: [RouterModule]
})
export class DashboardRouteModuel {}
</code>```

But the applciaiton is routing to PageNotFoundComponent always.

答:
Your routing concepts are not correct. Simply put, you have to do:

on the app-routing.module.ts:

```<code>const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', loadChildren: 'path/to/dashboard.module#DashboardModule' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

and on the dashboard-route.module.ts:

```<code>const routes: Routes = [
    { path: '', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class DashboardRouteModule {}
</code>```

don't forget you must have a dashboard.module.ts with the class name "DashboardModule" where you import the dashboard-rote.module.ts, in order for this to work.

Title: How to angular route for sub modules?

Body:
I have a dashboard module in my angular application. And my app.module.ts is like following.

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DashboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And app-routing.module.ts is

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

And dashboard.route.ts is

const dashboardRoutes: Routes = [
    { path: 'dashboard', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(dashboardRoutes)],
    exports: [RouterModule]
})
export class DashboardRouteModuel {}

But the applciaiton is routing to PageNotFoundComponent always.

Body:
Your routing concepts are not correct. Simply put, you have to do:

on the app-routing.module.ts:

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', loadChildren: 'path/to/dashboard.module#DashboardModule' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

and on the dashboard-route.module.ts:

const routes: Routes = [
    { path: '', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class DashboardRouteModule {}

don't forget you must have a dashboard.module.ts with the class name "DashboardModule" where you import the dashboard-rote.module.ts, in order for this to work.


问:
list of dictionary: aggregate value by grouping by inner dictionary key
I have this signature:

```<code>def aggregate_by_player_id(input, playerid, fields):
</code>```

By 'fields', i mean fields to sum up grouping by 'playerID' within the 'input'.

I call the function like this:

```<code>aggregate_by_player_id(input, 'player', ['stat1','stat3'])
</code>```

Input look like this:

```<code>[{'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
{'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
{'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}]
</code>```

My output structure is:

```<code>nested_dic = {value_of_playerid1: {'playerid': value_of_playerid1, 'stat1': value_of_stat1, 'stat2': value_of_stat2},
              value_of_playerid2: {'playerid': value_of_playerid2, 'stat2': value_of_stat2, 'stat2': value_of_stat2},
              value_of_playerid3: {'playerid': value_of_playerid3, 'stat3': value_of_stat3, 'stat3': value_of_stat3}}
</code>```

Hence the output should look like:

```<code>{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
 '2': {'player': '2', 'stat1': 2, 'stat3': 4},
 '3': {'player': '3', 'stat1': 4, 'stat3': 6}}
</code>```

答:
We can use itertools.groupby for this to group on playerid and then sum values across the fields.

```<code>from itertools import groupby
from operator import itemgetter

def aggregate_by_player_id(input_, playerid, fields):
    player = itemgetter(playerid)
    output = {}

    for k, v in groupby(input_, key=player):
        data = list(v)
        stats = {playerid: k}

        for field in fields:
            stats[field] = sum(int(d.get(field, 0)) for d in data)
        output[k] = stats
    return output

data.sort(key=player) # data must be pre-sorted on grouping key
results = aggregate_by_player_id(data, 'player', ['stat1', 'stat3'])

{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
 '2': {'player': '2', 'stat1': 2, 'stat3': 4},
 '3': {'player': '3', 'stat1': 4, 'stat3': 6}}
</code>```

Body:
I have this signature:

def aggregate_by_player_id(input, playerid, fields):

By 'fields', i mean fields to sum up grouping by 'playerID' within the 'input'.

I call the function like this:

aggregate_by_player_id(input, 'player', ['stat1','stat3'])

Input look like this:

[{'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
{'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
{'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}]

My output structure is:

nested_dic = {value_of_playerid1: {'playerid': value_of_playerid1, 'stat1': value_of_stat1, 'stat2': value_of_stat2},
              value_of_playerid2: {'playerid': value_of_playerid2, 'stat2': value_of_stat2, 'stat2': value_of_stat2},
              value_of_playerid3: {'playerid': value_of_playerid3, 'stat3': value_of_stat3, 'stat3': value_of_stat3}}

Hence the output should look like:

{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
 '2': {'player': '2', 'stat1': 2, 'stat3': 4},
 '3': {'player': '3', 'stat1': 4, 'stat3': 6}}

Body:
We can use itertools.groupby for this to group on playerid and then sum values across the fields.

from itertools import groupby
from operator import itemgetter

def aggregate_by_player_id(input_, playerid, fields):
    player = itemgetter(playerid)
    output = {}

    for k, v in groupby(input_, key=player):
        data = list(v)
        stats = {playerid: k}

        for field in fields:
            stats[field] = sum(int(d.get(field, 0)) for d in data)
        output[k] = stats
    return output

data.sort(key=player) # data must be pre-sorted on grouping key
results = aggregate_by_player_id(data, 'player', ['stat1', 'stat3'])

{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
 '2': {'player': '2', 'stat1': 2, 'stat3': 4},
 '3': {'player': '3', 'stat1': 4, 'stat3': 6}}


问:
pip install pcapy cannot open include file 'pcap.h'
I tried to install pcapy using pip install pcapy, but I encoutered an error stating that the file pcap.h does not exist as following:

```<code>Installing collected packages: pcapy
  Running setup.py install for pcapy ... error
    Complete output from command c:\python27\python.exe -u -c "import setuptools
tokenize;__file__='c:\\users\\username\\appdata\\local\\temp\\pip-install-1tyk
yr\\pcapy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))"
install --
record c:\users\username\appdata\local\temp\pip-record-u_q6qm\install-record.txt
 --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    building 'pcapy' extension
    creating build
    creating build\temp.win-amd64-2.7
    creating build\temp.win-amd64-2.7\Release
    creating build\temp.win-amd64-2.7\Release\win32
    C:\Users\UserName\AppData\Local\Programs\Common\Microsoft\Visual C++ for
Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -DWIN32=1 -I
c:\wpdpack\Include -Ic:\python27\include -Ic:\python27\PC /Tppcapdumper.cc /Fobuild\temp.win-amd64-2.7\Release\pcapdumper.obj
    pcapdumper.cc
    pcapdumper.cc(11) : fatal error C1083: Cannot open include file: 'pcap.h': N
o such file or directory
    error: command 'C:\\Users\\UserName\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\username\\appdata\\local\\temp\\pip-install-1tykyr\\pcapy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\username\appdata\local\temp\pip-record-u_q6qm\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\username\appdata\local\temp\pip-install-1tykyr\pcapy\
</code>```

I tried to upgrade setuptools but I got the same result. I tried to install libcap by running pip install libcap but I also got the same problem. How can I fix this problem?

答:
It's generally easier to download install a binary. If you do build from source:

Download the WinPcap Developer's Pack.

Use pip's --global-option. setup.py is different, but I think pip is preferred over setup.py anyway.

Here's an example line (substitute in the correct paths for your system; I just referenced them right in the Downloads folder):

```<code>pip install ./pcapy-src-dir --global-option=build_ext --global-option="-LC:\path\to\WpdPack_4_1_2\WpdPack\Lib" --global-option="-IC:\path\to\WpdPack_4_1_2\WpdPack\Include
</code>```

See also this answer

Body:
I tried to install pcapy using pip install pcapy, but I encoutered an error stating that the file pcap.h does not exist as following:

Installing collected packages: pcapy
  Running setup.py install for pcapy ... error
    Complete output from command c:\python27\python.exe -u -c "import setuptools
tokenize;__file__='c:\\users\\username\\appdata\\local\\temp\\pip-install-1tyk
yr\\pcapy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))"
install --
record c:\users\username\appdata\local\temp\pip-record-u_q6qm\install-record.txt
 --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    building 'pcapy' extension
    creating build
    creating build\temp.win-amd64-2.7
    creating build\temp.win-amd64-2.7\Release
    creating build\temp.win-amd64-2.7\Release\win32
    C:\Users\UserName\AppData\Local\Programs\Common\Microsoft\Visual C++ for
Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -DWIN32=1 -I
c:\wpdpack\Include -Ic:\python27\include -Ic:\python27\PC /Tppcapdumper.cc /Fobuild\temp.win-amd64-2.7\Release\pcapdumper.obj
    pcapdumper.cc
    pcapdumper.cc(11) : fatal error C1083: Cannot open include file: 'pcap.h': N
o such file or directory
    error: command 'C:\\Users\\UserName\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\username\\appdata\\local\\temp\\pip-install-1tykyr\\pcapy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\username\appdata\local\temp\pip-record-u_q6qm\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\username\appdata\local\temp\pip-install-1tykyr\pcapy\

I tried to upgrade setuptools but I got the same result. I tried to install libcap by running pip install libcap but I also got the same problem. How can I fix this problem?

Body:
It's generally easier to download install a binary. If you do build from source:

Download the WinPcap Developer's Pack.

Use pip's --global-option. setup.py is different, but I think pip is preferred over setup.py anyway.

Here's an example line (substitute in the correct paths for your system; I just referenced them right in the Downloads folder):

pip install ./pcapy-src-dir --global-option=build_ext --global-option="-LC:\path\to\WpdPack_4_1_2\WpdPack\Lib" --global-option="-IC:\path\to\WpdPack_4_1_2\WpdPack\Include

See also this answer


答:
That translates to:

```<code>diffList = []
for key in set(dict1.keys() + dict2.keys()):
    if dict1.get(key) != dict2.get(key):
        diffList.append(key)
</code>```

What this basically does is it generates a new list, with the unique values from both dicts. Not that those values are unique per key, and not necessarily unique global.

A set is a datastructure where there can be only one entry for each unique value. So it will make sure that it only has unique items. This will make sure that you only check each key once.

Update: Changed some things according to the updates to the question.

Title: Translation of this Python Line

Body:
That translates to:

diffList = []
for key in set(dict1.keys() + dict2.keys()):
    if dict1.get(key) != dict2.get(key):
        diffList.append(key)

What this basically does is it generates a new list, with the unique values from both dicts. Not that those values are unique per key, and not necessarily unique global.

A set is a datastructure where there can be only one entry for each unique value. So it will make sure that it only has unique items. This will make sure that you only check each key once.

Update: Changed some things according to the updates to the question.


问:
Recursive function on mutable object
I am trying to build all paths recursively in a class. Here is what I have so far:

```<code>def get_paths(self, component=None, current_path=None, all_paths=None):

    # set defaults
    if component is None:
        component = self._ground;
        current_path = [component,]

    ##### [START] RECURSIVE PART #####

    # get parents of component
    parents = component.parents()

    # if no parents (an endpoint/leaf), add the current_path
    if not parents:
        all_paths.append(current_path)

    # if parents ==> recurse
    # note: because we're starting from the ground and getting all parents
    # we insert the parent before the current path (not after, like if we
    # were recursively getting files in a directory)
    else:
        for parent in parents:
            self.get_paths(parent, [parent,] + current_path), all_paths)

    ##### [END] RECURSIVE PART #####

    # Note that the recursion doesn't 'return' anything, it only modifies
    # the list. We still have to return the list by the method at the end.
    return all_paths
</code>```

What this does is it starts at the 'ground' and then recurses up until the element does not have any parents. My question is whether this is a common way to do recursion -- to not actually return anything in the 'recursive part' but just to modify the mutable element (the list here) and then return the result later.

If the above isn't ideal, what would be an example of how it can be improved? Or, what are other ways in which to return a list of paths (the above is very similar to what the $ find ./ would do getting a list of paths).

答:
A simple way to do it would be to have a public "interface" method that calls a private recursive method.

Something along these lines:

```<code>class Klass:

    _ground = 'ground'

    # Public method.
    def get_paths(self, component=None, current_path=None):
        all_paths = []
        self._get_paths(all_paths, component, current_path)  # Call private method.
        return all_paths

    # Private method.
    def _get_paths(self, all_paths, component=None, current_path=None):
        # Modifies all_paths - executed for that side-effect.

        # set defaults
        if component is None:
            component = self._ground;
            current_path = [component,]

        # get parents of component
        parents = component.parents()

        # if no parents (an endpoint/leaf), add the current_path
        if not parents:
            all_paths.append(current_path)
        else:
            for parent in parents:
                self._get_paths(parent, [parent,] + current_path), all_paths)
</code>```

Title: Recursive function on mutable object

Body:
I am trying to build all paths recursively in a class. Here is what I have so far:

def get_paths(self, component=None, current_path=None, all_paths=None):

    # set defaults
    if component is None:
        component = self._ground;
        current_path = [component,]

    ##### [START] RECURSIVE PART #####

    # get parents of component
    parents = component.parents()

    # if no parents (an endpoint/leaf), add the current_path
    if not parents:
        all_paths.append(current_path)

    # if parents ==> recurse
    # note: because we're starting from the ground and getting all parents
    # we insert the parent before the current path (not after, like if we
    # were recursively getting files in a directory)
    else:
        for parent in parents:
            self.get_paths(parent, [parent,] + current_path), all_paths)

    ##### [END] RECURSIVE PART #####

    # Note that the recursion doesn't 'return' anything, it only modifies
    # the list. We still have to return the list by the method at the end.
    return all_paths

What this does is it starts at the 'ground' and then recurses up until the element does not have any parents. My question is whether this is a common way to do recursion -- to not actually return anything in the 'recursive part' but just to modify the mutable element (the list here) and then return the result later.

If the above isn't ideal, what would be an example of how it can be improved? Or, what are other ways in which to return a list of paths (the above is very similar to what the $ find ./ would do getting a list of paths).

Body:
A simple way to do it would be to have a public "interface" method that calls a private recursive method.

Something along these lines:

class Klass:

    _ground = 'ground'

    # Public method.
    def get_paths(self, component=None, current_path=None):
        all_paths = []
        self._get_paths(all_paths, component, current_path)  # Call private method.
        return all_paths

    # Private method.
    def _get_paths(self, all_paths, component=None, current_path=None):
        # Modifies all_paths - executed for that side-effect.

        # set defaults
        if component is None:
            component = self._ground;
            current_path = [component,]

        # get parents of component
        parents = component.parents()

        # if no parents (an endpoint/leaf), add the current_path
        if not parents:
            all_paths.append(current_path)
        else:
            for parent in parents:
                self._get_paths(parent, [parent,] + current_path), all_paths)


问:
How to Migrating from AMQ to SQS
I am using 3 AMQ in my current application and decided to use now SQS in place of AMQ .
With AMQ i have been using EC2 and micro services for produce and consume from AMQ .

Now when i decided to move to SQS in server less way,i am thinking how i can use it here ?
Here is my concern .

The SQS will have heavy load cumming from SNS and in server less way lambda handles that automatically but when i replace in my current application how EC2 application is going to handle that ?

Do i need auto scaling group here so that if heavy load in SQS then more ec2 application will come up ?

Is there any way i can user lambda consumer with my EC2 existing application so that my well tested EC2 application remain as it is and i would be able to use my lambda function also ?

答:
The SQS will have heavy load coming from SNS and in server less way
  lambda handles that automatically but when i replace in my current
  application how EC2 application is going to handle that ?

How is your EC2 application going to handle what exactly? The "load"? The SQS consumers (your EC2 instances) will poll SQS for new messages only when they are ready to consume more messages. SQS does not push messages, so it will not somehow overload your EC2 instances. SQS simply accepts messages and stores them until something asks for them (or until the messages time out).

Do i need auto scaling group here so that if heavy load in SQS then
  more ec2 application will come up ?

Only if you want the messages processed within a certain time frame.

Is there any way i can use lambda consumer with my EC2 existing
  application so that my well tested EC2 application remain as it is and
  i would be able to use my lambda function also?

What would the Lambda function do in this scenario exactly? The only option here would be to convert your EC2 application to a Lambda application. Otherwise there is nothing extra that Lambda can do to "help" your EC2 instances process the SQS messages.

Title: How to Migrating from AMQ to SQS


问:
How to create a teardrop/water drop filling using css and javascript
How to create a teardrop/water drop filling using the css and javascript dynamically filling the water.

for example.

it will fill the water/tear drop depends on the percentage.

example when the percentage is 100% it will full the water/tear drop.

答:
The best way to approach the problem is with SVG graphic so create it dynamically

<svg width="100%" viewbox="0 0 50 42">
  <path class="tear"
        d="M15 6
           Q 15 6, 25 18
           A 12.8 12.8 0 1 1 5 18
           Q 15 6 15 6z" />
</svg>

```
</div>
</div>
</p>

<p>The next thing you would want to look at is filling the path with a color based on </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tear {
  fill: red;
  stroke: black;
  stroke-width: 2PX;

  transform-origin: top center;
}</code>```

    <svg width="100%" viewbox="0 0 50 42">
      <path class="tear"
            d="M15 6
               Q 15 6, 25 18
               A 12.8 12.8 0 1 1 5 18
               Q 15 6 15 6z" />
    </svg>

```
</div>
</div>
</p>

<p>The last step is to create a create a gradient and with JS manipulate the where the gradient starts and finishes </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//change gradient

function change()
{
let tear = document.getElementById('tear');
tear.setAttribute("fill","url(#grad2)");

}

var click1 =document.getElementById('clickMe');
click1.addEventListener("click",change);</code>```

.tear {

  stroke: black;
  stroke-width: 2PX;

  transform-origin: top center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='clickMe'> Click here !</div>

 <div class="box">
<svg width="100%" viewbox="0 0 50 42">
<defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
      <stop offset="50%" style="stop-color:rgb(255,255,255);stop-opacity:1" />
      <stop offset="60%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
    </linearGradient>

     <linearGradient id="grad2" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
      <stop offset="20%" style="stop-color:rgb(255,255,255);stop-opacity:1" />
      <stop offset="30%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
    </linearGradient>
  </defs>

  <path id="tear" class="tear"
        d="M15 6
           Q 15 6, 25 18
           A 12.8 12.8 0 1 1 5 18
           Q 15 6 15 6z" fill="url(#grad1)"/>
</svg>
  </div></code>```

On other examples around the web the guys try to overlay another path but for the easiest approach just use a a couple of gradients with your svg and bit of JS

I trust this helps you

Body:
The best way to approach the problem is with SVG graphic so create it dynamically

<div class="box">
<svg width="100%" viewbox="0 0 50 42">
  <path class="tear"
        d="M15 6
           Q 15 6, 25 18
           A 12.8 12.8 0 1 1 5 18
           Q 15 6 15 6z" />
</svg>
  </div>

The next thing you would want to look at is filling the path with a color based on

.tear {
  fill: red;
  stroke: black;
  stroke-width: 2PX;

  transform-origin: top center;
}

    <div class="box">
    <svg width="100%" viewbox="0 0 50 42">
      <path class="tear"
            d="M15 6
               Q 15 6, 25 18
               A 12.8 12.8 0 1 1 5 18
               Q 15 6 15 6z" />
    </svg>
      </div>

The last step is to create a create a gradient and with JS manipulate the where the gradient starts and finishes

//change gradient

function change()
{
let tear = document.getElementById('tear');
tear.setAttribute("fill","url(#grad2)");

}

var click1 =document.getElementById('clickMe');
click1.addEventListener("click",change);

.tear {

  stroke: black;
  stroke-width: 2PX;

  transform-origin: top center;
}

<div id='clickMe'> Click here !</div>

 <div class="box">
<svg width="100%" viewbox="0 0 50 42">
<defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
      <stop offset="50%" style="stop-color:rgb(255,255,255);stop-opacity:1" />
      <stop offset="60%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
    </linearGradient>

     <linearGradient id="grad2" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
      <stop offset="20%" style="stop-color:rgb(255,255,255);stop-opacity:1" />
      <stop offset="30%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
    </linearGradient>
  </defs>

  <path id="tear" class="tear"
        d="M15 6
           Q 15 6, 25 18
           A 12.8 12.8 0 1 1 5 18
           Q 15 6 15 6z" fill="url(#grad1)"/>
</svg>
  </div>

On other examples around the web the guys try to overlay another path but for the easiest approach just use a a couple of gradients with your svg and bit of JS

I trust this helps you


问:
Why item select doesn't work in recyclerview on normal list but works in search list?
I have created arraylist for projects which is stored in firebase database. I was able to list the projects in recyclerview. Even search too works fine. But when it comes to clicking an item in the recyclerview list, the click works in search list but doesn't work in normal list. The code is given below

```<code>public class MainActivity extends AppCompatActivity implements Adapter.SelectedProject {

    DatabaseReference mDatabase;
    ArrayList<projects> list;
    RecyclerView PList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PList = findViewById(R.id.ProjList);
        PList.setHasFixedSize(true);
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Projects");
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mDatabase != null) {

            mDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    if (dataSnapshot.exists()) {

                        list = new ArrayList<>();
                        for (DataSnapshot ds : dataSnapshot.getChildren()) {
                            list.add(ds.getValue(projects.class));
                        }
                        Adapter adapter = new Adapter(list, null);
                        PList.setAdapter(adapter);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                    Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_home, menu);
        MenuItem item = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) item.getActionView();

        if (searchView != null) {

            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    search(newText);
                    return true;
                }
            });
        }

        return super.onCreateOptionsMenu(menu);
    }

    private void search(String str) {

        ArrayList<projects> sList = new ArrayList<>();

        for (projects object : list) {

            if (object.getPname().toLowerCase().contains(str.toLowerCase())) {

                sList.add(object);
            }

        }
        Adapter adapter = new Adapter(sList, this);
        PList.setAdapter(adapter);

    }

    @Override
    public void selectedProject(projects projects) {
        startActivity(new Intent(MainActivity.this, InfoActivity.class));
    }
}
</code>```

Adapter Class

```<code>public class Adapter extends RecyclerView.Adapter < Adapter.ProjViewHolder > {

    private ArrayList < projects > list;
    private SelectedProject selectedProject;

    public Adapter(ArrayList < projects > list, SelectedProject selectedProject) {

        this.list = list;
        this.selectedProject = selectedProject;
    }

    @NonNull
    @Override
    public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_list, parent, false);
        return new ProjViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ProjViewHolder holder, int position) {

        holder.prname.setText(list.get(position).getPname());
        holder.prlocation.setText(list.get(position).getPlocation());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public interface SelectedProject {
        void selectedProject(projects projects);
    }

    class ProjViewHolder extends RecyclerView.ViewHolder {

        TextView prname, prlocation;

        public ProjViewHolder(@NonNull View itemView) {
            super(itemView);

            prname = itemView.findViewById(R.id.FPName);
            prlocation = itemView.findViewById(R.id.FPLocation);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectedProject.selectedProject(list.get(getAdapterPosition()));
                }
            });
        }
    }
}
</code>```

The selection is accepted in the search adapter.

```<code>Adapter adapter = new Adapter(sList,this);
</code>```

But normal adapter shows error for the below code.

```<code>Adapter adapter = new Adapter(list,this);
</code>```

But if i change this to null as below, the error goes off.

```<code>Adapter adapter = new Adapter(list,null);
</code>```

But when I clicked, the app is closed.

Please let me know how to correct the error?

stackrace details

```<code> java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.volq.Adapter$SelectedProject.selectedProject(com.example.volq.projects)' on a null object reference
    at com.example.volq.Adapter$ProjViewHolder$1.onClick(Adapter.java:68)
    at android.view.View.performClick(View.java:5610)
    at android.view.View$PerformClick.run(View.java:22265)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    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>```

答:
Notice the difference between how you're setting your adapter for search vs normal

```<code>Adapter adapter = new Adapter(sList, this); // `this`as the second parameter/listener is ok
</code>```

But for the other one:

```<code>Adapter adapter = new Adapter(list, null);
</code>```

Here the listener is null, this error makes sense:

java.lang.NullPointerException: Attempt to invoke interface method
  'void
  com.example.volq.Adapter$SelectedProject.selectedProject(com.example.volq.projects)'
  on a null object reference

Instead of null, just pass MainActivity.this in your Activity's onStart() callback:

Adapter adapter = new Adapter(list, MainActivity.this);

But normal adapter shows error for the below code.

Adapter adapter = new Adapter(list,this);

It's because of this does not reference MainActivity inside onDataChange() callback, it refers to the ValueEventListener

Body:
I have created arraylist for projects which is stored in firebase database. I was able to list the projects in recyclerview. Even search too works fine. But when it comes to clicking an item in the recyclerview list, the click works in search list but doesn't work in normal list. The code is given below

public class MainActivity extends AppCompatActivity implements Adapter.SelectedProject {

    DatabaseReference mDatabase;
    ArrayList<projects> list;
    RecyclerView PList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PList = findViewById(R.id.ProjList);
        PList.setHasFixedSize(true);
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Projects");
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mDatabase != null) {

            mDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    if (dataSnapshot.exists()) {

                        list = new ArrayList<>();
                        for (DataSnapshot ds : dataSnapshot.getChildren()) {
                            list.add(ds.getValue(projects.class));
                        }
                        Adapter adapter = new Adapter(list, null);
                        PList.setAdapter(adapter);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                    Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_home, menu);
        MenuItem item = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) item.getActionView();

        if (searchView != null) {

            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    search(newText);
                    return true;
                }
            });
        }

        return super.onCreateOptionsMenu(menu);
    }

    private void search(String str) {

        ArrayList<projects> sList = new ArrayList<>();

        for (projects object : list) {

            if (object.getPname().toLowerCase().contains(str.toLowerCase())) {

                sList.add(object);
            }

        }
        Adapter adapter = new Adapter(sList, this);
        PList.setAdapter(adapter);

    }

    @Override
    public void selectedProject(projects projects) {
        startActivity(new Intent(MainActivity.this, InfoActivity.class));
    }
}

Adapter Class

public class Adapter extends RecyclerView.Adapter < Adapter.ProjViewHolder > {

    private ArrayList < projects > list;
    private SelectedProject selectedProject;

    public Adapter(ArrayList < projects > list, SelectedProject selectedProject) {

        this.list = list;
        this.selectedProject = selectedProject;
    }

    @NonNull
    @Override
    public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_list, parent, false);
        return new ProjViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ProjViewHolder holder, int position) {

        holder.prname.setText(list.get(position).getPname());
        holder.prlocation.setText(list.get(position).getPlocation());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public interface SelectedProject {
        void selectedProject(projects projects);
    }

    class ProjViewHolder extends RecyclerView.ViewHolder {

        TextView prname, prlocation;

        public ProjViewHolder(@NonNull View itemView) {
            super(itemView);

            prname = itemView.findViewById(R.id.FPName);
            prlocation = itemView.findViewById(R.id.FPLocation);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectedProject.selectedProject(list.get(getAdapterPosition()));
                }
            });
        }
    }
}

The selection is accepted in the search adapter.

Adapter adapter = new Adapter(sList,this);

But normal adapter shows error for the below code.

Adapter adapter = new Adapter(list,this);

But if i change this to null as below, the error goes off.

Adapter adapter = new Adapter(list,null);

But when I clicked, the app is closed.

Please let me know how to correct the error?

stackrace details

 java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.volq.Adapter$SelectedProject.selectedProject(com.example.volq.projects)' on a null object reference
    at com.example.volq.Adapter$ProjViewHolder$1.onClick(Adapter.java:68)
    at android.view.View.performClick(View.java:5610)
    at android.view.View$PerformClick.run(View.java:22265)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    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)

Body:
Notice the difference between how you're setting your adapter for search vs normal

Adapter adapter = new Adapter(sList, this); // `this`as the second parameter/listener is ok

But for the other one:

Adapter adapter = new Adapter(list, null);

Here the listener is null, this error makes sense:

java.lang.NullPointerException: Attempt to invoke interface method
  'void
  com.example.volq.Adapter$SelectedProject.selectedProject(com.example.volq.projects)'
  on a null object reference

Instead of null, just pass MainActivity.this in your Activity's onStart() callback:

Adapter adapter = new Adapter(list, MainActivity.this);

But normal adapter shows error for the below code.

Adapter adapter = new Adapter(list,this);

It's because of this does not reference MainActivity inside onDataChange() callback, it refers to the ValueEventListener


问:
Need of SingleThreadPool in Java?
I have a few questions regarding ExecutorService.

In what cases we should use newSingleThreadExecutor() than others and Why?

Can you tell me the real use case of having SnewSingleThreadExecutor()?

If we have a single thread either from (newSingleThreadExecutor() or newFixedThreadPool(1) or newCacheThreadPool(1)) Do we still need to check for Thread Safety?

Why do we need newSingleThreadExecutor() if we can already create a single thread using newFixedThreadPool(1)

答:
When you don't want tasks to run in parallel because of common data.

Swing's Event Dispatch Thread. It is not called executor, but in fact it is, just its execute method is called invokeLater.

It depends on what data you access. If that data can be accessed outside the tasks running on this executor, then yes. It does not depend of how you built your executor.

We do not need. I don't know what SingleThreadPool do you mean - there is no such class in Java runtime libarary.

Title: Need of SingleThreadPool in Java?